

Phobos Runtime Library
======================

 Phobos is the standard runtime library that comes with the D language compiler.

 Generally, the `std` namespace is used for the main modules in the Phobos standard library. The `etc` namespace is used for external C/C++ library bindings. The `core` namespace is used for low-level D runtime functions.

 The following table is a quick reference guide for which Phobos modules to use for a given category of functionality. Note that some modules may appear in more than one category, as some Phobos modules are quite generic and can be applied in a variety of situations.

 

| Modules | Description |
| --- | --- |
|  *Algorithms & ranges* |
| [`std.algorithm`](std_algorithm) [`std.range`](std_range) [`std.range.primitives`](std_range_primitives) [`std.range.interfaces`](std_range_interfaces) | Generic algorithms that work with [ranges](std_range) of any type, including strings, arrays, and other kinds of sequentially-accessed data. Algorithms include searching, comparison, iteration, sorting, set operations, and mutation.  |
|  *Array manipulation* |
| [`std.array`](std_array) [`std.algorithm`](std_algorithm) | Convenient operations commonly used with built-in arrays. Note that many common array operations are subsets of more generic algorithms that work with arbitrary ranges, so they are found in `std.algorithm`.  |
|  *Containers* |
| [`std.container.array`](std_container_array) [`std.container.binaryheap`](std_container_binaryheap) [`std.container.dlist`](std_container_dlist) [`std.container.rbtree`](std_container_rbtree) [`std.container.slist`](std_container_slist) | See [std.container.\*](std_container) for an overview.  |
|  *Data formats* |
| [`std.base64`](std_base64) | Encoding / decoding Base64 format. |
| [`std.csv`](std_csv) | Read Comma Separated Values and its variants from an input range of `dchar`. |
| [`std.json`](std_json) | Read/write data in JSON format. |
| [`std.xml`](std_xml) | Read/write data in XML format. |
| [`std.zip`](std_zip) | Read/write data in the ZIP archive format. |
| [`std.zlib`](std_zlib) | Compress/decompress data using the zlib library. |
|  *Data integrity* |
| [`std.experimental.checkedint`](std_experimental_checkedint) | Checked integral types. |
| [`std.digest`](std_digest) | Compute digests such as md5, sha1 and crc32. |
| [`std.digest.crc`](std_digest_crc) | Cyclic Redundancy Check (32-bit) implementation. |
| [`std.digest.hmac`](std_digest_hmac) | Compute HMAC digests of arbitrary data. |
| [`std.digest.md`](std_digest_md) | Compute MD5 hash of arbitrary data. |
| [`std.digest.murmurhash`](std_digest_murmurhash) | Compute MurmurHash of arbitrary data. |
| [`std.digest.ripemd`](std_digest_ripemd) | Compute RIPEMD-160 hash of arbitrary data. |
| [`std.digest.sha`](std_digest_sha) | Compute SHA1 and SHA2 hashes of arbitrary data. |
|  *Date & time* |
| [`std.datetime`](std_datetime) | Provides convenient access to date and time representations. |
| [`core.time`](core_time) | Implements low-level time primitives. |
|  *Exception handling* |
| [`std.exception`](std_exception) | Implements routines related to exceptions. |
| [`core.exception`](core_exception) | Defines built-in exception types and low-level language hooks required by the compiler. |
|  *External library bindings* |
| [`etc.c.curl`](etc_c_curl) | Interface to libcurl C library. |
| [`etc.c.odbc.sql`](etc_c_odbc_sql) | Interface to ODBC C library. |
| [`etc.c.odbc.sqlext`](etc_c_odbc_sqlext) |
| [`etc.c.odbc.sqltypes`](etc_c_odbc_sqltypes) |
| [`etc.c.odbc.sqlucode`](etc_c_odbc_sqlucode) |
| [`etc.c.sqlite3`](etc_c_sqlite3) | Interface to SQLite C library. |
| [`etc.c.zlib`](etc_c_zlib) | Interface to zlib C library. |
|  *I/O & File system* |
| [`std.file`](std_file) | Manipulate files and directories. |
| [`std.path`](std_path) | Manipulate strings that represent filesystem paths. |
| [`std.stdio`](std_stdio) | Perform buffered I/O. |
|  *Interoperability* |
| [`core.stdc.complex`](core_stdc_complex) [`core.stdc.ctype`](core_stdc_ctype) [`core.stdc.errno`](core_stdc_errno) [`core.stdc.fenv`](core_stdc_fenv) [`core.stdc.float_`](core_stdc_float_) [`core.stdc.inttypes`](core_stdc_inttypes) [`core.stdc.limits`](core_stdc_limits) [`core.stdc.locale`](core_stdc_locale) [`core.stdc.math`](core_stdc_math) [`core.stdc.signal`](core_stdc_signal) [`core.stdc.stdarg`](core_stdc_stdarg) [`core.stdc.stddef`](core_stdc_stddef) [`core.stdc.stdint`](core_stdc_stdint) [`core.stdc.stdio`](core_stdc_stdio) [`core.stdc.stdlib`](core_stdc_stdlib) [`core.stdc.string`](core_stdc_string) [`core.stdc.tgmath`](core_stdc_tgmath) [`core.stdc.time`](core_stdc_time) [`core.stdc.wchar_`](core_stdc_wchar_) [`core.stdc.wctype`](core_stdc_wctype) |  D bindings for standard C headers. These are mostly undocumented, as documentation for the functions these declarations provide bindings to can be found on external resources.  |
|  *Memory management* |
| [`core.memory`](core_memory) | Control the built-in garbage collector. |
| [`std.typecons`](std_typecons) | Build scoped variables and reference-counted types. |
|  *Metaprogramming* |
| [`core.attribute`](core_attribute) | Definitions of special attributes recognized by the compiler. |
| [`core.demangle`](core_demangle) | Convert *mangled* D symbol identifiers to source representation. |
| [`std.demangle`](std_demangle) | A simple wrapper around core.demangle. |
| [`std.meta`](std_meta) | Construct and manipulate template argument lists (aka type lists). |
| [`std.traits`](std_traits) | Extract information about types and symbols at compile time. |
| [`std.typecons`](std_typecons) | Construct new, useful general purpose types. |
|  *Multitasking* |
| [`std.concurrency`](std_concurrency) | Low level messaging API for threads. |
| [`std.parallelism`](std_parallelism) | High level primitives for SMP parallelism. |
| [`std.process`](std_process) | Starting and manipulating processes. |
| [`core.atomic`](core_atomic) | Basic support for lock-free concurrent programming. |
| [`core.sync.barrier`](core_sync_barrier) | Synchronize the progress of a group of threads. |
| [`core.sync.condition`](core_sync_condition) | Synchronized condition checking. |
| [`core.sync.exception`](core_sync_exception) | Base class for synchronization exceptions. |
| [`core.sync.mutex`](core_sync_mutex) | Mutex for mutually exclusive access. |
| [`core.sync.rwmutex`](core_sync_rwmutex) | Shared read access and mutually exclusive write access. |
| [`core.sync.semaphore`](core_sync_semaphore) | General use synchronization semaphore. |
| [`core.thread`](core_thread) | Thread creation and management. |
|  *Networking* |
| [`std.socket`](std_socket) | Socket primitives. |
| [`std.net.curl`](std_net_curl) | Networking client functionality as provided by libcurl. |
| [`std.net.isemail`](std_net_isemail) | Validates an email address according to RFCs 5321, 5322 and others. |
| [`std.uri`](std_uri) | Encode and decode Uniform Resource Identifiers (URIs). |
| [`std.uuid`](std_uuid) | Universally-unique identifiers for resources in distributed systems. |
|  *Numeric* |
| [`std.bigint`](std_bigint) | An arbitrary-precision integer type. |
| [`std.complex`](std_complex) | A complex number type. |
| [`std.math`](std_math) | Elementary mathematical functions (powers, roots, trigonometry). |
| [`std.mathspecial`](std_mathspecial) | Families of transcendental functions. |
| [`std.numeric`](std_numeric) | Floating point numerics functions. |
| [`std.random`](std_random) | Pseudo-random number generators. |
| [`core.checkedint`](core_checkedint) | Range-checking integral arithmetic primitives. |
| [`core.math`](core_math) | Built-in mathematical intrinsics. |
|  *Paradigms* |
| [`std.functional`](std_functional) | Functions that manipulate other functions. |
| [`std.algorithm`](std_algorithm) | Generic algorithms for processing sequences. |
| [`std.signals`](std_signals) | Signal-and-slots framework for event-driven programming. |
|  *Runtime utilities* |
| [`object`](object) | Core language definitions. Automatically imported. |
| [`std.getopt`](std_getopt) | Parsing of command-line arguments. |
| [`std.compiler`](std_compiler) | Host compiler vendor string and language version. |
| [`std.system`](std_system) | Runtime environment, such as OS type and endianness. |
| [`core.cpuid`](core_cpuid) | Capabilities of the CPU the program is running on. |
| [`core.memory`](core_memory) | Control the built-in garbage collector. |
| [`core.runtime`](core_runtime) | Control and configure the D runtime. |
|  *String manipulation* |
| [`std.string`](std_string) | Algorithms that work specifically with strings. |
| [`std.array`](std_array) | Manipulate builtin arrays. |
| [`std.algorithm`](std_algorithm) | Generic algorithms for processing sequences. |
| [`std.uni`](std_uni) | Fundamental Unicode algorithms and data structures. |
| [`std.utf`](std_utf) | Encode and decode UTF-8, UTF-16 and UTF-32 strings. |
| [`std.format`](std_format) | Format data into strings. |
| [`std.path`](std_path) | Manipulate strings that represent filesystem paths. |
| [`std.regex`](std_regex) | Regular expressions. |
| [`std.ascii`](std_ascii) | Routines specific to the ASCII subset of Unicode. |
| [`std.encoding`](std_encoding) | Handle and transcode between various text encodings. |
| [`std.windows.charset`](std_windows_charset) | Windows specific character set support. |
| [`std.outbuffer`](std_outbuffer) | Serialize data to `ubyte` arrays. |
|  *Type manipulations* |
| [`std.conv`](std_conv) | Convert types from one type to another. |
| [`std.typecons`](std_typecons) | Type constructors for scoped variables, ref counted types, etc. |
| [`std.bitmanip`](std_bitmanip) | High level bit level manipulation, bit arrays, bit fields. |
| [`std.variant`](std_variant) | Discriminated unions and algebraic types. |
| [`core.bitop`](core_bitop) | Low level bit manipulation. |
|  *Vector programming* |
| [`core.simd`](core_simd) | SIMD intrinsics |



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/index.html>

object
======

 Forms the symbols available to all D programs. Includes Object, which is the root of the class object hierarchy. This module is implicitly imported. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly
 
class **Object**;  
All D class objects inherit from Object.

 
string **toString**();  
Convert Object to a human readable string.

  nothrow @trusted size\_t **toHash**();  
Compute hash function for Object.

  int **opCmp**(Object o);  
Compare with another Object obj. 



Returns:


|  |  |
| --- | --- |
| this < obj | < 0 |
| this == obj | 0 |
| this > obj | > 0 |


  bool **opEquals**(Object o);  
Test whether `this` is equal to `o`. The default implementation only compares by identity (using the `is` operator). Generally, overrides for `opEquals` should attempt to compare objects by their contents.

  static Object **factory**(string classname);  
Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor. 



Returns:
null if failed 
 
Example


```
module foo.bar;

class C
{
    this() { x = 10; }
    int x;
}

void main()
{
    auto c = cast(C)Object.factory("foo.bar.C");
    assert(c !is null && c.x == 10);
}

```
    bool **opEquals**(const Object lhs, const Object rhs);  
Returns true if lhs and rhs are equal.



Examples:
If aliased to the same object or both null => equal 
```
class F { int flag; this(int flag) { this.flag = flag; } }

F f;
assert(f == f); // both null
f = new F(1);
assert(f == f); // both aliased to the same object

```
 
 
Examples:
If either is null => non-equal 
```
class F { int flag; this(int flag) { this.flag = flag; } }
F f;
assert(!(new F(0) == f));
assert(!(f == new F(0)));

```
 
 
Examples:
If same exact type => one call to method opEquals 
```
class F
{
    int flag;

    this(int flag)
    {
        this.flag = flag;
    }

    override bool opEquals(const Object o)
    {
        return flag == (cast(F) o).flag;
    }
}

F f;
assert(new F(0) == new F(0));
assert(!(new F(0) == new F(1)));

```
 
 
Examples:
General case => symmetric calls to method opEquals 
```
int fEquals, gEquals;

class Base
{
    int flag;
    this(int flag)
    {
        this.flag = flag;
    }
}

class F : Base
{
    this(int flag) { super(flag); }

    override bool opEquals(const Object o)
    {
        fEquals++;
        return flag == (cast(Base) o).flag;
    }
}

class G : Base
{
    this(int flag) { super(flag); }

    override bool opEquals(const Object o)
    {
        gEquals++;
        return flag == (cast(Base) o).flag;
    }
}

assert(new F(1) == new G(1));
assert(fEquals == 1);
assert(gEquals == 1);

```
 
  struct **Interface**;  
Information about an interface. When an object is accessed via an interface, an Interface\* appears as the first entry in its vtbl.

 
TypeInfo\_Class **classinfo**;  
.classinfo for this interface (not for containing class)

  size\_t **offset**;  
offset to Interface 'this' from Object 'this'

    struct **OffsetTypeInfo**;  
Array of pairs giving the offset and type information for each member in an aggregate.

 
size\_t **offset**;  
Offset of member from start of object

  TypeInfo **ti**;  
TypeInfo for this member

    abstract class **TypeInfo**;  
Runtime type information about a type. Can be retrieved for any type using a [*TypeidExpression*](https://dlang.org/spec/expression.html#TypeidExpression).

 
const nothrow @trusted size\_t **getHash**(scope const void\* p);  
Computes a hash of the instance of a type. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | pointer to start of instance of the type |


 
Returns:
the hash 
 
Bugs:
fix <https://issues.dlang.org/show_bug.cgi?id=12516> e.g. by changing this to a truly safe interface.
  const bool **equals**(in void\* p1, in void\* p2);  
Compares two instances for equality.

  const int **compare**(in void\* p1, in void\* p2);  
Compares two instances for <, ==, or >.

  const pure nothrow @nogc @property @safe size\_t **tsize**();  
Returns size of the type.

  const void **swap**(void\* p1, void\* p2);  
Swaps two instances of the type.

  inout pure nothrow @nogc @property inout(TypeInfo) **next**();  
Get TypeInfo for 'next' type, as defined by what kind of type this is, null if none.

  abstract const pure nothrow @nogc @safe const(void)[] **initializer**();  
Return default initializer. If the type should be initialized to all zeros, an array with a null ptr and a length equal to the type size will be returned. For static arrays, this returns the default initializer for a single element of the array, use `tsize` to get the correct size.

  const pure nothrow @nogc @property @safe uint **flags**();  
Get flags for type: 1 means GC should scan for pointers, 2 means arg of this type is passed in SIMD register(s) if available

  const const(OffsetTypeInfo)[] **offTi**();  
Get type information on the contents of the type; null if not available

  const void **destroy**(void\* p);  
Run the destructor on the object and all its sub-objects

  const void **postblit**(void\* p);  
Run the postblit on the object and all its sub-objects

  const pure nothrow @nogc @property @safe size\_t **talign**();  
Return alignment of type

  nothrow @safe int **argTypes**(out TypeInfo arg1, out TypeInfo arg2);  
Return internal info on arguments fitting into 8byte. See X86-64 ABI 3.2.3

  const pure nothrow @nogc @property @safe immutable(void)\* **rtInfo**();  
Return info used by the garbage collector to do precise collection.

    class **TypeInfo\_Class**: object.TypeInfo;  
Runtime type information about a class. Can be retrieved from an object instance by using the [.classinfo](https://dlang.org/spec/property.html#classinfo) property.

 
byte[] **m\_init**;  
class static initializer (init.length gives size in bytes of class)

  string **name**;  
class name

  void\*[] **vtbl**;  
virtual function pointer table

  Interface[] **interfaces**;  
interfaces this class implements

  TypeInfo\_Class **base**;  
base class

  static const(TypeInfo\_Class) **find**(scope const char[] classname);  
Search all modules for TypeInfo\_Class corresponding to classname. 



Returns:
null if not found
  const Object **create**();  
Create instance of Object represented by 'this'.

  final const pure nothrow @nogc @trusted bool **isBaseOf**(scope const TypeInfo\_Class child);  
Returns true if the class described by `child` derives from or is the class described by this `TypeInfo_Class`. Always returns false if the argument is null. 



Parameters:


|  |  |
| --- | --- |
| TypeInfo\_Class `child` | TypeInfo for some class |


 
Returns:
true if the class described by `child` derives from or is the class described by this `TypeInfo_Class`.
    struct **ModuleInfo**;  
An instance of ModuleInfo is generated into the object file for each compiled module. 


It provides access to various aspects of the module. It is not generated for betterC.

 
const pure nothrow @nogc @property void function() **tlsctor**();  

Returns:
module constructor for thread locals, `null` if there isn't one
  const pure nothrow @nogc @property void function() **tlsdtor**();  

Returns:
module destructor for thread locals, `null` if there isn't one
  const pure nothrow @nogc @property void\* **xgetMembers**();  

Returns:
address of a module's `const(MemberInfo)[] getMembers(string)` function, `null` if there isn't one
  const pure nothrow @nogc @property void function() **ctor**();  

Returns:
module constructor, `null` if there isn't one
  const pure nothrow @nogc @property void function() **dtor**();  

Returns:
module destructor, `null` if there isn't one
  const pure nothrow @nogc @property void function() **ictor**();  

Returns:
module order independent constructor, `null` if there isn't one
  const pure nothrow @nogc @property void function() **unitTest**();  

Returns:
address of function that runs the module's unittests, `null` if there isn't one
  const pure nothrow @nogc @property immutable(ModuleInfo\*)[] **importedModules**();  

Returns:
array of pointers to the ModuleInfo's of modules imported by this one
  const pure nothrow @nogc @property TypeInfo\_Class[] **localClasses**();  

Returns:
array of TypeInfo\_Class references for classes defined in this module
  const pure nothrow @nogc @property string **name**();  

Returns:
name of module, `null` if no name
    class **Throwable**;  
The base class of all thrown objects. 


All thrown objects must inherit from Throwable. Class `Exception`, which derives from this class, represents the category of thrown objects that are safe to catch and handle. In principle, one should not catch Throwable objects that are not derived from `Exception`, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them.

 
string **msg**;  
A message describing the error.

  string **file**;  
The file name of the D source code corresponding with where the error was thrown from.

  size\_t **line**;  
The line number of the D source code corresponding with where the error was thrown from.

  TraceInfo **info**;  
The stack trace of where the error happened. This is an opaque object that can either be converted to `string`, or iterated over with  `foreach` to extract the items in the stack trace (as strings).

  inout pure nothrow @nogc @property scope @safe inout(Throwable) **next**() return;  

Returns:
A reference to the next error in the list. This is used when a new `Throwable` is thrown from inside a `catch` block. The originally caught `Exception` will be chained to the new `Throwable` via this field.
  pure nothrow @nogc @property scope @safe void **next**(Throwable tail);  
Replace next in chain with `tail`. Use `chainTogether` instead if at all possible.

  final pure nothrow @nogc ref scope @system uint **refcount**() return;  

Returns:
mutable reference to the reference count, which is 0 - allocated by the GC, 1 - allocated by d\_newThrowable(), and >=2 which is the reference count + 1 
 
Note
 Marked as `@system` to discourage casual use of it.
  int **opApply**(scope int delegate(Throwable) dg);  
Loop over the chain of Throwables.

  static pure nothrow @nogc @system Throwable **chainTogether**(return scope Throwable e1, return scope Throwable e2);  
Append `e2` to chain of exceptions that starts with `e1`. 



Parameters:


|  |  |
| --- | --- |
| Throwable `e1` | start of chain (can be null) |
| Throwable `e2` | second part of chain (can be null) |


 
Returns:
Throwable that is at the start of the chain; null if both `e1` and `e2` are null
  string **toString**();  
Overrides `Object.toString` and returns the error message. Internally this forwards to the `toString` overload that takes a sink delegate.

  const void **toString**(scope void delegate(in char[]) sink);  
The Throwable hierarchy uses a toString overload that takes a sink delegate to avoid GC allocations, which cannot be performed in certain error situations. Override this  `toString` method to customize the error message.

  const const(char)[] **message**();  
Get the message describing the error. Base behavior is to return the `Throwable.msg` field. Override to return some other error message. 



Returns:
Error message
    class **Exception**: object.Throwable;  
The base class of all errors that are safe to catch and handle. 


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

 
Examples:


```
bool gotCaught;
try
{
    throw new Exception("msg");
}
catch (Exception e)
{
    gotCaught = true;
    assert(e.msg == "msg");
}
assert(gotCaught);

```
 
 
pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable nextInChain = null);  
Creates a new instance of Exception. The nextInChain parameter is used internally and should always be `null` when passed by user code. This constructor does not automatically throw the newly-created Exception; the `throw` statement should be used for that purpose.

    class **Error**: object.Throwable;  
The base class of all unrecoverable runtime errors. 


This represents the category of `Throwable` objects that are **not** safe to catch and handle. In principle, one should not catch Error objects, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them.

 
Examples:


```
bool gotCaught;
try
{
    throw new Error("msg");
}
catch (Error e)
{
    gotCaught = true;
    assert(e.msg == "msg");
}
assert(gotCaught);

```
 
 
pure nothrow @nogc @safe this(string msg, Throwable nextInChain = null);  
Creates a new instance of Error. The nextInChain parameter is used internally and should always be `null` when passed by user code. This constructor does not automatically throw the newly-created Error; the `throw` statement should be used for that purpose.

  Throwable **bypassedException**;  
The first `Exception` which was bypassed when this Error was thrown, or `null` if no `Exception`s were pending.

    void **clear**(Value, Key)(Value[Key] aa);  
Removes all remaining keys and values from an associative array. 



Parameters:


|  |  |
| --- | --- |
| Value[Key] `aa` | The associative array. |


  T **rehash**(T : Value[Key], Value, Key)(T aa);  
Reorganizes the associative array in place so that lookups are more efficient. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
The rehashed associative array.
  V[K] **dup**(T : V[K], K, V)(T aa);  
Create a new associative array of the same size and copy the contents of the associative array into it. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


  pure nothrow @nogc @safe auto **byKey**(T : V[K], K, V)(T aa);  
Returns a forward range over the keys of the associative array. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
A forward range.
  pure nothrow @nogc @safe auto **byValue**(T : V[K], K, V)(T aa);  
Returns a forward range over the values of the associative array. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
A forward range.
  pure nothrow @nogc @safe auto **byKeyValue**(T : V[K], K, V)(T aa);  
Returns a forward range over the key value pairs of the associative array. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
A forward range.
  @property Key[] **keys**(T : Value[Key], Value, Key)(T aa);  
Returns a dynamic array, the elements of which are the keys in the associative array. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
A dynamic array.
  @property Value[] **values**(T : Value[Key], Value, Key)(T aa);  
Returns a dynamic array, the elements of which are the values in the associative array. 



Parameters:


|  |  |
| --- | --- |
| T `aa` | The associative array. |


 
Returns:
A dynamic array.
  inout(V) **get**(K, V)(inout(V[K]) aa, K key, lazy inout(V) defaultValue);  
Looks up key; if it exists returns corresponding value else evaluates and returns defaultValue. 



Parameters:


|  |  |
| --- | --- |
| inout(V[K]) `aa` | The associative array. |
| K `key` | The key. |
| inout(V) `defaultValue` | The default value. |


 
Returns:
The value.
  ref V **require**(K, V)(ref V[K] aa, K key, lazy V value = V.init);  
Looks up key; if it exists returns corresponding value else evaluates value, adds it to the associative array and returns it. 



Parameters:


|  |  |
| --- | --- |
| V[K] `aa` | The associative array. |
| K `key` | The key. |
| V `value` | The required value. |


 
Returns:
The value.
 
Examples:


```
auto aa = ["k1": 1];
assert(aa.require("k1", 0) == 1);
assert(aa.require("k2", 0) == 0);
assert(aa["k2"] == 0);

```
 
  void **update**(K, V, C, U)(ref V[K] aa, K key, scope C create, scope U **update**)  
 Constraints: if (is(typeof(create()) : V) && (is(typeof(update(aa[K.init])) : V) || is(typeof(update(aa[K.init])) == void))); 
 
Looks up key; if it exists applies the update callable else evaluates the create callable and adds it to the associative array 



Parameters:


|  |  |
| --- | --- |
| V[K] `aa` | The associative array. |
| K `key` | The key. |
| C `create` | The callable to apply on create. |
| U `update` | The callable to apply on update. |


 
Examples:


```
auto aa = ["k1": 1];

aa.update("k1", {
    return -1; // create (won't be executed)
}, (ref int v) {
    v += 1; // update
});
assert(aa["k1"] == 2);

aa.update("k2", {
    return 0; // create
}, (ref int v) {
    v = -1; // update (won't be executed)
});
assert(aa["k2"] == 0);

```
 
  size\_t **hashOf**(T)(auto ref T arg, size\_t seed);   
  
size\_t **hashOf**(T)(auto ref T arg);  
Calculates the hash value of `arg` with an optional `seed` initial value. The result might not be equal to `typeid(T).getHash(&arg)`. 



Parameters:


|  |  |
| --- | --- |
| T `arg` | argument to calculate the hash value of |
| size\_t `seed` | optional `seed` value (may be used for hash chaining) |


 
Return
 calculated hash value of `arg`

 
Examples:


```
class MyObject
{
    size_t myMegaHash() const @safe pure nothrow
    {
        return 42;
    }
}
struct Test
{
    int a;
    string b;
    MyObject c;
    size_t toHash() const pure nothrow
    {
        size_t hash = a.hashOf();
        hash = b.hashOf(hash);
        size_t h1 = c.myMegaHash();
        hash = h1.hashOf(hash); //Mix two hash values
        return hash;
    }
}

```
 
  immutable size\_t[pointerBitmap.length] **RTInfoImpl**(size\_t[] pointerBitmap);  
Create RTInfo for type T

  enum immutable(void)\* **rtinfoNoPointers**;  
shortcuts for the precise GC, also generated by the compiler used instead of the actual pointer bitmap

  @property auto **dup**(T)(T[] a)  
 Constraints: if (!is(const(T) : T));   
  
@property T[] **dup**(T)(const(T)[] a)  
 Constraints: if (is(const(T) : T)); 
 
Provide the .dup array property.



Examples:


```
auto arr = [1, 2];
auto arr2 = arr.dup;
arr[0] = 0;
assert(arr == [0, 2]);
assert(arr2 == [1, 2]);

```
 
  @property immutable(T)[] **idup**(T)(T[] a);   
  
@property immutable(T)[] **idup**(T : void)(const(T)[] a);  
Provide the .idup array property.



Examples:


```
char[] arr = ['a', 'b', 'c'];
string s = arr.idup;
arr[0] = '.';
assert(s == "abc");

```
 
  pure nothrow @property @trusted size\_t **capacity**(T)(T[] arr);  
(Property) Gets the current capacity of a slice. The capacity is the size that the slice can grow to before the underlying array must be reallocated or extended. 


If an append must reallocate a slice with no possibility of extension, then `0` is returned. This happens when the slice references a static array, or if another slice references elements past the end of the current slice. 

 
Note
 The capacity of a slice may be impacted by operations on other slices.
 
Examples:


```
//Static array slice: no capacity
int[4] sarray = [1, 2, 3, 4];
int[]  slice  = sarray[];
assert(sarray.capacity == 0);
//Appending to slice will reallocate to a new array
slice ~= 5;
assert(slice.capacity >= 5);

//Dynamic array slices
int[] a = [1, 2, 3, 4];
int[] b = a[1 .. $];
int[] c = a[1 .. $ - 1];
debug(SENTINEL) {} else // non-zero capacity very much depends on the array and GC implementation
{
    assert(a.capacity != 0);
    assert(a.capacity == b.capacity + 1); //both a and b share the same tail
}
assert(c.capacity == 0);              //an append to c must relocate c.

```
 
  pure nothrow @trusted size\_t **reserve**(T)(ref T[] arr, size\_t newcapacity);  
Reserves capacity for a slice. The capacity is the size that the slice can grow to before the underlying array must be reallocated or extended. 



Returns:
The new capacity of the array (which may be larger than the requested capacity).
 
Examples:


```
//Static array slice: no capacity. Reserve relocates.
int[4] sarray = [1, 2, 3, 4];
int[]  slice  = sarray[];
auto u = slice.reserve(8);
assert(u >= 8);
assert(&sarray[0] !is &slice[0]);
assert(slice.capacity == u);

//Dynamic array slices
int[] a = [1, 2, 3, 4];
a.reserve(8); //prepare a for appending 4 more items
auto p = &a[0];
u = a.capacity;
a ~= [5, 6, 7, 8];
assert(p == &a[0]);      //a should not have been reallocated
assert(u == a.capacity); //a should not have been extended

```
 
  nothrow ref @system inout(T[]) **assumeSafeAppend**(T)(auto ref inout(T[]) arr);  
Assume that it is safe to append to this array. Appends made to this array after calling this function may append in place, even if the array was a slice of a larger array to begin with. 


Use this only when it is certain there are no elements in use beyond the array in the memory block. If there are, those elements will be overwritten by appending to this array. 

 
Warning
 Calling this function, and then using references to data located after the given array results in undefined behavior. 
 
Returns:
The input is returned.
 
Examples:


```
int[] a = [1, 2, 3, 4];

// Without assumeSafeAppend. Appending relocates.
int[] b = a [0 .. 3];
b ~= 5;
assert(a.ptr != b.ptr);

debug(SENTINEL) {} else
{
    // With assumeSafeAppend. Appending overwrites.
    int[] c = a [0 .. 3];
    c.assumeSafeAppend() ~= 5;
    assert(a.ptr == c.ptr);
}

```
 
  void **destroy**(bool initialize = true, T)(ref T obj)  
 Constraints: if (is(T == struct));   
  
void **destroy**(bool initialize = true, T)(T obj)  
 Constraints: if (is(T == class));   
  
void **destroy**(bool initialize = true, T)(T obj)  
 Constraints: if (is(T == interface));   
  
void **destroy**(bool initialize = true, T : U[n], U, size\_t n)(ref T obj)  
 Constraints: if (!is(T == struct) && !is(T == class) && !is(T == interface));   
  
void **destroy**(bool initialize = true, T)(ref T obj)  
 Constraints: if (!is(T == struct) && !is(T == interface) && !is(T == class) && !\_\_traits(isStaticArray, T)); 
 
Destroys the given object and optionally resets to initial state. It's used to destroy an object, calling its destructor or finalizer so it no longer references any other objects. It does *not* initiate a GC cycle or free any GC memory. If `initialize` is supplied `false`, the object is considered invalid after destruction, and should not be referenced.



Examples:
Reference type demonstration 
```
class C
{
    struct Agg
    {
        static int dtorCount;

        int x = 10;
        ~this() { dtorCount++; }
    }

    static int dtorCount;

    string s = "S";
    Agg a;
    ~this() { dtorCount++; }
}

C c = new C();
assert(c.dtorCount == 0);   // destructor not yet called
assert(c.s == "S");         // initial state `c.s` is `"S"`
assert(c.a.dtorCount == 0); // destructor not yet called
assert(c.a.x == 10);        // initial state `c.a.x` is `10`
c.s = "T";
c.a.x = 30;
assert(c.s == "T");         // `c.s` is `"T"`
destroy(c);
assert(c.dtorCount == 1);   // `c`'s destructor was called
assert(c.s == "S");         // `c.s` is back to its inital state, `"S"`
assert(c.a.dtorCount == 1); // `c.a`'s destructor was called
assert(c.a.x == 10);        // `c.a.x` is back to its inital state, `10`

// check C++ classes work too!
extern (C++) class CPP
{
    struct Agg
    {
        __gshared int dtorCount;

        int x = 10;
        ~this() { dtorCount++; }
    }

    __gshared int dtorCount;

    string s = "S";
    Agg a;
    ~this() { dtorCount++; }
}

CPP cpp = new CPP();
assert(cpp.dtorCount == 0);   // destructor not yet called
assert(cpp.s == "S");         // initial state `cpp.s` is `"S"`
assert(cpp.a.dtorCount == 0); // destructor not yet called
assert(cpp.a.x == 10);        // initial state `cpp.a.x` is `10`
cpp.s = "T";
cpp.a.x = 30;
assert(cpp.s == "T");         // `cpp.s` is `"T"`
destroy!false(cpp);           // destroy without initialization
assert(cpp.dtorCount == 1);   // `cpp`'s destructor was called
assert(cpp.s == "T");         // `cpp.s` is not initialized
assert(cpp.a.dtorCount == 1); // `cpp.a`'s destructor was called
assert(cpp.a.x == 30);        // `cpp.a.x` is not initialized
destroy(cpp);
assert(cpp.dtorCount == 2);   // `cpp`'s destructor was called again
assert(cpp.s == "S");         // `cpp.s` is back to its inital state, `"S"`
assert(cpp.a.dtorCount == 2); // `cpp.a`'s destructor was called again
assert(cpp.a.x == 10);        // `cpp.a.x` is back to its inital state, `10`

```
 
 
Examples:
Value type demonstration 
```
int i;
assert(i == 0);           // `i`'s initial state is `0`
i = 1;
assert(i == 1);           // `i` changed to `1`
destroy!false(i);
assert(i == 1);           // `i` was not initialized
destroy(i);
assert(i == 0);           // `i` is back to its initial state `0`

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/object.html>

std.container.rbtree
====================

 This module implements a red-black tree container. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/rbtree.d](https://github.com/dlang/phobos/blob/master/std/container/rbtree.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:
Steven Schveighoffer, [Andrei Alexandrescu](http://erdani.com)

 
Examples:


```
import std.algorithm.comparison : equal;
import std.container.rbtree;

auto rbt = redBlackTree(3, 1, 4, 2, 5);
writeln(rbt.front); // 1
assert(equal(rbt[], [1, 2, 3, 4, 5]));

rbt.removeKey(1, 4);
assert(equal(rbt[], [2, 3, 5]));

rbt.removeFront();
assert(equal(rbt[], [3, 5]));

rbt.insert([1, 2, 4]);
assert(equal(rbt[], [1, 2, 3, 4, 5]));

// Query bounds in O(log(n))
assert(rbt.lowerBound(3).equal([1, 2]));
assert(rbt.equalRange(3).equal([3]));
assert(rbt.upperBound(3).equal([4, 5]));

// A Red Black tree with the highest element at front:
import std.range : iota;
auto maxTree = redBlackTree!"a > b"(iota(5));
assert(equal(maxTree[], [4, 3, 2, 1, 0]));

// adding duplicates will not add them, but return 0
auto rbt2 = redBlackTree(1, 3);
writeln(rbt2.insert(1)); // 0
assert(equal(rbt2[], [1, 3]));
writeln(rbt2.insert(2)); // 1

// however you can allow duplicates
auto ubt = redBlackTree!true([0, 1, 0, 1]);
assert(equal(ubt[], [0, 0, 1, 1]));

```
 
 
class **RedBlackTree**(T, alias less = "a < b", bool allowDuplicates = false) if (is(typeof(binaryFun!less(T.init, T.init))));  
Implementation of a  [red-black tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) container. 


All inserts, removes, searches, and any function in general has complexity of Ο(`lg(n)`).   
  
 To use a different comparison than `"a < b"`, pass a different operator string that can be used by [`std.functional.binaryFun`](std_functional#binaryFun), or pass in a function, delegate, functor, or any type where `less(a, b)` results in a `bool` value.   
  
 Note that less should produce a strict ordering. That is, for two unequal elements `a` and `b`, `less(a, b) == !less(b, a)`. `less(a, a)` should always equal `false`.   
  
 If `allowDuplicates` is set to `true`, then inserting the same element more than once continues to add more elements. If it is `false`, duplicate elements are ignored on insertion. If duplicates are allowed, then new elements are inserted after all existing duplicate elements.

 
alias **Elem** = T;  
Element type for the tree

  alias **Range** = RBRange!(RBNode\*);   
  
alias **ConstRange** = RBRange!(const(RBNode)\*);   
  
alias **ImmutableRange** = RBRange!(immutable(RBNode)\*);  
The range types for `RedBlackTree`

  const @property bool **empty**();  
Check if any elements exist in the container. Returns `false` if at least one element exists.

  const @property size\_t **length**();  
Returns the number of elements in the container. 



Complexity
 Ο(`1`).
  @property RedBlackTree **dup**();  
Duplicate this container. The resulting container contains a shallow copy of the elements. 



Complexity
 Ο(`n`)

  Range **opSlice**();   
  
const ConstRange **opSlice**();   
  
immutable ImmutableRange **opSlice**();  
Fetch a range that spans all the elements in the container. 



Complexity
 Ο(`1`)

  inout inout(Elem) **front**();  
The front element in the container 



Complexity
 Ο(`1`)

  inout inout(Elem) **back**();  
The last element in the container 



Complexity
 Ο(`log(n)`)

  const bool **opBinaryRight**(string op)(Elem e)  
 Constraints: if (op == "in"); 
 
`in` operator. Check to see if the given element exists in the container. 



Complexity
 Ο(`log(n)`)

  bool **opEquals**(Object rhs);  
Compares two trees for equality. 



Complexity
 Ο(`n`)

  nothrow @safe size\_t **toHash**();  
Generates a hash for the tree. Note that with a custom comparison function it may not hold that if two rbtrees are equal, the hashes of the trees will be equal.

  void **clear**();  
Removes all elements from the container. 



Complexity
 Ο(`1`)

  size\_t **stableInsert**(Stuff)(Stuff stuff)  
 Constraints: if (isImplicitlyConvertible!(Stuff, Elem)); 
 
Insert a single element in the container. Note that this does not invalidate any ranges currently iterating the container. 



Returns:
The number of elements inserted. 
 
Complexity
 Ο(`log(n)`)

  size\_t **stableInsert**(Stuff)(scope Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, Elem));   
  
alias **insert** = stableInsert;  
Insert a range of elements in the container. Note that this does not invalidate any ranges currently iterating the container. 



Returns:
The number of elements inserted. 
 
Complexity
 Ο(`m * log(n)`)

  Elem **removeAny**();  
Remove an element from the container and return its value. 



Complexity
 Ο(`log(n)`)

  void **removeFront**();  
Remove the front element from the container. 



Complexity
 Ο(`log(n)`)

  void **removeBack**();  
Remove the back element from the container. 



Complexity
 Ο(`log(n)`)

  Range **remove**(Range r);  
Removes the given range from the container. 



Returns:
A range containing all of the elements that were after the given range. 
 
Complexity
 Ο(`m * log(n)`) (where m is the number of elements in the range)
  Range **remove**(Take!Range r);  
Removes the given `Take!Range` from the container 



Returns:
A range containing all of the elements that were after the given range. 
 
Complexity
 Ο(`m * log(n)`) (where m is the number of elements in the range)
  size\_t **removeKey**(U...)(U elems)  
 Constraints: if (allSatisfy!(isImplicitlyConvertibleToElem, U));   
  
size\_t **removeKey**(U)(scope U[] elems)  
 Constraints: if (isImplicitlyConvertible!(U, Elem));   
  
size\_t **removeKey**(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, Elem) && !isDynamicArray!Stuff); 
 
Removes elements from the container that are equal to the given values according to the less comparator. One element is removed for each value given which is in the container. If `allowDuplicates` is true, duplicates are removed only if duplicate values are given. 



Returns:
The number of elements removed. 
 
Complexity
 Ο(`m log(n)`) (where m is the number of elements to remove) 
 
Example


```
auto rbt = redBlackTree!true(0, 1, 1, 1, 4, 5, 7);
rbt.removeKey(1, 4, 7);
assert(equal(rbt[], [0, 1, 1, 5]));
rbt.removeKey(1, 1, 0);
assert(equal(rbt[], [5]));

```
  Range **upperBound**(Elem e);   
  
const ConstRange **upperBound**(Elem e);   
  
immutable ImmutableRange **upperBound**(Elem e);  
Get a range from the container with all elements that are > e according to the less comparator 



Complexity
 Ο(`log(n)`)

  Range **lowerBound**(Elem e);   
  
const ConstRange **lowerBound**(Elem e);   
  
immutable ImmutableRange **lowerBound**(Elem e);  
Get a range from the container with all elements that are < e according to the less comparator 



Complexity
 Ο(`log(n)`)

  auto **equalRange**(this This)(Elem e);  
Get a range from the container with all elements that are == e according to the less comparator 



Complexity
 Ο(`log(n)`)

  const void **toString**(scope void delegate(const(char)[]) sink, ref scope const FormatSpec!char fmt);  
Formats the RedBlackTree into a sink function. For more info see  `std.format.formatValue`. Note that this only is available when the element type can be formatted. Otherwise, the default toString from Object is used.

  this(Elem[] elems...);  
Constructor. Pass in an array of elements, or individual elements to initialize the tree with.

  this(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, Elem)); 
 
Constructor. Pass in a range of elements to initialize the tree with.

  this();    auto **redBlackTree**(E)(E[] elems...);   
  
auto **redBlackTree**(bool allowDuplicates, E)(E[] elems...);   
  
auto **redBlackTree**(alias less, E)(E[] elems...)  
 Constraints: if (is(typeof(binaryFun!less(E.init, E.init))));   
  
auto **redBlackTree**(alias less, bool allowDuplicates, E)(E[] elems...)  
 Constraints: if (is(typeof(binaryFun!less(E.init, E.init))));   
  
auto **redBlackTree**(Stuff)(Stuff range)  
 Constraints: if (isInputRange!Stuff && !isArray!Stuff);   
  
auto **redBlackTree**(bool allowDuplicates, Stuff)(Stuff range)  
 Constraints: if (isInputRange!Stuff && !isArray!Stuff);   
  
auto **redBlackTree**(alias less, Stuff)(Stuff range)  
 Constraints: if (is(typeof(binaryFun!less((ElementType!Stuff).init, (ElementType!Stuff).init))) && isInputRange!Stuff && !isArray!Stuff);   
  
auto **redBlackTree**(alias less, bool allowDuplicates, Stuff)(Stuff range)  
 Constraints: if (is(typeof(binaryFun!less((ElementType!Stuff).init, (ElementType!Stuff).init))) && isInputRange!Stuff && !isArray!Stuff); 
 
Convenience function for creating a `RedBlackTree!E` from a list of values. 



Parameters:


|  |  |
| --- | --- |
| allowDuplicates | Whether duplicates should be allowed (optional, default: false) |
| less | predicate to sort by (optional) |
| E[] `elems` | elements to insert into the rbtree (variadic arguments) |
| Stuff `range` | range elements to insert into the rbtree (alternative to elems) |


 
Examples:


```
import std.range : iota;

auto rbt1 = redBlackTree(0, 1, 5, 7);
auto rbt2 = redBlackTree!string("hello", "world");
auto rbt3 = redBlackTree!true(0, 1, 5, 7, 5);
auto rbt4 = redBlackTree!"a > b"(0, 1, 5, 7);
auto rbt5 = redBlackTree!("a > b", true)(0.1, 1.3, 5.9, 7.2, 5.9);

// also works with ranges
auto rbt6 = redBlackTree(iota(3));
auto rbt7 = redBlackTree!true(iota(3));
auto rbt8 = redBlackTree!"a > b"(iota(3));
auto rbt9 = redBlackTree!("a > b", true)(iota(3));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_rbtree.html>

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](std_range) and [tutorial on ranges](http://ddili.org/ders/d.en/ranges.html). 


   
  
 Algorithms are categorized into the following submodules:   
  
 

| Submodule | Functions |
| --- | --- |
| [Searching](std_algorithm_searching) | [*all*](std_algorithm_searching#all) [*any*](std_algorithm_searching#any) [*balancedParens*](std_algorithm_searching#balancedParens) [*boyerMooreFinder*](std_algorithm_searching#boyerMooreFinder) [*canFind*](std_algorithm_searching#canFind) [*commonPrefix*](std_algorithm_searching#commonPrefix) [*count*](std_algorithm_searching#count) [*countUntil*](std_algorithm_searching#countUntil) [*endsWith*](std_algorithm_searching#endsWith) [*find*](std_algorithm_searching#find) [*findAdjacent*](std_algorithm_searching#findAdjacent) [*findAmong*](std_algorithm_searching#findAmong) [*findSkip*](std_algorithm_searching#findSkip) [*findSplit*](std_algorithm_searching#findSplit) [*findSplitAfter*](std_algorithm_searching#findSplitAfter) [*findSplitBefore*](std_algorithm_searching#findSplitBefore) [*minCount*](std_algorithm_searching#minCount) [*maxCount*](std_algorithm_searching#maxCount) [*minElement*](std_algorithm_searching#minElement) [*maxElement*](std_algorithm_searching#maxElement) [*minIndex*](std_algorithm_searching#minIndex) [*maxIndex*](std_algorithm_searching#maxIndex) [*minPos*](std_algorithm_searching#minPos) [*maxPos*](std_algorithm_searching#maxPos) [*skipOver*](std_algorithm_searching#skipOver) [*startsWith*](std_algorithm_searching#startsWith) [*until*](std_algorithm_searching#until) |
| [Comparison](std_algorithm_comparison) | [*among*](std_algorithm_comparison#among) [*castSwitch*](std_algorithm_comparison#castSwitch) [*clamp*](std_algorithm_comparison#clamp) [*cmp*](std_algorithm_comparison#cmp) [*either*](std_algorithm_comparison#either) [*equal*](std_algorithm_comparison#equal) [*isPermutation*](std_algorithm_comparison#isPermutation) [*isSameLength*](std_algorithm_comparison#isSameLength) [*levenshteinDistance*](std_algorithm_comparison#levenshteinDistance) [*levenshteinDistanceAndPath*](std_algorithm_comparison#levenshteinDistanceAndPath) [*max*](std_algorithm_comparison#max) [*min*](std_algorithm_comparison#min) [*mismatch*](std_algorithm_comparison#mismatch) [*predSwitch*](std_algorithm_comparison#predSwitch) |
| [Iteration](std_algorithm_iteration) | [*cache*](std_algorithm_iteration#cache) [*cacheBidirectional*](std_algorithm_iteration#cacheBidirectional) [*chunkBy*](std_algorithm_iteration#chunkBy) [*cumulativeFold*](std_algorithm_iteration#cumulativeFold) [*each*](std_algorithm_iteration#each) [*filter*](std_algorithm_iteration#filter) [*filterBidirectional*](std_algorithm_iteration#filterBidirectional) [*fold*](std_algorithm_iteration#fold) [*group*](std_algorithm_iteration#group) [*joiner*](std_algorithm_iteration#joiner) [*map*](std_algorithm_iteration#map) [*mean*](std_algorithm_iteration#mean) [*permutations*](std_algorithm_iteration#permutations) [*reduce*](std_algorithm_iteration#reduce) [*splitter*](std_algorithm_iteration#splitter) [*substitute*](std_algorithm_iteration#substitute) [*sum*](std_algorithm_iteration#sum) [*uniq*](std_algorithm_iteration#uniq) |
| [Sorting](std_algorithm_sorting) | [*completeSort*](std_algorithm_sorting#completeSort) [*isPartitioned*](std_algorithm_sorting#isPartitioned) [*isSorted*](std_algorithm_sorting#isSorted) [*isStrictlyMonotonic*](std_algorithm_sorting#isStrictlyMonotonic) [*ordered*](std_algorithm_sorting#ordered) [*strictlyOrdered*](std_algorithm_sorting#strictlyOrdered) [*makeIndex*](std_algorithm_sorting#makeIndex) [*merge*](std_algorithm_sorting#merge) [*multiSort*](std_algorithm_sorting#multiSort) [*nextEvenPermutation*](std_algorithm_sorting#nextEvenPermutation) [*nextPermutation*](std_algorithm_sorting#nextPermutation) [*partialSort*](std_algorithm_sorting#partialSort) [*partition*](std_algorithm_sorting#partition) [*partition3*](std_algorithm_sorting#partition3) [*schwartzSort*](std_algorithm_sorting#schwartzSort) [*sort*](std_algorithm_sorting#sort) [*topN*](std_algorithm_sorting#topN) [*topNCopy*](std_algorithm_sorting#topNCopy) [*topNIndex*](std_algorithm_sorting#topNIndex) |
| Set operations ([setops](std_algorithm_setops)) | [*cartesianProduct*](std_algorithm_setops#cartesianProduct) [*largestPartialIntersection*](std_algorithm_setops#largestPartialIntersection) [*largestPartialIntersectionWeighted*](std_algorithm_setops#largestPartialIntersectionWeighted) [*multiwayMerge*](std_algorithm_setops#multiwayMerge) [*multiwayUnion*](std_algorithm_setops#multiwayUnion) [*setDifference*](std_algorithm_setops#setDifference) [*setIntersection*](std_algorithm_setops#setIntersection) [*setSymmetricDifference*](std_algorithm_setops#setSymmetricDifference) |
| [Mutation](std_algorithm_mutation) | [*bringToFront*](std_algorithm_mutation#bringToFront) [*copy*](std_algorithm_mutation#copy) [*fill*](std_algorithm_mutation#fill) [*initializeAll*](std_algorithm_mutation#initializeAll) [*move*](std_algorithm_mutation#move) [*moveAll*](std_algorithm_mutation#moveAll) [*moveSome*](std_algorithm_mutation#moveSome) [*moveEmplace*](std_algorithm_mutation#moveEmplace) [*moveEmplaceAll*](std_algorithm_mutation#moveEmplaceAll) [*moveEmplaceSome*](std_algorithm_mutation#moveEmplaceSome) [*remove*](std_algorithm_mutation#remove) [*reverse*](std_algorithm_mutation#reverse) [*strip*](std_algorithm_mutation#strip) [*stripLeft*](std_algorithm_mutation#stripLeft) [*stripRight*](std_algorithm_mutation#stripRight) [*swap*](std_algorithm_mutation#swap) [*swapRanges*](std_algorithm_mutation#swapRanges) [*uninitializedFill*](std_algorithm_mutation#uninitializedFill) |

   
  
 Many functions in this package are parameterized with a [predicate](http://dlang.org/glossary.html#predicate). The predicate may be any suitable callable type (a function, a delegate, a [functor](http://dlang.org/glossary.html#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

```
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/package.d](https://github.com/dlang/phobos/blob/master/std/algorithm/package.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm.html>

std.container
=============

 This module defines generic containers. 



Construction
 To implement the different containers both struct and class based approaches have been used. [`std.container.util.make`](std_container_util#make) allows for uniform construction with either approach. 
 
```
import std.container;
// Construct a red-black tree and an array both containing the values 1, 2, 3.
// RedBlackTree should typically be allocated using `new`
RedBlackTree!int rbTree = new RedBlackTree!int(1, 2, 3);
// But `new` should not be used with Array
Array!int array = Array!int(1, 2, 3);
// `make` hides the differences
RedBlackTree!int rbTree2 = make!(RedBlackTree!int)(1, 2, 3);
Array!int array2 = make!(Array!int)(1, 2, 3);

```
 Note that `make` can infer the element type from the given arguments. 
```
import std.container;
auto rbTree = make!RedBlackTree(1, 2, 3); // RedBlackTree!int
auto array = make!Array("1", "2", "3"); // Array!string

```
 
Reference semantics
 All containers have reference semantics, which means that after assignment both variables refer to the same underlying data. 
 To make a copy of a container, use the `c.dup` container primitive. 
```
import std.container, std.range;
Array!int originalArray = make!(Array!int)(1, 2, 3);
Array!int secondArray = originalArray;
assert(equal(originalArray[], secondArray[]));

// changing one instance changes the other one as well!
originalArray[0] = 12;
assert(secondArray[0] == 12);

// secondArray now refers to an independent copy of originalArray
secondArray = originalArray.dup;
secondArray[0] = 1;
// assert that originalArray has not been affected
assert(originalArray[0] == 12);

```
 **Attention:** If the container is implemented as a class, using an uninitialized instance can cause a null pointer dereference. 
```
import std.container;

RedBlackTree!int rbTree;
rbTree.insert(5); // null pointer dereference

```
 Using an uninitialized struct-based container will work, because the struct intializes itself upon use; however, up to this point the container will not have an identity and assignment does not create two references to the same data. 
```
import std.container;

// create an uninitialized array
Array!int array1;
// array2 does _not_ refer to array1
Array!int array2 = array1;
array2.insertBack(42);
// thus array1 will not be affected
assert(array1.empty);

// after initialization reference semantics work as expected
array1 = array2;
// now affects array2 as well
array1.removeBack();
assert(array2.empty);

```
 It is therefore recommended to always construct containers using [`std.container.util.make`](std_container_util#make). This is in fact necessary to put containers into another container. For example, to construct an `Array` of ten empty `Array`s, use the following that calls `make` ten times. 
```
import std.container, std.range;

auto arrOfArrs = make!Array(generate!(() => make!(Array!int)).take(10));

```
 
Submodules
 This module consists of the following submodules: 
 * The [`std.container.array`](std_container_array) module provides an array type with deterministic control of memory, not reliant on the GC unlike built-in arrays.
* The [`std.container.binaryheap`](std_container_binaryheap) module provides a binary heap implementation that can be applied to any user-provided random-access range.
* The [`std.container.dlist`](std_container_dlist) module provides a doubly-linked list implementation.
* The [`std.container.rbtree`](std_container_rbtree) module implements red-black trees.
* The [`std.container.slist`](std_container_slist) module implements singly-linked lists.
* The [`std.container.util`](std_container_util) module contains some generic tools commonly used by container implementations.

 
The primary range of a container
 While some containers offer direct access to their elements e.g. via `opIndex`, `c.front` or `c.back`, access and modification of a container's contents is generally done through its primary [range](std_range) type, which is aliased as `C.Range`. For example, the primary range type of `Array!int` is `Array!int.Range`. 
 If the documentation of a member function of a container takes a parameter of type `Range`, then it refers to the primary range type of this container. Oftentimes `Take!Range` will be used, in which case the range refers to a span of the elements in the container. Arguments to these parameters **must** be obtained from the same container instance as the one being worked with. It is important to note that many generic range algorithms return the same range type as their input range. 
```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : find;
import std.container;
import std.range : take;

auto array = make!Array(1, 2, 3);

// `find` returns an Array!int.Range advanced to the element "2"
array.linearRemove(array[].find(2));

assert(array[].equal([1]));

array = make!Array(1, 2, 3);

// the range given to `linearRemove` is a Take!(Array!int.Range)
// spanning just the element "2"
array.linearRemove(array[].find(2).take(1));

assert(array[].equal([1, 3]));

```
 When any [range](std_range) can be passed as an argument to a member function, the documention usually refers to the parameter's templated type as `Stuff`. 
```
import std.algorithm.comparison : equal;
import std.container;
import std.range : iota;

auto array = make!Array(1, 2);

// the range type returned by `iota` is completely unrelated to Array,
// which is fine for Array.insertBack:
array.insertBack(iota(3, 10));

assert(array[].equal([1, 2, 3, 4, 5, 6, 7, 8, 9]));

```
 
Container primitives
 Containers do not form a class hierarchy, instead they implement a common set of primitives (see table below). These primitives each guarantee a specific worst case complexity and thus allow generic code to be written independently of the container implementation. 
 For example the primitives `c.remove(r)` and `c.linearRemove(r)` both remove the sequence of elements in range `r` from the container `c`. The primitive `c.remove(r)` guarantees Ο(`nr log nc`) complexity in the worst case and `c.linearRemove(r)` relaxes this guarantee to Ο(`nc`). Since a sequence of elements can be removed from a [doubly linked list](std_container_dlist) in constant time, `DList` provides the primitive `c.remove(r)` as well as `c.linearRemove(r)`. On the other hand [Array](std_container_array) only offers `c.linearRemove(r)`. The following table describes the common set of primitives that containers implement. A container need not implement all primitives, but if a primitive is implemented, it must support the syntax described in the **syntax** column with the semantics described in the **description** column, and it must not have a worst-case complexity worse than denoted in big-O notation in the Ο(`·`) column. Below, `C` means a container type, `c` is a value of container type, `nx` represents the effective length of value `x`, which could be a single element (in which case `nx` is `1`), a container, or a range. 

Container primitives| Syntax | Ο(`·`) | Description |
| `C(x)` | `nx` | Creates a container of type `C` from either another container or a range. The created container must not be a null reference even if x is empty. |
| `c.dup` | `nc` | Returns a duplicate of the container. |
| `c ~ x` | `nc + nx` | Returns the concatenation of `c` and `r`. `x` may be a single element or an input range. |
| `x ~ c` | `nc + nx` | Returns the concatenation of `x` and `c`. `x` may be a single element or an input range type. |
|  *Iteration*  |
| `c.Range` |  | The primary range type associated with the container. |
| `c[]` | `log nc` | Returns a range iterating over the entire container, in a container-defined order. |
| `c[a .. b]` | `log nc` | Fetches a portion of the container from key `a` to key `b`. |
|  *Capacity*  |
| `c.empty` | `1` | Returns `true` if the container has no elements, `false` otherwise. |
| `c.length` | `log nc` | Returns the number of elements in the container. |
| `c.length = n` | `nc + n` | Forces the number of elements in the container to `n`. If the container ends up growing, the added elements are initialized in a container-dependent manner (usually with `T.init`). |
| `c.capacity` | `log nc` | Returns the maximum number of elements that can be stored in the container without triggering a reallocation. |
| `c.reserve(x)` | `nc` | Forces `capacity` to at least `x` without reducing it. |
|  *Access*  |
| `c.front` | `log nc` | Returns the first element of the container, in a container-defined order. |
| `c.moveFront` | `log nc` | Destructively reads and returns the first element of the container. The slot is not removed from the container; it is left initialized with `T.init`. This routine need not be defined if  `front` returns a `ref`. |
| `c.front = v` | `log nc` | Assigns `v` to the first element of the container. |
| `c.back` | `log nc` | Returns the last element of the container, in a container-defined order. |
| `c.moveBack` | `log nc` | Destructively reads and returns the last element of the container. The slot is not removed from the container; it is left initialized with `T.init`. This routine need not be defined if  `front` returns a `ref`. |
| `c.back = v` | `log nc` | Assigns `v` to the last element of the container. |
| `c[x]` | `log nc` | Provides indexed access into the container. The index type is container-defined. A container may define several index types (and consequently overloaded indexing). |
| `c.moveAt(x)` | `log nc` | Destructively reads and returns the value at position `x`. The slot is not removed from the container; it is left initialized with  `T.init`. |
| `c[x] = v` | `log nc` | Sets element at specified index into the container. |
| `c[x] *op*= v` | `log nc` | Performs read-modify-write operation at specified index into the container. |
|  *Operations*  |
| `e in c` | `log nc` | Returns nonzero if e is found in `c`. |
| `c.lowerBound(v)` | `log nc` | Returns a range of all elements strictly less than `v`. |
| `c.upperBound(v)` | `log nc` | Returns a range of all elements strictly greater than `v`. |
| `c.equalRange(v)` | `log nc` | Returns a range of all elements in `c` that are equal to `v`. |
|  *Modifiers*  |
| `c ~= x` | `nc + nx` | Appends `x` to `c`. `x` may be a single element or an input range type. |
| `c.clear()` | `nc` | Removes all elements in `c`. |
| `c.insert(x)` | `nx * log nc` | Inserts `x` in `c` at a position (or positions) chosen by `c`. |
| `c.stableInsert(x)` | `nx * log nc` | Same as `c.insert(x)`, but is guaranteed to not invalidate any ranges. |
| `c.linearInsert(v)` | `nc` | Same as `c.insert(v)` but relaxes complexity to linear. |
| `c.stableLinearInsert(v)` | `nc` | Same as `c.stableInsert(v)` but relaxes complexity to linear. |
| `c.removeAny()` | `log nc` | Removes some element from `c` and returns it. |
| `c.stableRemoveAny()` | `log nc` | Same as `c.removeAny()`, but is guaranteed to not invalidate any iterators. |
| `c.insertFront(v)` | `log nc` | Inserts `v` at the front of `c`. |
| `c.stableInsertFront(v)` | `log nc` | Same as `c.insertFront(v)`, but guarantees no ranges will be invalidated. |
| `c.insertBack(v)` | `log nc` | Inserts `v` at the back of `c`. |
| `c.stableInsertBack(v)` | `log nc` | Same as `c.insertBack(v)`, but guarantees no ranges will be invalidated. |
| `c.removeFront()` | `log nc` | Removes the element at the front of `c`. |
| `c.stableRemoveFront()` | `log nc` | Same as `c.removeFront()`, but guarantees no ranges will be invalidated. |
| `c.removeBack()` | `log nc` | Removes the value at the back of `c`. |
| `c.stableRemoveBack()` | `log nc` | Same as `c.removeBack()`, but guarantees no ranges will be invalidated. |
| `c.remove(r)` | `nr * log nc` | Removes range `r` from `c`. |
| `c.stableRemove(r)` | `nr * log nc` | Same as `c.remove(r)`, but guarantees iterators are not invalidated. |
| `c.linearRemove(r)` | `nc` | Removes range `r` from `c`. |
| `c.stableLinearRemove(r)` | `nc` | Same as `c.linearRemove(r)`, but guarantees iterators are not invalidated. |
| `c.removeKey(k)` | `log nc` | Removes an element from `c` by using its key `k`. The key's type is defined by the container. |

 
Source
 [std/container/package.d](https://github.com/dlang/phobos/blob/master/std/container/package.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:
Steven Schveighoffer, [Andrei Alexandrescu](http://erdani.com)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container.html>

std.base64
==========

 Support for Base64 encoding and decoding. 


This module provides two default implementations of Base64 encoding, [`Base64`](#Base64) with a standard encoding alphabet, and a variant [`Base64URL`](#Base64URL) that has a modified encoding alphabet designed to be safe for embedding in URLs and filenames.   
  
 Both variants are implemented as instantiations of the template [`Base64Impl`](#Base64Impl). Most users will not need to use this template directly; however, it can be used to create customized Base64 encodings, such as one that omits padding characters, or one that is safe to embed inside a regular expression. 

 
Example


```
ubyte[] data = [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e];

const(char)[] encoded = Base64.encode(data);
assert(encoded == "FPucA9l+");

ubyte[] decoded = Base64.decode("FPucA9l+");
assert(decoded == [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e]);

```
 The range API is supported for both encoding and decoding: 
Example


```
// Create MIME Base64 with CRLF, per line 76.
File f = File("./text.txt", "r");
scope(exit) f.close();

Appender!string mime64 = appender!string;

foreach (encoded; Base64.encoder(f.byChunk(57)))
{
    mime64.put(encoded);
    mime64.put("\r\n");
}

writeln(mime64.data);

```
 
References
 [RFC 4648 - The Base16, Base32, and Base64 Data Encodings](https://tools.ietf.org/html/rfc4648) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:
Masahiro Nakagawa, Daniel Murphy (Single value Encoder and Decoder) 
 
Source
 [std/base64.d](https://github.com/dlang/phobos/blob/master/std/base64.d) 
 
alias **Base64** = Base64Impl!('+', '/', '=');  
Implementation of standard Base64 encoding. 


See [`Base64Impl`](#Base64Impl) for a description of available methods.

 
Examples:


```
ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
writeln(Base64.encode(data)); // "g9cwegE/"
writeln(Base64.decode("g9cwegE/")); // data

```
 
  alias **Base64URL** = Base64Impl!('-', '\_', '=');  
Variation of Base64 encoding that is safe for use in URLs and filenames. 


See [`Base64Impl`](#Base64Impl) for a description of available methods.

 
Examples:


```
ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
writeln(Base64URL.encode(data)); // "g9cwegE_"
writeln(Base64URL.decode("g9cwegE_")); // data

```
 
  alias **Base64URLNoPadding** = Base64Impl!('-', '\_', '\x00');  
Unpadded variation of Base64 encoding that is safe for use in URLs and filenames, as used in RFCs 4648 and 7515 (JWS/JWT/JWE). 


See [`Base64Impl`](#Base64Impl) for a description of available methods.

 
Examples:


```
ubyte[] data = [0x83, 0xd7, 0x30, 0x7b, 0xef];
writeln(Base64URLNoPadding.encode(data)); // "g9cwe-8"
writeln(Base64URLNoPadding.decode("g9cwe-8")); // data

```
 
  template **Base64Impl**(char Map62th, char Map63th, char Padding = '=') 
Template for implementing Base64 encoding and decoding. 


 For most purposes, direct usage of this template is not necessary; instead, this module provides default implementations: [`Base64`](#Base64), implementing basic Base64 encoding, and [`Base64URL`](#Base64URL) and [`Base64URLNoPadding`](#Base64URLNoPadding), that implement the Base64 variant for use in URLs and filenames, with and without padding, respectively.   
  
 Customized Base64 encoding schemes can be implemented by instantiating this template with the appropriate arguments. For example:   
  
 
```
// Non-standard Base64 format for embedding in regular expressions.
alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding);

```
 

 
NOTE
 Encoded strings will not have any padding if the `Padding` parameter is set to `NoPadding`.
 
Examples:


```
import std.string : representation;

// pre-defined: alias Base64 = Base64Impl!('+', '/');
ubyte[] emptyArr;
writeln(Base64.encode(emptyArr)); // ""
writeln(Base64.encode("f".representation)); // "Zg=="
writeln(Base64.encode("foo".representation)); // "Zm9v"

alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding);
writeln(Base64Re.encode("f".representation)); // "Zg"
writeln(Base64Re.encode("foo".representation)); // "Zm9v"

```
 
 
enum auto **NoPadding**;  
represents no-padding encoding

  pure nothrow @safe size\_t **encodeLength**(in size\_t sourceLength);  
Calculates the length needed to store the encoded string corresponding to an input of the given length. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sourceLength` | Length of the source array. |


 
Returns:
The length of a Base64 encoding of an array of the given length.
 
Examples:


```
ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];

// Allocate a buffer large enough to hold the encoded string.
auto buf = new char[Base64.encodeLength(data.length)];

Base64.encode(data, buf);
writeln(buf); // "Gis8TV1u"

```
 
  pure @trusted char[] **encode**(R1, R2)(in R1 source, R2 buffer)  
 Constraints: if (isArray!R1 && is(ElementType!R1 : ubyte) && is(R2 == char[]));   
  
char[] **encode**(R1, R2)(R1 source, R2 buffer)  
 Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && is(R2 == char[])); 
 
Encode source into a `char[]` buffer using Base64 encoding. 



Parameters:


|  |  |
| --- | --- |
| R1 `source` | The [input range](std_range_primitives#isInputRange) to encode. |
| R2 `buffer` | The `char[]` buffer to store the encoded result. |


 
Returns:
The slice of buffer that contains the encoded string.
 
Examples:


```
ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
char[32] buffer;    // much bigger than necessary

// Just to be sure...
auto encodedLength = Base64.encodeLength(data.length);
assert(buffer.length >= encodedLength);

// encode() returns a slice to the provided buffer.
auto encoded = Base64.encode(data, buffer[]);
assert(encoded is buffer[0 .. encodedLength]);
writeln(encoded); // "g9cwegE/"

```
 
  size\_t **encode**(E, R)(scope const(E)[] source, auto ref R range)  
 Constraints: if (is(E : ubyte) && isOutputRange!(R, char) && !is(R == char[]));   
  
size\_t **encode**(R1, R2)(R1 source, auto ref R2 range)  
 Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && !is(R2 == char[]) && isOutputRange!(R2, char)); 
 
Encodes source into an [output range](std_range_primitives#isOutputRange) using Base64 encoding. 



Parameters:


|  |  |
| --- | --- |
| const(E)[] `source` | The [input range](std_range_primitives#isInputRange) to encode. |
| R `range` | The [output range](std_range_primitives#isOutputRange) to store the encoded result. |


 
Returns:
The number of times the output range's `put` method was invoked.
 
Examples:


```
import std.array : appender;

auto output = appender!string();
ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];

// This overload of encode() returns the number of calls to the output
// range's put method.
writeln(Base64.encode(data, output)); // 8
writeln(output.data); // "Gis8TV1u"

```
 
  pure @safe char[] **encode**(Range)(Range source)  
 Constraints: if (isArray!Range && is(ElementType!Range : ubyte));   
  
char[] **encode**(Range)(Range source)  
 Constraints: if (!isArray!Range && isInputRange!Range && is(ElementType!Range : ubyte) && hasLength!Range); 
 
Encodes source to newly-allocated buffer. 


This convenience method alleviates the need to manually manage output buffers. 

 
Parameters:


|  |  |
| --- | --- |
| Range `source` | The [input range](std_range_primitives#isInputRange) to encode. |


 
Returns:
A newly-allocated `char[]` buffer containing the encoded string.
 
Examples:


```
ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];
writeln(Base64.encode(data)); // "Gis8TV1u"

```
 
  struct **Encoder**(Range) if (isInputRange!Range && (is(ElementType!Range : const(ubyte)[]) || is(ElementType!Range : const(char)[])));  
An [input range](std_range_primitives#isInputRange) that iterates over the respective Base64 encodings of a range of data items. 


This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. 

 
Note
 This struct is not intended to be created in user code directly; use the [`encoder`](#encoder) function instead.
 
@property @trusted bool **empty**();  

Returns:
true if there is no more encoded data left.
  nothrow @property @safe char[] **front**();  

Returns:
The current chunk of encoded data.
  void **popFront**();  
Advance the range to the next chunk of encoded data. 



Throws:

`Base64Exception` If invoked when [`empty`](#Base64Impl.Encoder.empty) returns `true`.
  @property typeof(this) **save**();  
Save the current iteration state of the range. 


This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange). 

 
Returns:
A copy of `this`.
    struct **Encoder**(Range) if (isInputRange!Range && is(ElementType!Range : ubyte));  
An [input range](std_range_primitives#isInputRange) that iterates over the encoded bytes of the given source data. 


It will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. 

 
Note
 This struct is not intended to be created in user code directly; use the [`encoder`](#encoder) function instead.
 
const nothrow @property @safe bool **empty**();  

Returns:
true if there are no more encoded characters to be iterated.
  nothrow @property @safe ubyte **front**();  

Returns:
The current encoded character.
  void **popFront**();  
Advance to the next encoded character. 



Throws:

`Base64Exception` If invoked when [` empty`](#Base64Impl.Encoder.empty.2) returns `true`.
  @property typeof(this) **save**();  
Save the current iteration state of the range. 


This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange). 

 
Returns:
A copy of `this`.
    Encoder!Range **encoder**(Range)(Range range)  
 Constraints: if (isInputRange!Range); 
 
Construct an `Encoder` that iterates over the Base64 encoding of the given [input range](std_range_primitives#isInputRange). 



Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) over the data to be encoded. |


 
Returns:
If range is a range of bytes, an `Encoder` that iterates over the bytes of the corresponding Base64 encoding. If range is a range of ranges of bytes, an `Encoder` that iterates over the Base64 encoded strings of each element of the range. In both cases, the returned `Encoder` will be a [forward range](std_range_primitives#isForwardRange) if the given `range` is at least a forward range, otherwise it will be only an input range. 
 
Example
 This example encodes the input one line at a time. 


```
File f = File("text.txt", "r");
scope(exit) f.close();

uint line = 0;
foreach (encoded; Base64.encoder(f.byLine()))
{
    writeln(++line, ". ", encoded);
}

```
 
Example
 This example encodes the input data one byte at a time. 


```
ubyte[] data = cast(ubyte[]) "0123456789";

// The ElementType of data is not aggregation type
foreach (encoded; Base64.encoder(data))
{
    writeln(encoded);
}

```
  pure nothrow @safe size\_t **decodeLength**(in size\_t sourceLength);  
Given a Base64 encoded string, calculates the length of the decoded string. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sourceLength` | The length of the Base64 encoding. |


 
Returns:
The length of the decoded string corresponding to a Base64 encoding of length sourceLength.
 
Examples:


```
auto encoded = "Gis8TV1u";

// Allocate a sufficiently large buffer to hold to decoded result.
auto buffer = new ubyte[Base64.decodeLength(encoded.length)];

Base64.decode(encoded, buffer);
writeln(buffer); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

```
 
  pure @trusted ubyte[] **decode**(R1, R2)(in R1 source, R2 buffer)  
 Constraints: if (isArray!R1 && is(ElementType!R1 : dchar) && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));   
  
ubyte[] **decode**(R1, R2)(R1 source, R2 buffer)  
 Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); 
 
Decodes source into the given buffer. 



Parameters:


|  |  |
| --- | --- |
| R1 `source` | The [input range](std_range_primitives#isInputRange) to decode. |
| R2 `buffer` | The buffer to store decoded result. |


 
Returns:
The slice of buffer containing the decoded result. 
 
Throws:

`Base64Exception` if source contains characters outside the base alphabet of the current Base64 encoding scheme.
 
Examples:


```
auto encoded = "Gis8TV1u";
ubyte[32] buffer;   // much bigger than necessary

// Just to be sure...
auto decodedLength = Base64.decodeLength(encoded.length);
assert(buffer.length >= decodedLength);

// decode() returns a slice of the given buffer.
auto decoded = Base64.decode(encoded, buffer[]);
assert(decoded is buffer[0 .. decodedLength]);
writeln(decoded); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

```
 
  size\_t **decode**(R1, R2)(in R1 source, auto ref R2 range)  
 Constraints: if (isArray!R1 && is(ElementType!R1 : dchar) && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));   
  
size\_t **decode**(R1, R2)(R1 source, auto ref R2 range)  
 Constraints: if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte)); 
 
Decodes source into a given [output range](std_range_primitives#isOutputRange). 



Parameters:


|  |  |
| --- | --- |
| R1 `source` | The [input range](std_range_primitives#isInputRange) to decode. |
| R2 `range` | The [output range](std_range_primitives#isOutputRange) to store the decoded result. |


 
Returns:
The number of times the output range's `put` method was invoked. 
 
Throws:

`Base64Exception` if source contains characters outside the base alphabet of the current Base64 encoding scheme.
 
Examples:


```
struct OutputRange
{
    ubyte[] result;
    void put(ubyte b) { result ~= b; }
}
OutputRange output;

// This overload of decode() returns the number of calls to put().
writeln(Base64.decode("Gis8TV1u", output)); // 6
writeln(output.result); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

```
 
  pure @safe ubyte[] **decode**(Range)(Range source)  
 Constraints: if (isArray!Range && is(ElementType!Range : dchar));   
  
ubyte[] **decode**(Range)(Range source)  
 Constraints: if (!isArray!Range && isInputRange!Range && is(ElementType!Range : dchar) && hasLength!Range); 
 
Decodes source into newly-allocated buffer. 


This convenience method alleviates the need to manually manage decoding buffers. 

 
Parameters:


|  |  |
| --- | --- |
| Range `source` | The [input range](std_range_primitives#isInputRange) to decode. |


 
Returns:
A newly-allocated `ubyte[]` buffer containing the decoded string.
 
Examples:


```
auto data = "Gis8TV1u";
writeln(Base64.decode(data)); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

```
 
  struct **Decoder**(Range) if (isInputRange!Range && (is(ElementType!Range : const(char)[]) || is(ElementType!Range : const(ubyte)[])));  
An [input range](std_range_primitives#isInputRange) that iterates over the decoded data of a range of Base64 encodings. 


This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. 

 
Note
 This struct is not intended to be created in user code directly; use the [`decoder`](#decoder) function instead.
 
@property @trusted bool **empty**();  

Returns:
true if there are no more elements to be iterated.
  nothrow @property @safe ubyte[] **front**();  

Returns:
The decoding of the current element in the input.
  void **popFront**();  
Advance to the next element in the input to be decoded. 



Throws:

`Base64Exception` if invoked when [` empty`](#Base64Impl.Decoder.empty) returns `true`.
  @property typeof(this) **save**();  
Saves the current iteration state. 


This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange) 

 
Returns:
A copy of `this`.
    struct **Decoder**(Range) if (isInputRange!Range && is(ElementType!Range : char));  
An [input range](std_range_primitives#isInputRange) that iterates over the bytes of data decoded from a Base64 encoded string. 


This range will be a [forward range](std_range_primitives#isForwardRange) if the underlying data source is at least a forward range. 

 
Note
 This struct is not intended to be created in user code directly; use the [`decoder`](#decoder) function instead.
 
const nothrow @property @safe bool **empty**();  

Returns:
true if there are no more elements to be iterated.
  nothrow @property @safe ubyte **front**();  

Returns:
The current decoded byte.
  void **popFront**();  
Advance to the next decoded byte. 



Throws:

`Base64Exception` if invoked when [` empty`](#Base64Impl.Decoder.empty) returns `true`.
  @property typeof(this) **save**();  
Saves the current iteration state. 


This method is only available if the underlying range is a [forward range](std_range_primitives#isForwardRange) 

 
Returns:
A copy of `this`.
    Decoder!Range **decoder**(Range)(Range range)  
 Constraints: if (isInputRange!Range); 
 
Construct a `Decoder` that iterates over the decoding of the given Base64 encoded data. 



Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) over the data to be decoded. |


 
Returns:
If range is a range of characters, a `Decoder` that iterates over the bytes of the corresponding Base64 decoding. If range is a range of ranges of characters, a `Decoder` that iterates over the decoded strings corresponding to each element of the range. In this case, the length of each subrange must be a multiple of 4; the returned decoder does not keep track of Base64 decoding state across subrange boundaries. In both cases, the returned `Decoder` will be a [forward range](std_range_primitives#isForwardRange) if the given `range` is at least a forward range, otherwise it will be only an input range. If the input data contains characters not found in the base alphabet of the current Base64 encoding scheme, the returned range may throw a `Base64Exception`. 
 
Example
 This example shows decoding over a range of input data lines. 


```
foreach (decoded; Base64.decoder(stdin.byLine()))
{
    writeln(decoded);
}

```
 
Example
 This example shows decoding one byte at a time. 


```
auto encoded = Base64.encoder(cast(ubyte[])"0123456789");
foreach (n; map!q{a - '0'}(Base64.decoder(encoded)))
{
    writeln(n);
}

```
    class **Base64Exception**: object.Exception;  
Exception thrown upon encountering Base64 encoding or decoding errors.



Examples:


```
import std.exception : assertThrown;
assertThrown!Base64Exception(Base64.decode("ab|c"));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_base64.html>

std.algorithm.comparison
========================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic comparison algorithms. 


 

Cheat Sheet| Function Name | Description |
| [`among`](#among) |  Checks if a value is among a set of values, e.g. `if (v.among(1, 2, 3)) //` v `is 1, 2 or 3` |
| [`castSwitch`](#castSwitch) | `(new A()).castSwitch((A a)=>1,(B b)=>2)` returns `1`. |
| [`clamp`](#clamp) | `clamp(1, 3, 6)` returns `3`. `clamp(4, 3, 6)` returns `4`. |
| [`cmp`](#cmp) | `cmp("abc", "abcd")` is `-1`, `cmp("abc", "aba")` is `1`, and `cmp("abc", "abc")` is `0`. |
| [`either`](#either) |  Return first parameter `p` that passes an `if (p)` test, e.g. `either(0, 42, 43)` returns `42`. |
| [`equal`](#equal) |  Compares ranges for element-by-element equality, e.g. `equal([1, 2, 3], [1.0, 2.0, 3.0])` returns `true`. |
| [`isPermutation`](#isPermutation) | `isPermutation([1, 2], [2, 1])` returns `true`. |
| [`isSameLength`](#isSameLength) | `isSameLength([1, 2, 3], [4, 5, 6])` returns `true`. |
| [`levenshteinDistance`](#levenshteinDistance) | `levenshteinDistance("kitten", "sitting")` returns `3` by using the  [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). |
| [`levenshteinDistanceAndPath`](#levenshteinDistanceAndPath) | `levenshteinDistanceAndPath("kitten", "sitting")` returns `tuple(3, "snnnsni")` by using the  [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). |
| [`max`](#max) | `max(3, 4, 2)` returns `4`. |
| [`min`](#min) | `min(3, 4, 2)` returns `2`. |
| [`mismatch`](#mismatch) | `mismatch("oh hi", "ohayo")` returns `tuple(" hi", "ayo")`. |
| [`predSwitch`](#predSwitch) | `2.predSwitch(1, "one", 2, "two", 3, "three")` returns `"two"`. |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/comparison.d](https://github.com/dlang/phobos/blob/master/std/algorithm/comparison.d) 
 
uint **among**(alias pred = (a, b) => a == b, Value, Values...)(Value value, Values values)  
 Constraints: if (Values.length != 0);   
  
template **among**(values...) if (isExpressionTuple!values) 
Find `value` among `values`, returning the 1-based index of the first matching value in `values`, or `0` if `value` is not among `values`. The predicate `pred` is used to compare values, and uses equality by default. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate used to compare the values. |
| Value `value` | The value to search for. |
| Values `values` | The values to compare the value to. |


 
Returns:
0 if value was not found among the values, otherwise the index of the found value plus one is returned. 
 
See Also:

[find](std_algorithm_searching#find) and [canFind](std_algorithm_searching#canFind) for finding a value in a range.
 
Examples:


```
assert(3.among(1, 42, 24, 3, 2));

if (auto pos = "bar".among("foo", "bar", "baz"))
    writeln(pos); // 2
else
    assert(false);

// 42 is larger than 24
writeln(42.among!((lhs, rhs) => lhs > rhs)(43, 24, 100)); // 2

```
 
 
Examples:
Alternatively, `values` can be passed at compile-time, allowing for a more efficient search, but one that only supports matching on equality: 
```
assert(3.among!(2, 3, 4));
writeln("bar".among!("foo", "bar", "baz")); // 2

```
 
  auto **castSwitch**(choices...)(Object switchObject);  
Executes and returns one of a collection of handlers based on the type of the switch object. 


The first choice that `switchObject` can be casted to the type of argument it accepts will be called with `switchObject` casted to that type, and the value it'll return will be returned by `castSwitch`.   
  
 If a choice's return type is void, the choice must throw an exception, unless all the choices are void. In that case, castSwitch itself will return void. 

 
Throws:
If none of the choice matches, a `SwitchError` will be thrown. `SwitchError` will also be thrown if not all the choices are void and a void choice was executed without throwing anything. 
 
Parameters:


|  |  |
| --- | --- |
| choices | The `choices` needs to be composed of function or delegate handlers that accept one argument. There can also be a choice that accepts zero arguments. That choice will be invoked if the  `switchObject` is null. |
| Object `switchObject` | the object against which the tests are being made. |


 
Returns:
The value of the selected choice. 
 
Note
 `castSwitch` can only be used with object types.
 
Examples:


```
import std.algorithm.iteration : map;
import std.format : format;

class A
{
    int a;
    this(int a) {this.a = a;}
    @property int i() { return a; }
}
interface I { }
class B : I { }

Object[] arr = [new A(1), new B(), null];

auto results = arr.map!(castSwitch!(
                            (A a) => "A with a value of %d".format(a.a),
                            (I i) => "derived from I",
                            ()    => "null reference",
                        ))();

// A is handled directly:
writeln(results[0]); // "A with a value of 1"
// B has no handler - it is handled by the handler of I:
writeln(results[1]); // "derived from I"
// null is handled by the null handler:
writeln(results[2]); // "null reference"

```
 
 
Examples:
Using with void handlers: 
```
import std.exception : assertThrown;

class A { }
class B { }
// Void handlers are allowed if they throw:
assertThrown!Exception(
    new B().castSwitch!(
        (A a) => 1,
        (B d)    { throw new Exception("B is not allowed!"); }
    )()
);

// Void handlers are also allowed if all the handlers are void:
new A().castSwitch!(
    (A a) { },
    (B b) { assert(false); },
)();

```
 
  auto **clamp**(T1, T2, T3)(T1 val, T2 lower, T3 upper)  
 Constraints: if (is(typeof(max(min(val, upper), lower)))); 
 
Clamps a value into the given bounds. 


This function is equivalent to `max(lower, min(upper, val))`. 

 
Parameters:


|  |  |
| --- | --- |
| T1 `val` | The value to clamp. |
| T2 `lower` | The lower bound of the clamp. |
| T3 `upper` | The upper bound of the clamp. |


 
Returns:
Returns `val`, if it is between `lower` and `upper`. Otherwise returns the nearest of the two.
 
Examples:


```
writeln(clamp(2, 1, 3)); // 2
writeln(clamp(0, 1, 3)); // 1
writeln(clamp(4, 1, 3)); // 3

writeln(clamp(1, 1, 1)); // 1

writeln(clamp(5, -1, 2u)); // 2

```
 
  auto **cmp**(R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isInputRange!R1 && isInputRange!R2);   
  
int **cmp**(alias pred, R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isInputRange!R1 && isInputRange!R2); 
 
Performs a lexicographical comparison on two [input ranges](std_range_primitives#isInputRange). Iterating `r1` and `r2` in lockstep, `cmp` compares each element `e1` of `r1` with the corresponding element `e2` in `r2`. If one of the ranges has been finished, `cmp` returns a negative value if `r1` has fewer elements than `r2`, a positive value if `r1` has more elements than `r2`, and `0` if the ranges have the same number of elements. 


If the ranges are strings, `cmp` performs UTF decoding appropriately and compares the ranges one code point at a time.   
  
 A custom predicate may be specified, in which case `cmp` performs a three-way lexicographical comparison using `pred`. Otherwise the elements are compared using `opCmp`. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Predicate used for comparison. Without a predicate specified the ordering implied by `opCmp` is used. |
| R1 `r1` | The first range. |
| R2 `r2` | The second range. |


 
Returns:

`0` if the ranges compare equal. A negative value if `r1` is a prefix of `r2` or the first differing element of `r1` is less than the corresponding element of `r2` according to `pred`. A positive value if `r2` is a prefix of `r1` or the first differing element of `r2` is less than the corresponding element of `r1` according to `pred`. 
 
Note
 An earlier version of the documentation incorrectly stated that `-1` is the only negative value returned and `1` is the only positive value returned. Whether that is true depends on the types being compared.
 
Examples:


```
int result;

result = cmp("abc", "abc");
writeln(result); // 0
result = cmp("", "");
writeln(result); // 0
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
writeln(result); // 0
result = cmp("aaa"d, "aaa"d);
writeln(result); // 0
result = cmp(cast(int[])[], cast(int[])[]);
writeln(result); // 0
result = cmp([1, 2, 3], [1, 2, 3]);
writeln(result); // 0
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);

```
 
 
Examples:
Example predicate that compares individual elements in reverse lexical order 
```
int result;

result = cmp!"a > b"("abc", "abc");
writeln(result); // 0
result = cmp!"a > b"("", "");
writeln(result); // 0
result = cmp!"a > b"("abc", "abcd");
assert(result < 0);
result = cmp!"a > b"("abcd", "abc");
assert(result > 0);
result = cmp!"a > b"("abc"d, "abd");
assert(result > 0);
result = cmp!"a > b"("bbc", "abc"w);
assert(result < 0);
result = cmp!"a > b"("aaa", "aaaa"d);
assert(result < 0);
result = cmp!"a > b"("aaaa", "aaa"d);
assert(result > 0);
result = cmp!"a > b"("aaa", "aaa"d);
writeln(result); // 0
result = cmp("aaa"d, "aaa"d);
writeln(result); // 0
result = cmp!"a > b"(cast(int[])[], cast(int[])[]);
writeln(result); // 0
result = cmp!"a > b"([1, 2, 3], [1, 2, 3]);
writeln(result); // 0
result = cmp!"a > b"([1, 3, 2], [1, 2, 3]);
assert(result < 0);
result = cmp!"a > b"([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp!"a > b"([1L, 2, 3], [1, 2]);
assert(result > 0);

```
 
  template **equal**(alias pred = "a == b") 
Compares two ranges for equality, as defined by predicate `pred` (which is `==` by default).



Examples:


```
import std.algorithm.comparison : equal;
import std.math : approxEqual;

int[4] a = [ 1, 2, 4, 3 ];
assert(!equal(a[], a[1..$]));
assert(equal(a[], a[]));
assert(equal!((a, b) => a == b)(a[], a[]));

// different types
double[4] b = [ 1.0, 2, 4, 3];
assert(!equal(a[], b[1..$]));
assert(equal(a[], b[]));

// predicated: ensure that two vectors are approximately equal
double[4] c = [ 1.005, 2, 4, 3];
assert(equal!approxEqual(b[], c[]));

```
 
 
Examples:
Tip: `equal` can itself be used as a predicate to other functions. This can be very useful when the element type of a range is itself a range. In particular, `equal` can be its own predicate, allowing range of range (of range...) comparisons. 
```
import std.algorithm.comparison : equal;
import std.range : iota, chunks;
assert(equal!(equal!equal)(
    [[[0, 1], [2, 3]], [[4, 5], [6, 7]]],
    iota(0, 8).chunks(2).chunks(2)
));

```
 
 
bool **equal**(Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2 && !(isInfinite!Range1 && isInfinite!Range2) && is(typeof(binaryFun!pred(r1.front, r2.front)))); 
 
Compares two ranges for equality. The ranges may have different element types, as long as `pred(r1.front, r2.front)` evaluates to `bool`. Performs Ο(`min(r1.length, r2.length)`) evaluations of `pred`. 


At least one of the ranges must be finite. If one range involved is infinite, the result is (statically known to be) `false`.   
  
 If the two ranges are different kinds of UTF code unit (`char`, `wchar`, or `dchar`), then the arrays are compared using UTF decoding to avoid accidentally integer-promoting units. 

 
Parameters:


|  |  |
| --- | --- |
| Range1 `r1` | The first range to be compared. |
| Range2 `r2` | The second range to be compared. |


 
Returns:

`true` if and only if the two ranges compare equal element for element, according to binary predicate `pred`.
    enum **EditOp**: char;  
Encodes [edit operations](http://realityinteractive.com/rgrzywinski/archives/000249.html) necessary to transform one sequence into another. Given sequences `s` (source) and `t` (target), a sequence of `EditOp` encodes the steps that need to be taken to convert `s` into `t`. For example, if `s = "cat"` and `"cars"`, the minimal sequence that transforms `s` into `t` is: skip two characters, replace 't' with 'r', and insert an 's'. Working with edit operations is useful in applications such as spell-checkers (to find the closest word to a given misspelled word), approximate searches, diff-style programs that compute the difference between files, efficient encoding of patches, DNA sequence analysis, and plagiarism detection.



Examples:


```
with(EditOp)
{
    // [none, none, none, insert, insert, insert]
    writeln(levenshteinDistanceAndPath("foo", "foobar")[1]);
    // [substitute, none, substitute, none, none, remove]
    writeln(levenshteinDistanceAndPath("banana", "fazan")[1]);
}

```
 
 
**none** 
Current items are equal; no editing is necessary.

  **substitute** 
Substitute current item in target with current item in source.

  **insert** 
Insert current item from the source into the target.

  **remove** 
Remove current item from the target.

    size\_t **levenshteinDistance**(alias equals = (a, b) => a == b, Range1, Range2)(Range1 s, Range2 t)  
 Constraints: if (isForwardRange!Range1 && isForwardRange!Range2);   
  
size\_t **levenshteinDistance**(alias equals = (a, b) => a == b, Range1, Range2)(auto ref Range1 s, auto ref Range2 t)  
 Constraints: if (isConvertibleToString!Range1 || isConvertibleToString!Range2); 
 
Returns the [Levenshtein distance](http://wikipedia.org/wiki/Levenshtein_distance) between `s` and `t`. The Levenshtein distance computes the minimal amount of edit operations necessary to transform `s` into `t`. Performs Ο(`s.length * t.length`) evaluations of `equals` and occupies Ο(`min(s.length, t.length)`) storage. 



Parameters:


|  |  |
| --- | --- |
| equals | The binary predicate to compare the elements of the two ranges. |
| Range1 `s` | The original range. |
| Range2 `t` | The transformation target |


 
Returns:
The minimal number of edits to transform s into t. Does not allocate GC memory.
 
Examples:


```
import std.algorithm.iteration : filter;
import std.uni : toUpper;

writeln(levenshteinDistance("cat", "rat")); // 1
writeln(levenshteinDistance("parks", "spark")); // 2
writeln(levenshteinDistance("abcde", "abcde")); // 0
writeln(levenshteinDistance("abcde", "abCde")); // 1
writeln(levenshteinDistance("kitten", "sitting")); // 3
assert(levenshteinDistance!((a, b) => toUpper(a) == toUpper(b))
    ("parks", "SPARK") == 2);
writeln(levenshteinDistance("parks".filter!"true", "spark".filter!"true")); // 2
writeln(levenshteinDistance("ID", "I♥D")); // 1

```
 
  Tuple!(size\_t, EditOp[]) **levenshteinDistanceAndPath**(alias equals = (a, b) => a == b, Range1, Range2)(Range1 s, Range2 t)  
 Constraints: if (isForwardRange!Range1 && isForwardRange!Range2);   
  
Tuple!(size\_t, EditOp[]) **levenshteinDistanceAndPath**(alias equals = (a, b) => a == b, Range1, Range2)(auto ref Range1 s, auto ref Range2 t)  
 Constraints: if (isConvertibleToString!Range1 || isConvertibleToString!Range2); 
 
Returns the Levenshtein distance and the edit path between `s` and `t`. 



Parameters:


|  |  |
| --- | --- |
| equals | The binary predicate to compare the elements of the two ranges. |
| Range1 `s` | The original range. |
| Range2 `t` | The transformation target |


 
Returns:
Tuple with the first element being the minimal amount of edits to transform s into t and the second element being the sequence of edits to effect this transformation. Allocates GC memory for the returned EditOp[] array.
 
Examples:


```
string a = "Saturday", b = "Sundays";
auto p = levenshteinDistanceAndPath(a, b);
writeln(p[0]); // 4
assert(equal(p[1], "nrrnsnnni"));

```
 
  auto **max**(T...)(T args)  
 Constraints: if (T.length >= 2 && !is(CommonType!T == void)); 
 
Iterates the passed arguments and returns the maximum value. 



Parameters:


|  |  |
| --- | --- |
| T `args` | The values to select the maximum from. At least two arguments must be passed, and they must be comparable with `>`. |


 
Returns:
The maximum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the largest value. If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. 
 
See Also:
[`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement)
 
Examples:


```
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
writeln(d); // 6
auto e = min(a, b, c);
assert(is(typeof(e) == double));
writeln(e); // 2

```
 
  auto **min**(T...)(T args)  
 Constraints: if (T.length >= 2 && !is(CommonType!T == void)); 
 
Iterates the passed arguments and returns the minimum value. 



Parameters:


|  |  |
| --- | --- |
| T `args` | The values to select the minimum from. At least two arguments must be passed, and they must be comparable with `<`. |


 
Returns:
The 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 [`std.algorithm.searching.minElement`](std_algorithm_searching#minElement) for examples on how to cope with NaNs. 
 
See Also:
[`std.algorithm.searching.minElement`](std_algorithm_searching#minElement)
 
Examples:


```
int a = 5;
short b = 6;
double c = 2;
auto d = min(a, b);
static assert(is(typeof(d) == int));
writeln(d); // 5
auto e = min(a, b, c);
static assert(is(typeof(e) == double));
writeln(e); // 2
ulong f = 0xffff_ffff_ffff;
const uint g = min(f, 0xffff_0000);
writeln(g); // 0xffff_0000
dchar h = 100;
uint i = 101;
static assert(is(typeof(min(h, i)) == dchar));
static assert(is(typeof(min(i, h)) == uint));
writeln(min(h, i)); // 100

```
 
 
Examples:
With arguments of mixed signedness, the return type is the one that can store the lowest values. 
```
int a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
writeln(min(a, f)); // -10

```
 
 
Examples:
User-defined types that support comparison with < are supported. 
```
import std.datetime;
writeln(min(Date(2012, 12, 21), Date(1982, 1, 4))); // Date(1982, 1, 4)
writeln(min(Date(1982, 1, 4), Date(2012, 12, 21))); // Date(1982, 1, 4)
writeln(min(Date(1982, 1, 4), Date.min)); // Date.min
writeln(min(Date.min, Date(1982, 1, 4))); // Date.min
writeln(min(Date(1982, 1, 4), Date.max)); // Date(1982, 1, 4)
writeln(min(Date.max, Date(1982, 1, 4))); // Date(1982, 1, 4)
writeln(min(Date.min, Date.max)); // Date.min
writeln(min(Date.max, Date.min)); // Date.min

```
 
  Tuple!(Range1, Range2) **mismatch**(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2); 
 
Sequentially compares elements in `r1` and `r2` in lockstep, and stops at the first mismatch (according to `pred`, by default equality). Returns a tuple with the reduced ranges that start with the two mismatched values. Performs Ο(`min(r1.length, r2.length)`) evaluations of `pred`.



Examples:


```
int[6] x = [ 1,   5, 2, 7,   4, 3 ];
double[6] y = [ 1.0, 5, 2, 7.3, 4, 8 ];
auto m = mismatch(x[], y[]);
writeln(m[0]); // x[3 .. &dollar;]
writeln(m[1]); // y[3 .. &dollar;]

```
 
  auto **predSwitch**(alias pred = "a == b", T, R...)(T switchExpression, lazy R choices);  
Returns one of a collection of expressions based on the value of the switch expression. 


`choices` needs to be composed of pairs of test expressions and return expressions. Each test-expression is compared with `switchExpression` using `pred`(`switchExpression` is the first argument) and if that yields true - the return expression is returned.   
  
 Both the test and the return expressions are lazily evaluated. 

 
Parameters:


|  |  |
| --- | --- |
| T `switchExpression` | The first argument for the predicate. |
| R `choices` | Pairs of test expressions and return expressions. The test expressions will be the second argument for the predicate, and the return expression will be returned if the predicate yields true with `switchExpression` and the test expression as arguments. May also have a default return expression, that needs to be the last expression without a test expression before it. A return expression may be of void type only if it always throws. |


 
Returns:
The return expression associated with the first test expression that made the predicate yield true, or the default return expression if no test expression matched. 
 
Throws:
If there is no default return expression and the predicate does not yield true with any test expression - `SwitchError` is thrown. `SwitchError` is also thrown if a void return expression was executed without throwing anything.
 
Examples:


```
string res = 2.predSwitch!"a < b"(
    1, "less than 1",
    5, "less than 5",
    10, "less than 10",
    "greater or equal to 10");

writeln(res); // "less than 5"

//The arguments are lazy, which allows us to use predSwitch to create
//recursive functions:
int factorial(int n)
{
    return n.predSwitch!"a <= b"(
        -1, {throw new Exception("Can not calculate n! for n < 0");}(),
        0, 1, // 0! = 1
        n * factorial(n - 1) // n! = n * (n - 1)! for n >= 0
        );
}
writeln(factorial(3)); // 6

//Void return expressions are allowed if they always throw:
import std.exception : assertThrown;
assertThrown!Exception(factorial(-9));

```
 
  bool **isSameLength**(Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2); 
 
Checks if the two ranges have the same number of elements. This function is optimized to always take advantage of the `length` member of either range if it exists. 


If both ranges have a length member, this function is Ο(`1`). Otherwise, this function is Ο(`min(r1.length, r2.length)`).   
  
 Infinite ranges are considered of the same length. An infinite range has never the same length as a finite range. 

 
Parameters:


|  |  |
| --- | --- |
| Range1 `r1` | a finite [input range](std_range_primitives#isInputRange) |
| Range2 `r2` | a finite [input range](std_range_primitives#isInputRange) |


 
Returns:

`true` if both ranges have the same length, `false` otherwise.
 
Examples:


```
assert(isSameLength([1, 2, 3], [4, 5, 6]));
assert(isSameLength([0.3, 90.4, 23.7, 119.2], [42.6, 23.6, 95.5, 6.3]));
assert(isSameLength("abc", "xyz"));

int[] a;
int[] b;
assert(isSameLength(a, b));

assert(!isSameLength([1, 2, 3], [4, 5]));
assert(!isSameLength([0.3, 90.4, 23.7], [42.6, 23.6, 95.5, 6.3]));
assert(!isSameLength("abcd", "xyz"));

```
 
  bool **isPermutation**(Flag!"allocateGC" allocateGC, Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (allocateGC == Yes.allocateGC && isForwardRange!Range1 && isForwardRange!Range2 && !isInfinite!Range1 && !isInfinite!Range2);   
  
bool **isPermutation**(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (is(typeof(binaryFun!pred)) && isForwardRange!Range1 && isForwardRange!Range2 && !isInfinite!Range1 && !isInfinite!Range2); 
 
Checks if both ranges are permutations of each other. 


This function can allocate if the `Yes.allocateGC` flag is passed. This has the benefit of have better complexity than the `Yes.allocateGC` option. However, this option is only available for ranges whose equality can be determined via each element's `toHash` method. If customized equality is needed, then the `pred` template parameter can be passed, and the function will automatically switch to the non-allocating algorithm. See [`std.functional.binaryFun`](std_functional#binaryFun) for more details on how to define `pred`.   
  
 Non-allocating forward range option: Ο(`n^2`) Non-allocating forward range option with custom `pred`: Ο(`n^2`) Allocating forward range option: amortized Ο(`r1.length`) + Ο(`r2.length`) 

 
Parameters:


|  |  |
| --- | --- |
| pred | an optional parameter to change how equality is defined |
| allocateGC | `Yes.allocateGC`/`No.allocateGC` |
| Range1 `r1` | A finite [forward range](std_range_primitives#isForwardRange) |
| Range2 `r2` | A finite [forward range](std_range_primitives#isForwardRange) |


 
Returns:

`true` if all of the elements in `r1` appear the same number of times in `r2`. Otherwise, returns `false`.
 
Examples:


```
import std.typecons : Yes;

assert(isPermutation([1, 2, 3], [3, 2, 1]));
assert(isPermutation([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(isPermutation("abc", "bca"));

assert(!isPermutation([1, 2], [3, 4]));
assert(!isPermutation([1, 1, 2, 3], [1, 2, 2, 3]));
assert(!isPermutation([1, 1], [1, 1, 1]));

// Faster, but allocates GC handled memory
assert(isPermutation!(Yes.allocateGC)([1.1, 2.3, 3.5], [2.3, 3.5, 1.1]));
assert(!isPermutation!(Yes.allocateGC)([1, 2], [3, 4]));

```
 
  CommonType!(T, Ts) **either**(alias pred = (a) => a, T, Ts...)(T first, lazy Ts alternatives)  
 Constraints: if (alternatives.length >= 1 && !is(CommonType!(T, Ts) == void) && allSatisfy!(ifTestable, T, Ts)); 
 
Get the first argument `a` that passes an `if (unaryFun!pred(a))` test. If no argument passes the test, return the last argument. 


Similar to behaviour of the `or` operator in dynamic languages such as Lisp's `(or ...)` and Python's `a or b or ...` except that the last argument is returned upon no match.   
  
 Simplifies logic, for instance, in parsing rules where a set of alternative matchers are tried. The first one that matches returns it match result, typically as an abstract syntax tree (AST). 

 
Bugs:
Lazy parameters are currently, too restrictively, inferred by DMD to always throw even though they don't need to be. This makes it impossible to currently mark `either` as `nothrow`. See issue at [Bugzilla 12647](https://issues.dlang.org/show_bug.cgi?id=12647). 
 
Returns:
The first argument that passes the test `pred`.
 
Examples:


```
const a = 1;
const b = 2;
auto ab = either(a, b);
static assert(is(typeof(ab) == const(int)));
writeln(ab); // a

auto c = 2;
const d = 3;
auto cd = either!(a => a == 3)(c, d); // use predicate
static assert(is(typeof(cd) == int));
writeln(cd); // d

auto e = 0;
const f = 2;
auto ef = either(e, f);
static assert(is(typeof(ef) == int));
writeln(ef); // f

```
 
 
Examples:


```
immutable p = 1;
immutable q = 2;
auto pq = either(p, q);
static assert(is(typeof(pq) == immutable(int)));
writeln(pq); // p

writeln(either(3, 4)); // 3
writeln(either(0, 4)); // 4
writeln(either(0, 0)); // 0
writeln(either("", "a")); // ""

```
 
 
Examples:


```
string r = null;
writeln(either(r, "a")); // "a"
writeln(either("a", "")); // "a"

immutable s = [1, 2];
writeln(either(s, s)); // s

writeln(either([0, 1], [1, 2])); // [0, 1]
writeln(either([0, 1], [1])); // [0, 1]
writeln(either("a", "b")); // "a"

static assert(!__traits(compiles, either(1, "a")));
static assert(!__traits(compiles, either(1.0, "a")));
static assert(!__traits(compiles, either('a', "a")));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_comparison.html>

std.algorithm.mutation
======================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic mutation algorithms. 


 

Cheat Sheet| Function Name | Description |
| [`bringToFront`](#bringToFront) |  If `a = [1, 2, 3]` and `b = [4, 5, 6, 7]`, `bringToFront(a, b)` leaves `a = [4, 5, 6]` and `b = [7, 1, 2, 3]`. |
| [`copy`](#copy) |  Copies a range to another. If `a = [1, 2, 3]` and `b = new int[5]`, then `copy(a, b)` leaves `b = [1, 2, 3, 0, 0]` and returns `b[3 .. $]`. |
| [`fill`](#fill) |  Fills a range with a pattern, e.g., if `a = new int[3]`, then `fill(a, 4)` leaves `a = [4, 4, 4]` and `fill(a, [3, 4])` leaves `a = [3, 4, 3]`. |
| [`initializeAll`](#initializeAll) |  If `a = [1.2, 3.4]`, then `initializeAll(a)` leaves `a = [double.init, double.init]`. |
| [`move`](#move) | `move(a, b)` moves `a` into `b`. `move(a)` reads `a` destructively when necessary. |
| [`moveEmplace`](#moveEmplace) |  Similar to `move` but assumes `target` is uninitialized. |
| [`moveAll`](#moveAll) |  Moves all elements from one range to another. |
| [`moveEmplaceAll`](#moveEmplaceAll) |  Similar to `moveAll` but assumes all elements in `target` are uninitialized. |
| [`moveSome`](#moveSome) |  Moves as many elements as possible from one range to another. |
| [`moveEmplaceSome`](#moveEmplaceSome) |  Similar to `moveSome` but assumes all elements in `target` are uninitialized. |
| [`remove`](#remove) |  Removes elements from a range in-place, and returns the shortened range. |
| [`reverse`](#reverse) |  If `a = [1, 2, 3]`, `reverse(a)` changes it to `[3, 2, 1]`. |
| [`strip`](#strip) |  Strips all leading and trailing elements equal to a value, or that satisfy a predicate. If `a = [1, 1, 0, 1, 1]`, then `strip(a, 1)` and `strip!(e => e == 1)(a)` returns `[0]`. |
| [`stripLeft`](#stripLeft) |  Strips all leading elements equal to a value, or that satisfy a predicate. If `a = [1, 1, 0, 1, 1]`, then `stripLeft(a, 1)` and `stripLeft!(e => e == 1)(a)` returns `[0, 1, 1]`. |
| [`stripRight`](#stripRight) |  Strips all trailing elements equal to a value, or that satisfy a predicate. If `a = [1, 1, 0, 1, 1]`, then `stripRight(a, 1)` and `stripRight!(e => e == 1)(a)` returns `[1, 1, 0]`. |
| [`swap`](#swap) |  Swaps two values. |
| [`swapAt`](#swapAt) |  Swaps two values by indices. |
| [`swapRanges`](#swapRanges) |  Swaps all elements of two ranges. |
| [`uninitializedFill`](#uninitializedFill) |  Fills a range (assumed uninitialized) with a value. |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/mutation.d](https://github.com/dlang/phobos/blob/master/std/algorithm/mutation.d) 
 
size\_t **bringToFront**(InputRange, ForwardRange)(InputRange front, ForwardRange back)  
 Constraints: if (isInputRange!InputRange && isForwardRange!ForwardRange); 
 
`bringToFront` takes two ranges `front` and `back`, which may be of different types. Considering the concatenation of `front` and `back` one unified range, `bringToFront` rotates that unified range such that all elements in `back` are brought to the beginning of the unified range. The relative ordering of elements in `front` and `back`, respectively, remains unchanged. 


The `bringToFront` function treats strings at the code unit level and it is not concerned with Unicode character integrity. `bringToFront` is designed as a function for moving elements in ranges, not as a string function.   
  
 Performs Ο(`max(front.length, back.length)`) evaluations of `swap`.   
  
 The `bringToFront` function can rotate elements in one buffer left or right, swap buffers of equal length, and even move elements across disjoint buffers of different types and different lengths. 

 
Preconditions
 Either `front` and `back` are disjoint, or `back` is reachable from `front` and `front` is not reachable from `back`. 
 
Parameters:


|  |  |
| --- | --- |
| InputRange `front` | an [input range](std_range_primitives#isInputRange) |
| ForwardRange `back` | a [forward range](std_range_primitives#isForwardRange) |


 
Returns:
The number of elements brought to the front, i.e., the length of `back`. 
 
See Also:
[STL's `rotate`](http://en.cppreference.com/w/cpp/algorithm/rotate)
 
Examples:
The simplest use of `bringToFront` is for rotating elements in a buffer. For example: 
```
auto arr = [4, 5, 6, 7, 1, 2, 3];
auto p = bringToFront(arr[0 .. 4], arr[4 .. $]);
writeln(p); // arr.length - 4
writeln(arr); // [1, 2, 3, 4, 5, 6, 7]

```
 
 
Examples:
The `front` range may actually "step over" the `back` range. This is very useful with forward ranges that cannot compute comfortably right-bounded subranges like `arr[0 .. 4]` above. In the example below, `r2` is a right subrange of `r1`. 
```
import std.algorithm.comparison : equal;
import std.container : SList;
import std.range.primitives : popFrontN;

auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3);
auto r1 = list[];
auto r2 = list[]; popFrontN(r2, 4);
assert(equal(r2, [ 1, 2, 3 ]));
bringToFront(r1, r2);
assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ]));

```
 
 
Examples:
Elements can be swapped across ranges of different types: 
```
import std.algorithm.comparison : equal;
import std.container : SList;

auto list = SList!(int)(4, 5, 6, 7);
auto vec = [ 1, 2, 3 ];
bringToFront(list[], vec);
assert(equal(list[], [ 1, 2, 3, 4 ]));
assert(equal(vec, [ 5, 6, 7 ]));

```
 
 
Examples:
Unicode integrity is not preserved: 
```
import std.string : representation;
auto ar = representation("a".dup);
auto br = representation("ç".dup);

bringToFront(ar, br);

auto a = cast(char[]) ar;
auto b = cast(char[]) br;

// Illegal UTF-8
writeln(a); // "\303"
// Illegal UTF-8
writeln(b); // "\247a"

```
 
  TargetRange **copy**(SourceRange, TargetRange)(SourceRange source, TargetRange target)  
 Constraints: if (isInputRange!SourceRange && isOutputRange!(TargetRange, ElementType!SourceRange)); 
 
Copies the content of `source` into `target` and returns the remaining (unfilled) part of `target`. 



Preconditions
 `target` shall have enough room to accommodate the entirety of `source`. 
 
Parameters:


|  |  |
| --- | --- |
| SourceRange `source` | an [input range](std_range_primitives#isInputRange) |
| TargetRange `target` | an output range |


 
Returns:
The unfilled part of target
 
Examples:


```
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
int[] buf = new int[](a.length + b.length + 10);
auto rem = a.copy(buf);    // copy a into buf
rem = b.copy(rem);         // copy b into remainder of buf
writeln(buf[0 .. a.length + b.length]); // [1, 5, 9, 8]
assert(rem.length == 10);   // unused slots in buf

```
 
 
Examples:
As long as the target range elements support assignment from source range elements, different types of ranges are accepted: 
```
float[] src = [ 1.0f, 5 ];
double[] dest = new double[src.length];
src.copy(dest);

```
 
 
Examples:
To copy at most `n` elements from a range, you may want to use [`std.range.take`](std_range#take): 
```
import std.range;
int[] src = [ 1, 5, 8, 9, 10 ];
auto dest = new int[](3);
src.take(dest.length).copy(dest);
writeln(dest); // [1, 5, 8]

```
 
 
Examples:
To copy just those elements from a range that satisfy a predicate, use [`filter`](#filter): 
```
import std.algorithm.iteration : filter;
int[] src = [ 1, 5, 8, 9, 10, 1, 2, 0 ];
auto dest = new int[src.length];
auto rem = src
    .filter!(a => (a & 1) == 1)
    .copy(dest);
writeln(dest[0 .. $ - rem.length]); // [1, 5, 9, 1]

```
 
 
Examples:

[`std.range.retro`](std_range#retro) can be used to achieve behavior similar to [STL's `copy_backward`'](http://en.cppreference.com/w/cpp/algorithm/copy_backward): 
```
import std.algorithm, std.range;
int[] src = [1, 2, 4];
int[] dest = [0, 0, 0, 0, 0];
src.retro.copy(dest.retro);
writeln(dest); // [0, 0, 1, 2, 4]

```
 
  void **fill**(Range, Value)(auto ref Range range, auto ref Value value)  
 Constraints: if (isInputRange!Range && is(typeof(range.front = value)) || isSomeChar!Value && is(typeof(range[] = value)));   
  
void **fill**(InputRange, ForwardRange)(InputRange range, ForwardRange filler)  
 Constraints: if (isInputRange!InputRange && (isForwardRange!ForwardRange || isInputRange!ForwardRange && isInfinite!ForwardRange) && is(typeof(InputRange.init.front = ForwardRange.init.front))); 
 
Assigns `value` to each element of input range `range`. 


Alternatively, instead of using a single `value` to fill the `range`, a `filter` [forward range](std_range_primitives#isForwardRange) can be provided. The length of `filler` and `range` do not need to match, but `filler` must not be empty. 

 
Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) that exposes references to its elements and has assignable elements |
| Value `value` | Assigned to each element of range |
| ForwardRange `filler` | A [forward range](std_range_primitives#isForwardRange) representing the fill pattern. |


 
Throws:
If `filler` is empty. 
 
See Also:

[`uninitializedFill`](#uninitializedFill) [`initializeAll`](#initializeAll)

 
Examples:


```
int[] a = [ 1, 2, 3, 4 ];
fill(a, 5);
writeln(a); // [5, 5, 5, 5]

```
 
 
Examples:


```
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [ 8, 9 ];
fill(a, b);
writeln(a); // [8, 9, 8, 9, 8]

```
 
  void **initializeAll**(Range)(Range range)  
 Constraints: if (isInputRange!Range && hasLvalueElements!Range && hasAssignableElements!Range);   
  
void **initializeAll**(Range)(Range range)  
 Constraints: if (is(Range == char[]) || is(Range == wchar[])); 
 
Initializes all elements of `range` with their `.init` value. Assumes that the elements of the range are uninitialized. 



Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) that exposes references to its elements and has assignable elements |


 
See Also:

[`fill`](#fill) [`uninitializeFill`](#uninitializeFill)

 
Examples:


```
import core.stdc.stdlib : malloc, free;

struct S
{
    int a = 10;
}

auto s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5];
initializeAll(s);
writeln(s); // [S(10), S(10), S(10), S(10), S(10)]

scope(exit) free(s.ptr);

```
 
  void **move**(T)(ref T source, ref T target);   
  
T **move**(T)(return ref scope T source);  
Moves `source` into `target`, via a destructive copy when necessary. 


If `T` is a struct with a destructor or postblit defined, source is reset to its `.init` value after it is moved into target, otherwise it is left unchanged. 

 
Preconditions
 If source has internal pointers that point to itself and doesn't define opPostMove, it cannot be moved, and will trigger an assertion failure. 
 
Parameters:


|  |  |
| --- | --- |
| T `source` | Data to copy. |
| T `target` | Where to copy into. The destructor, if any, is invoked before the copy is performed. |


 
Examples:
For non-struct types, `move` just performs `target = source`: 
```
Object obj1 = new Object;
Object obj2 = obj1;
Object obj3;

move(obj2, obj3);
assert(obj3 is obj1);
// obj2 unchanged
assert(obj2 is obj1);

```
 
 
Examples:


```
// Structs without destructors are simply copied
struct S1
{
    int a = 1;
    int b = 2;
}
S1 s11 = { 10, 11 };
S1 s12;

move(s11, s12);

writeln(s12); // S1(10, 11)
writeln(s11); // s12

// But structs with destructors or postblits are reset to their .init value
// after copying to the target.
struct S2
{
    int a = 1;
    int b = 2;

    ~this() pure nothrow @safe @nogc { }
}
S2 s21 = { 3, 4 };
S2 s22;

move(s21, s22);

writeln(s21); // S2(1, 2)
writeln(s22); // S2(3, 4)

```
 
 
Examples:
Non-copyable structs can still be moved: 
```
struct S
{
    int a = 1;
    @disable this(this);
    ~this() pure nothrow @safe @nogc {}
}
S s1;
s1.a = 2;
S s2 = move(s1);
writeln(s1.a); // 1
writeln(s2.a); // 2

```
 
 
Examples:

`opPostMove` will be called if defined: 
```
struct S
{
    int a;
    void opPostMove(const ref S old)
    {
        writeln(a); // old.a
        a++;
    }
}
S s1;
s1.a = 41;
S s2 = move(s1);
writeln(s2.a); // 42

```
 
  pure @system void **moveEmplace**(T)(ref T source, ref T target);  
Similar to [`move`](#move) but assumes `target` is uninitialized. This is more efficient because `source` can be blitted over `target` without destroying or initializing it first. 



Parameters:


|  |  |
| --- | --- |
| T `source` | value to be moved into target |
| T `target` | uninitialized value to be filled by source |


 
Examples:


```
static struct Foo
{
pure nothrow @nogc:
    this(int* ptr) { _ptr = ptr; }
    ~this() { if (_ptr) ++*_ptr; }
    int* _ptr;
}

int val;
Foo foo1 = void; // uninitialized
auto foo2 = Foo(&val); // initialized
assert(foo2._ptr is &val);

// Using `move(foo2, foo1)` would have an undefined effect because it would destroy
// the uninitialized foo1.
// moveEmplace directly overwrites foo1 without destroying or initializing it first.
moveEmplace(foo2, foo1);
assert(foo1._ptr is &val);
assert(foo2._ptr is null);
writeln(val); // 0

```
 
  InputRange2 **moveAll**(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt)  
 Constraints: if (isInputRange!InputRange1 && isInputRange!InputRange2 && is(typeof(move(src.front, tgt.front)))); 
 
Calls `move(a, b)` for each element `a` in `src` and the corresponding element `b` in `tgt`, in increasing order. 



Preconditions
 `walkLength(src) <= walkLength(tgt)`. This precondition will be asserted. If you cannot ensure there is enough room in `tgt` to accommodate all of `src` use [`moveSome`](#moveSome) instead. 
 
Parameters:


|  |  |
| --- | --- |
| InputRange1 `src` | An [input range](std_range_primitives#isInputRange) with movable elements. |
| InputRange2 `tgt` | An [input range](std_range_primitives#isInputRange) with elements that elements from `src` can be moved into. |


 
Returns:
The leftover portion of `tgt` after all elements from `src` have been moved.
 
Examples:


```
int[3] a = [ 1, 2, 3 ];
int[5] b;
assert(moveAll(a[], b[]) is b[3 .. $]);
writeln(a[]); // b[0 .. 3]
int[3] cmp = [ 1, 2, 3 ];
writeln(a[]); // cmp[]

```
 
  @system InputRange2 **moveEmplaceAll**(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt)  
 Constraints: if (isInputRange!InputRange1 && isInputRange!InputRange2 && is(typeof(moveEmplace(src.front, tgt.front)))); 
 
Similar to [`moveAll`](#moveAll) but assumes all elements in `tgt` are uninitialized. Uses [`moveEmplace`](#moveEmplace) to move elements from `src` over elements from `tgt`.



Examples:


```
static struct Foo
{
    ~this() pure nothrow @nogc { if (_ptr) ++*_ptr; }
    int* _ptr;
}
int[3] refs = [0, 1, 2];
Foo[3] src = [Foo(&refs[0]), Foo(&refs[1]), Foo(&refs[2])];
Foo[5] dst = void;

auto tail = moveEmplaceAll(src[], dst[]); // move 3 value from src over dst
assert(tail.length == 2); // returns remaining uninitialized values
initializeAll(tail);

import std.algorithm.searching : all;
assert(src[].all!(e => e._ptr is null));
assert(dst[0 .. 3].all!(e => e._ptr !is null));

```
 
  Tuple!(InputRange1, InputRange2) **moveSome**(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt)  
 Constraints: if (isInputRange!InputRange1 && isInputRange!InputRange2 && is(typeof(move(src.front, tgt.front)))); 
 
Calls `move(a, b)` for each element `a` in `src` and the corresponding element `b` in `tgt`, in increasing order, stopping when either range has been exhausted. 



Parameters:


|  |  |
| --- | --- |
| InputRange1 `src` | An [input range](std_range_primitives#isInputRange) with movable elements. |
| InputRange2 `tgt` | An [input range](std_range_primitives#isInputRange) with elements that elements from `src` can be moved into. |


 
Returns:
The leftover portions of the two ranges after one or the other of the ranges have been exhausted.
 
Examples:


```
int[5] a = [ 1, 2, 3, 4, 5 ];
int[3] b;
assert(moveSome(a[], b[])[0] is a[3 .. $]);
writeln(a[0 .. 3]); // b
writeln(a); // [1, 2, 3, 4, 5]

```
 
  @system Tuple!(InputRange1, InputRange2) **moveEmplaceSome**(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt)  
 Constraints: if (isInputRange!InputRange1 && isInputRange!InputRange2 && is(typeof(move(src.front, tgt.front)))); 
 
Same as [`moveSome`](#moveSome) but assumes all elements in `tgt` are uninitialized. Uses [`moveEmplace`](#moveEmplace) to move elements from `src` over elements from `tgt`.



Examples:


```
static struct Foo
{
    ~this() pure nothrow @nogc { if (_ptr) ++*_ptr; }
    int* _ptr;
}
int[4] refs = [0, 1, 2, 3];
Foo[4] src = [Foo(&refs[0]), Foo(&refs[1]), Foo(&refs[2]), Foo(&refs[3])];
Foo[3] dst = void;

auto res = moveEmplaceSome(src[], dst[]);
writeln(res.length); // 2

import std.algorithm.searching : all;
assert(src[0 .. 3].all!(e => e._ptr is null));
assert(src[3]._ptr !is null);
assert(dst[].all!(e => e._ptr !is null));

```
 
  enum **SwapStrategy**: int;  
Defines the swapping strategy for algorithms that need to swap elements in a range (such as partition and sort). The strategy concerns the swapping of elements that are not the core concern of the algorithm. For example, consider an algorithm that sorts `[ "abc", "b", "aBc" ]` according to `toUpper(a) < toUpper(b)`. That algorithm might choose to swap the two equivalent strings `"abc"` and `"aBc"`. That does not affect the sorting since both `["abc", "aBc", "b" ]` and `[ "aBc", "abc", "b" ]` are valid outcomes. 


Some situations require that the algorithm must NOT ever change the relative ordering of equivalent elements (in the example above, only `[ "abc", "aBc", "b" ]` would be the correct result). Such algorithms are called **stable**. If the ordering algorithm may swap equivalent elements discretionarily, the ordering is called **unstable**.   
  
 Yet another class of algorithms may choose an intermediate tradeoff by being stable only on a well-defined subrange of the range. There is no established terminology for such behavior; this library calls it **semistable**.   
  
 Generally, the `stable` ordering strategy may be more costly in time and/or space than the other two because it imposes additional constraints. Similarly, `semistable` may be costlier than `unstable`. As (semi-)stability is not needed very often, the ordering algorithms in this module parameterized by `SwapStrategy` all choose `SwapStrategy.unstable` as the default.

 
Examples:


```
int[] a = [0, 1, 2, 3];
writeln(remove!(SwapStrategy.stable)(a, 1)); // [0, 2, 3]
a = [0, 1, 2, 3];
writeln(remove!(SwapStrategy.unstable)(a, 1)); // [0, 3, 2]

```
 
 
Examples:


```
import std.algorithm.sorting : partition;

// Put stuff greater than 3 on the left
auto arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
writeln(partition!(a => a > 3, SwapStrategy.stable)(arr)); // [1, 2, 3]
writeln(arr); // [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
writeln(partition!(a => a > 3, SwapStrategy.semistable)(arr)); // [2, 3, 1]
writeln(arr); // [4, 5, 6, 7, 8, 9, 10, 2, 3, 1]

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
writeln(partition!(a => a > 3, SwapStrategy.unstable)(arr)); // [3, 2, 1]
writeln(arr); // [10, 9, 8, 4, 5, 6, 7, 3, 2, 1]

```
 
 
**unstable** 
Allows freely swapping of elements as long as the output satisfies the algorithm's requirements.

  **semistable** 
In algorithms partitioning ranges in two, preserve relative ordering of elements only to the left of the partition point.

  **stable** 
Preserve the relative ordering of elements to the largest extent allowed by the algorithm's requirements.

    Range **remove**(SwapStrategy s = SwapStrategy.stable, Range, Offset...)(Range range, Offset offset)  
 Constraints: if (Offset.length >= 1 && allSatisfy!(isValidIntegralTuple, Offset)); 
 
Eliminates elements at given offsets from `range` and returns the shortened range. 


For example, here is how to remove a single element from an array:   
  
 
```
string[] a = [ "a", "b", "c", "d" ];
a = a.remove(1); // remove element at offset 1
assert(a == [ "a", "c", "d"]);

```
   
  
 Note that `remove` does not change the length of the original range directly; instead, it returns the shortened range. If its return value is not assigned to the original range, the original range will retain its original length, though its contents will have changed:   
  
 
```
int[] a = [ 3, 5, 7, 8 ];
assert(remove(a, 1) == [ 3, 7, 8 ]);
assert(a == [ 3, 7, 8, 8 ]);

```
   
  
 The element at offset `1` has been removed and the rest of the elements have shifted up to fill its place, however, the original array remains of the same length. This is because all functions in `std.algorithm` only change *content*, not *topology*. The value `8` is repeated because [`move`](#move) was invoked to rearrange elements, and on integers `move` simply copies the source to the destination. To replace `a` with the effect of the removal, simply assign the slice returned by `remove` to it, as shown in the first example.   
  
 Multiple indices can be passed into `remove`. In that case, elements at the respective indices are all removed. The indices must be passed in increasing order, otherwise an exception occurs.   
  
 
```
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove(a, 1, 3, 5) ==
    [ 0, 2, 4, 6, 7, 8, 9, 10 ]);

```
   
  
 (Note that all indices refer to slots in the *original* array, not in the array as it is being progressively shortened.)   
  
 Tuples of two integral offsets can be used to remove an indices range:   
  
 
```
int[] a = [ 3, 4, 5, 6, 7];
assert(remove(a, 1, tuple(1, 3), 9) == [ 3, 6, 7 ]);

```
   
  
 The tuple passes in a range closed to the left and open to the right (consistent with built-in slices), e.g. `tuple(1, 3)` means indices `1` and `2` but not `3`.   
  
 Finally, any combination of integral offsets and tuples composed of two integral offsets can be passed in:   
  
 
```
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove(a, 1, tuple(3, 5), 9) == [ 0, 2, 5, 6, 7, 8, 10 ]);

```
   
  
 In this case, the slots at positions 1, 3, 4, and 9 are removed from the array.   
  
 If the need is to remove some elements in the range but the order of the remaining elements does not have to be preserved, you may want to pass `SwapStrategy.unstable` to `remove`.   
  
 
```
int[] a = [ 0, 1, 2, 3 ];
assert(remove!(SwapStrategy.unstable)(a, 1) == [ 0, 3, 2 ]);

```
   
  
 In the case above, the element at slot `1` is removed, but replaced with the last element of the range. Taking advantage of the relaxation of the stability requirement, `remove` moved elements from the end of the array over the slots to be removed. This way there is less data movement to be done which improves the execution time of the function.   
  
 The function `remove` works on bidirectional ranges that have assignable lvalue elements. The moving strategy is (listed from fastest to slowest):   
  
 * If `s == SwapStrategy.unstable && isRandomAccessRange!Range && hasLength!Range && hasLvalueElements!Range`, then elements are moved from the end of the range into the slots to be filled. In this case, the absolute minimum of moves is performed.
* Otherwise, if `s == SwapStrategy.unstable && isBidirectionalRange!Range && hasLength!Range && hasLvalueElements!Range`, then elements are still moved from the end of the range, but time is spent on advancing between slots by repeated calls to `range.popFront`.
* Otherwise, elements are moved incrementally towards the front of `range`; a given element is never moved several times, but more elements are moved than in the previous cases.

 

 
Parameters:


|  |  |
| --- | --- |
| s | a SwapStrategy to determine if the original order needs to be preserved |
| Range `range` | a [bidirectional range](std_range_primitives#isBidirectionalRange) with a length member |
| Offset `offset` | which element(s) to remove |


 
Returns:
A range containing all of the elements of range with offset removed.
  Range **remove**(alias pred, SwapStrategy s = SwapStrategy.stable, Range)(Range range);  
Reduces the length of the [bidirectional range](std_range_primitives#isBidirectionalRange) `range` by removing elements that satisfy `pred`. If `s = SwapStrategy.unstable`, elements are moved from the right end of the range over the elements to eliminate. If `s = SwapStrategy.stable` (the default), elements are moved progressively to front such that their relative order is preserved. Returns the filtered range. 



Parameters:


|  |  |
| --- | --- |
| Range `range` | a bidirectional ranges with lvalue elements or mutable character arrays |


 
Returns:
the range with all of the elements where `pred` is `true` removed
 
Examples:


```
static immutable base = [1, 2, 3, 2, 4, 2, 5, 2];

int[] arr = base[].dup;

// using a string-based predicate
writeln(remove!("a == 2")(arr)); // [1, 3, 4, 5]

// The original array contents have been modified,
// so we need to reset it to its original state.
// The length is unmodified however.
arr[] = base[];

// using a lambda predicate
writeln(remove!(a => a == 2)(arr)); // [1, 3, 4, 5]

```
 
  Range **reverse**(Range)(Range r)  
 Constraints: if (isBidirectionalRange!Range && (hasSwappableElements!Range || hasAssignableElements!Range && hasLength!Range && isRandomAccessRange!Range || isNarrowString!Range && isAssignable!(ElementType!Range))); 
 
Reverses `r` in-place. Performs `r.length / 2` evaluations of `swap`. UTF sequences consisting of multiple code units are preserved properly. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | a [bidirectional range](std_range_primitives#isBidirectionalRange) with either swappable elements, a random access range with a length member, or a narrow string |


 
Returns:

`r` 
 
Note
 When passing a string with unicode modifiers on characters, such as `\u0301`, this function will not properly keep the position of the modifier. For example, reversing `ba\u0301d` ("bád") will result in d\u0301ab ("d́ab") instead of `da\u0301b` ("dáb"). 
 
See Also:

[`std.range.retro`](std_range#retro) for a lazy reverse without changing `r`

 
Examples:


```
int[] arr = [ 1, 2, 3 ];
writeln(arr.reverse); // [3, 2, 1]

```
 
 
Examples:


```
char[] arr = "hello\U00010143\u0100\U00010143".dup;
writeln(arr.reverse); // "\U00010143\u0100\U00010143olleh"

```
 
  Range **strip**(Range, E)(Range range, E element)  
 Constraints: if (isBidirectionalRange!Range && is(typeof(range.front == element) : bool));   
  
Range **strip**(alias pred, Range)(Range range)  
 Constraints: if (isBidirectionalRange!Range && is(typeof(pred(range.back)) : bool));   
  
Range **stripLeft**(Range, E)(Range range, E element)  
 Constraints: if (isInputRange!Range && is(typeof(range.front == element) : bool));   
  
Range **stripLeft**(alias pred, Range)(Range range)  
 Constraints: if (isInputRange!Range && is(typeof(pred(range.front)) : bool));   
  
Range **stripRight**(Range, E)(Range range, E element)  
 Constraints: if (isBidirectionalRange!Range && is(typeof(range.back == element) : bool));   
  
Range **stripRight**(alias pred, Range)(Range range)  
 Constraints: if (isBidirectionalRange!Range && is(typeof(pred(range.back)) : bool)); 
 
The strip group of functions allow stripping of either leading, trailing, or both leading and trailing elements. 


The `stripLeft` function will strip the `front` of the range, the `stripRight` function will strip the `back` of the range, while the `strip` function will strip both the `front` and `back` of the range.   
  
 Note that the `strip` and `stripRight` functions require the range to be a [`BidirectionalRange`](#BidirectionalRange) range.   
  
 All of these functions come in two varieties: one takes a target element, where the range will be stripped as long as this element can be found. The other takes a lambda predicate, where the range will be stripped as long as the predicate returns true. 

 
Parameters:


|  |  |
| --- | --- |
| Range `range` | a [bidirectional range](std_range_primitives#isBidirectionalRange) or [input range](std_range_primitives#isInputRange) |
| E `element` | the elements to remove |


 
Returns:
a Range with all of range except element at the start and end
 
Examples:
Strip leading and trailing elements equal to the target element. 
```
writeln("  foobar  ".strip(' ')); // "foobar"
writeln("00223.444500".strip('0')); // "223.4445"
writeln("ëëêéüŗōpéêëë".strip('ë')); // "êéüŗōpéê"
writeln([1, 1, 0, 1, 1].strip(1)); // [0]
writeln([0.0, 0.01, 0.01, 0.0].strip(0).length); // 2

```
 
 
Examples:
Strip leading and trailing elements while the predicate returns true. 
```
writeln("  foobar  ".strip!(a => a == ' ')()); // "foobar"
writeln("00223.444500".strip!(a => a == '0')()); // "223.4445"
writeln("ëëêéüŗōpéêëë".strip!(a => a == 'ë')()); // "êéüŗōpéê"
writeln([1, 1, 0, 1, 1].strip!(a => a == 1)()); // [0]
writeln([0.0, 0.01, 0.5, 0.6, 0.01, 0.0].strip!(a => a < 0.4)().length); // 2

```
 
 
Examples:
Strip leading elements equal to the target element. 
```
writeln("  foobar  ".stripLeft(' ')); // "foobar  "
writeln("00223.444500".stripLeft('0')); // "223.444500"
writeln("ůůűniçodêéé".stripLeft('ů')); // "űniçodêéé"
writeln([1, 1, 0, 1, 1].stripLeft(1)); // [0, 1, 1]
writeln([0.0, 0.01, 0.01, 0.0].stripLeft(0).length); // 3

```
 
 
Examples:
Strip leading elements while the predicate returns true. 
```
writeln("  foobar  ".stripLeft!(a => a == ' ')()); // "foobar  "
writeln("00223.444500".stripLeft!(a => a == '0')()); // "223.444500"
writeln("ůůűniçodêéé".stripLeft!(a => a == 'ů')()); // "űniçodêéé"
writeln([1, 1, 0, 1, 1].stripLeft!(a => a == 1)()); // [0, 1, 1]
writeln([0.0, 0.01, 0.10, 0.5, 0.6].stripLeft!(a => a < 0.4)().length); // 2

```
 
 
Examples:
Strip trailing elements equal to the target element. 
```
writeln("  foobar  ".stripRight(' ')); // "  foobar"
writeln("00223.444500".stripRight('0')); // "00223.4445"
writeln("ùniçodêéé".stripRight('é')); // "ùniçodê"
writeln([1, 1, 0, 1, 1].stripRight(1)); // [1, 1, 0]
writeln([0.0, 0.01, 0.01, 0.0].stripRight(0).length); // 3

```
 
 
Examples:
Strip trailing elements while the predicate returns true. 
```
writeln("  foobar  ".stripRight!(a => a == ' ')()); // "  foobar"
writeln("00223.444500".stripRight!(a => a == '0')()); // "00223.4445"
writeln("ùniçodêéé".stripRight!(a => a == 'é')()); // "ùniçodê"
writeln([1, 1, 0, 1, 1].stripRight!(a => a == 1)()); // [1, 1, 0]
writeln([0.0, 0.01, 0.10, 0.5, 0.6].stripRight!(a => a > 0.4)().length); // 3

```
 
  pure nothrow @nogc @trusted void **swap**(T)(ref T lhs, ref T rhs)  
 Constraints: if (isBlitAssignable!T && !is(typeof(lhs.proxySwap(rhs))));   
  
void **swap**(T)(ref T lhs, ref T rhs)  
 Constraints: if (is(typeof(lhs.proxySwap(rhs)))); 
 
Swaps `lhs` and `rhs`. The instances `lhs` and `rhs` are moved in memory, without ever calling `opAssign`, nor any other function. `T` need not be assignable at all to be swapped. 


If `lhs` and `rhs` reference the same instance, then nothing is done.   
  
 `lhs` and `rhs` must be mutable. If `T` is a struct or union, then its fields must also all be (recursively) mutable. 

 
Parameters:


|  |  |
| --- | --- |
| T `lhs` | Data to be swapped with `rhs`. |
| T `rhs` | Data to be swapped with `lhs`. |


 
Examples:


```
// Swapping POD (plain old data) types:
int a = 42, b = 34;
swap(a, b);
assert(a == 34 && b == 42);

// Swapping structs with indirection:
static struct S { int x; char c; int[] y; }
S s1 = { 0, 'z', [ 1, 2 ] };
S s2 = { 42, 'a', [ 4, 6 ] };
swap(s1, s2);
writeln(s1.x); // 42
writeln(s1.c); // 'a'
writeln(s1.y); // [4, 6]

writeln(s2.x); // 0
writeln(s2.c); // 'z'
writeln(s2.y); // [1, 2]

// Immutables cannot be swapped:
immutable int imm1 = 1, imm2 = 2;
static assert(!__traits(compiles, swap(imm1, imm2)));

int c = imm1 + 0;
int d = imm2 + 0;
swap(c, d);
writeln(c); // 2
writeln(d); // 1

```
 
 
Examples:


```
// Non-copyable types can still be swapped.
static struct NoCopy
{
    this(this) { assert(0); }
    int n;
    string s;
}
NoCopy nc1, nc2;
nc1.n = 127; nc1.s = "abc";
nc2.n = 513; nc2.s = "uvwxyz";

swap(nc1, nc2);
assert(nc1.n == 513 && nc1.s == "uvwxyz");
assert(nc2.n == 127 && nc2.s == "abc");

swap(nc1, nc1);
swap(nc2, nc2);
assert(nc1.n == 513 && nc1.s == "uvwxyz");
assert(nc2.n == 127 && nc2.s == "abc");

// Types containing non-copyable fields can also be swapped.
static struct NoCopyHolder
{
    NoCopy noCopy;
}
NoCopyHolder h1, h2;
h1.noCopy.n = 31; h1.noCopy.s = "abc";
h2.noCopy.n = 65; h2.noCopy.s = null;

swap(h1, h2);
assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");

swap(h1, h1);
swap(h2, h2);
assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");

// Const types cannot be swapped.
const NoCopy const1, const2;
assert(const1.n == 0 && const2.n == 0);
static assert(!__traits(compiles, swap(const1, const2)));

```
 
  void **swapAt**(R)(auto ref R r, size\_t i1, size\_t i2);  
Swaps two elements in-place of a range `r`, specified by their indices `i1` and `i2`. 



Parameters:


|  |  |
| --- | --- |
| R `r` | a range with swappable elements |
| size\_t `i1` | first index |
| size\_t `i2` | second index |


 
Examples:


```
import std.algorithm.comparison : equal;
auto a = [1, 2, 3];
a.swapAt(1, 2);
assert(a.equal([1, 3, 2]));

```
 
  Tuple!(InputRange1, InputRange2) **swapRanges**(InputRange1, InputRange2)(InputRange1 r1, InputRange2 r2)  
 Constraints: if (hasSwappableElements!InputRange1 && hasSwappableElements!InputRange2 && is(ElementType!InputRange1 == ElementType!InputRange2)); 
 
Swaps all elements of `r1` with successive elements in `r2`. Returns a tuple containing the remainder portions of `r1` and `r2` that were not swapped (one of them will be empty). The ranges may be of different types but must have the same element type and support swapping. 



Parameters:


|  |  |
| --- | --- |
| InputRange1 `r1` | an [input range](std_range_primitives#isInputRange) with swappable elements |
| InputRange2 `r2` | an [input range](std_range_primitives#isInputRange) with swappable elements |


 
Returns:
Tuple containing the remainder portions of r1 and r2 that were not swapped
 
Examples:


```
import std.range : empty;
int[] a = [ 100, 101, 102, 103 ];
int[] b = [ 0, 1, 2, 3 ];
auto c = swapRanges(a[1 .. 3], b[2 .. 4]);
assert(c[0].empty && c[1].empty);
writeln(a); // [100, 2, 3, 103]
writeln(b); // [0, 1, 101, 102]

```
 
  void **uninitializedFill**(Range, Value)(Range range, Value value)  
 Constraints: if (isInputRange!Range && hasLvalueElements!Range && is(typeof(range.front = value))); 
 
Initializes each element of `range` with `value`. Assumes that the elements of the range are uninitialized. This is of interest for structs that define copy constructors (for all other types, [`fill`](#fill) and uninitializedFill are equivalent). 



Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) that exposes references to its elements and has assignable elements |
| Value `value` | Assigned to each element of range |


 
See Also:

[`fill`](#fill) [`initializeAll`](#initializeAll)

 
Examples:


```
import core.stdc.stdlib : malloc, free;

auto s = (cast(int*) malloc(5 * int.sizeof))[0 .. 5];
uninitializedFill(s, 42);
writeln(s); // [42, 42, 42, 42, 42]

scope(exit) free(s.ptr);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_mutation.html>

std.algorithm.setops
====================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic algorithms that implement set operations. 


The functions [`multiwayMerge`](#multiwayMerge), [`multiwayUnion`](#multiwayUnion), [`setDifference`](#setDifference), [`setIntersection`](#setIntersection), [`setSymmetricDifference`](#setSymmetricDifference) expect a range of sorted ranges as input.   
  
 All algorithms are generalized to accept as input not only sets but also [multisets](http://https//en.wikipedia.org/wiki/Multiset). Each algorithm documents behaviour in the presence of duplicated inputs.   
  
 

Cheat Sheet| Function Name | Description |
| [`cartesianProduct`](#cartesianProduct) |  Computes Cartesian product of two ranges. |
| [`largestPartialIntersection`](#largestPartialIntersection) |  Copies out the values that occur most frequently in a range of ranges. |
| [`largestPartialIntersectionWeighted`](#largestPartialIntersectionWeighted) |  Copies out the values that occur most frequently (multiplied by per-value weights) in a range of ranges. |
| [`multiwayMerge`](#multiwayMerge) |  Merges a range of sorted ranges. |
| [`multiwayUnion`](#multiwayUnion) |  Computes the union of a range of sorted ranges. |
| [`setDifference`](#setDifference) |  Lazily computes the set difference of two or more sorted ranges. |
| [`setIntersection`](#setIntersection) |  Lazily computes the intersection of two or more sorted ranges. |
| [`setSymmetricDifference`](#setSymmetricDifference) |  Lazily computes the symmetric set difference of two or more sorted ranges. |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/setops.d](https://github.com/dlang/phobos/blob/master/std/algorithm/setops.d) 
 
auto **cartesianProduct**(R1, R2)(R1 range1, R2 range2)  
 Constraints: if (!allSatisfy!(isForwardRange, R1, R2) || anySatisfy!(isInfinite, R1, R2));   
  
auto **cartesianProduct**(RR...)(RR ranges)  
 Constraints: if (ranges.length >= 2 && allSatisfy!(isForwardRange, RR) && !anySatisfy!(isInfinite, RR));   
  
auto **cartesianProduct**(R1, R2, RR...)(R1 range1, R2 range2, RR otherRanges)  
 Constraints: if (!allSatisfy!(isForwardRange, R1, R2, RR) || anySatisfy!(isInfinite, R1, R2, RR)); 
 
Lazily computes the Cartesian product of two or more ranges. The product is a range of tuples of elements from each respective range. 


The conditions for the two-range case are as follows:   
  
 If both ranges are finite, then one must be (at least) a [forward range](std_range_primitives#isForwardRange) and the other an [input range](std_range_primitives#isInputRange).   
  
 If one range is infinite and the other finite, then the finite range must be a forward range, and the infinite range can be an input range.   
  
 If both ranges are infinite, then both must be forward ranges.   
  
 When there are more than two ranges, the above conditions apply to each adjacent pair of ranges. 

 
Parameters:


|  |  |
| --- | --- |
| R1 `range1` | The first range |
| R2 `range2` | The second range |
| RR `ranges` | Two or more non-infinite forward ranges |
| RR `otherRanges` | Zero or more non-infinite forward ranges |


 
Returns:
A forward range of [`std.typecons.Tuple`](std_typecons#Tuple) representing elements of the cartesian product of the given ranges.
 
Examples:


```
import std.algorithm.searching : canFind;
import std.range;
import std.typecons : tuple;

auto N = sequence!"n"(0);         // the range of natural numbers
auto N2 = cartesianProduct(N, N); // the range of all pairs of natural numbers

// Various arbitrary number pairs can be found in the range in finite time.
assert(canFind(N2, tuple(0, 0)));
assert(canFind(N2, tuple(123, 321)));
assert(canFind(N2, tuple(11, 35)));
assert(canFind(N2, tuple(279, 172)));

```
 
 
Examples:


```
import std.algorithm.searching : canFind;
import std.typecons : tuple;

auto B = [ 1, 2, 3 ];
auto C = [ 4, 5, 6 ];
auto BC = cartesianProduct(B, C);

foreach (n; [[1, 4], [2, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6],
             [2, 6], [3, 6]])
{
    assert(canFind(BC, tuple(n[0], n[1])));
}

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.typecons : tuple;

auto A = [ 1, 2, 3 ];
auto B = [ 'a', 'b', 'c' ];
auto C = [ "x", "y", "z" ];
auto ABC = cartesianProduct(A, B, C);

assert(ABC.equal([
    tuple(1, 'a', "x"), tuple(1, 'a', "y"), tuple(1, 'a', "z"),
    tuple(1, 'b', "x"), tuple(1, 'b', "y"), tuple(1, 'b', "z"),
    tuple(1, 'c', "x"), tuple(1, 'c', "y"), tuple(1, 'c', "z"),
    tuple(2, 'a', "x"), tuple(2, 'a', "y"), tuple(2, 'a', "z"),
    tuple(2, 'b', "x"), tuple(2, 'b', "y"), tuple(2, 'b', "z"),
    tuple(2, 'c', "x"), tuple(2, 'c', "y"), tuple(2, 'c', "z"),
    tuple(3, 'a', "x"), tuple(3, 'a', "y"), tuple(3, 'a', "z"),
    tuple(3, 'b', "x"), tuple(3, 'b', "y"), tuple(3, 'b', "z"),
    tuple(3, 'c', "x"), tuple(3, 'c', "y"), tuple(3, 'c', "z")
]));

```
 
  void **largestPartialIntersection**(alias less = "a < b", RangeOfRanges, Range)(RangeOfRanges ror, Range tgt, SortOutput sorted = No.sortOutput);  
Given a range of sorted [forward ranges](std_range_primitives#isForwardRange) `ror`, copies to `tgt` the elements that are common to most ranges, along with their number of occurrences. All ranges in `ror` are assumed to be sorted by `less`. Only the most frequent `tgt.length` elements are returned. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate the ranges are sorted by. |
| RangeOfRanges `ror` | A range of forward ranges sorted by `less`. |
| Range `tgt` | The target range to copy common elements to. |
| SortOutput `sorted` | Whether the elements copied should be in sorted order. The function `largestPartialIntersection` is useful for e.g. searching an [inverted index](https://en.wikipedia.org/wiki/Inverted_index) for the documents most likely to contain some terms of interest. The complexity of the search is Ο(`n * log(tgt.length)`), where `n` is the sum of lengths of all input ranges. This approach is faster than keeping an associative array of the occurrences and then selecting its top items, and also requires less memory (`largestPartialIntersection` builds its result directly in `tgt` and requires no extra memory). If at least one of the ranges is a multiset, then all occurences of a duplicate element are taken into account. The result is equivalent to merging all ranges and picking the most frequent `tgt.length` elements. |


 
Warning
 Because `largestPartialIntersection` does not allocate extra memory, it will leave `ror` modified. Namely, `largestPartialIntersection` assumes ownership of `ror` and discretionarily swaps and advances elements of it. If you want `ror` to preserve its contents after the call, you may want to pass a duplicate to `largestPartialIntersection` (and perhaps cache the duplicate in between calls).
 
Examples:


```
import std.typecons : tuple, Tuple;

// Figure which number can be found in most arrays of the set of
// arrays below.
double[][] a =
[
    [ 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];
auto b = new Tuple!(double, uint)[1];
// it will modify the input range, hence we need to create a duplicate
largestPartialIntersection(a.dup, b);
// First member is the item, second is the occurrence count
writeln(b[0]); // tuple(7.0, 4u)
// 7.0 occurs in 4 out of 5 inputs, more than any other number

// If more of the top-frequent numbers are needed, just create a larger
// tgt range
auto c = new Tuple!(double, uint)[2];
largestPartialIntersection(a, c);
writeln(c[0]); // tuple(1.0, 3u)
// 1.0 occurs in 3 inputs

// multiset
double[][] x =
[
    [1, 1, 1, 1, 4, 7, 8],
    [1, 7],
    [1, 7, 8],
    [4, 7],
    [7]
];
auto y = new Tuple!(double, uint)[2];
largestPartialIntersection(x.dup, y);
// 7.0 occurs 5 times
writeln(y[0]); // tuple(7.0, 5u)
// 1.0 occurs 6 times
writeln(y[1]); // tuple(1.0, 6u)

```
 
  void **largestPartialIntersectionWeighted**(alias less = "a < b", RangeOfRanges, Range, WeightsAA)(RangeOfRanges ror, Range tgt, WeightsAA weights, SortOutput sorted = No.sortOutput);  
Similar to `largestPartialIntersection`, but associates a weight with each distinct element in the intersection. 


If at least one of the ranges is a multiset, then all occurences of a duplicate element are taken into account. The result is equivalent to merging all input ranges and picking the highest `tgt.length`, weight-based ranking elements. 

 
Parameters:


|  |  |
| --- | --- |
| less | The predicate the ranges are sorted by. |
| RangeOfRanges `ror` | A range of [forward ranges](std_range_primitives#isForwardRange) sorted by `less`. |
| Range `tgt` | The target range to copy common elements to. |
| WeightsAA `weights` | An associative array mapping elements to weights. |
| SortOutput `sorted` | Whether the elements copied should be in sorted order. |


 
Examples:


```
import std.typecons : tuple, Tuple;

// Figure which number can be found in most arrays of the set of
// arrays below, with specific per-element weights
double[][] a =
[
    [ 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];
auto b = new Tuple!(double, uint)[1];
double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ];
largestPartialIntersectionWeighted(a, b, weights);
// First member is the item, second is the occurrence count
writeln(b[0]); // tuple(4.0, 2u)
// 4.0 occurs 2 times -> 4.6 (2 * 2.3)
// 7.0 occurs 3 times -> 4.4 (3 * 1.1)

// multiset
double[][] x =
[
    [ 1, 1, 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];
auto y = new Tuple!(double, uint)[1];
largestPartialIntersectionWeighted(x, y, weights);
writeln(y[0]); // tuple(1.0, 5u)
// 1.0 occurs 5 times -> 1.2 * 5 = 6

```
 
  struct **MultiwayMerge**(alias less, RangeOfRanges);   
  
MultiwayMerge!(less, RangeOfRanges) **multiwayMerge**(alias less = "a < b", RangeOfRanges)(RangeOfRanges ror);  
Merges multiple sets. The input sets are passed as a range of ranges and each is assumed to be sorted by `less`. Computation is done lazily, one union element at a time. The complexity of one `popFront` operation is Ο(`log(ror.length)`). However, the length of `ror` decreases as ranges in it are exhausted, so the complexity of a full pass through `MultiwayMerge` is dependent on the distribution of the lengths of ranges contained within `ror`. If all ranges have the same length `n` (worst case scenario), the complexity of a full pass through `MultiwayMerge` is Ο(`n * ror.length * log(ror.length)`), i.e., `log(ror.length)` times worse than just spanning all ranges in turn. The output comes sorted (unstably) by `less`. 


The length of the resulting range is the sum of all lengths of the ranges passed as input. This means that all elements (duplicates included) are transferred to the resulting range.   
  
 For backward compatibility, `multiwayMerge` is available under the name `nWayUnion` and `MultiwayMerge` under the name of `NWayUnion` . Future code should use `multiwayMerge` and `MultiwayMerge` as `nWayUnion` and `NWayUnion` will be deprecated. 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| RangeOfRanges `ror` | A range of ranges sorted by `less` to compute the union for. |


 
Returns:
A range of the union of the ranges in `ror`. 
 
Warning
 Because `MultiwayMerge` does not allocate extra memory, it will leave `ror` modified. Namely, `MultiwayMerge` assumes ownership of `ror` and discretionarily swaps and advances elements of it. If you want `ror` to preserve its contents after the call, you may want to pass a duplicate to `MultiwayMerge` (and perhaps cache the duplicate in between calls). 
 
See Also:

[`std.algorithm.sorting.merge`](std_algorithm_sorting#merge) for an analogous function that takes a static number of ranges of possibly disparate types.
 
Examples:


```
import std.algorithm.comparison : equal;

double[][] a =
[
    [ 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];
auto witness = [
    1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8
];
assert(equal(multiwayMerge(a), witness));

double[][] b =
[
    // range with duplicates
    [ 1, 1, 4, 7, 8 ],
    [ 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];
// duplicates are propagated to the resulting range
assert(equal(multiwayMerge(b), witness));

```
 
 
static bool **compFront**(.ElementType!RangeOfRanges a, .ElementType!RangeOfRanges b);  this(RangeOfRanges ror);  @property bool **empty**();  @property ref auto **front**();  void **popFront**();    auto **multiwayUnion**(alias less = "a < b", RangeOfRanges)(RangeOfRanges ror);  
Computes the union of multiple ranges. The [input ranges](std_range_primitives#isInputRange) are passed as a range of ranges and each is assumed to be sorted by `less`. Computation is done lazily, one union element at a time. `multiwayUnion(ror)` is functionally equivalent to `multiwayMerge(ror).uniq`. 


"The output of multiwayUnion has no duplicates even when its inputs contain duplicates." 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| RangeOfRanges `ror` | A range of ranges sorted by `less` to compute the intersection for. |


 
Returns:
A range of the union of the ranges in `ror`. See also: [`multiwayMerge`](#multiwayMerge)

 
Examples:


```
import std.algorithm.comparison : equal;

// sets
double[][] a =
[
    [ 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 8],
    [ 4 ],
    [ 7 ],
];

auto witness = [1, 4, 7, 8];
assert(equal(multiwayUnion(a), witness));

// multisets
double[][] b =
[
    [ 1, 1, 1, 4, 7, 8 ],
    [ 1, 7 ],
    [ 1, 7, 7, 8],
    [ 4 ],
    [ 7 ],
];
assert(equal(multiwayUnion(b), witness));

double[][] c =
[
    [9, 8, 8, 8, 7, 6],
    [9, 8, 6],
    [9, 8, 5]
];
auto witness2 = [9, 8, 7, 6, 5];
assert(equal(multiwayUnion!"a > b"(c), witness2));

```
 
  struct **SetDifference**(alias less = "a < b", R1, R2) if (isInputRange!R1 && isInputRange!R2);   
  
SetDifference!(less, R1, R2) **setDifference**(alias less = "a < b", R1, R2)(R1 r1, R2 r2);  
Lazily computes the difference of `r1` and `r2`. The two ranges are assumed to be sorted by `less`. The element types of the two ranges must have a common type. 


In the case of multisets, considering that element `a` appears `x` times in `r1` and `y` times and `r2`, the number of occurences of `a` in the resulting range is going to be `x-y` if x > y or 0 otherwise. 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| R1 `r1` | The first range. |
| R2 `r2` | The range to subtract from `r1`. |


 
Returns:
A range of the difference of `r1` and `r2`. 
 
See Also:
[`setSymmetricDifference`](#setSymmetricDifference)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range.primitives : isForwardRange;

//sets
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setDifference(a, b), [5, 9]));
static assert(isForwardRange!(typeof(setDifference(a, b))));

// multisets
int[] x = [1, 1, 1, 2, 3];
int[] y = [1, 1, 2, 4, 5];
auto r = setDifference(x, y);
assert(equal(r, [1, 3]));
assert(setDifference(r, x).empty);

```
 
 
this(R1 r1, R2 r2);  void **popFront**();  @property ref auto **front**();  @property typeof(this) **save**();  @property bool **empty**();    struct **SetIntersection**(alias less = "a < b", Rs...) if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void));   
  
SetIntersection!(less, Rs) **setIntersection**(alias less = "a < b", Rs...)(Rs ranges)  
 Constraints: if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void)); 
 
Lazily computes the intersection of two or more [input ranges](std_range_primitives#isInputRange) `ranges`. The ranges are assumed to be sorted by `less`. The element types of the ranges must have a common type. 


In the case of multisets, the range with the minimum number of occurences of a given element, propagates the number of occurences of this element to the resulting range. 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| Rs `ranges` | The ranges to compute the intersection for. |


 
Returns:
A range containing the intersection of the given ranges.
 
Examples:


```
import std.algorithm.comparison : equal;

// sets
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7]));
assert(equal(setIntersection(a, b, c), [1, 4, 7]));

// multisets
int[] d = [ 1, 1, 2, 2, 7, 7 ];
int[] e = [ 1, 1, 1, 7];
assert(equal(setIntersection(a, d), [1, 2, 7]));
assert(equal(setIntersection(d, e), [1, 1, 7]));

```
 
 
this(Rs input);  @property bool **empty**();  void **popFront**();  @property ElementType **front**();  @property SetIntersection **save**();    struct **SetSymmetricDifference**(alias less = "a < b", R1, R2) if (isInputRange!R1 && isInputRange!R2);   
  
SetSymmetricDifference!(less, R1, R2) **setSymmetricDifference**(alias less = "a < b", R1, R2)(R1 r1, R2 r2);  
Lazily computes the symmetric difference of `r1` and `r2`, i.e. the elements that are present in exactly one of `r1` and `r2`. The two ranges are assumed to be sorted by `less`, and the output is also sorted by `less`. The element types of the two ranges must have a common type. 


If both ranges are sets (without duplicated elements), the resulting range is going to be a set. If at least one of the ranges is a multiset, the number of occurences of an element `x` in the resulting range is `abs(a-b)` where `a` is the number of occurences of `x` in `r1`, `b` is the number of occurences of `x` in `r2`, and `abs` is the absolute value.   
  
 If both arguments are ranges of L-values of the same type then `SetSymmetricDifference` will also be a range of L-values of that type. 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| R1 `r1` | The first range. |
| R2 `r2` | The second range. |


 
Returns:
A range of the symmetric difference between `r1` and `r2`. 
 
See Also:
[`setDifference`](#setDifference)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range.primitives : isForwardRange;

// sets
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][]));
static assert(isForwardRange!(typeof(setSymmetricDifference(a, b))));

//mutisets
int[] c = [1, 1, 1, 1, 2, 2, 2, 4, 5, 6];
int[] d = [1, 1, 2, 2, 2, 2, 4, 7, 9];
assert(equal(setSymmetricDifference(c, d), setSymmetricDifference(d, c)));
assert(equal(setSymmetricDifference(c, d), [1, 1, 2, 5, 6, 7, 9]));

```
 
 
this(R1 r1, R2 r2);  void **popFront**();  @property ref auto **front**();  @property typeof(this) **save**();  ref auto **opSlice**();  @property bool **empty**();    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_setops.html>

std.ascii
=========

 Functions which operate on ASCII characters. 


All of the functions in std.ascii accept Unicode characters but effectively ignore them if they're not ASCII. All `isX` functions return `false` for non-ASCII characters, and all `toX` functions do nothing to non-ASCII characters.   
  
 For functions which operate on Unicode characters, see [`std.uni`](std_uni).   
  
 

| Category | Functions |
| --- | --- |
| Validation | [`isAlpha`](#isAlpha) [`isAlphaNum`](#isAlphaNum) [`isASCII`](#isASCII) [`isControl`](#isControl) [`isDigit`](#isDigit) [`isGraphical`](#isGraphical) [`isHexDigit`](#isHexDigit) [`isOctalDigit`](#isOctalDigit) [`isPrintable`](#isPrintable) [`isPunctuation`](#isPunctuation) [`isUpper`](#isUpper) [`isWhite`](#isWhite) |
| Conversions | [`toLower`](#toLower) [`toUpper`](#toUpper) |
| Constants | [`digits`](#digits) [`fullHexDigits`](#fullHexDigits) [`hexDigits`](#hexDigits) [`letters`](#letters) [`lowercase`](#lowercase) [`lowerHexDigits`](#lowerHexDigits) [`newline`](#newline) [`octalDigits`](#octalDigits) [`uppercase`](#uppercase) [`whitespace`](#whitespace) |
| Enums | [`ControlChar`](#ControlChar) [`LetterCase`](#LetterCase) |

 

 
References
 [ASCII Table](http://www.digitalmars.com/d/ascii-table.html), [Wikipedia](http://en.wikipedia.org/wiki/Ascii) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/ascii.d](https://github.com/dlang/phobos/blob/master/std/ascii.d)

 
immutable string **fullHexDigits**;  
0 .. 9A .. Fa .. f

  immutable string **hexDigits**;  
0 .. 9A .. F

  immutable string **lowerHexDigits**;  
0 .. 9a .. f

  immutable string **digits**;  
0 .. 9

  immutable string **octalDigits**;  
0 .. 7

  immutable string **letters**;  
A .. Za .. z

  immutable string **uppercase**;  
A .. Z

  immutable string **lowercase**;  
a .. z

  immutable string **whitespace**;  
ASCII whitespace

  enum **LetterCase**: bool;  
Letter case specifier.



Examples:


```
import std.conv : to;

writeln(42.to!string(16, LetterCase.upper)); // "2A"
writeln(42.to!string(16, LetterCase.lower)); // "2a"

```
 
 
Examples:


```
import std.digest.hmac : hmac;
import std.digest : toHexString;
import std.digest.sha : SHA1;
import std.string : representation;

const sha1HMAC = "A very long phrase".representation
    .hmac!SHA1("secret".representation)
    .toHexString!(LetterCase.lower);
writeln(sha1HMAC); // "49f2073c7bf58577e8c9ae59fe8cfd37c9ab94e5"

```
 
 
**upper** 
Upper case letters

  **lower** 
Lower case letters

    enum **ControlChar**: char;  
All control characters in the ASCII table ([source](https://www.asciitable.com)).



Examples:


```
import std.algorithm.comparison, std.algorithm.searching, std.range, std.traits;

// Because all ASCII characters fit in char, so do these
static assert(ControlChar.ack.sizeof == 1);

// All control characters except del are in row starting from 0
static assert(EnumMembers!ControlChar.only.until(ControlChar.del).equal(iota(32)));

static assert(ControlChar.nul == '\0');
static assert(ControlChar.bel == '\a');
static assert(ControlChar.bs  == '\b');
static assert(ControlChar.ff  == '\f');
static assert(ControlChar.lf  == '\n');
static assert(ControlChar.cr  == '\r');
static assert(ControlChar.tab == '\t');
static assert(ControlChar.vt  == '\v');

```
 
 
Examples:


```
import std.conv;
//Control character table can be used in place of hexcodes.
with (ControlChar) assert(text("Phobos", us, "Deimos", us, "Tango", rs) == "Phobos\x1FDeimos\x1FTango\x1E");

```
 
 
**nul** 
Null

  **soh** 
Start of heading

  **stx** 
Start of text

  **etx** 
End of text

  **eot** 
End of transmission

  **enq** 
Enquiry

  **ack** 
Acknowledge

  **bel** 
Bell

  **bs** 
Backspace

  **tab** 
Horizontal tab

  **lf** 
NL line feed, new line

  **vt** 
Vertical tab

  **ff** 
NP form feed, new page

  **cr** 
Carriage return

  **so** 
Shift out

  **si** 
Shift in

  **dle** 
Data link escape

  **dc1** 
Device control 1

  **dc2** 
Device control 2

  **dc3** 
Device control 3

  **dc4** 
Device control 4

  **nak** 
Negative acknowledge

  **syn** 
Synchronous idle

  **etb** 
End of transmission block

  **can** 
Cancel

  **em** 
End of medium

  **sub** 
Substitute

  **esc** 
Escape

  **fs** 
File separator

  **gs** 
Group separator

  **rs** 
Record separator

  **us** 
Unit separator

  **del** 
Delete

    immutable string **newline**;  
Newline sequence for this system.

  pure nothrow @nogc @safe bool **isAlphaNum**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a letter or a number (0 .. 9, a .. z, A .. Z).
 
Examples:


```
assert( isAlphaNum('A'));
assert( isAlphaNum('1'));
assert(!isAlphaNum('#'));

// N.B.: does not return true for non-ASCII Unicode alphanumerics:
assert(!isAlphaNum('á'));

```
 
  pure nothrow @nogc @safe bool **isAlpha**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is an ASCII letter (A .. Z, a .. z).
 
Examples:


```
assert( isAlpha('A'));
assert(!isAlpha('1'));
assert(!isAlpha('#'));

// N.B.: does not return true for non-ASCII Unicode alphabetic characters:
assert(!isAlpha('á'));

```
 
  pure nothrow @nogc @safe bool **isLower**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a lowercase ASCII letter (a .. z).
 
Examples:


```
assert( isLower('a'));
assert(!isLower('A'));
assert(!isLower('#'));

// N.B.: does not return true for non-ASCII Unicode lowercase letters
assert(!isLower('á'));
assert(!isLower('Á'));

```
 
  pure nothrow @nogc @safe bool **isUpper**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is an uppercase ASCII letter (A .. Z).
 
Examples:


```
assert( isUpper('A'));
assert(!isUpper('a'));
assert(!isUpper('#'));

// N.B.: does not return true for non-ASCII Unicode uppercase letters
assert(!isUpper('á'));
assert(!isUpper('Á'));

```
 
  pure nothrow @nogc @safe bool **isDigit**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a digit (0 .. 9).
 
Examples:


```
assert( isDigit('3'));
assert( isDigit('8'));
assert(!isDigit('B'));
assert(!isDigit('#'));

// N.B.: does not return true for non-ASCII Unicode numbers
assert(!isDigit('０')); // full-width digit zero (U+FF10)
assert(!isDigit('４')); // full-width digit four (U+FF14)

```
 
  pure nothrow @nogc @safe bool **isOctalDigit**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a digit in base 8 (0 .. 7).
 
Examples:


```
assert( isOctalDigit('0'));
assert( isOctalDigit('7'));
assert(!isOctalDigit('8'));
assert(!isOctalDigit('A'));
assert(!isOctalDigit('#'));

```
 
  pure nothrow @nogc @safe bool **isHexDigit**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a digit in base 16 (0 .. 9, A .. F, a .. f).
 
Examples:


```
assert( isHexDigit('0'));
assert( isHexDigit('A'));
assert( isHexDigit('f')); // lowercase hex digits are accepted
assert(!isHexDigit('g'));
assert(!isHexDigit('G'));
assert(!isHexDigit('#'));

```
 
  pure nothrow @nogc @safe bool **isWhite**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether or not `c` is a whitespace character. That includes the space, tab, vertical tab, form feed, carriage return, and linefeed characters.
 
Examples:


```
assert( isWhite(' '));
assert( isWhite('\t'));
assert( isWhite('\n'));
assert(!isWhite('1'));
assert(!isWhite('a'));
assert(!isWhite('#'));

// N.B.: Does not return true for non-ASCII Unicode whitespace characters.
static import std.uni;
assert(std.uni.isWhite('\u00A0'));
assert(!isWhite('\u00A0')); // std.ascii.isWhite

```
 
  pure nothrow @nogc @safe bool **isControl**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether `c` is a control character.
 
Examples:


```
assert( isControl('\0'));
assert( isControl('\022'));
assert( isControl('\n')); // newline is both whitespace and control
assert(!isControl(' '));
assert(!isControl('1'));
assert(!isControl('a'));
assert(!isControl('#'));

// N.B.: non-ASCII Unicode control characters are not recognized:
assert(!isControl('\u0080'));
assert(!isControl('\u2028'));
assert(!isControl('\u2029'));

```
 
  pure nothrow @nogc @safe bool **isPunctuation**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether or not `c` is a punctuation character. That includes all ASCII characters which are not control characters, letters, digits, or whitespace.
 
Examples:


```
assert( isPunctuation('.'));
assert( isPunctuation(','));
assert( isPunctuation(':'));
assert( isPunctuation('!'));
assert( isPunctuation('#'));
assert( isPunctuation('~'));
assert( isPunctuation('+'));
assert( isPunctuation('_'));

assert(!isPunctuation('1'));
assert(!isPunctuation('a'));
assert(!isPunctuation(' '));
assert(!isPunctuation('\n'));
assert(!isPunctuation('\0'));

// N.B.: Non-ASCII Unicode punctuation characters are not recognized.
assert(!isPunctuation('\u2012')); // (U+2012 = en-dash)

```
 
  pure nothrow @nogc @safe bool **isGraphical**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether or not `c` is a printable character other than the space character.
 
Examples:


```
assert( isGraphical('1'));
assert( isGraphical('a'));
assert( isGraphical('#'));
assert(!isGraphical(' ')); // whitespace is not graphical
assert(!isGraphical('\n'));
assert(!isGraphical('\0'));

// N.B.: Unicode graphical characters are not regarded as such.
assert(!isGraphical('á'));

```
 
  pure nothrow @nogc @safe bool **isPrintable**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether or not `c` is a printable character - including the space character.
 
Examples:


```
assert( isPrintable(' '));  // whitespace is printable
assert( isPrintable('1'));
assert( isPrintable('a'));
assert( isPrintable('#'));
assert(!isPrintable('\0')); // control characters are not printable

// N.B.: Printable non-ASCII Unicode characters are not recognized.
assert(!isPrintable('á'));

```
 
  pure nothrow @nogc @safe bool **isASCII**(dchar c);  

Parameters:


|  |  |
| --- | --- |
| dchar `c` | The character to test. |


 
Returns:
Whether or not `c` is in the ASCII character set - i.e. in the range 0 .. 0x7F.
 
Examples:


```
assert( isASCII('a'));
assert(!isASCII('á'));

```
 
  auto **toLower**(C)(C c)  
 Constraints: if (is(C : dchar)); 
 
Converts an ASCII letter to lowercase. 



Parameters:


|  |  |
| --- | --- |
| C `c` | A character of any type that implicitly converts to `dchar`. In the case where it's a built-in type, or an enum of a built-in type, `Unqual!(OriginalType!C)` is returned, whereas if it's a user-defined type, `dchar` is returned. |


 
Returns:
The corresponding lowercase letter, if `c` is an uppercase ASCII character, otherwise `c` itself.
 
Examples:


```
writeln(toLower('a')); // 'a'
writeln(toLower('A')); // 'a'
writeln(toLower('#')); // '#'

// N.B.: Non-ASCII Unicode uppercase letters are not converted.
writeln(toLower('Á')); // 'Á'

```
 
  auto **toUpper**(C)(C c)  
 Constraints: if (is(C : dchar)); 
 
Converts an ASCII letter to uppercase. 



Parameters:


|  |  |
| --- | --- |
| C `c` | Any type which implicitly converts to `dchar`. In the case where it's a built-in type, or an enum of a built-in type, `Unqual!(OriginalType!C)` is returned, whereas if it's a user-defined type, `dchar` is returned. |


 
Returns:
The corresponding uppercase letter, if `c` is a lowercase ASCII character, otherwise `c` itself.
 
Examples:


```
writeln(toUpper('a')); // 'A'
writeln(toUpper('A')); // 'A'
writeln(toUpper('#')); // '#'

// N.B.: Non-ASCII Unicode lowercase letters are not converted.
writeln(toUpper('á')); // 'á'

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_ascii.html>

std.algorithm.iteration
=======================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic iteration algorithms. 


 

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

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/iteration.d](https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d) 
 
auto **cache**(Range)(Range range)  
 Constraints: if (isInputRange!Range);   
  
auto **cacheBidirectional**(Range)(Range range)  
 Constraints: if (isBidirectionalRange!Range); 
 
`cache` eagerly evaluates [front](std_range_primitives#front) of `range` on each construction or call to [popFront](std_range_primitives#popFront), to store the result in a cache. The result is then directly returned when [front](std_range_primitives#front) is called, rather than re-evaluated. 


This can be a useful function to place in a chain, after functions that have expensive evaluation, as a lazy alternative to [`std.array.array`](std_array#array). In particular, it can be placed after a call to [`map`](#map), or before a call [`std.range.filter`](std_range#filter) or [`std.range.tee`](std_range#tee)   
  
 `cache` may provide [bidirectional range](std_range_primitives#isBidirectionalRange) iteration if needed, but since this comes at an increased cost, it must be explicitly requested via the call to `cacheBidirectional`. Furthermore, a bidirectional cache will evaluate the "center" element twice, when there is only one element left in the range.   
  
 `cache` does not provide random access primitives, as `cache` would be unable to cache the random accesses. If `Range` provides slicing primitives, then `cache` will provide the same slicing primitives, but `hasSlicing!Cache` will not yield true (as the [`std.range.primitives.hasSlicing`](std_range_primitives#hasSlicing) trait also checks for random access). 

 
Parameters:


|  |  |
| --- | --- |
| Range `range` | an [input range](std_range_primitives#isInputRange) |


 
Returns:
An [input range](std_range_primitives#isInputRange) with the cached values of range
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range, std.stdio;
import std.typecons : tuple;

ulong counter = 0;
double fun(int x)
{
    ++counter;
    // http://en.wikipedia.org/wiki/Quartic_function
    return ( (x + 4.0) * (x + 1.0) * (x - 1.0) * (x - 3.0) ) / 14.0 + 0.5;
}
// Without cache, with array (greedy)
auto result1 = iota(-4, 5).map!(a =>tuple(a, fun(a)))()
                         .filter!(a => a[1] < 0)()
                         .map!(a => a[0])()
                         .array();

// the values of x that have a negative y are:
assert(equal(result1, [-3, -2, 2]));

// Check how many times fun was evaluated.
// As many times as the number of items in both source and result.
writeln(counter); // iota(-4, 5).length + result1.length

counter = 0;
// Without array, with cache (lazy)
auto result2 = iota(-4, 5).map!(a =>tuple(a, fun(a)))()
                         .cache()
                         .filter!(a => a[1] < 0)()
                         .map!(a => a[0])();

// the values of x that have a negative y are:
assert(equal(result2, [-3, -2, 2]));

// Check how many times fun was evaluated.
// Only as many times as the number of items in source.
writeln(counter); // iota(-4, 5).length

```
 
 
Examples:
Tip: `cache` is eager when evaluating elements. If calling front on the underlying range has a side effect, it will be observable before calling front on the actual cached range. Furthermore, care should be taken composing `cache` with [`std.range.take`](std_range#take). By placing `take` before `cache`, then `cache` will be "aware" of when the range ends, and correctly stop caching elements when needed. If calling front has no side effect though, placing `take` after `cache` may yield a faster range. Either way, the resulting ranges will be equivalent, but maybe not at the same cost or side effects. 
```
import std.algorithm.comparison : equal;
import std.range;
int i = 0;

auto r = iota(0, 4).tee!((a){i = a;}, No.pipeOnPop);
auto r1 = r.take(3).cache();
auto r2 = r.cache().take(3);

assert(equal(r1, [0, 1, 2]));
assert(i == 2); //The last "seen" element was 2. The data in cache has been cleared.

assert(equal(r2, [0, 1, 2]));
assert(i == 3); //cache has accessed 3. It is still stored internally by cache.

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



Parameters:


|  |  |
| --- | --- |
| fun | one or more transformation functions |


 
See Also:
[Map (higher-order function)](http://en.wikipedia.org/wiki/Map_(higher-order_function))
 
Examples:


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

```
 
 
Examples:
Multiple functions can be passed to `map`. In that case, the element type of `map` is a tuple containing one element for each function. 
```
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];

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

```
 
 
Examples:
You may alias `map` with some function(s) to a symbol and use it separately: 
```
import std.algorithm.comparison : equal;
import std.conv : to;

alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));

```
 
 
auto **map**(Range)(Range r)  
 Constraints: if (isInputRange!(Unqual!Range)); 
 

Parameters:


|  |  |
| --- | --- |
| Range `r` | an [input range](std_range_primitives#isInputRange) |


 
Returns:
A range with each fun applied to all the elements. If there is more than one fun, the element type will be `Tuple` containing one element for each fun.
    template **each**(alias fun = "a") 
Eagerly iterates over `r` and calls `fun` over each element. 


If no function to call is specified, `each` defaults to doing nothing but consuming the entire range. `r.front` will be evaluated, but that can be avoided by specifying a lambda with a `lazy` parameter.   
  
 `each` also supports `opApply`-based types, so it works with e.g. [`std.parallelism.parallel`](std_parallelism#parallel).   
  
 Normally the entire range is iterated. If partial iteration (early stopping) is desired, `fun` needs to return a value of type [`std.typecons.Flag`](std_typecons#Flag)`!"each"` (`Yes.each` to continue iteration, or `No.each` to stop iteration). 

 
Parameters:


|  |  |
| --- | --- |
| fun | function to apply to each element of the range |
| Range r | range or iterable over which `each` iterates |


 
Returns:

`Yes.each` if the entire range was iterated, `No.each` in case of early stopping. 
 
See Also:
[`std.range.tee`](std_range#tee)
 
Examples:


```
import std.range : iota;
import std.typecons : Flag, Yes, No;

long[] arr;
iota(5).each!(n => arr ~= n);
writeln(arr); // [0, 1, 2, 3, 4]
iota(5).each!((n) { arr ~= n; return No.each; });
writeln(arr); // [0, 1, 2, 3, 4, 0]

// If the range supports it, the value can be mutated in place
arr.each!((ref n) => n++);
writeln(arr); // [1, 2, 3, 4, 5, 1]

arr.each!"a++";
writeln(arr); // [2, 3, 4, 5, 6, 2]

// by-ref lambdas are not allowed for non-ref ranges
static assert(!is(typeof(arr.map!(n => n).each!((ref n) => n++))));

// The default predicate consumes the range
auto m = arr.map!(n => n);
(&m).each();
assert(m.empty);

// Indexes are also available for in-place mutations
arr[] = 0;
arr.each!"a=i"();
writeln(arr); // [0, 1, 2, 3, 4, 5]

// opApply iterators work as well
static class S
{
    int x;
    int opApply(scope int delegate(ref int _x) dg) { return dg(x); }
}

auto s = new S;
s.each!"a++";
writeln(s.x); // 1

```
 
 
Examples:

`each` works with iterable objects which provide an index variable, along with each element 
```
import std.range : iota, lockstep;

auto arr = [1, 2, 3, 4];

// 1 ref parameter
arr.each!((ref e) => e = 0);
writeln(arr.sum); // 0

// 1 ref parameter and index
arr.each!((i, ref e) => e = cast(int) i);
writeln(arr.sum); // 4.iota.sum

```
 
 
Flag!"**each**" **each**(Range)(Range r)  
 Constraints: if (!isForeachIterable!Range && (isRangeIterable!Range || \_\_traits(compiles, typeof(r.front).length)));   
  
Flag!"**each**" **each**(Iterable)(auto ref Iterable r)  
 Constraints: if (isForeachIterable!Iterable || \_\_traits(compiles, Parameters!(Parameters!(r.opApply)))); 
 

Parameters:


|  |  |
| --- | --- |
| Range `r` | range or iterable over which each iterates |


    template **filter**(alias predicate) if (is(typeof(unaryFun!predicate))) 
Implements the higher order filter function. The predicate is passed to [`std.functional.unaryFun`](std_functional#unaryFun), and can either accept a string, or any callable that can be executed via `pred(element)`. 



Parameters:


|  |  |
| --- | --- |
| predicate | Function to apply to each element of range |


 
Returns:

`filter!(predicate)(range)` returns a new range containing only elements `x` in `range` for which `predicate(x)` returns `true`. 
 
See Also:
[Filter (higher-order function)](http://en.wikipedia.org/wiki/Filter_(higher-order_function))
 
Examples:


```
import std.algorithm.comparison : equal;
import std.math : approxEqual;
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(approxEqual(r1, [ 2.5 ]));

```
 
 
auto **filter**(Range)(Range range)  
 Constraints: if (isInputRange!(Unqual!Range)); 
 

Parameters:


|  |  |
| --- | --- |
| Range `range` | An [input range](std_range_primitives#isInputRange) of elements |


 
Returns:
A range containing only elements `x` in `range` for which `predicate(x)` returns `true`.
    template **filterBidirectional**(alias pred) 
Similar to `filter`, except it defines a [bidirectional range](std_range_primitives#isBidirectionalRange). There is a speed disadvantage - the constructor spends time finding the last element in the range that satisfies the filtering condition (in addition to finding the first one). The advantage is that the filtered range can be spanned from both directions. Also, [`std.range.retro`](std_range#retro) can be applied against the filtered range. 


The predicate is passed to [`std.functional.unaryFun`](std_functional#unaryFun), and can either accept a string, or any callable that can be executed via `pred(element)`. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Function to apply to each element of range |


 
Examples:


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

int[] arr = [ 1, 2, 3, 4, 5 ];
auto small = filterBidirectional!("a < 3")(arr);
static assert(isBidirectionalRange!(typeof(small)));
writeln(small.back); // 2
assert(equal(small, [ 1, 2 ]));
assert(equal(retro(small), [ 2, 1 ]));
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = filterBidirectional!("a > 0")(chain(a, b));
writeln(r.back); // 102

```
 
 
auto **filterBidirectional**(Range)(Range r)  
 Constraints: if (isBidirectionalRange!(Unqual!Range)); 
 

Parameters:


|  |  |
| --- | --- |
| Range `r` | Bidirectional range of elements |


 
Returns:
A range containing only the elements in `r` for which `pred` returns `true`.
    Group!(pred, Range) **group**(alias pred = "a == b", Range)(Range r);   
  
struct **Group**(alias pred, R) if (isInputRange!R);  
Groups consecutively equivalent elements into a single tuple of the element and the number of its repetitions. 


Similarly to `uniq`, `group` produces a range that iterates over unique consecutive elements of the given range. Each element of this range is a tuple of the element and the number of times it is repeated in the original range. Equivalence of elements is assessed by using the predicate `pred`, which defaults to `"a == b"`. The predicate is passed to [`std.functional.binaryFun`](std_functional#binaryFun), and can either accept a string, or any callable that can be executed via `pred(element, element)`. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Binary predicate for determining equivalence of two elements. |
| R | The range type |
| Range `r` | The [input range](std_range_primitives#isInputRange) to iterate over. |


 
Returns:
A range of elements of type `Tuple!(ElementType!R, uint)`, representing each consecutively unique element and its respective number of occurrences in that run. This will be an input range if `R` is an input range, and a forward range in all other cases. 
 
See Also:

[`chunkBy`](#chunkBy), which chunks an input range into subranges of equivalent adjacent elements.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.typecons : tuple, Tuple;

int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u),
    tuple(4, 3u), tuple(5, 1u) ][]));

```
 
 
Examples:
Using group, an associative array can be easily generated with the count of each unique element in the range. 
```
import std.algorithm.sorting : sort;
import std.array : assocArray;

uint[string] result;
auto range = ["a", "b", "a", "c", "b", "c", "c", "d", "e"];
result = range.sort!((a, b) => a < b)
    .group
    .assocArray;

writeln(result); // ["a":2U, "b":2U, "c":3U, "d":1U, "e":1U]

```
 
  auto **chunkBy**(alias pred, Range)(Range r)  
 Constraints: if (isInputRange!Range); 
 
Chunks an input range into subranges of equivalent adjacent elements. In other languages this is often called `partitionBy`, `groupBy` or `sliceWhen`. 


Equivalence is defined by the predicate `pred`, which can be either binary, which is passed to [`std.functional.binaryFun`](std_functional#binaryFun), or unary, which is passed to [`std.functional.unaryFun`](std_functional#unaryFun). In the binary form, two range elements `a` and `b` are considered equivalent if `pred(a,b)` is true. In unary form, two elements are considered equivalent if `pred(a) == pred(b)` is true.   
  
 This predicate must be an equivalence relation, that is, it must be reflexive (`pred(x,x)` is always true), symmetric (`pred(x,y) == pred(y,x)`), and transitive (`pred(x,y) && pred(y,z)` implies `pred(x,z)`). If this is not the case, the range returned by chunkBy may assert at runtime or behave erratically. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Predicate for determining equivalence. |
| Range `r` | An [input range](std_range_primitives#isInputRange) to be chunked. |


 
Returns:
With a binary predicate, a range of ranges is returned in which all elements in a given subrange are equivalent under the given predicate. With a unary predicate, a range of tuples is returned, with the tuple consisting of the result of the unary predicate for each subrange, and the subrange itself. 
 
Notes
 Equivalent elements separated by an intervening non-equivalent element will appear in separate subranges; this function only considers adjacent equivalence. Elements in the subranges will always appear in the same order they appear in the original range. 
 
See Also:

[`group`](#group), which collapses adjacent equivalent elements into a single element.
 
Examples:
Showing usage with binary predicate: 
```
import std.algorithm.comparison : equal;

// Grouping by particular attribute of each element:
auto data = [
    [1, 1],
    [1, 2],
    [2, 2],
    [2, 3]
];

auto r1 = data.chunkBy!((a,b) => a[0] == b[0]);
assert(r1.equal!equal([
    [[1, 1], [1, 2]],
    [[2, 2], [2, 3]]
]));

auto r2 = data.chunkBy!((a,b) => a[1] == b[1]);
assert(r2.equal!equal([
    [[1, 1]],
    [[1, 2], [2, 2]],
    [[2, 3]]
]));

```
 
 
Examples:
Showing usage with unary predicate: 
```
import std.algorithm.comparison : equal;
import std.range.primitives;
import std.typecons : tuple;

// Grouping by particular attribute of each element:
auto range =
[
    [1, 1],
    [1, 1],
    [1, 2],
    [2, 2],
    [2, 3],
    [2, 3],
    [3, 3]
];

auto byX = chunkBy!(a => a[0])(range);
auto expected1 =
[
    tuple(1, [[1, 1], [1, 1], [1, 2]]),
    tuple(2, [[2, 2], [2, 3], [2, 3]]),
    tuple(3, [[3, 3]])
];
foreach (e; byX)
{
    assert(!expected1.empty);
    writeln(e[0]); // expected1.front[0]
    assert(e[1].equal(expected1.front[1]));
    expected1.popFront();
}

auto byY = chunkBy!(a => a[1])(range);
auto expected2 =
[
    tuple(1, [[1, 1], [1, 1]]),
    tuple(2, [[1, 2], [2, 2]]),
    tuple(3, [[2, 3], [2, 3], [3, 3]])
];
foreach (e; byY)
{
    assert(!expected2.empty);
    writeln(e[0]); // expected2.front[0]
    assert(e[1].equal(expected2.front[1]));
    expected2.popFront();
}

```
 
  auto **joiner**(RoR, Separator)(RoR r, Separator sep)  
 Constraints: if (isInputRange!RoR && isInputRange!(ElementType!RoR) && isForwardRange!Separator && is(ElementType!Separator : ElementType!(ElementType!RoR)));   
  
auto **joiner**(RoR)(RoR r)  
 Constraints: if (isInputRange!RoR && isInputRange!(ElementType!RoR)); 
 
Lazily joins a range of ranges with a separator. The separator itself is a range. If a separator is not provided, then the ranges are joined directly without anything in between them (often called `flatten` in other languages). 



Parameters:


|  |  |
| --- | --- |
| RoR `r` | An [input range](std_range_primitives#isInputRange) of input ranges to be joined. |
| Separator `sep` | A [forward range](std_range_primitives#isForwardRange) of element(s) to serve as separators in the joined range. |


 
Returns:
A range of elements in the joined range. This will be a forward range if both outer and inner ranges of `RoR` are forward ranges; otherwise it will be only an input range. The [range bidirectionality](std_range_primitives#isBidirectionalRange) is propagated if no separator is specified. 
 
See Also:

[`std.range.chain`](std_range#chain), which chains a sequence of ranges with compatible elements into a single range.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.conv : text;

assert(["abc", "def"].joiner.equal("abcdef"));
assert(["Mary", "has", "a", "little", "lamb"]
    .joiner("...")
    .equal("Mary...has...a...little...lamb"));
assert(["", "abc"].joiner("xyz").equal("xyzabc"));
assert([""].joiner("xyz").equal(""));
assert(["", ""].joiner("xyz").equal("xyz"));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : repeat;

assert([""].joiner.equal(""));
assert(["", ""].joiner.equal(""));
assert(["", "abc"].joiner.equal("abc"));
assert(["abc", ""].joiner.equal("abc"));
assert(["abc", "def"].joiner.equal("abcdef"));
assert(["Mary", "has", "a", "little", "lamb"].joiner.equal("Maryhasalittlelamb"));
assert("abc".repeat(3).joiner.equal("abcabcabc"));

```
 
 
Examples:
joiner allows in-place mutation! 
```
import std.algorithm.comparison : equal;
auto a = [ [1, 2, 3], [42, 43] ];
auto j = joiner(a);
j.front = 44;
writeln(a); // [[44, 2, 3], [42, 43]]
assert(equal(j, [44, 2, 3, 42, 43]));

```
 
 
Examples:
insert characters fully lazily into a string 
```
import std.algorithm.comparison : equal;
import std.range : chain, cycle, iota, only, retro, take, zip;
import std.format : format;

static immutable number = "12345678";
static immutable delimiter = ",";
auto formatted = number.retro
    .zip(3.iota.cycle.take(number.length))
    .map!(z => chain(z[0].only, z[1] == 2 ? delimiter : null))
    .joiner
    .retro;
static immutable expected = "12,345,678";
assert(formatted.equal(expected));

```
 
 
Examples:
joiner can be bidirectional 
```
import std.algorithm.comparison : equal;
import std.range : retro;

auto a = [[1, 2, 3], [4, 5]];
auto j = a.joiner;
j.back = 44;
writeln(a); // [[1, 2, 3], [4, 44]]
assert(equal(j.retro, [44, 4, 3, 2, 1]));

```
 
  template **reduce**(fun...) if (fun.length >= 1) 
Implements the homonym function (also known as `accumulate`, `compress`, `inject`, or `foldl`) present in various programming languages of functional flavor. There is also [`fold`](#fold) which does the same thing but with the opposite parameter order. The call `reduce!(fun)(seed, range)` first assigns `seed` to an internal variable `result`, also called the accumulator. Then, for each element `x` in `range`, `result = fun(result, x)` gets evaluated. Finally, `result` is returned. The one-argument version `reduce!(fun)(range)` works similarly, but it uses the first element of the range as the seed (the range must be non-empty). 



Returns:
the accumulated `result` 
 
Parameters:


|  |  |
| --- | --- |
| fun | one or more functions |


 
See Also:

[Fold (higher-order function)](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) [`fold`](#fold) is functionally equivalent to [`reduce`](#reduce) with the argument order reversed, and without the need to use [`tuple`](std_typecons#tuple) for multiple seeds. This makes it easier to use in UFCS chains. [`sum`](#sum) is similar to `reduce!((a, b) => a + b)` that offers pairwise summing of floating point numbers.
 
Examples:
Many aggregate range operations turn out to be solved with `reduce` quickly and easily. The example below illustrates `reduce`'s remarkable power and flexibility. 
```
import std.algorithm.comparison : max, min;
import std.math : approxEqual;
import std.range;

int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto sum = reduce!((a,b) => a + b)(0, arr);
writeln(sum); // 15

// Sum again, using a string predicate with "a" and "b"
sum = reduce!"a + b"(0, arr);
writeln(sum); // 15

// Compute the maximum of all elements
auto largest = reduce!(max)(arr);
writeln(largest); // 5

// Max again, but with Uniform Function Call Syntax (UFCS)
largest = arr.reduce!(max);
writeln(largest); // 5

// Compute the number of odd elements
auto odds = reduce!((a,b) => a + (b & 1))(0, arr);
writeln(odds); // 3

// Compute the sum of squares
auto ssquares = reduce!((a,b) => a + b * b)(0, arr);
writeln(ssquares); // 55

// Chain multiple ranges into seed
int[] a = [ 3, 4 ];
int[] b = [ 100 ];
auto r = reduce!("a + b")(chain(a, b));
writeln(r); // 107

// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = reduce!("a + b")(chain(a, b, c));
assert(approxEqual(r1, 112.5));

// To minimize nesting of parentheses, Uniform Function Call Syntax can be used
auto r2 = chain(a, b, c).reduce!("a + b");
assert(approxEqual(r2, 112.5));

```
 
 
Examples:
Sometimes it is very useful to compute multiple aggregates in one pass. One advantage is that the computation is faster because the looping overhead is shared. That's why `reduce` accepts multiple functions. If two or more functions are passed, `reduce` returns a [`std.typecons.Tuple`](std_typecons#Tuple) object with one member per passed-in function. The number of seeds must be correspondingly increased. 
```
import std.algorithm.comparison : max, min;
import std.math : approxEqual, sqrt;
import std.typecons : tuple, Tuple;

double[] a = [ 3.0, 4, 7, 11, 3, 2, 5 ];
// Compute minimum and maximum in one pass
auto r = reduce!(min, max)(a);
// The type of r is Tuple!(int, int)
assert(approxEqual(r[0], 2));  // minimum
assert(approxEqual(r[1], 11)); // maximum

// Compute sum and sum of squares in one pass
r = reduce!("a + b", "a + b * b")(tuple(0.0, 0.0), a);
assert(approxEqual(r[0], 35));  // sum
assert(approxEqual(r[1], 233)); // sum of squares
// Compute average and standard deviation from the above
auto avg = r[0] / a.length;
writeln(avg); // 5
auto stdev = sqrt(r[1] / a.length - avg * avg);
writeln(cast(int)stdev); // 2

```
 
 
auto **reduce**(R)(R r)  
 Constraints: if (isIterable!R); 
 
No-seed version. The first element of `r` is used as the seed's value. 


For each function `f` in `fun`, the corresponding seed type `S` is `Unqual!(typeof(f(e, e)))`, where `e` is an element of `r`: `ElementType!R` for ranges, and `ForeachType!R` otherwise.   
  
 Once S has been determined, then `S s = e;` and `s = f(s, e);` must both be legal. 

 
Parameters:


|  |  |
| --- | --- |
| R `r` | an iterable value as defined by `isIterable` |


 
Returns:
the final result of the accumulator applied to the iterable 
 
Throws:

`Exception` if `r` is empty
  auto **reduce**(S, R)(S seed, R r)  
 Constraints: if (isIterable!R); 
 
Seed version. The seed should be a single value if `fun` is a single function. If `fun` is multiple functions, then `seed` should be a [`std.typecons.Tuple`](std_typecons#Tuple), with one field per function in `f`. 


For convenience, if the seed is const, or has qualified fields, then `reduce` will operate on an unqualified copy. If this happens then the returned type will not perfectly match `S`.   
  
 Use `fold` instead of `reduce` to use the seed version in a UFCS chain. 

 
Parameters:


|  |  |
| --- | --- |
| S `seed` | the initial value of the accumulator |
| R `r` | an iterable value as defined by `isIterable` |


 
Returns:
the final result of the accumulator applied to the iterable
    template **fold**(fun...) if (fun.length >= 1) 
Implements the homonym function (also known as `accumulate`, `compress`, `inject`, or `foldl`) present in various programming languages of functional flavor. The call `fold!(fun)(range, seed)` first assigns `seed` to an internal variable `result`, also called the accumulator. Then, for each element `x` in `range`, `result = fun(result, x)` gets evaluated. Finally, `result` is returned. The one-argument version `fold!(fun)(range)` works similarly, but it uses the first element of the range as the seed (the range must be non-empty). 



Parameters:


|  |  |
| --- | --- |
| fun | the predicate function(s) to apply to the elements |


 
See Also:

[Fold (higher-order function)](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) [`sum`](#sum) is similar to `fold!((a, b) => a + b)` that offers precise summing of floating point numbers. This is functionally equivalent to [`reduce`](#reduce) with the argument order reversed, and without the need to use [`tuple`](std_typecons#tuple) for multiple seeds.
 
Examples:


```
immutable arr = [1, 2, 3, 4, 5];

// Sum all elements
writeln(arr.fold!((a, b) => a + b)); // 15

// Sum all elements with explicit seed
writeln(arr.fold!((a, b) => a + b)(6)); // 21

import std.algorithm.comparison : min, max;
import std.typecons : tuple;

// Compute minimum and maximum at the same time
writeln(arr.fold!(min, max)); // tuple(1, 5)

// Compute minimum and maximum at the same time with seeds
writeln(arr.fold!(min, max)(0, 7)); // tuple(0, 7)

// Can be used in a UFCS chain
writeln(arr.map!(a => a + 1).fold!((a, b) => a + b)); // 20

// Return the last element of any range
writeln(arr.fold!((a, b) => b)); // 5

```
 
 
auto **fold**(R, S...)(R r, S seed);  

Parameters:


|  |  |
| --- | --- |
| R `r` | the [input range](std_range_primitives#isInputRange) to fold |
| S `seed` | the initial value of the accumulator |


 
Returns:
the accumulated `result`

    template **cumulativeFold**(fun...) if (fun.length >= 1) 
Similar to `fold`, but returns a range containing the successive reduced values. The call `cumulativeFold!(fun)(range, seed)` first assigns `seed` to an internal variable `result`, also called the accumulator. The returned range contains the values `result = fun(result, x)` lazily evaluated for each element `x` in `range`. Finally, the last element has the same value as `fold!(fun)(seed, range)`. The one-argument version `cumulativeFold!(fun)(range)` works similarly, but it returns the first element unchanged and uses it as seed for the next elements. This function is also known as [partial\_sum](http://en.cppreference.com/w/cpp/algorithm/partial_sum), [accumulate](http://docs.python.org/3/library/itertools.html#itertools.accumulate), [scan](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:scanl), [Cumulative Sum](http://mathworld.wolfram.com/CumulativeSum.html). 



Parameters:


|  |  |
| --- | --- |
| fun | one or more functions to use as fold operation |


 
Returns:
The function returns a range containing the consecutive reduced values. If there is more than one `fun`, the element type will be  [`std.typecons.Tuple`](std_typecons#Tuple) containing one element for each `fun`. 
 
See Also:

[Prefix Sum](http://en.wikipedia.org/wiki/Prefix_sum) 
 
Note
 In functional programming languages this is typically called `scan`, `scanl`, `scanLeft` or `reductions`.
 
Examples:


```
import std.algorithm.comparison : max, min;
import std.array : array;
import std.math : approxEqual;
import std.range : chain;

int[] arr = [1, 2, 3, 4, 5];
// Partial sum of all elements
auto sum = cumulativeFold!((a, b) => a + b)(arr, 0);
writeln(sum.array); // [1, 3, 6, 10, 15]

// Partial sum again, using a string predicate with "a" and "b"
auto sum2 = cumulativeFold!"a + b"(arr, 0);
writeln(sum2.array); // [1, 3, 6, 10, 15]

// Compute the partial maximum of all elements
auto largest = cumulativeFold!max(arr);
writeln(largest.array); // [1, 2, 3, 4, 5]

// Partial max again, but with Uniform Function Call Syntax (UFCS)
largest = arr.cumulativeFold!max;
writeln(largest.array); // [1, 2, 3, 4, 5]

// Partial count of odd elements
auto odds = arr.cumulativeFold!((a, b) => a + (b & 1))(0);
writeln(odds.array); // [1, 1, 2, 2, 3]

// Compute the partial sum of squares
auto ssquares = arr.cumulativeFold!((a, b) => a + b * b)(0);
writeln(ssquares.array); // [1, 5, 14, 30, 55]

// Chain multiple ranges into seed
int[] a = [3, 4];
int[] b = [100];
auto r = cumulativeFold!"a + b"(chain(a, b));
writeln(r.array); // [3, 7, 107]

// Mixing convertible types is fair game, too
double[] c = [2.5, 3.0];
auto r1 = cumulativeFold!"a + b"(chain(a, b, c));
assert(approxEqual(r1, [3, 7, 107, 109.5, 112.5]));

// To minimize nesting of parentheses, Uniform Function Call Syntax can be used
auto r2 = chain(a, b, c).cumulativeFold!"a + b";
assert(approxEqual(r2, [3, 7, 107, 109.5, 112.5]));

```
 
 
Examples:
Sometimes it is very useful to compute multiple aggregates in one pass. One advantage is that the computation is faster because the looping overhead is shared. That's why `cumulativeFold` accepts multiple functions. If two or more functions are passed, `cumulativeFold` returns a [`std.typecons.Tuple`](std_typecons#Tuple) object with one member per passed-in function. The number of seeds must be correspondingly increased. 
```
import std.algorithm.comparison : max, min;
import std.algorithm.iteration : map;
import std.math : approxEqual;
import std.typecons : tuple;

double[] a = [3.0, 4, 7, 11, 3, 2, 5];
// Compute minimum and maximum in one pass
auto r = a.cumulativeFold!(min, max);
// The type of r is Tuple!(int, int)
assert(approxEqual(r.map!"a[0]", [3, 3, 3, 3, 3, 2, 2]));     // minimum
assert(approxEqual(r.map!"a[1]", [3, 4, 7, 11, 11, 11, 11])); // maximum

// Compute sum and sum of squares in one pass
auto r2 = a.cumulativeFold!("a + b", "a + b * b")(tuple(0.0, 0.0));
assert(approxEqual(r2.map!"a[0]", [3, 7, 14, 25, 28, 30, 35]));      // sum
assert(approxEqual(r2.map!"a[1]", [9, 25, 74, 195, 204, 208, 233])); // sum of squares

```
 
 
auto **cumulativeFold**(R)(R range)  
 Constraints: if (isInputRange!(Unqual!R)); 
 
No-seed version. The first element of `r` is used as the seed's value. For each function `f` in `fun`, the corresponding seed type `S` is `Unqual!(typeof(f(e, e)))`, where `e` is an element of `r`: `ElementType!R`. Once `S` has been determined, then `S s = e;` and `s = f(s, e);` must both be legal. 



Parameters:


|  |  |
| --- | --- |
| R `range` | An [input range](std_range_primitives#isInputRange) |


 
Returns:
a range containing the consecutive reduced values.
  auto **cumulativeFold**(R, S)(R range, S seed)  
 Constraints: if (isInputRange!(Unqual!R)); 
 
Seed version. The seed should be a single value if `fun` is a single function. If `fun` is multiple functions, then `seed` should be a [`std.typecons.Tuple`](std_typecons#Tuple), with one field per function in `f`. For convenience, if the seed is `const`, or has qualified fields, then `cumulativeFold` will operate on an unqualified copy. If this happens then the returned type will not perfectly match `S`. 



Parameters:


|  |  |
| --- | --- |
| R `range` | An [input range](std_range_primitives#isInputRange) |
| S `seed` | the initial value of the accumulator |


 
Returns:
a range containing the consecutive reduced values.
    auto **splitter**(alias pred = "a == b", Range, Separator)(Range r, Separator s)  
 Constraints: if (is(typeof(binaryFun!pred(r.front, s)) : bool) && (hasSlicing!Range && hasLength!Range || isNarrowString!Range));   
  
auto **splitter**(alias pred = "a == b", Range, Separator)(Range r, Separator s)  
 Constraints: if (is(typeof(binaryFun!pred(r.front, s.front)) : bool) && (hasSlicing!Range || isNarrowString!Range) && isForwardRange!Separator && (hasLength!Separator || isNarrowString!Separator));   
  
auto **splitter**(alias isTerminator, Range)(Range r)  
 Constraints: if (isForwardRange!Range && is(typeof(unaryFun!isTerminator(r.front)))); 
 
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 [`std.functional.binaryFun`](std_functional#binaryFun) and accepts any callable function that can be executed via `pred(element, s)`. 

 
Notes
 If splitting a string on whitespace and token compression is desired, consider using `splitter` without specifying a separator. 
 If no separator is passed, the predicate `isTerminator` decides whether to accept an element of `r`. 
Parameters:


|  |  |
| --- | --- |
| pred | The predicate for comparing each element with the separator, defaulting to `"a == b"`. |
| Range `r` | The [input range](std_range_primitives#isInputRange) to be split. Must support slicing and `.length` or be a narrow string type. |
| Separator `s` | The element (or range) to be treated as the separator between range segments to be split. |
| isTerminator | The predicate for deciding where to split the range when no separator is passed |


 
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 [forward range](std_range_primitives#isForwardRange) or [bidirectional range](std_range_primitives#isBidirectionalRange), the returned range will be likewise. When a range is used a separator, bidirectionality isn't possible. 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:

[`std.regex.splitter`](std_regex#splitter) for a version that splits using a regular expression defined separator and [`std.array.split`](std_array#split) for a version that splits eagerly.
 
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));

```
 
 
Examples:
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));

```
 
 
Examples:
Empty and separator-only ranges. 
```
import std.algorithm.comparison : equal;
import std.range : empty;

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

```
 
 
Examples:
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] ]));

```
 
 
Examples:
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]] ]));

```
 
 
Examples:
Use splitter without a separator 
```
import std.algorithm.comparison : equal;
import std.range.primitives : front;

assert(equal(splitter!(a => a == '|')("a|bc|def"), [ "a", "bc", "def" ]));
assert(equal(splitter!(a => a == ' ')("hello  world"), [ "hello", "", "world" ]));

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

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

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

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

```
 
 
Examples:
Leading separators, trailing separators, or no separators. 
```
import std.algorithm.comparison : equal;

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

```
 
 
Examples:
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" ]));

```
 
 
Examples:
Splitting by word lazily 
```
import std.ascii : isWhite;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : splitter;

string str = "Hello World!";
assert(str.splitter!(isWhite).equal(["Hello", "World!"]));

```
 
  auto **splitter**(Range)(Range s)  
 Constraints: if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range)); 
 
Lazily splits the character-based range `s` into words, using whitespace as the delimiter. 


This function is character-range specific and, contrary to `splitter!(std.uni.isWhite)`, runs of whitespace will be merged together (no empty tokens will be produced). 

 
Parameters:


|  |  |
| --- | --- |
| Range `s` | The character-based range to be split. Must be a string, or a random-access range of character types. |


 
Returns:
An [input range](std_range_primitives#isInputRange) of slices of the original range split by whitespace.
 
Examples:


```
import std.algorithm.comparison : equal;
auto a = " a     bcd   ef gh ";
assert(equal(splitter(a), ["a", "bcd", "ef", "gh"][]));

```
 
  template **substitute**(substs...) if (substs.length >= 2 && isExpressions!substs)  
  
auto **substitute**(alias pred = (a, b) => a == b, R, Substs...)(R r, Substs substs)  
 Constraints: if (isInputRange!R && (Substs.length >= 2) && !is(CommonType!Substs == void)); 
 
Returns a range with all occurrences of `substs` in `r`. replaced with their substitution. 


Single value replacements (`'ö'.substitute!('ä', 'a', 'ö', 'o', 'ü', 'u)`) are supported as well and in Ο(`1`). 

 
Parameters:


|  |  |
| --- | --- |
| R `r` | an [input range](std_range_primitives#isInputRange) |
| Value value | a single value which can be substituted in Ο(`1`) |
| Substs `substs` | a set of replacements/substitutions |
| pred | the equality function to test if element(s) are equal to a substitution |


 
Returns:
a range with the substitutions replaced. 
 
See Also:

[`std.array.replace`](std_array#replace) for an eager replace algorithm or [`std.string.translate`](std_string#translate), and [`std.string.tr`](std_string#tr) for string algorithms with translation tables.
 
Examples:


```
import std.algorithm.comparison : equal;

// substitute single elements
assert("do_it".substitute('_', ' ').equal("do it"));

// substitute multiple, single elements
assert("do_it".substitute('_', ' ',
                           'd', 'g',
                           'i', 't',
                           't', 'o')
              .equal("go to"));

// substitute subranges
assert("do_it".substitute("_", " ",
                          "do", "done")
              .equal("done it"));

// substitution works for any ElementType
int[] x = [1, 2, 3];
auto y = x.substitute(1, 0.1);
assert(y.equal([0.1, 2, 3]));
static assert(is(typeof(y.front) == double));

import std.range : retro;
assert([1, 2, 3].substitute(1, 0.1).retro.equal([3, 2, 0.1]));

```
 
 
Examples:
Use the faster compile-time overload 
```
import std.algorithm.comparison : equal;

// substitute subranges of a range
assert("apple_tree".substitute!("apple", "banana",
                                "tree", "shrub").equal("banana_shrub"));

// substitute subranges of a range
assert("apple_tree".substitute!('a', 'b',
                                't', 'f').equal("bpple_free"));

// substitute values
writeln('a'.substitute!('a', 'b', 't', 'f')); // 'b'

```
 
 
Examples:
Multiple substitutes 
```
import std.algorithm.comparison : equal;
import std.range.primitives : ElementType;

int[3] x = [1, 2, 3];
auto y = x[].substitute(1, 0.1)
            .substitute(0.1, 0.2);
static assert(is(typeof(y.front) == double));
assert(y.equal([0.2, 2, 3]));

auto z = "42".substitute('2', '3')
             .substitute('3', '1');
static assert(is(ElementType!(typeof(z)) == dchar));
assert(equal(z, "41"));

```
 
 
auto **substitute**(Value)(Value value)  
 Constraints: if (isInputRange!Value || !is(CommonType!(Value, typeof(substs[0])) == void)); 
 
Substitute single values with compile-time substitution mappings. 



Complexity
 Ο(`1`) due to D's `switch` guaranteeing Ο(`1`);
    auto **sum**(R)(R r)  
 Constraints: if (isInputRange!R && !isInfinite!R && is(typeof(r.front + r.front)));   
  
auto **sum**(R, E)(R r, E seed)  
 Constraints: if (isInputRange!R && !isInfinite!R && is(typeof(seed = seed + r.front))); 
 
Sums elements of `r`, which must be a finite [input range](std_range_primitives#isInputRange). Although conceptually `sum(r)` is equivalent to [`fold`](#fold)!((a, b) => a + b)(r, 0), `sum` uses specialized algorithms to maximize accuracy, as follows. 


* If [`std.range.primitives.ElementType`](std_range_primitives#ElementType)!R is a floating-point type and `R` is a [random-access range](std_range_primitives#isRandomAccessRange) with length and slicing, then `sum` uses the [pairwise summation](http://en.wikipedia.org/wiki/Pairwise_summation) algorithm.
* If `ElementType!R` is a floating-point type and `R` is a finite input range (but not a random-access range with slicing), then `sum` uses the [Kahan summation](http://en.wikipedia.org/wiki/Kahan_summation) algorithm.
* In all other cases, a simple element by element addition is done.

   
  
 For floating point inputs, calculations are made in [`real`](https://dlang.org/spec/type.html) precision for `real` inputs and in `double` precision otherwise (Note this is a special case that deviates from `fold`'s behavior, which would have kept `float` precision for a `float` range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of [integral promotion](https://dlang.org/spec/type.html#integer-promotions)).   
  
 A seed may be passed to `sum`. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of `typeof(r.front + r.front)(0)`, or `typeof(r.front + r.front).zero` if no constructor exists that takes an int.   
  
 Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use `fold!((a, b) => a + b)(r, 0)`, which is not specialized for summation. 

 
Parameters:


|  |  |
| --- | --- |
| E `seed` | the initial value of the summation |
| R `r` | a finite input range |


 
Returns:
The sum of all the elements in the range r.
 
Examples:
Ditto 
```
import std.range;

//simple integral sumation
writeln(sum([1, 2, 3, 4])); // 10

//with integral promotion
writeln(sum([false, true, true, false, true])); // 3
writeln(sum(ubyte.max.repeat(100))); // 25500

//The result may overflow
writeln(uint.max.repeat(3).sum()); // 4294967293U
//But a seed can be used to change the sumation primitive
writeln(uint.max.repeat(3).sum(ulong.init)); // 12884901885UL

//Floating point sumation
writeln(sum([1.0, 2.0, 3.0, 4.0])); // 10

//Floating point operations have double precision minimum
static assert(is(typeof(sum([1F, 2F, 3F, 4F])) == double));
writeln(sum([1F, 2, 3, 4])); // 10

//Force pair-wise floating point sumation on large integers
import std.math : approxEqual;
assert(iota(ulong.max / 2, ulong.max / 2 + 4096).sum(0.0)
           .approxEqual((ulong.max / 2) * 4096.0 + 4096^^2 / 2));

```
 
  T **mean**(T = double, R)(R r)  
 Constraints: if (isInputRange!R && isNumeric!(ElementType!R) && !isInfinite!R);   
  
auto **mean**(R, T)(R r, T seed)  
 Constraints: if (isInputRange!R && !isNumeric!(ElementType!R) && is(typeof(r.front + seed)) && is(typeof(r.front / size\_t(1))) && !isInfinite!R); 
 
Finds the mean (colloquially known as the average) of a range. 


For built-in numerical types, accurate Knuth & Welford mean calculation is used. For user-defined types, element by element summation is used. Additionally an extra parameter `seed` is needed in order to correctly seed the summation with the equivalent to `0`.   
  
 The first overload of this function will return `T.init` if the range is empty. However, the second overload will return `seed` on empty ranges.   
  
 This function is Ο(`r.length`). 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of the return value. |
| R `r` | An [input range](std_range_primitives#isInputRange) |
| T `seed` | For user defined types. Should be equivalent to `0`. |


 
Returns:
The mean of `r` when `r` is non-empty.
 
Examples:


```
import std.math : approxEqual, isNaN;

static immutable arr1 = [1, 2, 3];
static immutable arr2 = [1.5, 2.5, 12.5];

assert(arr1.mean.approxEqual(2));
assert(arr2.mean.approxEqual(5.5));

assert(arr1[0 .. 0].mean.isNaN);

```
 
  auto **uniq**(alias pred = "a == b", Range)(Range r)  
 Constraints: if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, r.front)) == bool)); 
 
Lazily iterates unique consecutive elements of the given range (functionality akin to the [uniq](http://wikipedia.org/wiki/Uniq) system utility). Equivalence of elements is assessed by using the predicate `pred`, by default `"a == b"`. The predicate is passed to [`std.functional.binaryFun`](std_functional#binaryFun), and can either accept a string, or any callable that can be executed via `pred(element, element)`. If the given range is bidirectional, `uniq` also yields a [bidirectional range](std_range_primitives#isBidirectionalRange). 



Parameters:


|  |  |
| --- | --- |
| pred | Predicate for determining equivalence between range elements. |
| Range `r` | An [input range](std_range_primitives#isInputRange) of elements to filter. |


 
Returns:
An [input range](std_range_primitives#isInputRange) of consecutively unique elements in the original range. If `r` is also a forward range or bidirectional range, the returned range will be likewise.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.mutation : copy;

int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][]));

// Filter duplicates in-place using copy
arr.length -= arr.uniq().copy(arr).length;
writeln(arr); // [1, 2, 3, 4, 5]

// Note that uniqueness is only determined consecutively; duplicated
// elements separated by an intervening different element will not be
// eliminated:
assert(equal(uniq([ 1, 1, 2, 1, 1, 3, 1]), [1, 2, 1, 3, 1]));

```
 
  Permutations!Range **permutations**(Range)(Range r)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range);   
  
struct **Permutations**(Range) if (isRandomAccessRange!Range && hasLength!Range);  
Lazily computes all permutations of `r` using [Heap's algorithm](http://en.wikipedia.org/wiki/Heap%27s_algorithm). 



Parameters:


|  |  |
| --- | --- |
| Range | the range type |
| Range `r` | the [random access range](std_range_primitives#isRandomAccessRange) to find the permutations for. |


 
Returns:
A [forward range](std_range_primitives#isForwardRange) of elements of which are an [`std.range.indexed`](std_range#indexed) view into `r`. 
 
See Also:

[`std.algorithm.sorting.nextPermutation`](std_algorithm_sorting#nextPermutation).
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
assert(equal!equal(iota(3).permutations,
    [[0, 1, 2],
     [1, 0, 2],
     [2, 0, 1],
     [0, 2, 1],
     [1, 2, 0],
     [2, 1, 0]]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_iteration.html>

std.container.slist
===================

 This module implements a singly-linked list container. It can be used as a stack. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/slist.d](https://github.com/dlang/phobos/blob/master/std/container/slist.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.container : SList;

auto s = SList!int(1, 2, 3);
assert(equal(s[], [1, 2, 3]));

s.removeFront();
assert(equal(s[], [2, 3]));

s.insertFront([5, 6]);
assert(equal(s[], [5, 6, 2, 3]));

// If you want to apply range operations, simply slice it.
import std.algorithm.searching : countUntil;
import std.range : popFrontN, walkLength;

auto sl = SList!int(1, 2, 3, 4, 5);
writeln(countUntil(sl[], 2)); // 1

auto r = sl[];
popFrontN(r, 2);
writeln(walkLength(r)); // 3

```
 
 
struct **SList**(T) if (!is(T == shared));  
Implements a simple and fast singly-linked list. It can be used as a stack. 


`SList` uses reference semantics.

 
this(U)(U[] values...)  
 Constraints: if (isImplicitlyConvertible!(U, T)); 
 
Constructor taking a number of nodes

  this(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T) && !is(Stuff == T[])); 
 
Constructor taking an [input range](std_range_primitives#isInputRange)

  const bool **opEquals**(const SList rhs);   
  
const bool **opEquals**(ref const SList rhs);  
Comparison for equality. 



Complexity
 Ο(`min(n, n1)`) where `n1` is the number of elements in `rhs`.
  struct **Range**;  
Defines the container's primary range, which embodies a forward range.

 
const @property bool **empty**();   
  
@property ref T **front**();   
  
void **popFront**();  
Input range primitives.

  @property Range **save**();  
Forward range primitive.

    const @property bool **empty**();  
Property returning `true` if and only if the container has no elements. 



Complexity
 Ο(`1`)

  @property SList **dup**();  
Duplicates the container. The elements themselves are not transitively duplicated. 



Complexity
 Ο(`n`).
  Range **opSlice**();  
Returns a range that iterates over all elements of the container, in forward order. 



Complexity
 Ο(`1`)

  @property ref T **front**();  
Forward to `opSlice().front`. 



Complexity
 Ο(`1`)

  SList **opBinary**(string op, Stuff)(Stuff rhs)  
 Constraints: if (op == "~" && is(typeof(SList(rhs))));   
  
SList **opBinaryRight**(string op, Stuff)(Stuff lhs)  
 Constraints: if (op == "~" && !is(typeof(lhs.opBinary!"~"(this))) && is(typeof(SList(lhs)))); 
 
Returns a new `SList` that's the concatenation of `this` and its argument. `opBinaryRight` is only defined if `Stuff` does not define `opBinary`.

  void **clear**();  
Removes all contents from the `SList`. 



Postcondition
 `empty` 
 
Complexity
 Ο(`1`)

  void **reverse**();  
Reverses SList in-place. Performs no memory allocation. 



Complexity
 Ο(`n`)

  size\_t **insertFront**(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T));   
  
alias **insert** = insertFront;   
  
alias **stableInsert** = insert;   
  
alias **stableInsertFront** = insertFront;  
Inserts `stuff` to the front of the container. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Returns:
The number of elements inserted 
 
Complexity
 Ο(`m`), where `m` is the length of `stuff`

  T **removeAny**();   
  
alias **stableRemoveAny** = removeAny;  
Picks one value in an unspecified position in the container, removes it from the container, and returns it. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Precondition
 `!empty` 
 
Returns:
The element removed. 
 
Complexity
 Ο(`1`).
  void **removeFront**();   
  
alias **stableRemoveFront** = removeFront;  
Removes the value at the front of the container. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Precondition
 `!empty` 
 
Complexity
 Ο(`1`).
  size\_t **removeFront**(size\_t howMany);   
  
alias **stableRemoveFront** = removeFront;  
Removes `howMany` values at the front or back of the container. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Returns:
The number of elements removed 
 
Complexity
 Ο(`howMany * log(n)`).
  size\_t **insertAfter**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T)); 
 
Inserts `stuff` after range `r`, which must be a range previously extracted from this container. Given that all ranges for a list end at the end of the list, this function essentially appends to the list and uses `r` as a potentially fast way to reach the last node in the list. Ideally `r` is positioned near or at the last element of the list. 


`stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 

 
Returns:
The number of values inserted. 
 
Complexity
 Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`. 
 
Example


```
auto sl = SList!string(["a", "b", "d"]);
sl.insertAfter(sl[], "e"); // insert at the end (slowest)
assert(std.algorithm.equal(sl[], ["a", "b", "d", "e"]));
sl.insertAfter(std.range.take(sl[], 2), "c"); // insert after "b"
assert(std.algorithm.equal(sl[], ["a", "b", "c", "d", "e"]));

```
  size\_t **insertAfter**(Stuff)(Take!Range r, Stuff stuff)  
 Constraints: if (isInputRange!Stuff || isImplicitlyConvertible!(Stuff, T));   
  
alias **stableInsertAfter** = insertAfter;  
Similar to `insertAfter` above, but accepts a range bounded in count. This is important for ensuring fast insertions in the middle of the list. For fast insertions after a specified position `r`, use `insertAfter(take(r, 1), stuff)`. The complexity of that operation only depends on the number of elements in `stuff`. 



Precondition
 `r.original.empty || r.maxLength > 0` 
 
Returns:
The number of values inserted. 
 
Complexity
 Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`.
  Range **linearRemove**(Range r);  
Removes a range from the list in linear time. 



Returns:
An empty range. 
 
Complexity
 Ο(`n`)

  Range **linearRemove**(Take!Range r);   
  
alias **stableLinearRemove** = linearRemove;  
Removes a `Take!Range` from the list in linear time. 



Returns:
A range comprehending the elements after the removed range. 
 
Complexity
 Ο(`n`)

  bool **linearRemoveElement**(T value);  
Removes the first occurence of an element from the list in linear time. 



Returns:
True if the element existed and was successfully removed, false otherwise. 
 
Parameters:


|  |  |
| --- | --- |
| T `value` | value of the node to be removed |


 
Complexity
 Ο(`n`)

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_slist.html>

std.algorithm.sorting
=====================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic sorting algorithms. 


 

Cheat Sheet| Function Name | Description |
| [`completeSort`](#completeSort) |  If `a = [10, 20, 30]` and `b = [40, 6, 15]`, then `completeSort(a, b)` leaves `a = [6, 10, 15]` and `b = [20, 30, 40]`. The range `a` must be sorted prior to the call, and as a result the combination `[std.range.chain](std_range#chain)(a, b)` is sorted. |
| [`isPartitioned`](#isPartitioned) | `isPartitioned!"a < 0"([-1, -2, 1, 0, 2])` returns `true` because the predicate is `true` for a portion of the range and `false` afterwards. |
| [`isSorted`](#isSorted) | `isSorted([1, 1, 2, 3])` returns `true`. |
| [`isStrictlyMonotonic`](#isStrictlyMonotonic) | `isStrictlyMonotonic([1, 1, 2, 3])` returns `false`. |
| [`ordered`](#ordered) | `ordered(1, 1, 2, 3)` returns `true`. |
| [`strictlyOrdered`](#strictlyOrdered) | `strictlyOrdered(1, 1, 2, 3)` returns `false`. |
| [`makeIndex`](#makeIndex) |  Creates a separate index for a range. |
| [`merge`](#merge) |  Lazily merges two or more sorted ranges. |
| [`multiSort`](#multiSort) |  Sorts by multiple keys. |
| [`nextEvenPermutation`](#nextEvenPermutation) |  Computes the next lexicographically greater even permutation of a range in-place. |
| [`nextPermutation`](#nextPermutation) |  Computes the next lexicographically greater permutation of a range in-place. |
| [`nthPermutation`](#nthPermutation) |  Computes the nth permutation of a range in-place. |
| [`partialSort`](#partialSort) |  If `a = [5, 4, 3, 2, 1]`, then `partialSort(a, 3)` leaves `a[0 .. 3] = [1, 2, 3]`. The other elements of `a` are left in an unspecified order. |
| [`partition`](#partition) |  Partitions a range according to a unary predicate. |
| [`partition3`](#partition3) |  Partitions a range according to a binary predicate in three parts (less than, equal, greater than the given pivot). Pivot is not given as an index, but instead as an element independent from the range's content. |
| [`pivotPartition`](#pivotPartition) |  Partitions a range according to a binary predicate in two parts: less than or equal, and greater than or equal to the given pivot, passed as an index in the range. |
| [`schwartzSort`](#schwartzSort) |  Sorts with the help of the [Schwartzian transform](https://en.wikipedia.org/wiki/Schwartzian_transform). |
| [`sort`](#sort) |  Sorts. |
| [`topN`](#topN) |  Separates the top elements in a range. |
| [`topNCopy`](#topNCopy) |  Copies out the top elements of a range. |
| [`topNIndex`](#topNIndex) |  Builds an index of the top elements of a range. |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/sorting.d](https://github.com/dlang/phobos/blob/master/std/algorithm/sorting.d) 
 
alias **SortOutput** = std.typecons.Flag!"sortOutput".Flag;  
Specifies whether the output of certain algorithm is desired in sorted format. 


If set to `SortOutput.no`, the output should not be sorted.   
  
 Otherwise if set to `SortOutput.yes`, the output should be sorted.

  void **completeSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Lhs, Rhs)(SortedRange!(Lhs, less) lhs, Rhs rhs)  
 Constraints: if (hasLength!Rhs && hasSlicing!Rhs && hasSwappableElements!Lhs && hasSwappableElements!Rhs); 
 
Sorts the random-access range `chain(lhs, rhs)` according to predicate `less`. The left-hand side of the range `lhs` is assumed to be already sorted; `rhs` is assumed to be unsorted. The exact strategy chosen depends on the relative sizes of `lhs` and `rhs`. Performs Ο(`lhs.length + rhs.length * log(rhs.length)`) (best case) to Ο(`(lhs.length + rhs.length) * log(lhs.length + rhs.length)`) (worst-case) evaluations of `swap`. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| SortedRange!(Lhs, less) `lhs` | The sorted, left-hand side of the random access range to be sorted. |
| Rhs `rhs` | The unsorted, right-hand side of the random access range to be sorted. |


 
Examples:


```
import std.range : assumeSorted;
int[] a = [ 1, 2, 3 ];
int[] b = [ 4, 0, 6, 5 ];
completeSort(assumeSorted(a), b);
writeln(a); // [0, 1, 2]
writeln(b); // [3, 4, 5, 6]

```
 
  bool **isSorted**(alias less = "a < b", Range)(Range r)  
 Constraints: if (isForwardRange!Range);   
  
bool **isStrictlyMonotonic**(alias less = "a < b", Range)(Range r)  
 Constraints: if (isForwardRange!Range); 
 
Checks whether a [forward range](std_range_primitives#isForwardRange) is sorted according to the comparison operation `less`. Performs Ο(`r.length`) evaluations of `less`. 


Unlike `isSorted`, `isStrictlyMonotonic` does not allow for equal values, i.e. values for which both `less(a, b)` and `less(b, a)` are false.   
  
 With either function, the predicate must be a strict ordering just like with `isSorted`. For example, using `"a <= b"` instead of `"a < b"` is incorrect and will cause failed assertions. 

 
Parameters:


|  |  |
| --- | --- |
| less | Predicate the range should be sorted by. |
| Range `r` | Forward range to check for sortedness. |


 
Returns:

`true` if the range is sorted, false otherwise. `isSorted` allows duplicates, `isStrictlyMonotonic` not.
 
Examples:


```
assert([1, 1, 2].isSorted);
// strictly monotonic doesn't allow duplicates
assert(![1, 1, 2].isStrictlyMonotonic);

int[] arr = [4, 3, 2, 1];
assert(!isSorted(arr));
assert(!isStrictlyMonotonic(arr));

assert(isSorted!"a > b"(arr));
assert(isStrictlyMonotonic!"a > b"(arr));

sort(arr);
assert(isSorted(arr));
assert(isStrictlyMonotonic(arr));

```
 
  bool **ordered**(alias less = "a < b", T...)(T values)  
 Constraints: if (T.length == 2 && is(typeof(binaryFun!less(values[1], values[0])) : bool) || T.length > 2 && is(typeof(ordered!less(values[0..1 + $ / 2]))) && is(typeof(ordered!less(values[$ / 2..$]))));   
  
bool **strictlyOrdered**(alias less = "a < b", T...)(T values)  
 Constraints: if (is(typeof(ordered!less(values)))); 
 
Like `isSorted`, returns `true` if the given `values` are ordered according to the comparison operation `less`. Unlike `isSorted`, takes values directly instead of structured in a range. 


`ordered` allows repeated values, e.g. `ordered(1, 1, 2)` is `true`. To verify that the values are ordered strictly monotonically, use `strictlyOrdered`; `strictlyOrdered(1, 1, 2)` is `false`.   
  
 With either function, the predicate must be a strict ordering. For example, using `"a <= b"` instead of `"a < b"` is incorrect and will cause failed assertions. 

 
Parameters:


|  |  |
| --- | --- |
| T `values` | The tested value |
| less | The comparison predicate |


 
Returns:

`true` if the values are ordered; `ordered` allows for duplicates, `strictlyOrdered` does not.
 
Examples:


```
assert(ordered(42, 42, 43));
assert(!strictlyOrdered(43, 42, 45));
assert(ordered(42, 42, 43));
assert(!strictlyOrdered(42, 42, 43));
assert(!ordered(43, 42, 45));
// Ordered lexicographically
assert(ordered("Jane", "Jim", "Joe"));
assert(strictlyOrdered("Jane", "Jim", "Joe"));
// Incidentally also ordered by length decreasing
assert(ordered!((a, b) => a.length > b.length)("Jane", "Jim", "Joe"));
// ... but not strictly so: "Jim" and "Joe" have the same length
assert(!strictlyOrdered!((a, b) => a.length > b.length)("Jane", "Jim", "Joe"));

```
 
  Range **partition**(alias predicate, SwapStrategy ss, Range)(Range r)  
 Constraints: if (ss == SwapStrategy.stable && isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasSwappableElements!Range);   
  
Range **partition**(alias predicate, SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)  
 Constraints: if (ss != SwapStrategy.stable && isInputRange!Range && hasSwappableElements!Range); 
 
Partitions a range in two using the given `predicate`. Specifically, reorders the range `r = [left, right)` using `swap` such that all elements `i` for which `predicate(i)` is `true` come before all elements `j` for which `predicate(j)` returns `false`. 


Performs Ο(`r.length`) (if unstable or semistable) or Ο(`r.length * log(r.length)`) (if stable) evaluations of `less` and `swap`. The unstable version computes the minimum possible evaluations of `swap` (roughly half of those performed by the semistable version). 

 
Parameters:


|  |  |
| --- | --- |
| predicate | The predicate to partition by. |
| ss | The swapping strategy to employ. |
| Range `r` | The random-access range to partition. |


 
Returns:
The right part of `r` after partitioning. If `ss == SwapStrategy.stable`, `partition` preserves the relative ordering of all elements `a`, `b` in `r` for which `predicate(a) == predicate(b)`. If `ss == SwapStrategy.semistable`, `partition` preserves the relative ordering of all elements `a`, `b` in the left part of `r` for which `predicate(a) == predicate(b)`.
 
Examples:


```
import std.algorithm.mutation : SwapStrategy;
import std.algorithm.searching : count, find;
import std.conv : text;
import std.range.primitives : empty;

auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto arr = Arr.dup;
static bool even(int a) { return (a & 1) == 0; }
// Partition arr such that even numbers come first
auto r = partition!(even)(arr);
// Now arr is separated in evens and odds.
// Numbers may have become shuffled due to instability
writeln(r); // arr[5 .. &dollar;]
writeln(count!(even)(arr[0 .. 5])); // 5
assert(find!(even)(r).empty);

// Can also specify the predicate as a string.
// Use 'a' as the predicate argument name
arr[] = Arr[];
r = partition!(q{(a & 1) == 0})(arr);
writeln(r); // arr[5 .. &dollar;]

// Now for a stable partition:
arr[] = Arr[];
r = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr);
// Now arr is [2 4 6 8 10 1 3 5 7 9], and r points to 1
assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] && r == arr[5 .. $]);

// In case the predicate needs to hold its own state, use a delegate:
arr[] = Arr[];
int x = 3;
// Put stuff greater than 3 on the left
bool fun(int a) { return a > x; }
r = partition!(fun, SwapStrategy.semistable)(arr);
// Now arr is [4 5 6 7 8 9 10 2 3 1] and r points to 2
assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && r == arr[7 .. $]);

```
 
  size\_t **pivotPartition**(alias less = "a < b", Range)(Range r, size\_t pivot)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasAssignableElements!Range); 
 
Partitions `r` around `pivot` using comparison function `less`, algorithm akin to [Hoare partition](https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme). Specifically, permutes elements of `r` and returns an index `k < r.length` such that: 


  
  
* `r[pivot]` is swapped to `r[k]`
  
  
* All elements `e` in subrange `r[0 .. k]` satisfy `!less(r[k], e)` (i.e. `r[k]` is greater than or equal to each element to its left according to predicate `less`)
  
  
* All elements `e` in subrange `r[k .. $]` satisfy `!less(e, r[k])` (i.e. `r[k]` is less than or equal to each element to its right according to predicate `less`)

   
  
 If `r` contains equivalent elements, multiple permutations of `r` satisfy these constraints. In such cases, `pivotPartition` attempts to distribute equivalent elements fairly to the left and right of `k` such that `k` stays close to `r.length / 2`. 

 
Parameters:


|  |  |
| --- | --- |
| less | The predicate used for comparison, modeled as a  [strict weak ordering](https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings) (irreflexive, antisymmetric, transitive, and implying a transitive equivalence) |
| Range `r` | The range being partitioned |
| size\_t `pivot` | The index of the pivot for partitioning, must be less than `r.length` or `0` if `r.length` is `0` |


 
Returns:
The new position of the pivot 
 
See Also:

[Engineering of a Quicksort Partitioning Algorithm](http://jgrcs.info/index.php/jgrcs/article/view/142), D. Abhyankar, Journal of Global Research in Computer Science, February 2011. [ACCU 2016 Keynote](https://youtube.com/watch?v=AxnotgLql0k), Andrei Alexandrescu.
 
Examples:


```
int[] a = [5, 3, 2, 6, 4, 1, 3, 7];
size_t pivot = pivotPartition(a, a.length / 2);
import std.algorithm.searching : all;
assert(a[0 .. pivot].all!(x => x <= a[pivot]));
assert(a[pivot .. $].all!(x => x >= a[pivot]));

```
 
  bool **isPartitioned**(alias pred, Range)(Range r)  
 Constraints: if (isForwardRange!Range); 
 

Parameters:


|  |  |
| --- | --- |
| pred | The predicate that the range should be partitioned by. |
| Range `r` | The range to check. |


 
Returns:

`true` if `r` is partitioned according to predicate `pred`.
 
Examples:


```
int[] r = [ 1, 3, 5, 7, 8, 2, 4, ];
assert(isPartitioned!"a & 1"(r));

```
 
  auto **partition3**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E)(Range r, E pivot)  
 Constraints: if (ss == SwapStrategy.unstable && isRandomAccessRange!Range && hasSwappableElements!Range && hasLength!Range && hasSlicing!Range && is(typeof(binaryFun!less(r.front, pivot)) == bool) && is(typeof(binaryFun!less(pivot, r.front)) == bool) && is(typeof(binaryFun!less(r.front, r.front)) == bool)); 
 
Rearranges elements in `r` in three adjacent ranges and returns them. The first and leftmost range only contains elements in `r` less than `pivot`. The second and middle range only contains elements in `r` that are equal to `pivot`. Finally, the third and rightmost range only contains elements in `r` that are greater than `pivot`. The less-than test is defined by the binary function `less`. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to use for the rearrangement. |
| ss | The swapping strategy to use. |
| Range `r` | The random-access range to rearrange. |
| E `pivot` | The pivot element. |


 
Returns:
A [`std.typecons.Tuple`](std_typecons#Tuple) of the three resulting ranges. These ranges are slices of the original range. 
 
Bugs:
stable `partition3` has not been implemented yet.
 
Examples:


```
auto a = [ 8, 3, 4, 1, 4, 7, 4 ];
auto pieces = partition3(a, 4);
writeln(pieces[0]); // [1, 3]
writeln(pieces[1]); // [4, 4, 4]
writeln(pieces[2]); // [8, 7]

```
 
  SortedRange!(RangeIndex, (a, b) => binaryFun!less(\*a, \*b)) **makeIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index)  
 Constraints: if (isForwardRange!Range && isRandomAccessRange!RangeIndex && is(ElementType!RangeIndex : ElementType!Range\*) && hasAssignableElements!RangeIndex);   
  
void **makeIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index)  
 Constraints: if (isRandomAccessRange!Range && !isInfinite!Range && isRandomAccessRange!RangeIndex && !isInfinite!RangeIndex && isIntegral!(ElementType!RangeIndex) && hasAssignableElements!RangeIndex); 
 
Computes an index for `r` based on the comparison `less`. The index is a sorted array of pointers or indices into the original range. This technique is similar to sorting, but it is more flexible because (1) it allows "sorting" of immutable collections, (2) allows binary search even if the original collection does not offer random access, (3) allows multiple indexes, each on a different predicate, and (4) may be faster when dealing with large objects. However, using an index may also be slower under certain circumstances due to the extra indirection, and is always larger than a sorting-based solution because it needs space for the index in addition to the original collection. The complexity is the same as `sort`'s. 


The first overload of `makeIndex` writes to a range containing pointers, and the second writes to a range containing offsets. The first overload requires `Range` to be a [forward range](std_range_primitives#isForwardRange), and the latter requires it to be a random-access range.   
  
 `makeIndex` overwrites its second argument with the result, but never reallocates it. 

 
Parameters:


|  |  |
| --- | --- |
| less | The comparison to use. |
| ss | The swapping strategy. |
| Range `r` | The range to index. |
| RangeIndex `index` | The resulting index. |


 
Returns:
The pointer-based version returns a `SortedRange` wrapper over index, of type `SortedRange!(RangeIndex, (a, b) => binaryFun!less(*a, *b))` thus reflecting the ordering of the index. The index-based version returns `void` because the ordering relation involves not only `index` but also `r`. 
 
Throws:
If the second argument's length is less than that of the range indexed, an exception is thrown.
 
Examples:


```
immutable(int[]) arr = [ 2, 3, 1, 5, 0 ];
// index using pointers
auto index1 = new immutable(int)*[arr.length];
makeIndex!("a < b")(arr, index1);
assert(isSorted!("*a < *b")(index1));
// index using offsets
auto index2 = new size_t[arr.length];
makeIndex!("a < b")(arr, index2);
assert(isSorted!
    ((size_t a, size_t b){ return arr[a] < arr[b];})
    (index2));

```
 
  Merge!(less, Rs) **merge**(alias less = "a < b", Rs...)(Rs rs)  
 Constraints: if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) && !is(CommonType!(staticMap!(ElementType, Rs)) == void)); 
 
Merge multiple sorted ranges `rs` with less-than predicate function `pred` into one single sorted output range containing the sorted union of the elements of inputs. Duplicates are not eliminated, meaning that the total number of elements in the output is the sum of all elements in the ranges passed to it; the `length` member is offered if all inputs also have `length`. The element types of all the inputs must have a common type `CommonType`. 



Parameters:


|  |  |
| --- | --- |
| less | Predicate the given ranges are sorted by. |
| Rs `rs` | The ranges to compute the union for. |


 
Returns:
A range containing the union of the given ranges. 
 
Details
 All of its inputs are assumed to be sorted. This can mean that inputs are instances of [`std.range.SortedRange`](std_range#SortedRange). Use the result of  [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort), or [`std.range.assumeSorted`](std_range#assumeSorted) to merge ranges known to be sorted (show in the example below). Note that there is currently no way of ensuring that two or more instances of  [`std.range.SortedRange`](std_range#SortedRange) are sorted using a specific comparison function `pred`. Therefore no checking is done here to assure that all inputs `rs` are instances of [`std.range.SortedRange`](std_range#SortedRange). 
 This algorithm is lazy, doing work progressively as elements are pulled off the result. Time complexity is proportional to the sum of element counts over all inputs. If all inputs have the same element type and offer it by `ref`, output becomes a range with mutable `front` (and `back` where appropriate) that reflects in the original inputs. If any of the inputs `rs` is infinite so is the result (`empty` being always `false`). 
See Also:

[`std.algorithm.setops.multiwayMerge`](std_algorithm_setops#multiwayMerge) for an analogous function that merges a dynamic number of ranges.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : retro;

int[] a = [1, 3, 5];
int[] b = [2, 3, 4];

assert(a.merge(b).equal([1, 2, 3, 3, 4, 5]));
assert(a.merge(b).retro.equal([5, 4, 3, 3, 2, 1]));

```
 
 
Examples:
test bi-directional access and common type 
```
import std.algorithm.comparison : equal;
import std.range : retro;
import std.traits : CommonType;

alias S = short;
alias I = int;
alias D = double;

S[] a = [1, 2, 3];
I[] b = [50, 60];
D[] c = [10, 20, 30, 40];

auto m = merge(a, b, c);

static assert(is(typeof(m.front) == CommonType!(S, I, D)));

assert(equal(m, [1, 2, 3, 10, 20, 30, 40, 50, 60]));
assert(equal(m.retro, [60, 50, 40, 30, 20, 10, 3, 2, 1]));

m.popFront();
assert(equal(m, [2, 3, 10, 20, 30, 40, 50, 60]));
m.popBack();
assert(equal(m, [2, 3, 10, 20, 30, 40, 50]));
m.popFront();
assert(equal(m, [3, 10, 20, 30, 40, 50]));
m.popBack();
assert(equal(m, [3, 10, 20, 30, 40]));
m.popFront();
assert(equal(m, [10, 20, 30, 40]));
m.popBack();
assert(equal(m, [10, 20, 30]));
m.popFront();
assert(equal(m, [20, 30]));
m.popBack();
assert(equal(m, [20]));
m.popFront();
assert(m.empty);

```
 
  template **multiSort**(less...) 
Sorts a range by multiple keys. The call `multiSort!("a.id < b.id", "a.date > b.date")(r)` sorts the range `r` by `id` ascending, and sorts elements that have the same `id` by `date` descending. Such a call is equivalent to `sort!"a.id != b.id ? a.id < b.id : a.date > b.date"(r)`, but `multiSort` is faster because it does fewer comparisons (in addition to being more convenient). 



Returns:
The initial range wrapped as a `SortedRange` with its predicates converted to an equivalent single predicate.
 
Examples:


```
import std.algorithm.mutation : SwapStrategy;
static struct Point { int x, y; }
auto pts1 = [ Point(0, 0), Point(5, 5), Point(0, 1), Point(0, 2) ];
auto pts2 = [ Point(0, 0), Point(0, 1), Point(0, 2), Point(5, 5) ];
multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1);
writeln(pts1); // pts2

```
 
  SortedRange!(Range, less) **sort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)  
 Constraints: if ((ss == SwapStrategy.unstable && (hasSwappableElements!Range || hasAssignableElements!Range) || ss != SwapStrategy.unstable && hasAssignableElements!Range) && isRandomAccessRange!Range && hasSlicing!Range && hasLength!Range); 
 
Sorts a random-access range according to the predicate `less`. Performs Ο(`r.length * log(r.length)`) evaluations of `less`. If `less` involves expensive computations on the sort key, it may be worthwhile to use [`schwartzSort`](#schwartzSort) instead. 


Stable sorting requires `hasAssignableElements!Range` to be true.   
  
 `sort` returns a [`std.range.SortedRange`](std_range#SortedRange) over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The [`std.range.SortedRange`](std_range#SortedRange) is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they *can* know that [`std.range.SortedRange`](std_range#SortedRange) has been sorted. 

 
Preconditions
 The predicate is expected to satisfy certain rules in order for `sort` to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory `assumeSorted` check. Specifically, `sort` expects `less(a,b) && less(b,c)` to imply `less(a,c)` (transitivity), and, conversely, `!less(a,b) && !less(b,c)` to imply `!less(a,c)`. Note that the default predicate (`"a < b"`) does not always satisfy these conditions for floating point types, because the expression will always be `false` when either `a` or `b` is NaN. Use [`std.math.cmp`](std_math#cmp) instead. 
 
Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| Range `r` | The range to sort. |


 
Returns:
The initial range wrapped as a `SortedRange` with the predicate `binaryFun!less`. 
 
Algorithms
 [Introsort](http://en.wikipedia.org/wiki/Introsort) is used for unstable sorting and [Timsort](http://en.wikipedia.org/wiki/Timsort) is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have Ο(`n log n`) worst-case time complexity. 
 
See Also:

[`std.range.assumeSorted`](std_range#assumeSorted)  
 [`std.range.SortedRange`](std_range#SortedRange)  
 [`std.algorithm.mutation.SwapStrategy`](std_algorithm_mutation#SwapStrategy)  
 [`std.functional.binaryFun`](std_functional#binaryFun)

 
Examples:


```
int[] array = [ 1, 2, 3, 4 ];

// sort in descending order
array.sort!("a > b");
writeln(array); // [4, 3, 2, 1]

// sort in ascending order
array.sort();
writeln(array); // [1, 2, 3, 4]

// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
writeln(array.sort!(myComp).release); // [4, 3, 2, 1]

```
 
 
Examples:


```
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
writeln(words); // ["a", "aBc", "abc", "ABC", "b", "c"]

```
 
 
Examples:


```
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];

import std.algorithm.comparison : equal;
import std.math : cmp, isIdentical;

sort!((a, b) => cmp(a, b) < 0)(numbers);

double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));

```
 
  SortedRange!(R, (a, b) => binaryFun!less(unaryFun!transform(a), unaryFun!transform(b))) **schwartzSort**(alias transform, alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, R)(R r)  
 Constraints: if (isRandomAccessRange!R && hasLength!R && hasSwappableElements!R && !is(typeof(binaryFun!less) == SwapStrategy));   
  
auto **schwartzSort**(alias transform, SwapStrategy ss, R)(R r)  
 Constraints: if (isRandomAccessRange!R && hasLength!R && hasSwappableElements!R); 
 
Alternative sorting method that should be used when comparing keys involves an expensive computation. Instead of using `less(a, b)` for comparing elements, `schwartzSort` uses `less(transform(a), transform(b))`. The values of the `transform` function are precomputed in a temporary array, thus saving on repeatedly computing it. Conversely, if the cost of `transform` is small compared to the cost of allocating and filling the precomputed array, `sort` may be faster and therefore preferable. 


This approach to sorting is akin to the [Schwartzian transform](http://wikipedia.org/wiki/Schwartzian_transform), also known as the decorate-sort-undecorate pattern in Python and Lisp. The complexity is the same as that of the corresponding `sort`, but `schwartzSort` evaluates `transform` only `r.length` times (less than half when compared to regular sorting). The usage can be best illustrated with an example. 

 
Example


```
uint hashFun(string) { ... expensive computation ... }
string[] array = ...;
// Sort strings by hash, slow
sort!((a, b) => hashFun(a) < hashFun(b))(array);
// Sort strings by hash, fast (only computes arr.length hashes):
schwartzSort!(hashFun, "a < b")(array);

```
 The `schwartzSort` function might require less temporary data and be faster than the Perl idiom or the decorate-sort-undecorate idiom present in Python and Lisp. This is because sorting is done in-place and only minimal extra data (one array of transformed elements) is created. To check whether an array was sorted and benefit of the speedup of Schwartz sorting, a function `schwartzIsSorted` is not provided because the effect can be achieved by calling `isSorted!less(map!transform(r))`. 
Parameters:


|  |  |
| --- | --- |
| transform | The transformation to apply. Either a unary function (`unaryFun!transform(element)`), or a binary function (`binaryFun!transform(element, index)`). |
| less | The predicate to sort the transformed elements by. |
| ss | The swapping strategy to use. |
| R `r` | The range to sort. |


 
Returns:
The initial range wrapped as a `SortedRange` with the predicate `(a, b) => binaryFun!less(transform(a), transform(b))`.
 
Examples:


```
import std.algorithm.iteration : map;
import std.numeric : entropy;

auto lowEnt = [ 1.0, 0, 0 ],
     midEnt = [ 0.1, 0.1, 0.8 ],
    highEnt = [ 0.31, 0.29, 0.4 ];
auto arr = new double[][3];
arr[0] = midEnt;
arr[1] = lowEnt;
arr[2] = highEnt;

schwartzSort!(entropy, "a > b")(arr);

writeln(arr[0]); // highEnt
writeln(arr[1]); // midEnt
writeln(arr[2]); // lowEnt
assert(isSorted!("a > b")(map!(entropy)(arr)));

```
 
  void **partialSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size\_t n)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range); 
 
Reorders the random-access range `r` such that the range `r[0 .. mid]` is the same as if the entire `r` were sorted, and leaves the range `r[mid .. r.length]` in no particular order. Performs Ο(`r.length * log(mid)`) evaluations of `pred`. The implementation simply calls `topN!(less, ss)(r, n)` and then `sort!(less, ss)(r[0 .. n])`. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| Range `r` | The random-access range to reorder. |
| size\_t `n` | The length of the initial segment of `r` to sort. |


 
Examples:


```
int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ];
partialSort(a, 5);
writeln(a[0 .. 5]); // [0, 1, 2, 3, 4]

```
 
  void **partialSort**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (isRandomAccessRange!Range1 && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2) && hasLvalueElements!Range1 && hasLvalueElements!Range2); 
 
Stores the smallest elements of the two ranges in the left-hand range in sorted order. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| Range1 `r1` | The first range. |
| Range2 `r2` | The second range. |


 
Examples:


```
int[] a = [5, 7, 2, 6, 7];
int[] b = [2, 1, 5, 6, 7, 3, 0];

partialSort(a, b);
writeln(a); // [0, 1, 2, 2, 3]

```
 
  auto **topN**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size\_t nth)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && hasAssignableElements!Range); 
 
Reorders the range `r` using `swap` such that `r[nth]` refers to the element that would fall there if the range were fully sorted. In addition, it also partitions `r` such that all elements `e1` from `r[0]` to `r[nth]` satisfy `!less(r[nth], e1)`, and all elements `e2` from `r[nth]` to `r[r.length]` satisfy `!less(e2, r[nth])`. Effectively, it finds the nth smallest (according to `less`) elements in `r`. Performs an expected Ο(`r.length`) (if unstable) or Ο(`r.length * log(r.length)`) (if stable) evaluations of `less` and `swap`. 


If `n >= r.length`, the algorithm has no effect and returns `r[0 .. r.length]`. 

 
Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| Range `r` | The random-access range to reorder. |
| size\_t `nth` | The index of the element that should be in sorted position after the function is done. |


 
See Also:

[`topNIndex`](#topNIndex), 
 
Bugs:
Stable topN has not been implemented yet.
 
Examples:


```
int[] v = [ 25, 7, 9, 2, 0, 5, 21 ];
topN!"a < b"(v, 100);
writeln(v); // [25, 7, 9, 2, 0, 5, 21]
auto n = 4;
topN!((a, b) => a < b)(v, n);
writeln(v[n]); // 9

```
 
  auto **topN**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(Range1 r1, Range2 r2)  
 Constraints: if (isRandomAccessRange!Range1 && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2) && hasLvalueElements!Range1 && hasLvalueElements!Range2); 
 
Stores the smallest elements of the two ranges in the left-hand range. 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| ss | The swapping strategy to use. |
| Range1 `r1` | The first range. |
| Range2 `r2` | The second range. |


 
Examples:


```
int[] a = [ 5, 7, 2, 6, 7 ];
int[] b = [ 2, 1, 5, 6, 7, 3, 0 ];
topN(a, b);
sort(a);
writeln(a); // [0, 1, 2, 2, 3]

```
 
  TRange **topNCopy**(alias less = "a < b", SRange, TRange)(SRange source, TRange target, SortOutput sorted = No.sortOutput)  
 Constraints: if (isInputRange!SRange && isRandomAccessRange!TRange && hasLength!TRange && hasSlicing!TRange); 
 
Copies the top `n` elements of the [input range](std_range_primitives#isInputRange) `source` into the random-access range `target`, where `n = target.length`. Elements of `source` are not touched. If `sorted` is `true`, the target is sorted. Otherwise, the target respects the [heap property](http://en.wikipedia.org/wiki/Binary_heap). 



Parameters:


|  |  |
| --- | --- |
| less | The predicate to sort by. |
| SRange `source` | The source range. |
| TRange `target` | The target range. |
| SortOutput `sorted` | Whether to sort the elements copied into `target`. |


 
Returns:
The slice of `target` containing the copied elements.
 
Examples:


```
import std.typecons : Yes;

int[] a = [ 10, 16, 2, 3, 1, 5, 0 ];
int[] b = new int[3];
topNCopy(a, b, Yes.sortOutput);
writeln(b); // [0, 1, 2]

```
 
  void **topNIndex**(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index, SortOutput sorted = No.sortOutput)  
 Constraints: if (isRandomAccessRange!Range && isRandomAccessRange!RangeIndex && hasAssignableElements!RangeIndex); 
 
Given a range of elements, constructs an index of its top *n* elements (i.e., the first *n* elements if the range were sorted). 


Similar to [`topN`](#topN), except that the range is not modified. 

 
Parameters:


|  |  |
| --- | --- |
| less | A binary predicate that defines the ordering of range elements. Defaults to `a < b`. |
| ss | (Not implemented yet.) Specify the swapping strategy. |
| Range `r` | A [random-access range](std_range_primitives#isRandomAccessRange) of elements to make an index for. |
| RangeIndex `index` | A [random-access range](std_range_primitives#isRandomAccessRange) with assignable elements to build the index in. The length of this range determines how many top elements to index in `r`. This index range can either have integral elements, in which case the constructed index will consist of zero-based numerical indices into `r`; or it can have pointers to the element type of `r`, in which case the constructed index will be pointers to the top elements in `r`. |
| SortOutput `sorted` | Determines whether to sort the index by the elements they refer to. |


 
See Also:

[`topN`](#topN), [`topNCopy`](#topNCopy). 
 
Bugs:
The swapping strategy parameter is not implemented yet; currently it is ignored.
 
Examples:


```
import std.typecons : Yes;

// Construct index to top 3 elements using numerical indices:
int[] a = [ 10, 2, 7, 5, 8, 1 ];
int[] index = new int[3];
topNIndex(a, index, Yes.sortOutput);
assert(index == [5, 1, 3]); // because a[5]==1, a[1]==2, a[3]==5

// Construct index to top 3 elements using pointer indices:
int*[] ptrIndex = new int*[3];
topNIndex(a, ptrIndex, Yes.sortOutput);
writeln(ptrIndex); // [&a[5], &a[1], &a[3]]

```
 
  bool **nextPermutation**(alias less = "a < b", BidirectionalRange)(BidirectionalRange range)  
 Constraints: if (isBidirectionalRange!BidirectionalRange && hasSwappableElements!BidirectionalRange); 
 
Permutes `range` in-place to the next lexicographically greater permutation. 


 The predicate `less` defines the lexicographical ordering to be used on the range.   
  
 If the range is currently the lexicographically greatest permutation, it is permuted back to the least permutation and false is returned. Otherwise, true is returned. One can thus generate all permutations of a range by sorting it according to `less`, which produces the lexicographically least permutation, and then calling nextPermutation until it returns false. This is guaranteed to generate all distinct permutations of the range exactly once. If there are *N* elements in the range and all of them are unique, then *N*! permutations will be generated. Otherwise, if there are some duplicated elements, fewer permutations will be produced. 
```
// Enumerate all permutations
int[] a = [1,2,3,4,5];
do
{
    // use the current permutation and
    // proceed to the next permutation of the array.
} while (nextPermutation(a));

```
 

 
Parameters:


|  |  |
| --- | --- |
| less | The ordering to be used to determine lexicographical ordering of the permutations. |
| BidirectionalRange `range` | The range to permute. |


 
Returns:
false if the range was lexicographically the greatest, in which case the range is reversed back to the lexicographically smallest permutation; otherwise returns true. 
 
See Also:

[`std.algorithm.iteration.permutations`](std_algorithm_iteration#permutations).
 
Examples:


```
// Step through all permutations of a sorted array in lexicographic order
int[] a = [1,2,3];
writeln(nextPermutation(a)); // true
writeln(a); // [1, 3, 2]
writeln(nextPermutation(a)); // true
writeln(a); // [2, 1, 3]
writeln(nextPermutation(a)); // true
writeln(a); // [2, 3, 1]
writeln(nextPermutation(a)); // true
writeln(a); // [3, 1, 2]
writeln(nextPermutation(a)); // true
writeln(a); // [3, 2, 1]
writeln(nextPermutation(a)); // false
writeln(a); // [1, 2, 3]

```
 
 
Examples:


```
// Step through permutations of an array containing duplicate elements:
int[] a = [1,1,2];
writeln(nextPermutation(a)); // true
writeln(a); // [1, 2, 1]
writeln(nextPermutation(a)); // true
writeln(a); // [2, 1, 1]
writeln(nextPermutation(a)); // false
writeln(a); // [1, 1, 2]

```
 
  bool **nextEvenPermutation**(alias less = "a < b", BidirectionalRange)(BidirectionalRange range)  
 Constraints: if (isBidirectionalRange!BidirectionalRange && hasSwappableElements!BidirectionalRange); 
 
Permutes `range` in-place to the next lexicographically greater *even* permutation. 


 The predicate `less` defines the lexicographical ordering to be used on the range.   
  
 An even permutation is one which is produced by swapping an even number of pairs of elements in the original range. The set of *even* permutations is distinct from the set of *all* permutations only when there are no duplicate elements in the range. If the range has *N* unique elements, then there are exactly *N*!/2 even permutations.   
  
 If the range is already the lexicographically greatest even permutation, it is permuted back to the least even permutation and false is returned. Otherwise, true is returned, and the range is modified in-place to be the lexicographically next even permutation.   
  
 One can thus generate the even permutations of a range with unique elements by starting with the lexicographically smallest permutation, and repeatedly calling nextEvenPermutation until it returns false. 
```
// Enumerate even permutations
int[] a = [1,2,3,4,5];
do
{
    // use the current permutation and
    // proceed to the next even permutation of the array.
} while (nextEvenPermutation(a));

```
 One can also generate the *odd* permutations of a range by noting that permutations obey the rule that even + even = even, and odd + even = odd. Thus, by swapping the last two elements of a lexicographically least range, it is turned into the first odd permutation. Then calling nextEvenPermutation on this first odd permutation will generate the next even permutation relative to this odd permutation, which is actually the next odd permutation of the original range. Thus, by repeatedly calling nextEvenPermutation until it returns false, one enumerates the odd permutations of the original range. 
```
// Enumerate odd permutations
int[] a = [1,2,3,4,5];
swap(a[$-2], a[$-1]);    // a is now the first odd permutation of [1,2,3,4,5]
do
{
    // use the current permutation and
    // proceed to the next odd permutation of the original array
    // (which is an even permutation of the first odd permutation).
} while (nextEvenPermutation(a));

```
 

 
Warning
 Since even permutations are only distinct from all permutations when the range elements are unique, this function assumes that there are no duplicate elements under the specified ordering. If this is not true, some permutations may fail to be generated. When the range has non-unique elements, you should use [*nextPermutation*](#nextPermutation) instead. 
 
Parameters:


|  |  |
| --- | --- |
| less | The ordering to be used to determine lexicographical ordering of the permutations. |
| BidirectionalRange `range` | The range to permute. |


 
Returns:
false if the range was lexicographically the greatest, in which case the range is reversed back to the lexicographically smallest permutation; otherwise returns true.
 
Examples:


```
// Step through even permutations of a sorted array in lexicographic order
int[] a = [1,2,3];
writeln(nextEvenPermutation(a)); // true
writeln(a); // [2, 3, 1]
writeln(nextEvenPermutation(a)); // true
writeln(a); // [3, 1, 2]
writeln(nextEvenPermutation(a)); // false
writeln(a); // [1, 2, 3]

```
 
 
Examples:
Even permutations are useful for generating coordinates of certain geometric shapes. Here's a non-trivial example: 
```
import std.math : sqrt;

// Print the 60 vertices of a uniform truncated icosahedron (soccer ball)
enum real Phi = (1.0 + sqrt(5.0)) / 2.0;    // Golden ratio
real[][] seeds = [
    [0.0, 1.0, 3.0*Phi],
    [1.0, 2.0+Phi, 2.0*Phi],
    [Phi, 2.0, Phi^^3]
];
size_t n;
foreach (seed; seeds)
{
    // Loop over even permutations of each seed
    do
    {
        // Loop over all sign changes of each permutation
        size_t i;
        do
        {
            // Generate all possible sign changes
            for (i=0; i < seed.length; i++)
            {
                if (seed[i] != 0.0)
                {
                    seed[i] = -seed[i];
                    if (seed[i] < 0.0)
                        break;
                }
            }
            n++;
        } while (i < seed.length);
    } while (nextEvenPermutation(seed));
}
writeln(n); // 60

```
 
  ref Range **nthPermutation**(Range)(auto ref Range range, const ulong perm)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range); 
 
Permutes `range` into the `perm` permutation. The algorithm has a constant runtime complexity with respect to the number of permutations created. Due to the number of unique values of `ulong` only the first 21 elements of `range` can be permuted. The rest of the range will therefore not be permuted. This algorithm uses the [Lehmer Code](http://en.wikipedia.org/wiki/Lehmer_code). 


The algorithm works as follows: 
```
    auto pem = [4,0,4,1,0,0,0]; // permutation 2982 in factorial
    auto src = [0,1,2,3,4,5,6]; // the range to permutate


    auto i = 0;                    // range index
    // range index iterates pem and src in sync
    // pem[i] + i is used as index into src
    // first src[pem[i] + i] is stored in t
    auto t = 4;                    // tmp value
    src = [0,1,2,3,n,5,6];


    // then the values between i and pem[i] + i are moved one
    // to the right
    src = [n,0,1,2,3,5,6];
    // at last t is inserted into position i
    src = [4,0,1,2,3,5,6];
    // finally i is incremented
    ++i;


    // this process is repeated while i < pem.length


    t = 0;
    src = [4,n,1,2,3,5,6];
    src = [4,0,1,2,3,5,6];
    ++i;
    t = 6;
    src = [4,0,1,2,3,5,n];
    src = [4,0,n,1,2,3,5];
    src = [4,0,6,1,2,3,5];

```
 

 
Returns:
The permuted range. 
 
Parameters:


|  |  |
| --- | --- |
| Range `range` | The Range to permute. The original ordering will be lost. |
| ulong `perm` | The permutation to permutate `range` to. |


 
Examples:


```
auto src = [0, 1, 2, 3, 4, 5, 6];
auto rslt = [4, 0, 6, 2, 1, 3, 5];

src = nthPermutation(src, 2982);
writeln(src); // rslt

```
 
  bool **nthPermutationImpl**(Range)(auto ref Range range, ulong perm)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range); 
 

Returns:

`true` in case the permutation worked, `false` in case `perm` had more digits in the factorial number system than range had elements. This case must not occur as this would lead to out of range accesses.
 
Examples:


```
auto src = [0, 1, 2, 3, 4, 5, 6];
auto rslt = [4, 0, 6, 2, 1, 3, 5];

bool worked = nthPermutationImpl(src, 2982);
assert(worked);
writeln(src); // rslt

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_sorting.html>

std.bitmanip
============

 Bit-level manipulation facilities. 


 

| Category | Functions |
| --- | --- |
| Bit constructs | [`BitArray`](#BitArray) [`bitfields`](#bitfields) [`bitsSet`](#bitsSet) |
| Endianness conversion | [`bigEndianToNative`](#bigEndianToNative) [`littleEndianToNative`](#littleEndianToNative) [`nativeToBigEndian`](#nativeToBigEndian) [`nativeToLittleEndian`](#nativeToLittleEndian) [`swapEndian`](#swapEndian) |
| Integral ranges | [`append`](#append) [`peek`](#peek) [`read`](#read) [`write`](#write) |
| Floating-Point manipulation | [`DoubleRep`](#DoubleRep) [`FloatRep`](#FloatRep) |
| Tagging | [`taggedClassRef`](#taggedClassRef) [`taggedPointer`](#taggedPointer) |

 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), [Jonathan M Davis](http://jmdavisprog.com), Alex Rønne Petersen, Damian Ziemba, Amaury SECHET 
 
Source
 [std/bitmanip.d](https://github.com/dlang/phobos/blob/master/std/bitmanip.d)

 
template **bitfields**(T...) 
Allows creating bit fields inside structs and classes. 


The type of a bit field can be any integral type or enumerated type. The most efficient type to store in bitfields is bool, followed by unsigned types, followed by signed types. 

 
See Also:
[`std.typecons.BitFlags`](std_typecons#BitFlags)
 
Examples:
Create a bitfield pack of eight bits, which fit in one ubyte. The bitfields are allocated starting from the least significant bit, i.e. x occupies the two least significant bits of the bitfields storage. 
```
struct A
{
    int a;
    mixin(bitfields!(
        uint, "x",    2,
        int,  "y",    3,
        uint, "z",    2,
        bool, "flag", 1));
}

A obj;
obj.x = 2;
obj.z = obj.x;

writeln(obj.x); // 2
writeln(obj.y); // 0
writeln(obj.z); // 2
writeln(obj.flag); // false

```
 
 
Examples:
The sum of all bit lengths in one bitfield instantiation must be exactly 8, 16, 32, or 64. If padding is needed, just allocate one bitfield with an empty name. 
```
struct A
{
    mixin(bitfields!(
        bool, "flag1",    1,
        bool, "flag2",    1,
        uint, "",         6));
}

A a;
writeln(a.flag1); // 0
a.flag1 = 1;
writeln(a.flag1); // 1
a.flag1 = 0;
writeln(a.flag1); // 0

```
 
 
Examples:
enums can be used too 
```
enum ABC { A, B, C }
struct EnumTest
{
    mixin(bitfields!(
              ABC, "x", 2,
              bool, "y", 1,
              ubyte, "z", 5));
}

```
 
  enum auto **taggedPointer**(T : T\*, string name, Ts...);  
This string mixin generator allows one to create tagged pointers inside structs and classes. 


A tagged pointer uses the bits known to be zero in a normal pointer or class reference to store extra information. For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero. One can store a 2-bit integer there.   
  
 The example above creates a tagged pointer in the struct A. The pointer is of type `uint*` as specified by the first argument, and is named x, as specified by the second argument.   
  
 Following arguments works the same way as `bitfield`'s. The bitfield must fit into the bits known to be zero because of the pointer alignment.

 
Examples:


```
struct A
{
    int a;
    mixin(taggedPointer!(
        uint*, "x",
        bool, "b1", 1,
        bool, "b2", 1));
}
A obj;
obj.x = new uint;
obj.b1 = true;
obj.b2 = false;

```
 
  template **taggedClassRef**(T, string name, Ts...) if (is(T == class)) 
This string mixin generator allows one to create tagged class reference inside structs and classes. 


A tagged class reference uses the bits known to be zero in a normal class reference to store extra information. For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero. One can store a 2-bit integer there.   
  
 The example above creates a tagged reference to an Object in the struct A. This expects the same parameters as `taggedPointer`, except the first argument which must be a class type instead of a pointer type.

 
Examples:


```
struct A
{
    int a;
    mixin(taggedClassRef!(
        Object, "o",
        uint, "i", 2));
}
A obj;
obj.o = new Object();
obj.i = 3;

```
 
  struct **FloatRep**;  
Allows manipulating the fraction, exponent, and sign parts of a float separately. The definition is: 



```
struct FloatRep
{
    union
    {
        float value;
        mixin(bitfields!(
                  uint,  "fraction", 23,
                  ubyte, "exponent",  8,
                  bool,  "sign",      1));
    }
    enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1;
}

```
 

 
Examples:


```
FloatRep rep = {value: 0};
writeln(rep.fraction); // 0
writeln(rep.exponent); // 0
assert(!rep.sign);

rep.value = 42;
writeln(rep.fraction); // 2621440
writeln(rep.exponent); // 132
assert(!rep.sign);

rep.value = 10;
writeln(rep.fraction); // 2097152
writeln(rep.exponent); // 130

```
 
 
Examples:


```
FloatRep rep = {value: 1};
writeln(rep.fraction); // 0
writeln(rep.exponent); // 127
assert(!rep.sign);

rep.exponent = 126;
writeln(rep.value); // 0.5

rep.exponent = 130;
writeln(rep.value); // 8

```
 
 
Examples:


```
FloatRep rep = {value: 1};
rep.value = -0.5;
writeln(rep.fraction); // 0
writeln(rep.exponent); // 126
assert(rep.sign);

rep.value = -1. / 3;
writeln(rep.fraction); // 2796203
writeln(rep.exponent); // 125
assert(rep.sign);

```
 
  struct **DoubleRep**;  
Allows manipulating the fraction, exponent, and sign parts of a double separately. The definition is: 



```
struct DoubleRep
{
    union
    {
        double value;
        mixin(bitfields!(
                  ulong,   "fraction", 52,
                  ushort,  "exponent", 11,
                  bool,    "sign",      1));
    }
    enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11;
}

```
 

 
Examples:


```
DoubleRep rep = {value: 0};
writeln(rep.fraction); // 0
writeln(rep.exponent); // 0
assert(!rep.sign);

rep.value = 42;
writeln(rep.fraction); // 1407374883553280
writeln(rep.exponent); // 1028
assert(!rep.sign);

rep.value = 10;
writeln(rep.fraction); // 1125899906842624
writeln(rep.exponent); // 1026

```
 
 
Examples:


```
DoubleRep rep = {value: 1};
writeln(rep.fraction); // 0
writeln(rep.exponent); // 1023
assert(!rep.sign);

rep.exponent = 1022;
writeln(rep.value); // 0.5

rep.exponent = 1026;
writeln(rep.value); // 8

```
 
 
Examples:


```
DoubleRep rep = {value: 1};
rep.value = -0.5;
writeln(rep.fraction); // 0
writeln(rep.exponent); // 1022
assert(rep.sign);

rep.value = -1. / 3;
writeln(rep.fraction); // 1501199875790165
writeln(rep.exponent); // 1021
assert(rep.sign);

```
 
 
Examples:
Reading 
```
DoubleRep x;
x.value = 1.0;
assert(x.fraction == 0 && x.exponent == 1023 && !x.sign);
x.value = -0.5;
assert(x.fraction == 0 && x.exponent == 1022 && x.sign);
x.value = 0.5;
assert(x.fraction == 0 && x.exponent == 1022 && !x.sign);

```
 
 
Examples:
Writing 
```
DoubleRep x;
x.fraction = 1125899906842624;
x.exponent = 1025;
x.sign = true;
writeln(x.value); // -5.0

```
 
  struct **BitArray**;  
A dynamic array of bits. Each bit in a `BitArray` can be manipulated individually or by the standard bitwise operators `&`, `|`, `^`, `~`, `>>`, `<<` and also by other effective member functions; most of them work relative to the `BitArray`'s dimension (see [`dim`](#dim)), instead of its [`length`](#length).



Examples:
Slicing & bitsSet 
```
import std.algorithm.comparison : equal;
import std.range : iota;

bool[] buf = new bool[64 * 3];
buf[0 .. 64] = true;
BitArray b = BitArray(buf);
assert(b.bitsSet.equal(iota(0, 64)));
b <<= 64;
assert(b.bitsSet.equal(iota(64, 128)));

```
 
 
Examples:
Concatenation and appending 
```
import std.algorithm.comparison : equal;

auto b = BitArray([1, 0]);
b ~= true;
writeln(b[2]); // 1
b ~= BitArray([0, 1]);
auto c = BitArray([1, 0, 1, 0, 1]);
writeln(b); // c
assert(b.bitsSet.equal([0, 2, 4]));

```
 
 
Examples:
Bit flipping 
```
import std.algorithm.comparison : equal;

auto b = BitArray([1, 1, 0, 1]);
b &= BitArray([0, 1, 1, 0]);
assert(b.bitsSet.equal([1]));
b.flip;
assert(b.bitsSet.equal([0, 2, 3]));

```
 
 
Examples:
String format of bitarrays 
```
import std.format : format;
auto b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
writeln(format("%b", b)); // "1_00001111_00001111"

```
 
 
Examples:


```
import std.format : format;

BitArray b;

b = BitArray([]);
writeln(format("%s", b)); // "[]"
assert(format("%b", b) is null);

b = BitArray([1]);
writeln(format("%s", b)); // "[1]"
writeln(format("%b", b)); // "1"

b = BitArray([0, 0, 0, 0]);
writeln(format("%b", b)); // "0000"

b = BitArray([0, 0, 0, 0, 1, 1, 1, 1]);
writeln(format("%s", b)); // "[0, 0, 0, 0, 1, 1, 1, 1]"
writeln(format("%b", b)); // "00001111"

b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
writeln(format("%s", b)); // "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]"
writeln(format("%b", b)); // "00001111_00001111"

b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1]);
writeln(format("%b", b)); // "1_00001111"

b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
writeln(format("%b", b)); // "1_00001111_00001111"

```
 
 
pure nothrow this(in bool[] ba);  
Creates a `BitArray` from a `bool` array, such that `bool` values read from left to right correspond to subsequent bits in the `BitArray`. 



Parameters:


|  |  |
| --- | --- |
| bool[] `ba` | Source array of `bool` values. |


 
Examples:


```
import std.algorithm.comparison : equal;

bool[] input = [true, false, false, true, true];
auto a = BitArray(input);
writeln(a.length); // 5
assert(a.bitsSet.equal([0, 3, 4]));

// This also works because an implicit cast to bool[] occurs for this array.
auto b = BitArray([0, 0, 1]);
writeln(b.length); // 3
assert(b.bitsSet.equal([2]));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.array : array;
import std.range : iota, repeat;

BitArray a = true.repeat(70).array;
writeln(a.length); // 70
assert(a.bitsSet.equal(iota(0, 70)));

```
 
  pure nothrow @nogc this(void[] v, size\_t numbits);  
Creates a `BitArray` from the raw contents of the source array. The source array is not copied but simply acts as the underlying array of bits, which stores data as `size_t` units. 


 That means a particular care should be taken when passing an array of a type different than `size_t`, firstly because its length should be a multiple of `size_t.sizeof`, and secondly because how the bits are mapped: 
```
size_t[] source = [1, 2, 3, 3424234, 724398, 230947, 389492];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
    auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
    assert(ba[n] == nth_bit);
}

```
 The least significant bit in any `size_t` unit is the starting bit of this unit, and the most significant bit is the last bit of this unit. Therefore, passing e.g. an array of `int`s may result in a different `BitArray` depending on the processor's endianness.   
  
 This constructor is the inverse of [`opCast`](#opCast). 

 
Parameters:


|  |  |
| --- | --- |
| void[] `v` | Source array. `v.length` must be a multple of `size_t.sizeof`. |
| size\_t `numbits` | Number of bits to be mapped from the source array, i.e. length of the created `BitArray`. |


 
Examples:


```
import std.algorithm.comparison : equal;

auto a = BitArray([1, 0, 0, 1, 1]);

// Inverse of the cast.
auto v = cast(void[]) a;
auto b = BitArray(v, a.length);

writeln(b.length); // 5
assert(b.bitsSet.equal([0, 3, 4]));

// a and b share the underlying data.
a[0] = 0;
writeln(b[0]); // 0
writeln(a); // b

```
 
 
Examples:


```
import std.algorithm.comparison : equal;

size_t[] source = [0b1100, 0b0011];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
// The least significant bit in each unit is this unit's starting bit.
assert(ba.bitsSet.equal([2, 3, sbits, sbits + 1]));

```
 
 
Examples:


```
// Example from the doc for this constructor.
static immutable size_t[] sourceData = [1, 0b101, 3, 3424234, 724398, 230947, 389492];
size_t[] source = sourceData.dup;
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
    auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
    writeln(ba[n]); // nth_bit
}

// Example of mapping only part of the array.
import std.algorithm.comparison : equal;

auto bc = BitArray(source, sbits + 1);
assert(bc.bitsSet.equal([0, sbits]));
// Source array has not been modified.
writeln(source); // sourceData

```
 
  const pure nothrow @nogc @property @safe size\_t **dim**();  

Returns:
Dimension i.e. the number of native words backing this `BitArray`. Technically, this is the length of the underlying array storing bits, which is equal to `ceil(length / (size_t.sizeof * 8))`, as bits are packed into `size_t` units.
  const pure nothrow @nogc @property @safe size\_t **length**();  

Returns:
Number of bits in the `BitArray`.
  pure nothrow @property @system size\_t **length**(size\_t newlen);  
Sets the amount of bits in the `BitArray`. Warning: increasing length may overwrite bits in the final word of the current underlying data regardless of whether it is shared between BitArray objects. i.e. D dynamic array extension semantics are not followed.

  const pure nothrow @nogc bool **opIndex**(size\_t i);  
Gets the `i`'th bit in the `BitArray`.



Examples:


```
static void fun(const BitArray arr)
{
    auto x = arr[0];
    writeln(x); // 1
}
BitArray a;
a.length = 3;
a[0] = 1;
fun(a);

```
 
  pure nothrow @nogc bool **opIndexAssign**(bool b, size\_t i);  
Sets the `i`'th bit in the `BitArray`.

  pure nothrow @nogc void **opSliceAssign**(bool val);  
Sets all the values in the `BitArray` to the value specified by `val`.



Examples:


```
import std.algorithm.comparison : equal;

auto b = BitArray([1, 0, 1, 0, 1, 1]);

b[] = true;
// all bits are set
assert(b.bitsSet.equal([0, 1, 2, 3, 4, 5]));

b[] = false;
// none of the bits are set
assert(b.bitsSet.empty);

```
 
  pure nothrow @nogc void **opSliceAssign**(bool val, size\_t start, size\_t end);  
Sets the bits of a slice of `BitArray` starting at index `start` and ends at index ($D end - 1) with the values specified by `val`.



Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
import std.stdio;

auto b = BitArray([1, 0, 0, 0, 1, 1, 0]);
b[1 .. 3] = true;
assert(b.bitsSet.equal([0, 1, 2, 4, 5]));

bool[72] bitArray;
auto b1 = BitArray(bitArray);
b1[63 .. 67] = true;
assert(b1.bitsSet.equal([63, 64, 65, 66]));
b1[63 .. 67] = false;
assert(b1.bitsSet.empty);
b1[0 .. 64] = true;
assert(b1.bitsSet.equal(iota(0, 64)));
b1[0 .. 64] = false;
assert(b1.bitsSet.empty);

bool[256] bitArray2;
auto b2 = BitArray(bitArray2);
b2[3 .. 245] = true;
assert(b2.bitsSet.equal(iota(3, 245)));
b2[3 .. 245] = false;
assert(b2.bitsSet.empty);

```
 
  pure nothrow @nogc void **flip**();  
Flips all the bits in the `BitArray`



Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;

// positions 0, 2, 4 are set
auto b = BitArray([1, 0, 1, 0, 1, 0]);
b.flip();
// after flipping, positions 1, 3, 5 are set
assert(b.bitsSet.equal([1, 3, 5]));

bool[270] bits;
auto b1 = BitArray(bits);
b1.flip();
assert(b1.bitsSet.equal(iota(0, 270)));

```
 
  pure nothrow @nogc void **flip**(size\_t i);  
Flips a single bit, specified by `pos`



Examples:


```
auto ax = BitArray([1, 0, 0, 1]);
ax.flip(0);
writeln(ax[0]); // 0

bool[200] y;
y[90 .. 130] = true;
auto ay = BitArray(y);
ay.flip(100);
writeln(ay[100]); // 0

```
 
  const pure nothrow @nogc size\_t **count**();  
Counts all the set bits in the `BitArray`



Examples:


```
auto a = BitArray([0, 1, 1, 0, 0, 1, 1]);
writeln(a.count); // 4

BitArray b;
writeln(b.count); // 0

bool[200] boolArray;
boolArray[45 .. 130] = true;
auto c = BitArray(boolArray);
writeln(c.count); // 85

```
 
  const pure nothrow @property BitArray **dup**();  
Duplicates the `BitArray` and its contents.



Examples:


```
BitArray a;
BitArray b;

a.length = 3;
a[0] = 1; a[1] = 0; a[2] = 1;
b = a.dup;
writeln(b.length); // 3
foreach (i; 0 .. 3)
    writeln(b[i]); // (((i ^ 1) & 1) ? true : false)

```
 
  int **opApply**(scope int delegate(ref bool) dg);   
  
const int **opApply**(scope int delegate(bool) dg);   
  
int **opApply**(scope int delegate(size\_t, ref bool) dg);   
  
const int **opApply**(scope int delegate(size\_t, bool) dg);  
Support for `foreach` loops for `BitArray`.



Examples:


```
bool[] ba = [1,0,1];

auto a = BitArray(ba);

int i;
foreach (b;a)
{
    switch (i)
    {
        case 0: assert(b == true); break;
        case 1: assert(b == false); break;
        case 2: assert(b == true); break;
        default: assert(0);
    }
    i++;
}

foreach (j,b;a)
{
    switch (j)
    {
        case 0: assert(b == true); break;
        case 1: assert(b == false); break;
        case 2: assert(b == true); break;
        default: assert(0);
    }
}

```
 
  pure nothrow @nogc @property BitArray **reverse**();  
Reverses the bits of the `BitArray`.



Examples:


```
BitArray b;
bool[5] data = [1,0,1,1,0];

b = BitArray(data);
b.reverse;
foreach (i; 0 .. data.length)
    writeln(b[i]); // data[4 - i]

```
 
  pure nothrow @nogc @property BitArray **sort**();  
Sorts the `BitArray`'s elements.



Examples:


```
size_t x = 0b1100011000;
auto ba = BitArray(10, &x);
ba.sort;
foreach (i; 0 .. 6)
    writeln(ba[i]); // false
foreach (i; 6 .. 10)
    writeln(ba[i]); // true

```
 
  const pure nothrow @nogc bool **opEquals**(ref const BitArray a2);  
Support for operators == and != for `BitArray`.



Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1];
bool[] bc = [1,0,1,0,1,0,1];
bool[] bd = [1,0,1,1,1];
bool[] be = [1,0,1,0,1];
bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];

auto a = BitArray(ba);
auto b = BitArray(bb);
auto c = BitArray(bc);
auto d = BitArray(bd);
auto e = BitArray(be);
auto f = BitArray(bf);
auto g = BitArray(bg);

assert(a != b);
assert(a != c);
assert(a != d);
writeln(a); // e
assert(f != g);

```
 
  const pure nothrow @nogc int **opCmp**(BitArray a2);  
Supports comparison operators for `BitArray`.



Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1];
bool[] bc = [1,0,1,0,1,0,1];
bool[] bd = [1,0,1,1,1];
bool[] be = [1,0,1,0,1];
bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);
auto c = BitArray(bc);
auto d = BitArray(bd);
auto e = BitArray(be);
auto f = BitArray(bf);
auto g = BitArray(bg);

assert(a >  b);
assert(a >= b);
assert(a <  c);
assert(a <= c);
assert(a <  d);
assert(a <= d);
writeln(a); // e
assert(a <= e);
assert(a >= e);
assert(f <  g);
assert(g <= g);

```
 
  const pure nothrow @nogc size\_t **toHash**();  
Support for hashing for `BitArray`.

  inout pure nothrow @nogc inout(void)[] **opCast**(T : const(void[]))();  
Convert to `void[]`.

  inout pure nothrow @nogc inout(size\_t)[] **opCast**(T : const(size\_t[]))();  
Convert to `size_t[]`.



Examples:


```
import std.array : array;
import std.range : repeat, take;

// bit array with 300 elements
auto a = BitArray(true.repeat.take(300).array);
size_t[] v = cast(size_t[]) a;
const blockSize = size_t.sizeof * 8;
writeln(v.length); // (a.length + blockSize - 1) / blockSize

```
 
  const pure nothrow BitArray **opUnary**(string op)()  
 Constraints: if (op == "~"); 
 
Support for unary operator ~ for `BitArray`.



Examples:


```
bool[] ba = [1,0,1,0,1];

auto a = BitArray(ba);
BitArray b = ~a;

writeln(b[0]); // 0
writeln(b[1]); // 1
writeln(b[2]); // 0
writeln(b[3]); // 1
writeln(b[4]); // 0

```
 
  const pure nothrow BitArray **opBinary**(string op)(const BitArray e2)  
 Constraints: if (op == "-" || op == "&" || op == "|" || op == "^"); 
 
Support for binary bitwise operators for `BitArray`.



Examples:


```
static bool[] ba = [1,0,1,0,1];
static bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

BitArray c = a & b;

writeln(c[0]); // 1
writeln(c[1]); // 0
writeln(c[2]); // 1
writeln(c[3]); // 0
writeln(c[4]); // 0

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

BitArray c = a | b;

writeln(c[0]); // 1
writeln(c[1]); // 0
writeln(c[2]); // 1
writeln(c[3]); // 1
writeln(c[4]); // 1

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

BitArray c = a ^ b;

writeln(c[0]); // 0
writeln(c[1]); // 0
writeln(c[2]); // 0
writeln(c[3]); // 1
writeln(c[4]); // 1

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

BitArray c = a - b;

writeln(c[0]); // 0
writeln(c[1]); // 0
writeln(c[2]); // 0
writeln(c[3]); // 0
writeln(c[4]); // 1

```
 
  pure nothrow @nogc BitArray **opOpAssign**(string op)(const BitArray e2)  
 Constraints: if (op == "-" || op == "&" || op == "|" || op == "^"); 
 
Support for operator op= for `BitArray`.



Examples:


```
bool[] ba = [1,0,1,0,1,1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a;
c.length = 5;
c &= b;
writeln(a[5]); // 1
writeln(a[6]); // 0
writeln(a[7]); // 1
writeln(a[8]); // 0
writeln(a[9]); // 1

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

a &= b;
writeln(a[0]); // 1
writeln(a[1]); // 0
writeln(a[2]); // 1
writeln(a[3]); // 0
writeln(a[4]); // 0

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

a |= b;
writeln(a[0]); // 1
writeln(a[1]); // 0
writeln(a[2]); // 1
writeln(a[3]); // 1
writeln(a[4]); // 1

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

a ^= b;
writeln(a[0]); // 0
writeln(a[1]); // 0
writeln(a[2]); // 0
writeln(a[3]); // 1
writeln(a[4]); // 1

```
 
 
Examples:


```
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);

a -= b;
writeln(a[0]); // 0
writeln(a[1]); // 0
writeln(a[2]); // 0
writeln(a[3]); // 0
writeln(a[4]); // 1

```
 
  pure nothrow BitArray **opOpAssign**(string op)(bool b)  
 Constraints: if (op == "~");   
  
pure nothrow BitArray **opOpAssign**(string op)(BitArray b)  
 Constraints: if (op == "~"); 
 
Support for operator ~= for `BitArray`. Warning: This will overwrite a bit in the final word of the current underlying data regardless of whether it is shared between BitArray objects. i.e. D dynamic array concatenation semantics are not followed



Examples:


```
bool[] ba = [1,0,1,0,1];

auto a = BitArray(ba);
BitArray b;

b = (a ~= true);
writeln(a[0]); // 1
writeln(a[1]); // 0
writeln(a[2]); // 1
writeln(a[3]); // 0
writeln(a[4]); // 1
writeln(a[5]); // 1

writeln(b); // a

```
 
 
Examples:


```
bool[] ba = [1,0];
bool[] bb = [0,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c;

c = (a ~= b);
writeln(a.length); // 5
writeln(a[0]); // 1
writeln(a[1]); // 0
writeln(a[2]); // 0
writeln(a[3]); // 1
writeln(a[4]); // 0

writeln(c); // a

```
 
  const pure nothrow BitArray **opBinary**(string op)(bool b)  
 Constraints: if (op == "~");   
  
const pure nothrow BitArray **opBinaryRight**(string op)(bool b)  
 Constraints: if (op == "~");   
  
const pure nothrow BitArray **opBinary**(string op)(BitArray b)  
 Constraints: if (op == "~"); 
 
Support for binary operator ~ for `BitArray`.



Examples:


```
bool[] ba = [1,0];
bool[] bb = [0,1,0];

auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c;

c = (a ~ b);
writeln(c.length); // 5
writeln(c[0]); // 1
writeln(c[1]); // 0
writeln(c[2]); // 0
writeln(c[3]); // 1
writeln(c[4]); // 0

c = (a ~ true);
writeln(c.length); // 3
writeln(c[0]); // 1
writeln(c[1]); // 0
writeln(c[2]); // 1

c = (false ~ a);
writeln(c.length); // 3
writeln(c[0]); // 0
writeln(c[1]); // 1
writeln(c[2]); // 0

```
 
  pure nothrow @nogc void **opOpAssign**(string op)(size\_t nbits)  
 Constraints: if (op == "<<"); 
 
Operator `<<=` support. 


Shifts all the bits in the array to the left by the given number of bits. The leftmost bits are dropped, and 0's are appended to the end to fill up the vacant bits.   
  
 Warning: unused bits in the final word up to the next word boundary may be overwritten by this operation. It does not attempt to preserve bits past the end of the array.

  pure nothrow @nogc void **opOpAssign**(string op)(size\_t nbits)  
 Constraints: if (op == ">>"); 
 
Operator `>>=` support. 


Shifts all the bits in the array to the right by the given number of bits. The rightmost bits are dropped, and 0's are inserted at the back to fill up the vacant bits.   
  
 Warning: unused bits in the final word up to the next word boundary may be overwritten by this operation. It does not attempt to preserve bits past the end of the array.

 
Examples:


```
import std.format : format;

auto b = BitArray([1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1]);

b <<= 1;
writeln(format("%b", b)); // "01100_10101101"

b >>= 1;
writeln(format("%b", b)); // "11001_01011010"

b <<= 4;
writeln(format("%b", b)); // "00001_10010101"

b >>= 5;
writeln(format("%b", b)); // "10010_10100000"

b <<= 13;
writeln(format("%b", b)); // "00000_00000000"

b = BitArray([1, 0, 1, 1, 0, 1, 1, 1]);
b >>= 8;
writeln(format("%b", b)); // "00000000"

```
 
  const void **toString**(W)(ref W sink, ref scope const FormatSpec!char fmt)  
 Constraints: if (isOutputRange!(W, char)); 
 
Return a string representation of this BitArray. 


Two format specifiers are supported: - **%s** which prints the bits as an array, and
 - **%b** which prints the bits as 8-bit byte packets
 separated with an underscore. 

 
Parameters:


|  |  |
| --- | --- |
| W `sink` | A `char` accepting [output range](std_range_primitives#isOutputRange). |
| FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which controls how the data is displayed. |


 
Examples:


```
import std.format : format;

auto b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);

auto s1 = format("%s", b);
writeln(s1); // "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]"

auto s2 = format("%b", b);
writeln(s2); // "00001111_00001111"

```
 
  const nothrow @property auto **bitsSet**();  
Return a lazy range of the indices of set bits.



Examples:


```
import std.algorithm.comparison : equal;

auto b1 = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(b1.bitsSet.equal([4, 5, 6, 7, 12, 13, 14, 15]));

BitArray b2;
b2.length = 1000;
b2[333] = true;
b2[666] = true;
b2[999] = true;
assert(b2.bitsSet.equal([333, 666, 999]));

```
 
    pure nothrow @nogc @safe T **swapEndian**(T)(const T val)  
 Constraints: if (isIntegral!T || isSomeChar!T || isBoolean!T); 
 
Swaps the endianness of the given integral value or character.



Examples:


```
writeln(42.swapEndian); // 704643072
assert(42.swapEndian.swapEndian == 42); // reflexive
writeln(1.swapEndian); // 16777216

writeln(true.swapEndian); // true
writeln(byte(10).swapEndian); // 10
writeln(char(10).swapEndian); // 10

writeln(ushort(10).swapEndian); // 2560
writeln(long(10).swapEndian); // 720575940379279360
writeln(ulong(10).swapEndian); // 720575940379279360

```
 
  pure nothrow @nogc @safe auto **nativeToBigEndian**(T)(const T val)  
 Constraints: if (canSwapEndianness!T); 
 
Converts the given value from the native endianness to big endian and returns it as a `ubyte[n]` where `n` is the size of the given type. 


Returning a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values).   
  
 `real` is not supported, because its size is implementation-dependent and therefore could vary from machine to machine (which could make it unusable if you tried to transfer it to another machine).

 
Examples:


```
int i = 12345;
ubyte[4] swappedI = nativeToBigEndian(i);
writeln(i); // bigEndianToNative!int(swappedI)

float f = 123.45f;
ubyte[4] swappedF = nativeToBigEndian(f);
writeln(f); // bigEndianToNative!float(swappedF)

const float cf = 123.45f;
ubyte[4] swappedCF = nativeToBigEndian(cf);
writeln(cf); // bigEndianToNative!float(swappedCF)

double d = 123.45;
ubyte[8] swappedD = nativeToBigEndian(d);
writeln(d); // bigEndianToNative!double(swappedD)

const double cd = 123.45;
ubyte[8] swappedCD = nativeToBigEndian(cd);
writeln(cd); // bigEndianToNative!double(swappedCD)

```
 
  pure nothrow @nogc @safe T **bigEndianToNative**(T, size\_t n)(ubyte[n] val)  
 Constraints: if (canSwapEndianness!T && (n == T.sizeof)); 
 
Converts the given value from big endian to the native endianness and returns it. The value is given as a `ubyte[n]` where `n` is the size of the target type. You must give the target type as a template argument, because there are multiple types with the same size and so the type of the argument is not enough to determine the return type. 


Taking a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values).

 
Examples:


```
ushort i = 12345;
ubyte[2] swappedI = nativeToBigEndian(i);
writeln(i); // bigEndianToNative!ushort(swappedI)

dchar c = 'D';
ubyte[4] swappedC = nativeToBigEndian(c);
writeln(c); // bigEndianToNative!dchar(swappedC)

```
 
  pure nothrow @nogc @safe auto **nativeToLittleEndian**(T)(const T val)  
 Constraints: if (canSwapEndianness!T); 
 
Converts the given value from the native endianness to little endian and returns it as a `ubyte[n]` where `n` is the size of the given type. 


Returning a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values).

 
Examples:


```
int i = 12345;
ubyte[4] swappedI = nativeToLittleEndian(i);
writeln(i); // littleEndianToNative!int(swappedI)

double d = 123.45;
ubyte[8] swappedD = nativeToLittleEndian(d);
writeln(d); // littleEndianToNative!double(swappedD)

```
 
  pure nothrow @nogc @safe T **littleEndianToNative**(T, size\_t n)(ubyte[n] val)  
 Constraints: if (canSwapEndianness!T && (n == T.sizeof)); 
 
Converts the given value from little endian to the native endianness and returns it. The value is given as a `ubyte[n]` where `n` is the size of the target type. You must give the target type as a template argument, because there are multiple types with the same size and so the type of the argument is not enough to determine the return type. 


Taking a `ubyte[n]` helps prevent accidentally using a swapped value as a regular one (and in the case of floating point values, it's necessary, because the FPU will mess up any swapped floating point values. So, you can't actually have swapped floating point values as floating point values).   
  
 `real` is not supported, because its size is implementation-dependent and therefore could vary from machine to machine (which could make it unusable if you tried to transfer it to another machine).

 
Examples:


```
ushort i = 12345;
ubyte[2] swappedI = nativeToLittleEndian(i);
writeln(i); // littleEndianToNative!ushort(swappedI)

dchar c = 'D';
ubyte[4] swappedC = nativeToLittleEndian(c);
writeln(c); // littleEndianToNative!dchar(swappedC)

```
 
  T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range)  
 Constraints: if (canSwapEndianness!T && isForwardRange!R && is(ElementType!R : const(ubyte)));   
  
T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range, size\_t index)  
 Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : const(ubyte)));   
  
T **peek**(T, Endian endianness = Endian.bigEndian, R)(R range, size\_t\* index)  
 Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : const(ubyte))); 
 
Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to `T`. The value returned is converted from the given endianness to the native endianness. The range is not consumed. 



Parameters:


|  |  |
| --- | --- |
| T | The integral type to convert the first `T.sizeof` bytes to. |
| endianness | The endianness that the bytes are assumed to be in. |
| R `range` | The range to read from. |
| size\_t `index` | The index to start reading from (instead of starting at the front). If index is a pointer, then it is updated to the index after the bytes read. The overloads with index are only available if `hasSlicing!R` is `true`. |


 
Examples:


```
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
writeln(buffer.peek!uint()); // 17110537
writeln(buffer.peek!ushort()); // 261
writeln(buffer.peek!ubyte()); // 1

writeln(buffer.peek!uint(2)); // 369700095
writeln(buffer.peek!ushort(2)); // 5641
writeln(buffer.peek!ubyte(2)); // 22

size_t index = 0;
writeln(buffer.peek!ushort(&index)); // 261
writeln(index); // 2

writeln(buffer.peek!uint(&index)); // 369700095
writeln(index); // 6

writeln(buffer.peek!ubyte(&index)); // 8
writeln(index); // 7

```
 
 
Examples:


```
import std.algorithm.iteration : filter;
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 7];
auto range = filter!"true"(buffer);
writeln(range.peek!uint()); // 17110537
writeln(range.peek!ushort()); // 261
writeln(range.peek!ubyte()); // 1

```
 
  T **read**(T, Endian endianness = Endian.bigEndian, R)(ref R range)  
 Constraints: if (canSwapEndianness!T && isInputRange!R && is(ElementType!R : const(ubyte))); 
 
Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to `T`. The value returned is converted from the given endianness to the native endianness. The `T.sizeof` bytes which are read are consumed from the range. 



Parameters:


|  |  |
| --- | --- |
| T | The integral type to convert the first `T.sizeof` bytes to. |
| endianness | The endianness that the bytes are assumed to be in. |
| R `range` | The range to read from. |


 
Examples:


```
import std.range.primitives : empty;
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
writeln(buffer.length); // 7

writeln(buffer.read!ushort()); // 261
writeln(buffer.length); // 5

writeln(buffer.read!uint()); // 369700095
writeln(buffer.length); // 1

writeln(buffer.read!ubyte()); // 8
assert(buffer.empty);

```
 
  void **write**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size\_t index)  
 Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : ubyte));   
  
void **write**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size\_t\* index)  
 Constraints: if (canSwapEndianness!T && isForwardRange!R && hasSlicing!R && is(ElementType!R : ubyte)); 
 
Takes an integral value, converts it to the given endianness, and writes it to the given range of `ubyte`s as a sequence of `T.sizeof` `ubyte`s starting at index. `hasSlicing!R` must be `true`. 



Parameters:


|  |  |
| --- | --- |
| T | The integral type to convert the first `T.sizeof` bytes to. |
| endianness | The endianness to write the bytes in. |
| R `range` | The range to write to. |
| T `value` | The value to write. |
| size\_t `index` | The index to start writing to. If index is a pointer, then it is updated to the index after the bytes read. |


 
Examples:


```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!uint(29110231u, 0);
writeln(buffer); // [1, 188, 47, 215, 0, 0, 0, 0]

buffer.write!ushort(927, 0);
writeln(buffer); // [3, 159, 47, 215, 0, 0, 0, 0]

buffer.write!ubyte(42, 0);
writeln(buffer); // [42, 159, 47, 215, 0, 0, 0, 0]

```
 
 
Examples:


```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!uint(142700095u, 2);
writeln(buffer); // [0, 0, 8, 129, 110, 63, 0, 0, 0]

buffer.write!ushort(19839, 2);
writeln(buffer); // [0, 0, 77, 127, 110, 63, 0, 0, 0]

buffer.write!ubyte(132, 2);
writeln(buffer); // [0, 0, 132, 127, 110, 63, 0, 0, 0]

```
 
 
Examples:


```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
size_t index = 0;
buffer.write!ushort(261, &index);
writeln(buffer); // [1, 5, 0, 0, 0, 0, 0, 0]
writeln(index); // 2

buffer.write!uint(369700095u, &index);
writeln(buffer); // [1, 5, 22, 9, 44, 255, 0, 0]
writeln(index); // 6

buffer.write!ubyte(8, &index);
writeln(buffer); // [1, 5, 22, 9, 44, 255, 8, 0]
writeln(index); // 7

```
 
 
Examples:
bool 
```
ubyte[] buffer = [0, 0];
buffer.write!bool(false, 0);
writeln(buffer); // [0, 0]

buffer.write!bool(true, 0);
writeln(buffer); // [1, 0]

buffer.write!bool(true, 1);
writeln(buffer); // [1, 1]

buffer.write!bool(false, 1);
writeln(buffer); // [1, 0]

size_t index = 0;
buffer.write!bool(false, &index);
writeln(buffer); // [0, 0]
writeln(index); // 1

buffer.write!bool(true, &index);
writeln(buffer); // [0, 1]
writeln(index); // 2

```
 
 
Examples:
char(8-bit) 
```
ubyte[] buffer = [0, 0, 0];

buffer.write!char('a', 0);
writeln(buffer); // [97, 0, 0]

buffer.write!char('b', 1);
writeln(buffer); // [97, 98, 0]

size_t index = 0;
buffer.write!char('a', &index);
writeln(buffer); // [97, 98, 0]
writeln(index); // 1

buffer.write!char('b', &index);
writeln(buffer); // [97, 98, 0]
writeln(index); // 2

buffer.write!char('c', &index);
writeln(buffer); // [97, 98, 99]
writeln(index); // 3

```
 
 
Examples:
wchar (16bit - 2x ubyte) 
```
ubyte[] buffer = [0, 0, 0, 0];

buffer.write!wchar('ą', 0);
writeln(buffer); // [1, 5, 0, 0]

buffer.write!wchar('”', 2);
writeln(buffer); // [1, 5, 32, 29]

size_t index = 0;
buffer.write!wchar('ć', &index);
writeln(buffer); // [1, 7, 32, 29]
writeln(index); // 2

buffer.write!wchar('ą', &index);
writeln(buffer); // [1, 7, 1, 5]
writeln(index); // 4

```
 
 
Examples:
dchar (32bit - 4x ubyte) 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];

buffer.write!dchar('ą', 0);
writeln(buffer); // [0, 0, 1, 5, 0, 0, 0, 0]

buffer.write!dchar('”', 4);
writeln(buffer); // [0, 0, 1, 5, 0, 0, 32, 29]

size_t index = 0;
buffer.write!dchar('ć', &index);
writeln(buffer); // [0, 0, 1, 7, 0, 0, 32, 29]
writeln(index); // 4

buffer.write!dchar('ą', &index);
writeln(buffer); // [0, 0, 1, 7, 0, 0, 1, 5]
writeln(index); // 8

```
 
 
Examples:
float (32bit - 4x ubyte) 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];

buffer.write!float(32.0f, 0);
writeln(buffer); // [66, 0, 0, 0, 0, 0, 0, 0]

buffer.write!float(25.0f, 4);
writeln(buffer); // [66, 0, 0, 0, 65, 200, 0, 0]

size_t index = 0;
buffer.write!float(25.0f, &index);
writeln(buffer); // [65, 200, 0, 0, 65, 200, 0, 0]
writeln(index); // 4

buffer.write!float(32.0f, &index);
writeln(buffer); // [65, 200, 0, 0, 66, 0, 0, 0]
writeln(index); // 8

```
 
 
Examples:
double (64bit - 8x ubyte) 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

buffer.write!double(32.0, 0);
writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

buffer.write!double(25.0, 8);
writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]

size_t index = 0;
buffer.write!double(25.0, &index);
writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]
writeln(index); // 8

buffer.write!double(32.0, &index);
writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]
writeln(index); // 16

```
 
 
Examples:
enum 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

enum Foo
{
    one = 10,
    two = 20,
    three = 30
}

buffer.write!Foo(Foo.one, 0);
writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0]

buffer.write!Foo(Foo.two, 4);
writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 0]

buffer.write!Foo(Foo.three, 8);
writeln(buffer); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30]

size_t index = 0;
buffer.write!Foo(Foo.three, &index);
writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 20, 0, 0, 0, 30]
writeln(index); // 4

buffer.write!Foo(Foo.one, &index);
writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 30]
writeln(index); // 8

buffer.write!Foo(Foo.two, &index);
writeln(buffer); // [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 20]
writeln(index); // 12

```
 
 
Examples:
enum - float 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];

enum Float: float
{
    one = 32.0f,
    two = 25.0f
}

buffer.write!Float(Float.one, 0);
writeln(buffer); // [66, 0, 0, 0, 0, 0, 0, 0]

buffer.write!Float(Float.two, 4);
writeln(buffer); // [66, 0, 0, 0, 65, 200, 0, 0]

size_t index = 0;
buffer.write!Float(Float.two, &index);
writeln(buffer); // [65, 200, 0, 0, 65, 200, 0, 0]
writeln(index); // 4

buffer.write!Float(Float.one, &index);
writeln(buffer); // [65, 200, 0, 0, 66, 0, 0, 0]
writeln(index); // 8

```
 
 
Examples:
enum - double 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

enum Double: double
{
    one = 32.0,
    two = 25.0
}

buffer.write!Double(Double.one, 0);
writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

buffer.write!Double(Double.two, 8);
writeln(buffer); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]

size_t index = 0;
buffer.write!Double(Double.two, &index);
writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]
writeln(index); // 8

buffer.write!Double(Double.one, &index);
writeln(buffer); // [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]
writeln(index); // 16

```
 
 
Examples:
enum - real 
```
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

enum Real: real
{
    one = 32.0,
    two = 25.0
}

static assert(!__traits(compiles, buffer.write!Real(Real.one)));

```
 
  void **append**(T, Endian endianness = Endian.bigEndian, R)(R range, const T value)  
 Constraints: if (canSwapEndianness!T && isOutputRange!(R, ubyte)); 
 
Takes an integral value, converts it to the given endianness, and appends it to the given range of `ubyte`s (using `put`) as a sequence of `T.sizeof` `ubyte`s starting at index. `hasSlicing!R` must be `true`. 



Parameters:


|  |  |
| --- | --- |
| T | The integral type to convert the first `T.sizeof` bytes to. |
| endianness | The endianness to write the bytes in. |
| R `range` | The range to append to. |
| T `value` | The value to append. |


 
Examples:


```
import std.array;
auto buffer = appender!(const ubyte[])();
buffer.append!ushort(261);
writeln(buffer.data); // [1, 5]

buffer.append!uint(369700095u);
writeln(buffer.data); // [1, 5, 22, 9, 44, 255]

buffer.append!ubyte(8);
writeln(buffer.data); // [1, 5, 22, 9, 44, 255, 8]

```
 
 
Examples:
bool 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

buffer.append!bool(true);
writeln(buffer.data); // [1]

buffer.append!bool(false);
writeln(buffer.data); // [1, 0]

```
 
 
Examples:
char wchar dchar 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

buffer.append!char('a');
writeln(buffer.data); // [97]

buffer.append!char('b');
writeln(buffer.data); // [97, 98]

buffer.append!wchar('ą');
writeln(buffer.data); // [97, 98, 1, 5]

buffer.append!dchar('ą');
    writeln(buffer.data); // [97, 98, 1, 5, 0, 0, 1, 5]

```
 
 
Examples:
float double 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

buffer.append!float(32.0f);
writeln(buffer.data); // [66, 0, 0, 0]

buffer.append!double(32.0);
writeln(buffer.data); // [66, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]

```
 
 
Examples:
enum 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

enum Foo
{
    one = 10,
    two = 20,
    three = 30
}

buffer.append!Foo(Foo.one);
writeln(buffer.data); // [0, 0, 0, 10]

buffer.append!Foo(Foo.two);
writeln(buffer.data); // [0, 0, 0, 10, 0, 0, 0, 20]

buffer.append!Foo(Foo.three);
writeln(buffer.data); // [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30]

```
 
 
Examples:
enum - bool 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

enum Bool: bool
{
    bfalse = false,
    btrue = true,
}

buffer.append!Bool(Bool.btrue);
writeln(buffer.data); // [1]

buffer.append!Bool(Bool.bfalse);
writeln(buffer.data); // [1, 0]

buffer.append!Bool(Bool.btrue);
writeln(buffer.data); // [1, 0, 1]

```
 
 
Examples:
enum - float 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

enum Float: float
{
    one = 32.0f,
    two = 25.0f
}

buffer.append!Float(Float.one);
writeln(buffer.data); // [66, 0, 0, 0]

buffer.append!Float(Float.two);
writeln(buffer.data); // [66, 0, 0, 0, 65, 200, 0, 0]

```
 
 
Examples:
enum - double 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

enum Double: double
{
    one = 32.0,
    two = 25.0
}

buffer.append!Double(Double.one);
writeln(buffer.data); // [64, 64, 0, 0, 0, 0, 0, 0]

buffer.append!Double(Double.two);
writeln(buffer.data); // [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]

```
 
 
Examples:
enum - real 
```
import std.array : appender;
auto buffer = appender!(const ubyte[])();

enum Real: real
{
    one = 32.0,
    two = 25.0
}

static assert(!__traits(compiles, buffer.append!Real(Real.one)));

```
 
  pure nothrow @nogc auto **bitsSet**(T)(const T value)  
 Constraints: if (isIntegral!T); 
 
Range that iterates the indices of the set bits in `value`. Index 0 corresponds to the least significant bit. For signed integers, the highest index corresponds to the sign bit.



Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;

assert(bitsSet(1).equal([0]));
assert(bitsSet(5).equal([0, 2]));
assert(bitsSet(-1).equal(iota(32)));
assert(bitsSet(int.min).equal([31]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_bitmanip.html>

std.container.util
==================

 This module contains some common utilities used by containers. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/util.d](https://github.com/dlang/phobos/blob/master/std/container/util.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
template **make**(T) if (is(T == struct) || is(T == class)) 
Returns an initialized object. This function is mainly for eliminating construction differences between structs and classes. It allows code to not worry about whether the type it's constructing is a struct or a class.



Examples:


```
import std.algorithm.comparison : equal;
import std.container;

auto arr = make!(Array!int)([4, 2, 3, 1]);
assert(equal(arr[], [4, 2, 3, 1]));

auto rbt = make!(RedBlackTree!(int, "a > b"))([4, 2, 3, 1]);
assert(equal(rbt[], [4, 3, 2, 1]));

alias makeList = make!(SList!int);
auto slist = makeList(1, 2, 3);
assert(equal(slist[], [1, 2, 3]));

```
 
  template **make**(alias Container, Args...) if (!is(Container)) 
Convenience function for constructing a generic container.



Examples:
forbid construction from infinite range 
```
import std.container.array : Array;
import std.range : only, repeat;
import std.range.primitives : isInfinite;
static assert(__traits(compiles, { auto arr = make!Array(only(5)); }));
static assert(!__traits(compiles, { auto arr = make!Array(repeat(5)); }));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.container.array, std.container.rbtree, std.container.slist;
import std.range : iota;

auto arr = make!Array(iota(5));
assert(equal(arr[], [0, 1, 2, 3, 4]));

auto rbtmax = make!(RedBlackTree, "a > b")(iota(5));
assert(equal(rbtmax[], [4, 3, 2, 1, 0]));

auto rbtmin = make!RedBlackTree(4, 1, 3, 2);
assert(equal(rbtmin[], [1, 2, 3, 4]));

alias makeList = make!SList;
auto list = makeList(1, 7, 42);
assert(equal(list[], [1, 7, 42]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_util.html>

std.container.array
===================

 This module provides an `Array` type with deterministic memory usage not reliant on the GC, as an alternative to the built-in arrays. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/array.d](https://github.com/dlang/phobos/blob/master/std/container/array.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://%20boost.org/LICENSE_1_0.txt)). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Examples:


```
auto arr = Array!int(0, 2, 3);
writeln(arr[0]); // 0
writeln(arr.front); // 0
writeln(arr.back); // 3

// reserve space
arr.reserve(1000);
writeln(arr.length); // 3
assert(arr.capacity >= 1000);

// insertion
arr.insertBefore(arr[1..$], 1);
writeln(arr.front); // 0
writeln(arr.length); // 4

arr.insertBack(4);
writeln(arr.back); // 4
writeln(arr.length); // 5

// set elements
arr[1] *= 42;
writeln(arr[1]); // 42

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
auto arr = Array!int(1, 2, 3);

// concat
auto b = Array!int(11, 12, 13);
arr ~= b;
writeln(arr.length); // 6

// slicing
assert(arr[1 .. 3].equal([2, 3]));

// remove
arr.linearRemove(arr[1 .. 3]);
assert(arr[0 .. 2].equal([1, 11]));

```
 
 
Examples:

`Array!bool` packs together values efficiently by allocating one bit per element 
```
Array!bool arr;
arr.insert([true, true, false, true, false]);
writeln(arr.length); // 5

```
 
 
struct **Array**(T) if (!is(immutable(T) == immutable(bool)));  
Array type with deterministic control of memory. The memory allocated for the array is reclaimed as soon as possible; there is no reliance on the garbage collector. `Array` uses `malloc`, `realloc` and `free` for managing its own memory. 


This means that pointers to elements of an `Array` will become dangling as soon as the element is removed from the `Array`. On the other hand the memory allocated by an `Array` will be scanned by the GC and GC managed objects referenced from an `Array` will be kept alive. 

 
Note
 When using `Array` with range-based functions like those in `std.algorithm`, `Array` must be sliced to get a range (for example, use `array[].map!` instead of `array.map!`). The container itself is not a range.
 
Examples:
typeof may give wrong result in case of classes defining `opCall` operator <https://issues.dlang.org/show_bug.cgi?id=20589> destructor std.container.array.Array!(MyClass).Array.~this is @system so the unittest is @system too 
```
class MyClass
{
    T opCall(T)(T p)
    {
        return p;
    }
}

Array!MyClass arr;

```
 
 
this(U)(U[] values...)  
 Constraints: if (isImplicitlyConvertible!(U, T)); 
 
Constructor taking a number of items.

  this(Range)(Range r)  
 Constraints: if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range, T) && !is(Range == T[])); 
 
Constructor taking an [input range](std_range_primitives#isInputRange)

  const bool **opEquals**(const Array rhs);   
  
const bool **opEquals**(ref const Array rhs);  
Comparison for equality.

  alias **Range** = RangeT!Array;   
  
alias **ConstRange** = RangeT!(const(Array));   
  
alias **ImmutableRange** = RangeT!(immutable(Array));  
Defines the array's primary range, which is a random-access range. 


`ConstRange` is a variant with `const` elements. `ImmutableRange` is a variant with `immutable` elements.

  @property Array **dup**();  
Duplicates the array. The elements themselves are not transitively duplicated. 



Complexity
 Ο(`length`).
  const @property bool **empty**();  

Returns:

`true` if and only if the array has no elements. 
 
Complexity
 Ο(`1`)

  const @property size\_t **length**();   
  
const size\_t **opDollar**();  

Returns:
The number of elements in the array. 
 
Complexity
 Ο(`1`).
  @property size\_t **capacity**();  

Returns:
The maximum number of elements the array can store without reallocating memory and invalidating iterators upon insertion. 
 
Complexity
 Ο(`1`)

  void **reserve**(size\_t elements);  
Ensures sufficient capacity to accommodate `e` elements. If `e < capacity`, this method does nothing. 



Postcondition
 `capacity >= e` 
 
Note
 If the capacity is increased, one should assume that all iterators to the elements are invalidated. 
 
Complexity
 at most Ο(`length`) if `e > capacity`, otherwise Ο(`1`).
  Range **opSlice**();  

Returns:
A range that iterates over elements of the array in forward order. 
 
Complexity
 Ο(`1`)

  Range **opSlice**(size\_t i, size\_t j);  

Returns:
A range that iterates over elements of the array from index `i` up to (excluding) index `j`. 
 
Precondition
 `i <= j && j <= length` 
 
Complexity
 Ο(`1`)

  inout @property ref inout(T) **front**();  

Returns:
The first element of the array. 
 
Precondition
 `empty == false` 
 
Complexity
 Ο(`1`)

  inout @property ref inout(T) **back**();  

Returns:
The last element of the array. 
 
Precondition
 `empty == false` 
 
Complexity
 Ο(`1`)

  inout ref inout(T) **opIndex**(size\_t i);  

Returns:
The element or a reference to the element at the specified index. 
 
Precondition
 `i < length` 
 
Complexity
 Ο(`1`)

  void **opSliceAssign**(T value);   
  
void **opSliceAssign**(T value, size\_t i, size\_t j);   
  
void **opSliceUnary**(string op)()  
 Constraints: if (op == "++" || op == "--");   
  
void **opSliceUnary**(string op)(size\_t i, size\_t j)  
 Constraints: if (op == "++" || op == "--");   
  
void **opSliceOpAssign**(string op)(T value);   
  
void **opSliceOpAssign**(string op)(T value, size\_t i, size\_t j);  
Slicing operators executing the specified operation on the entire slice. 



Precondition
 `i < j && j < length` 
 
Complexity
 Ο(`slice.length`)

  Array **opBinary**(string op, Stuff)(Stuff stuff)  
 Constraints: if (op == "~"); 
 

Returns:
A new array which is a concatenation of `this` and its argument. 
 
Complexity
 Ο(`length + m`), where `m` is the number of elements in `stuff`.
  void **opOpAssign**(string op, Stuff)(auto ref Stuff stuff)  
 Constraints: if (op == "~"); 
 
Forwards to `insertBack`.

  void **clear**();  
Removes all the elements from the array and releases allocated memory. 



Postcondition
 `empty == true && capacity == 0` 
 
Complexity
 Ο(`length`)

  @property void **length**(size\_t newLength);  
Sets the number of elements in the array to `newLength`. If `newLength` is greater than `length`, the new elements are added to the end of the array and initialized with `T.init`. 



Complexity
 Guaranteed Ο(`abs(length - newLength)`) if `capacity >= newLength`. If `capacity < newLength` the worst case is Ο(`newLength`). 
 
Postcondition
 `length == newLength`

  T **removeAny**();   
  
alias **stableRemoveAny** = removeAny;  
Removes the last element from the array and returns it. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Precondition
 `empty == false` 
 
Returns:
The element removed. 
 
Complexity
 Ο(`1`). 
 
Throws:

`Exception` if the array is empty.
  size\_t **insertBack**(Stuff)(Stuff stuff)  
 Constraints: if (isImplicitlyConvertible!(Stuff, T) || isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T));   
  
alias **insert** = insertBack;  
Inserts the specified elements at the back of the array. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. 



Returns:
The number of elements inserted. 
 
Complexity
 Ο(`length + m`) if reallocation takes place, otherwise Ο(`m`), where `m` is the number of elements in `stuff`.
  void **removeBack**();   
  
alias **stableRemoveBack** = removeBack;  
Removes the value from the back of the array. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Precondition
 `empty == false` 
 
Complexity
 Ο(`1`). 
 
Throws:

`Exception` if the array is empty.
  size\_t **removeBack**(size\_t howMany);   
  
alias **stableRemoveBack** = removeBack;  
Removes `howMany` values from the back of the array. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Returns:
The number of elements removed. 
 
Complexity
 Ο(`howMany`).
  size\_t **insertBefore**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (isImplicitlyConvertible!(Stuff, T));   
  
size\_t **insertBefore**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T));   
  
alias **stableInsertBefore** = insertBefore;   
  
size\_t **insertAfter**(Stuff)(Range r, Stuff stuff);   
  
size\_t **replace**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T));   
  
size\_t **replace**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (isImplicitlyConvertible!(Stuff, T)); 
 
Inserts `stuff` before, after, or instead range `r`, which must be a valid range previously extracted from this array. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. Both stable and non-stable version behave the same and guarantee that ranges iterating over the array are never invalidated. 



Returns:
The number of values inserted. 
 
Complexity
 Ο(`length + m`), where `m` is the length of `stuff`. 
 
Throws:

`Exception` if `r` is not a range extracted from this array.
  Range **linearRemove**(Range r);  
Removes all elements belonging to `r`, which must be a range obtained originally from this array. 



Returns:
A range spanning the remaining elements in the array that initially were right after `r`. 
 
Complexity
 Ο(`length`) 
 
Throws:

`Exception` if `r` is not a valid range extracted from this array.
    struct **Array**(T) if (is(immutable(T) == immutable(bool)));  
Array specialized for `bool`. Packs together values efficiently by allocating one bit per element.

 
struct **Range**;  
Defines the array's primary range.

 
@property Range **save**();   
  
@property bool **empty**();   
  
@property T **front**();   
  
@property void **front**(bool value);   
  
T **moveFront**();   
  
void **popFront**();   
  
@property T **back**();   
  
@property void **back**(bool value);   
  
T **moveBack**();   
  
void **popBack**();   
  
T **opIndex**(size\_t i);   
  
void **opIndexAssign**(T value, size\_t i);   
  
T **moveAt**(size\_t i);   
  
const @property size\_t **length**();   
  
Range **opSlice**(size\_t low, size\_t high);  
Range primitives

    @property bool **empty**();  
Property returning `true` if and only if the array has no elements. 



Complexity
 Ο(`1`)

  @property Array **dup**();  

Returns:
A duplicate of the array. 
 
Complexity
 Ο(`length`).
  const @property size\_t **length**();  
Returns the number of elements in the array. 



Complexity
 Ο(`1`).
  @property size\_t **capacity**();  

Returns:
The maximum number of elements the array can store without reallocating memory and invalidating iterators upon insertion. 
 
Complexity
 Ο(`1`).
  void **reserve**(size\_t e);  
Ensures sufficient capacity to accommodate `e` elements. If `e < capacity`, this method does nothing. 



Postcondition
 `capacity >= e` 
 
Note
 If the capacity is increased, one should assume that all iterators to the elements are invalidated. 
 
Complexity
 at most Ο(`length`) if `e > capacity`, otherwise Ο(`1`).
  Range **opSlice**();  

Returns:
A range that iterates over all elements of the array in forward order. 
 
Complexity
 Ο(`1`)

  Range **opSlice**(size\_t a, size\_t b);  

Returns:
A range that iterates the array between two specified positions. 
 
Complexity
 Ο(`1`)

  @property bool **front**();   
  
@property void **front**(bool value);  

Returns:
The first element of the array. 
 
Precondition
 `empty == false` 
 
Complexity
 Ο(`1`) 
 
Throws:

`Exception` if the array is empty.
  @property bool **back**();   
  
@property void **back**(bool value);  

Returns:
The last element of the array. 
 
Precondition
 `empty == false` 
 
Complexity
 Ο(`1`) 
 
Throws:

`Exception` if the array is empty.
  bool **opIndex**(size\_t i);   
  
void **opIndexAssign**(bool value, size\_t i);   
  
void **opIndexOpAssign**(string op)(bool value, size\_t i);   
  
T **moveAt**(size\_t i);  
Indexing operators yielding or modifyng the value at the specified index. 



Precondition
 `i < length` 
 
Complexity
 Ο(`1`)

  Array!bool **opBinary**(string op, Stuff)(Stuff rhs)  
 Constraints: if (op == "~"); 
 

Returns:
A new array which is a concatenation of `this` and its argument. 
 
Complexity
 Ο(`length + m`), where `m` is the number of elements in `stuff`.
  Array!bool **opOpAssign**(string op, Stuff)(Stuff stuff)  
 Constraints: if (op == "~"); 
 
Forwards to `insertBack`.

  void **clear**();  
Removes all the elements from the array and releases allocated memory. 



Postcondition
 `empty == true && capacity == 0` 
 
Complexity
 Ο(`length`)

  @property void **length**(size\_t newLength);  
Sets the number of elements in the array to `newLength`. If `newLength` is greater than `length`, the new elements are added to the end of the array and initialized with `false`. 



Complexity
 Guaranteed Ο(`abs(length - newLength)`) if `capacity >= newLength`. If `capacity < newLength` the worst case is Ο(`newLength`). 
 
Postcondition
 `length == newLength`

  T **removeAny**();   
  
alias **stableRemoveAny** = removeAny;  
Removes the last element from the array and returns it. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Precondition
 `empty == false` 
 
Returns:
The element removed. 
 
Complexity
 Ο(`1`). 
 
Throws:

`Exception` if the array is empty.
  size\_t **insertBack**(Stuff)(Stuff stuff)  
 Constraints: if (is(Stuff : bool));   
  
size\_t **insertBack**(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff && is(ElementType!Stuff : bool));   
  
alias **stableInsertBack** = insertBack;   
  
alias **insert** = insertBack;   
  
alias **stableInsert** = insertBack;   
  
alias **linearInsert** = insertBack;   
  
alias **stableLinearInsert** = insertBack;  
Inserts the specified elements at the back of the array. `stuff` can be a value convertible to `bool` or a range of objects convertible to `bool`. 



Returns:
The number of elements inserted. 
 
Complexity
 Ο(`length + m`) if reallocation takes place, otherwise Ο(`m`), where `m` is the number of elements in `stuff`.
  void **removeBack**();   
  
alias **stableRemoveBack** = removeBack;  
Removes the value from the back of the array. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Precondition
 `empty == false` 
 
Complexity
 Ο(`1`). 
 
Throws:

`Exception` if the array is empty.
  size\_t **removeBack**(size\_t howMany);   
  
alias **stableRemoveBack** = removeBack;  
Removes `howMany` values from the back of the array. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. Both stable and non-stable versions behave the same and guarantee that ranges iterating over the array are never invalidated. 



Returns:
The number of elements removed. 
 
Complexity
 Ο(`howMany`).
  size\_t **insertBefore**(Stuff)(Range r, Stuff stuff);   
  
alias **stableInsertBefore** = insertBefore;   
  
size\_t **insertAfter**(Stuff)(Range r, Stuff stuff);   
  
alias **stableInsertAfter** = insertAfter;   
  
size\_t **replace**(Stuff)(Range r, Stuff stuff)  
 Constraints: if (is(Stuff : bool));   
  
alias **stableReplace** = replace;  
Inserts `stuff` before, after, or instead range `r`, which must be a valid range previously extracted from this array. `stuff` can be a value convertible to `bool` or a range of objects convertible to `bool`. Both stable and non-stable version behave the same and guarantee that ranges iterating over the array are never invalidated. 



Returns:
The number of values inserted. 
 
Complexity
 Ο(`length + m`), where `m` is the length of `stuff`.
  Range **linearRemove**(Range r);  
Removes all elements belonging to `r`, which must be a range obtained originally from this array. 



Returns:
A range spanning the remaining elements in the array that initially were right after `r`. 
 
Complexity
 Ο(`length`)

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_array.html>

std.algorithm.searching
=======================

 This is a submodule of [`std.algorithm`](std_algorithm). It contains generic searching algorithms. 


 

Cheat Sheet| Function Name | Description |
| [`all`](#all) | `all!"a > 0"([1, 2, 3, 4])` returns `true` because all elements are positive |
| [`any`](#any) | `any!"a > 0"([1, 2, -3, -4])` returns `true` because at least one element is positive |
| [`balancedParens`](#balancedParens) | `balancedParens("((1 + 1) / 2)")` returns `true` because the string has balanced parentheses. |
| [`boyerMooreFinder`](#boyerMooreFinder) | `find("hello world", boyerMooreFinder("or"))` returns `"orld"` using the  [Boyer-Moore algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm). |
| [`canFind`](#canFind) | `canFind("hello world", "or")` returns `true`. |
| [`count`](#count) |  Counts elements that are equal to a specified value or satisfy a predicate. `count([1, 2, 1], 1)` returns `2` and `count!"a < 0"([1, -3, 0])` returns `1`. |
| [`countUntil`](#countUntil) | `countUntil(a, b)` returns the number of steps taken in `a` to reach `b`; for example, `countUntil("hello!", "o")` returns `4`. |
| [`commonPrefix`](#commonPrefix) | `commonPrefix("parakeet", "parachute")` returns `"para"`. |
| [`endsWith`](#endsWith) | `endsWith("rocks", "ks")` returns `true`. |
| [`find`](#find) | `find("hello world", "or")` returns `"orld"` using linear search. (For binary search refer to [`std.range.SortedRange`](std_range#SortedRange).) |
| [`findAdjacent`](#findAdjacent) | `findAdjacent([1, 2, 3, 3, 4])` returns the subrange starting with two equal adjacent elements, i.e. `[3, 3, 4]`. |
| [`findAmong`](#findAmong) | `findAmong("abcd", "qcx")` returns `"cd"` because `'c'` is among `"qcx"`. |
| [`findSkip`](#findSkip) |  If `a = "abcde"`, then `findSkip(a, "x")` returns `false` and leaves `a` unchanged, whereas `findSkip(a, "c")` advances `a` to `"de"` and returns `true`. |
| [`findSplit`](#findSplit) | `findSplit("abcdefg", "de")` returns the three ranges `"abc"`, `"de"`, and `"fg"`. |
| [`findSplitAfter`](#findSplitAfter) | `findSplitAfter("abcdefg", "de")` returns the two ranges `"abcde"` and `"fg"`. |
| [`findSplitBefore`](#findSplitBefore) | `findSplitBefore("abcdefg", "de")` returns the two ranges `"abc"` and `"defg"`. |
| [`minCount`](#minCount) | `minCount([2, 1, 1, 4, 1])` returns `tuple(1, 3)`. |
| [`maxCount`](#maxCount) | `maxCount([2, 4, 1, 4, 1])` returns `tuple(4, 2)`. |
| [`minElement`](#minElement) |  Selects the minimal element of a range. `minElement([3, 4, 1, 2])` returns `1`. |
| [`maxElement`](#maxElement) |  Selects the maximal element of a range. `maxElement([3, 4, 1, 2])` returns `4`. |
| [`minIndex`](#minIndex) |  Index of the minimal element of a range. `minElement([3, 4, 1, 2])` returns `2`. |
| [`maxIndex`](#maxIndex) |  Index of the maximal element of a range. `maxElement([3, 4, 1, 2])` returns `1`. |
| [`minPos`](#minPos) | `minPos([2, 3, 1, 3, 4, 1])` returns the subrange `[1, 3, 4, 1]`, i.e., positions the range at the first occurrence of its minimal element. |
| [`maxPos`](#maxPos) | `maxPos([2, 3, 1, 3, 4, 1])` returns the subrange `[4, 1]`, i.e., positions the range at the first occurrence of its maximal element. |
| [`skipOver`](#skipOver) |  Assume `a = "blah"`. Then `skipOver(a, "bi")` leaves `a` unchanged and returns `false`, whereas `skipOver(a, "bl")` advances `a` to refer to `"ah"` and returns `true`. |
| [`startsWith`](#startsWith) | `startsWith("hello, world", "hello")` returns `true`. |
| [`until`](#until) |  Lazily iterates a range until a specific value is found. |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/algorithm/searching.d](https://github.com/dlang/phobos/blob/master/std/algorithm/searching.d) 
 
template **all**(alias pred = "a") 
Checks if *all* of the elements verify `pred`.



Examples:


```
assert( all!"a & 1"([1, 3, 5, 7, 9]));
assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));

```
 
 
Examples:

`all` can also be used without a predicate, if its items can be evaluated to true or false in a conditional statement. This can be a convenient way to quickly evaluate that *all* of the elements of a range are true. 
```
int[3] vals = [5, 3, 18];
assert( all(vals[]));

```
 
 
bool **all**(Range)(Range range)  
 Constraints: if (isInputRange!Range); 
 
Returns `true` if and only if *all* values `v` found in the input range `range` satisfy the predicate `pred`. Performs (at most) Ο(`range.length`) evaluations of `pred`.

    template **any**(alias pred = "a") 
Checks if *any* of the elements verifies `pred`. `!any` can be used to verify that *none* of the elements verify `pred`. This is sometimes called `exists` in other languages.



Examples:


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

```
 
 
Examples:

`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[]));

```
 
 
bool **any**(Range)(Range range)  
 Constraints: if (isInputRange!Range && is(typeof(unaryFun!pred(range.front)))); 
 
Returns `true` if and only if *any* value `v` found in the input range `range` satisfies the predicate `pred`. Performs (at most) Ο(`range.length`) evaluations of `pred`.

    bool **balancedParens**(Range, E)(Range r, E lPar, E rPar, size\_t maxNestingLevel = size\_t.max)  
 Constraints: if (isInputRange!Range && is(typeof(r.front == lPar))); 
 
Checks whether `r` has "balanced parentheses", i.e. all instances of `lPar` are closed by corresponding instances of `rPar`. The parameter `maxNestingLevel` controls the nesting level allowed. The most common uses are the default or `0`. In the latter case, no nesting is allowed. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | The range to check. |
| E `lPar` | The element corresponding with a left (opening) parenthesis. |
| E `rPar` | The element corresponding with a right (closing) parenthesis. |
| size\_t `maxNestingLevel` | The maximum allowed nesting level. |


 
Returns:
true if the given range has balanced parenthesis within the given maximum nesting level; false otherwise.
 
Examples:


```
auto s = "1 + (2 * (3 + 1 / 2)";
assert(!balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(!balancedParens(s, '(', ')', 0));
s = "1 + (2 * 3 + 1) / (2 - 5)";
assert(balancedParens(s, '(', ')', 0));
s = "f(x) = ⌈x⌉";
assert(balancedParens(s, '⌈', '⌉'));

```
 
  struct **BoyerMooreFinder**(alias pred, Range);   
  
BoyerMooreFinder!(binaryFun!pred, Range) **boyerMooreFinder**(alias pred = "a == b", Range)(Range needle)  
 Constraints: if (isRandomAccessRange!Range && hasSlicing!Range || isSomeString!Range); 
 
Sets up Boyer-Moore matching for use with `find` below. By default, elements are compared for equality. 


`BoyerMooreFinder` allocates GC memory. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Predicate used to compare elements. |
| Range `needle` | A random-access range with length and slicing. |


 
Returns:
An instance of `BoyerMooreFinder` that can be used with `find()` to invoke the Boyer-Moore matching algorithm for finding of `needle` in a given haystack.
 
Examples:


```
auto bmFinder = boyerMooreFinder("TG");

string r = "TAGTGCCTGA";
// search for the first match in the haystack r
r = bmFinder.beFound(r);
writeln(r); // "TGCCTGA"

// continue search in haystack
r = bmFinder.beFound(r[2 .. $]);
writeln(r); // "TGA"

```
 
 
this(Range needle);  scope Range **beFound**(Range haystack);  @property size\_t **length**();  alias **opDollar** = length;    auto **commonPrefix**(alias pred = "a == b", R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isForwardRange!R1 && isInputRange!R2 && !isNarrowString!R1 && is(typeof(binaryFun!pred(r1.front, r2.front))));   
  
auto **commonPrefix**(alias pred, R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isNarrowString!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(r1.front, r2.front))));   
  
auto **commonPrefix**(R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isNarrowString!R1 && isInputRange!R2 && !isNarrowString!R2 && is(typeof(r1.front == r2.front)));   
  
auto **commonPrefix**(R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isNarrowString!R1 && isNarrowString!R2); 
 
Returns the common prefix of two ranges. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate to use in comparing elements for commonality. Defaults to equality `"a == b"`. |
| R1 `r1` | A [forward range](std_range_primitives#isForwardRange) of elements. |
| R2 `r2` | An [input range](std_range_primitives#isInputRange) of elements. |


 
Returns:
A slice of `r1` which contains the characters that both ranges start with, if the first argument is a string; otherwise, the same as the result of `takeExactly(r1, n)`, where `n` is the number of elements in the common prefix of both ranges. 
 
See Also:
[`std.range.takeExactly`](std_range#takeExactly)
 
Examples:


```
writeln(commonPrefix("hello, world", "hello, there")); // "hello, "

```
 
  size\_t **count**(alias pred = "a == b", Range, E)(Range haystack, E needle)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(haystack.front, needle)) : bool));   
  
size\_t **count**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)  
 Constraints: if (isForwardRange!R1 && !isInfinite!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool));   
  
size\_t **count**(alias pred, R)(R haystack)  
 Constraints: if (isInputRange!R && !isInfinite!R && is(typeof(unaryFun!pred(haystack.front)) : bool));   
  
size\_t **count**(R)(R haystack)  
 Constraints: if (isInputRange!R && !isInfinite!R); 
 
The first version counts the number of elements `x` in `r` for which `pred(x, value)` is `true`. `pred` defaults to equality. Performs Ο(`haystack.length`) evaluations of `pred`. 


The second version returns the number of times `needle` occurs in `haystack`. Throws an exception if `needle.empty`, as the count of the empty range in any range would be infinite. Overlapped counts are not considered, for example `count("aaa", "aa")` is `1`, not `2`.   
  
 The third version counts the elements for which `pred(x)` is `true`. Performs Ο(`haystack.length`) evaluations of `pred`.   
  
 The fourth version counts the number of elements in a range. It is an optimization for the third version: if the given range has the `length` property the count is returned right away, otherwise performs Ο(`haystack.length`) to walk the range. 

 
Note
 Regardless of the overload, `count` will not accept infinite ranges for `haystack`. 
 
Parameters:


|  |  |
| --- | --- |
| pred | The predicate to evaluate. |
| Range `haystack` | The range to count. |
| E `needle` | The element or sub-range to count in the `haystack`. |


 
Returns:
The number of positions in the `haystack` for which `pred` returned true.
 
Examples:


```
import std.uni : toLower;

// count elements in range
int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
writeln(count(a)); // 9
writeln(count(a, 2)); // 3
writeln(count!("a > b")(a, 2)); // 5
// count range in range
writeln(count("abcadfabf", "ab")); // 2
writeln(count("ababab", "abab")); // 1
writeln(count("ababab", "abx")); // 0
// fuzzy count range in range
writeln(count!((a, b) => toLower(a) == toLower(b))("AbcAdFaBf", "ab")); // 2
// count predicate in range
writeln(count!("a > 1")(a)); // 8

```
 
  ptrdiff\_t **countUntil**(alias pred = "a == b", R, Rs...)(R haystack, Rs needles)  
 Constraints: if (isForwardRange!R && (Rs.length > 0) && (isForwardRange!(Rs[0]) == isInputRange!(Rs[0])) && is(typeof(startsWith!pred(haystack, needles[0]))) && (Rs.length == 1 || is(typeof(countUntil!pred(haystack, needles[1..$])))));   
  
ptrdiff\_t **countUntil**(alias pred = "a == b", R, N)(R haystack, N needle)  
 Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(haystack.front, needle)) : bool));   
  
ptrdiff\_t **countUntil**(alias pred, R)(R haystack)  
 Constraints: if (isInputRange!R && is(typeof(unaryFun!pred(haystack.front)) : bool)); 
 
Counts elements in the given [forward range](std_range_primitives#isForwardRange) until the given predicate is true for one of the given `needles`. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate for determining when to stop counting. |
| R `haystack` | The [input range](std_range_primitives#isInputRange) to be counted. |
| Rs `needles` | Either a single element, or a [forward range](std_range_primitives#isForwardRange) of elements, to be evaluated in turn against each element in `haystack` under the given predicate. |


 
Returns:
The number of elements which must be popped from the front of `haystack` before reaching an element for which `startsWith!pred(haystack, needles)` is `true`. If `startsWith!pred(haystack, needles)` is not `true` for any element in `haystack`, then `-1` is returned. If only `pred` is provided, `pred(haystack)` is tested for each element. 
 
See Also:
[`std.string.indexOf`](std_string#indexOf)
 
Examples:


```
writeln(countUntil("hello world", "world")); // 6
writeln(countUntil("hello world", 'r')); // 8
writeln(countUntil("hello world", "programming")); // -1
writeln(countUntil("日本語", "本語")); // 1
writeln(countUntil("日本語", '語')); // 2
writeln(countUntil("日本語", "五")); // -1
writeln(countUntil("日本語", '五')); // -1
writeln(countUntil([0, 7, 12, 22, 9], [12, 22])); // 2
writeln(countUntil([0, 7, 12, 22, 9], 9)); // 4
writeln(countUntil!"a > b"([0, 7, 12, 22, 9], 20)); // 3

```
 
 
Examples:


```
import std.ascii : isDigit;
import std.uni : isWhite;

writeln(countUntil!(std.uni.isWhite)("hello world")); // 5
writeln(countUntil!(std.ascii.isDigit)("hello world")); // -1
writeln(countUntil!"a > 20"([0, 7, 12, 22, 9])); // 3

```
 
  uint **endsWith**(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese)  
 Constraints: if (isBidirectionalRange!Range && (Needles.length > 1) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[0])) : bool) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[1..$])) : uint));   
  
bool **endsWith**(alias pred = "a == b", R1, R2)(R1 doesThisEnd, R2 withThis)  
 Constraints: if (isBidirectionalRange!R1 && isBidirectionalRange!R2 && is(typeof(binaryFun!pred(doesThisEnd.back, withThis.back)) : bool));   
  
bool **endsWith**(alias pred = "a == b", R, E)(R doesThisEnd, E withThis)  
 Constraints: if (isBidirectionalRange!R && is(typeof(binaryFun!pred(doesThisEnd.back, withThis)) : bool));   
  
bool **endsWith**(alias pred, R)(R doesThisEnd)  
 Constraints: if (isInputRange!R && ifTestable!(typeof(doesThisEnd.front), unaryFun!pred)); 
 
Checks if the given range ends with (one of) the given needle(s). The reciprocal of `startsWith`. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate to use for comparing elements between the range and the needle(s). |
| Range `doesThisEnd` | The [bidirectional range](std_range_primitives#isBidirectionalRange) to check. |
| Needles `withOneOfThese` | The needles to check against, which may be single elements, or bidirectional ranges of elements. |
| R2 `withThis` | The single element to check. |


 
Returns:
0 if the needle(s) do not occur at the end of the given range; otherwise the position of the matching needle, that is, 1 if the range ends with `withOneOfThese[0]`, 2 if it ends with `withOneOfThese[1]`, and so on. In the case when no needle parameters are given, return `true` iff back of `doesThisStart` fulfils predicate `pred`.
 
Examples:


```
import std.ascii : isAlpha;
assert("abc".endsWith!(a => a.isAlpha));
assert("abc".endsWith!isAlpha);

assert(!"ab1".endsWith!(a => a.isAlpha));

assert(!"ab1".endsWith!isAlpha);
assert(!"".endsWith!(a => a.isAlpha));

import std.algorithm.comparison : among;
assert("abc".endsWith!(a => a.among('c', 'd') != 0));
assert(!"abc".endsWith!(a => a.among('a', 'b') != 0));

assert(endsWith("abc", ""));
assert(!endsWith("abc", "b"));
writeln(endsWith("abc", "a", 'c')); // 2
writeln(endsWith("abc", "c", "a")); // 1
writeln(endsWith("abc", "c", "c")); // 1
writeln(endsWith("abc", "bc", "c")); // 2
writeln(endsWith("abc", "x", "c", "b")); // 2
writeln(endsWith("abc", "x", "aa", "bc")); // 3
writeln(endsWith("abc", "x", "aaa", "sab")); // 0
writeln(endsWith("abc", "x", "aaa", 'c', "sab")); // 3

```
 
  InputRange **find**(alias pred = "a == b", InputRange, Element)(InputRange haystack, scope Element needle)  
 Constraints: if (isInputRange!InputRange && is(typeof(binaryFun!pred(haystack.front, needle)) : bool) && !is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool));   
  
InputRange **find**(alias pred, InputRange)(InputRange haystack)  
 Constraints: if (isInputRange!InputRange);   
  
R1 **find**(alias pred = "a == b", R1, R2)(R1 haystack, scope R2 needle)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)); 
 
Finds an individual element in an [input range](std_range_primitives#isInputRange). Elements of `haystack` are compared with `needle` by using predicate `pred` with `pred(haystack.front, needle)`. `find` performs Ο(`walkLength(haystack)`) evaluations of `pred`. 


The predicate is passed to [`std.functional.binaryFun`](std_functional#binaryFun), and can either accept a string, or any callable that can be executed via `pred(element, element)`.   
  
 To find the last occurrence of `needle` in a [bidirectional](std_range_primitives#isBidirectionalRange) `haystack`, call `find(retro(haystack), needle)`. See [`std.range.retro`](std_range#retro).   
  
 If no `needle` is provided, `pred(haystack.front)` will be evaluated on each element of the input range.   
  
 If `input` is a [forward range](std_range_primitives#isForwardRange), `needle` can be a [forward range](std_range_primitives#isForwardRange) too. In this case `startsWith!pred(haystack, needle)` is evaluated on each evaluation. 

 
Note
 `find` behaves similar to `dropWhile` in other languages. 
 
Complexity
 `find` performs Ο(`walkLength(haystack)`) evaluations of `pred`. There are specializations that improve performance by taking advantage of [bidirectional](std_range_primitives#isBidirectionalRange) or [random access](std_range_primitives#isRandomAccess) ranges (where possible). 
 
Parameters:


|  |  |
| --- | --- |
| pred | The predicate for comparing each element with the needle, defaulting to equality `"a == b"`. The negated predicate `"a != b"` can be used to search instead for the first element *not* matching the needle. |
| InputRange `haystack` | The [input range](std_range_primitives#isInputRange) searched in. |
| Element `needle` | The element searched for. |


 
Returns:

`haystack` advanced such that the front element is the one searched for; that is, until `binaryFun!pred(haystack.front, needle)` is `true`. If no such position exists, returns an empty `haystack`. 
 
See Also:

[`findAdjacent`](#findAdjacent), [`findAmong`](#findAmong), [`findSkip`](#findSkip), [`findSplit`](#findSplit), [`startsWith`](#startsWith)

 
Examples:


```
import std.range.primitives;

auto arr = [1, 2, 4, 4, 4, 4, 5, 6, 9];
writeln(arr.find(4)); // [4, 4, 4, 4, 5, 6, 9]
writeln(arr.find(1)); // arr
writeln(arr.find(9)); // [9]
writeln(arr.find!((a, b) => a > b)(4)); // [5, 6, 9]
writeln(arr.find!((a, b) => a < b)(4)); // arr
assert(arr.find(0).empty);
assert(arr.find(10).empty);
assert(arr.find(8).empty);

writeln(find("hello, world", ',')); // ", world"

```
 
 
Examples:
Case-insensitive find of a string 
```
import std.range.primitives;
import std.uni : toLower;

string[] s = ["Hello", "world", "!"];
writeln(s.find!((a, b) => toLower(a) == b)("hello")); // s

```
 
 
Examples:


```
auto arr = [ 1, 2, 3, 4, 1 ];
writeln(find!("a > 2")(arr)); // [3, 4, 1]

// with predicate alias
bool pred(int x) { return x + 1 > 1.5; }
writeln(find!(pred)(arr)); // arr

```
 
 
Examples:


```
import std.container : SList;
import std.range.primitives : empty;
import std.typecons : Tuple;

assert(find("hello, world", "World").empty);
writeln(find("hello, world", "wo")); // "world"
writeln([1, 2, 3, 4].find(SList!int(2, 3)[])); // [2, 3, 4]
alias C = Tuple!(int, "x", int, "y");
auto a = [C(1,0), C(2,0), C(3,1), C(4,0)];
writeln(a.find!"a.x == b"([2, 3])); // [C(2, 0), C(3, 1), C(4, 0)]
writeln(a[1 .. $].find!"a.x == b"([2, 3])); // [C(2, 0), C(3, 1), C(4, 0)]

```
 
  Tuple!(Range, size\_t) **find**(alias pred = "a == b", Range, Ranges...)(Range haystack, Ranges needles)  
 Constraints: if (Ranges.length > 1 && is(typeof(startsWith!pred(haystack, needles)))); 
 
Finds two or more `needles` into a `haystack`. The predicate `pred` is used throughout to compare elements. By default, elements are compared for equality. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate to use for comparing elements. |
| Range `haystack` | The target of the search. Must be an input range. If any of `needles` is a range with elements comparable to elements in `haystack`, then `haystack` must be a [forward range](std_range_primitives#isForwardRange) such that the search can backtrack. |
| Ranges `needles` | One or more items to search for. Each of `needles` must be either comparable to one element in `haystack`, or be itself a forward range with elements comparable with elements in `haystack`. |


 
Returns:
A tuple containing `haystack` positioned to match one of the needles and also the 1-based index of the matching element in `needles` (0 if none of `needles` matched, 1 if `needles[0]` matched, 2 if `needles[1]` matched...). The first needle to be found will be the one that matches. If multiple needles are found at the same spot in the range, then the shortest one is the one which matches (if multiple needles of the same length are found at the same spot (e.g `"a"` and `'a'`), then the left-most of them in the argument list matches). The relationship between `haystack` and `needles` simply means that one can e.g. search for individual `int`s or arrays of `int`s in an array of `int`s. In addition, if elements are individually comparable, searches of heterogeneous types are allowed as well: a `double[]` can be searched for an `int` or a `short[]`, and conversely a `long` can be searched for a `float` or a `double[]`. This makes for efficient searches without the need to coerce one side of the comparison into the other's side type. The complexity of the search is Ο(`haystack.length * max(needles.length)`). (For needles that are individual items, length is considered to be 1.) The strategy used in searching several subranges at once maximizes cache usage by moving in `haystack` as few times as possible.
 
Examples:


```
import std.typecons : tuple;
int[] a = [ 1, 4, 2, 3 ];
writeln(find(a, 4)); // [4, 2, 3]
writeln(find(a, [1, 4])); // [1, 4, 2, 3]
writeln(find(a, [1, 3], 4)); // tuple([4, 2, 3], 2)
// Mixed types allowed if comparable
writeln(find(a, 5, [1.2, 3.5], 2.0)); // tuple([2, 3], 3)

```
 
  RandomAccessRange **find**(RandomAccessRange, alias pred, InputRange)(RandomAccessRange haystack, scope BoyerMooreFinder!(pred, InputRange) needle);  
Finds `needle` in `haystack` efficiently using the  [Boyer-Moore](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) method. 



Parameters:


|  |  |
| --- | --- |
| RandomAccessRange `haystack` | A random-access range with length and slicing. |
| BoyerMooreFinder!(pred, InputRange) `needle` | A [`BoyerMooreFinder`](#BoyerMooreFinder). |


 
Returns:

`haystack` advanced such that `needle` is a prefix of it (if no such position exists, returns `haystack` advanced to termination).
 
Examples:


```
import std.range.primitives : empty;
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];
int[] b = [ 1, 2, 3 ];

writeln(find(a, boyerMooreFinder(b))); // [1, 2, 3, 4, 5]
assert(find(b, boyerMooreFinder(a)).empty);

```
 
  template **canFind**(alias pred = "a == b") 
Convenience function. Like find, but only returns whether or not the search was successful. 



See Also:

[`std.algorithm.comparison.among`](std_algorithm_comparison#among) for checking a value against multiple possibilities.
 
Examples:


```
writeln(canFind([0, 1, 2, 3], 2)); // true
assert(canFind([0, 1, 2, 3], [1, 2], [2, 3]));
writeln(canFind([0, 1, 2, 3], [1, 2], [2, 3])); // 1
assert(canFind([0, 1, 2, 3], [1, 7], [2, 3]));
writeln(canFind([0, 1, 2, 3], [1, 7], [2, 3])); // 2

writeln(canFind([0, 1, 2, 3], 4)); // false
assert(!canFind([0, 1, 2, 3], [1, 3], [2, 4]));
writeln(canFind([0, 1, 2, 3], [1, 3], [2, 4])); // 0

```
 
 
Examples:
Example using a custom predicate. Note that the needle appears as the second argument of the predicate. 
```
auto words = [
    "apple",
    "beeswax",
    "cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string a, string b) => a.startsWith(b))(words, "bees"));

```
 
 
Examples:
Search for mutliple items in an array of items (search for needles in an array of hay stacks) 
```
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => (e.canFind("111", "222"))));

```
 
 
bool **canFind**(Range)(Range haystack)  
 Constraints: if (is(typeof(find!pred(haystack)))); 
 
Returns `true` if and only if any value `v` found in the input range `range` satisfies the predicate `pred`. Performs (at most) Ο(`haystack.length`) evaluations of `pred`.

  bool **canFind**(Range, Element)(Range haystack, scope Element needle)  
 Constraints: if (is(typeof(find!pred(haystack, needle)))); 
 
Returns `true` if and only if `needle` can be found in  `range`. Performs Ο(`haystack.length`) evaluations of `pred`.

  size\_t **canFind**(Range, Ranges...)(Range haystack, scope Ranges needles)  
 Constraints: if (Ranges.length > 1 && allSatisfy!(isForwardRange, Ranges) && is(typeof(find!pred(haystack, needles)))); 
 
Returns the 1-based index of the first needle found in `haystack`. If no needle is found, then `0` is returned. 


So, if used directly in the condition of an if statement or loop, the result will be `true` if one of the needles is found and `false` if none are found, whereas if the result is used elsewhere, it can either be cast to `bool` for the same effect or used to get which needle was found first without having to deal with the tuple that `LREF find` returns for the same operation.

    Range **findAdjacent**(alias pred = "a == b", Range)(Range r)  
 Constraints: if (isForwardRange!Range); 
 
Advances `r` until it finds the first two adjacent elements `a`, `b` that satisfy `pred(a, b)`. Performs Ο(`r.length`) evaluations of `pred`. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate to satisfy. |
| Range `r` | A [forward range](std_range_primitives#isForwardRange) to search in. |


 
Returns:

`r` advanced to the first occurrence of two adjacent elements that satisfy the given predicate. If there are no such two elements, returns `r` advanced until empty. 
 
See Also:
[STL's `adjacent_find`](http://en.cppreference.com/w/cpp/algorithm/adjacent_find)
 
Examples:


```
int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ];
auto r = findAdjacent(a);
writeln(r); // [10, 10, 9, 8, 8, 7, 8, 9]
auto p = findAdjacent!("a < b")(a);
writeln(p); // [7, 8, 9]

```
 
  InputRange **findAmong**(alias pred = "a == b", InputRange, ForwardRange)(InputRange seq, ForwardRange choices)  
 Constraints: if (isInputRange!InputRange && isForwardRange!ForwardRange); 
 
Searches the given range for an element that matches one of the given choices. 


Advances `seq` by calling `seq.popFront` until either `find!(pred)(choices, seq.front)` is `true`, or `seq` becomes empty. Performs Ο(`seq.length * choices.length`) evaluations of `pred`. 

 
Parameters:


|  |  |
| --- | --- |
| pred | The predicate to use for determining a match. |
| InputRange `seq` | The [input range](std_range_primitives#isInputRange) to search. |
| ForwardRange `choices` | A [forward range](std_range_primitives#isForwardRange) of possible choices. |


 
Returns:

`seq` advanced to the first matching element, or until empty if there are no matching elements. 
 
See Also:

[`find`](#find), [`algorithm.comparison.among.std`](algorithm_comparison_among#std)

 
Examples:


```
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];
int[] b = [ 3, 1, 2 ];
writeln(findAmong(a, b)); // a[2 .. &dollar;]

```
 
  bool **findSkip**(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front))));   
  
size\_t **findSkip**(alias pred, R1)(ref R1 haystack)  
 Constraints: if (isForwardRange!R1 && ifTestable!(typeof(haystack.front), unaryFun!pred)); 
 
Finds `needle` in `haystack` and positions `haystack` right after the first occurrence of `needle`. 


If no needle is provided, the `haystack` is advanced as long as `pred` evaluates to `true`. Similarly, the haystack is positioned so as `pred` evaluates to `false` for `haystack.front`. 

 
Parameters:


|  |  |
| --- | --- |
| R1 `haystack` | The [forward range](std_range_primitives#isForwardRange) to search in. |
| R2 `needle` | The [forward range](std_range_primitives#isForwardRange) to search for. |
| pred | Custom predicate for comparison of haystack and needle |


 
Returns:

`true` if the needle was found, in which case `haystack` is positioned after the end of the first occurrence of `needle`; otherwise `false`, leaving `haystack` untouched. If no needle is provided, it returns the number of times `pred(haystack.front)` returned true. 
 
See Also:
[`find`](#find)
 
Examples:


```
import std.range.primitives : empty;
// Needle is found; s is replaced by the substring following the first
// occurrence of the needle.
string s = "abcdef";
assert(findSkip(s, "cd") && s == "ef");

// Needle is not found; s is left untouched.
s = "abcdef";
assert(!findSkip(s, "cxd") && s == "abcdef");

// If the needle occurs at the end of the range, the range is left empty.
s = "abcdef";
assert(findSkip(s, "def") && s.empty);

```
 
 
Examples:


```
import std.ascii : isWhite;
string s = "    abc";
assert(findSkip!isWhite(s) && s == "abc");
assert(!findSkip!isWhite(s) && s == "abc");

s = "  ";
writeln(findSkip!isWhite(s)); // 2

```
 
  auto **findSplit**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2);   
  
auto **findSplitBefore**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2);   
  
auto **findSplitAfter**(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2); 
 
These functions find the first occurrence of `needle` in `haystack` and then split `haystack` as follows. 


`findSplit` returns a tuple `result` containing *three* ranges. `result[0]` is the portion of `haystack` before `needle`, `result[1]` is the portion of `haystack` that matches `needle`, and `result[2]` is the portion of `haystack` after the match. If `needle` was not found, `result[0]` comprehends `haystack` entirely and `result[1]` and `result[2]` are empty.   
  
 `findSplitBefore` returns a tuple `result` containing two ranges. `result[0]` is the portion of `haystack` before `needle`, and `result[1]` is the balance of `haystack` starting with the match. If `needle` was not found, `result[0]` comprehends `haystack` entirely and `result[1]` is empty.   
  
 `findSplitAfter` returns a tuple `result` containing two ranges. `result[0]` is the portion of `haystack` up to and including the match, and `result[1]` is the balance of `haystack` starting after the match. If `needle` was not found, `result[0]` is empty and `result[1]` is `haystack`.   
  
 In all cases, the concatenation of the returned ranges spans the entire `haystack`.   
  
 If `haystack` is a random-access range, all three components of the tuple have the same type as `haystack`. Otherwise, `haystack` must be a [forward range](std_range_primitives#isForwardRange) and the type of `result[0]` and `result[1]` is the same as [`std.range.takeExactly`](std_range#takeExactly). 

 
Parameters:


|  |  |
| --- | --- |
| pred | Predicate to use for comparing needle against haystack. |
| R1 `haystack` | The range to search. |
| R2 `needle` | What to look for. |


 
Returns:
A sub-type of `Tuple!()` of the split portions of `haystack` (see above for details). This sub-type of `Tuple!()` has `opCast` defined for `bool`. This `opCast` returns `true` when the separating `needle` was found and `false` otherwise. 
 
See Also:
[`find`](#find)
 
Examples:
Returning a subtype of [`std.typecons.Tuple`](std_typecons#Tuple) enables the following convenient idiom: 
```
// findSplit returns a triplet
if (auto split = "dlang-rocks".findSplit("-"))
{
    writeln(split[0]); // "dlang"
    writeln(split[1]); // "-"
    writeln(split[2]); // "rocks"
}
else assert(0);

// works with const aswell
if (const split = "dlang-rocks".findSplit("-"))
{
    writeln(split[0]); // "dlang"
    writeln(split[1]); // "-"
    writeln(split[2]); // "rocks"
}
else assert(0);

```
 
 
Examples:


```
import std.range.primitives : empty;

auto a = "Carl Sagan Memorial Station";
auto r = findSplit(a, "Velikovsky");
import std.typecons : isTuple;
static assert(isTuple!(typeof(r.asTuple)));
static assert(isTuple!(typeof(r)));
assert(!r);
writeln(r[0]); // a
assert(r[1].empty);
assert(r[2].empty);
r = findSplit(a, " ");
writeln(r[0]); // "Carl"
writeln(r[1]); // " "
writeln(r[2]); // "Sagan Memorial Station"
if (const r1 = findSplitBefore(a, "Sagan"))
{
    assert(r1);
    writeln(r1[0]); // "Carl "
    writeln(r1[1]); // "Sagan Memorial Station"
}
if (const r2 = findSplitAfter(a, "Sagan"))
{
    assert(r2);
    writeln(r2[0]); // "Carl Sagan"
    writeln(r2[1]); // " Memorial Station"
}

```
 
 
Examples:
Use [`std.range.only`](std_range#only) to find single elements: 
```
import std.range : only;
writeln([1, 2, 3, 4].findSplitBefore(only(3))[0]); // [1, 2]

```
 
  Tuple!(ElementType!Range, size\_t) **minCount**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front))));   
  
Tuple!(ElementType!Range, size\_t) **maxCount**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); 
 
Computes the minimum (respectively maximum) of `range` along with its number of occurrences. Formally, the minimum is a value `x` in `range` such that `pred(a, x)` is `false` for all values `a` in `range`. Conversely, the maximum is a value `x` in `range` such that `pred(x, a)` is `false` for all values `a` in `range` (note the swapped arguments to `pred`). 


These functions may be used for computing arbitrary extrema by choosing `pred` appropriately. For corrrect functioning, `pred` must be a strict partial order, i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and irreflexive (`pred(a, a)` is `false`). The [trichotomy property of inequality](#) is not required: these algorithms consider elements `a` and `b` equal (for the purpose of counting) if `pred` puts them in the same equivalence class, i.e. `!pred(a, b) && !pred(b, a)`. 

 
Parameters:


|  |  |
| --- | --- |
| pred | The ordering predicate to use to determine the extremum (minimum or maximum). |
| Range `range` | The [input range](std_range_primitives#isInputRange) to count. |


 
Returns:
The minimum, respectively maximum element of a range together with the number it occurs in the range. 
 
Limitations
 If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. 
 
Throws:

`Exception` if `range.empty`. 
 
See Also:

[`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minIndex`](#minIndex), [`minElement`](#minElement), [`minPos`](#minPos)

 
Examples:


```
import std.conv : text;
import std.typecons : tuple;

int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
// Minimum is 1 and occurs 3 times
writeln(a.minCount); // tuple(1, 3)
// Maximum is 4 and occurs 2 times
writeln(a.maxCount); // tuple(4, 2)

```
 
  auto **minElement**(alias map = (a) => a, Range)(Range r)  
 Constraints: if (isInputRange!Range && !isInfinite!Range);   
  
auto **minElement**(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Range r, RangeElementType seed)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void)); 
 
Iterates the passed range and returns the minimal element. A custom mapping function can be passed to `map`. In other languages this is sometimes called `argmin`. 



Complexity
 O(n) Exactly `n - 1` comparisons are needed. 
 
Parameters:


|  |  |
| --- | --- |
| map | custom accessor for the comparison key |
| Range `r` | range from which the minimal element will be selected |
| RangeElementType `seed` | custom seed to use as initial element |


 
Returns:
The minimal element of the passed-in range. 
 
Note
 If at least one of the arguments is NaN, the result is an unspecified value. 
 If you want to ignore NaNs, you can use [`std.algorithm.iteration.filter`](std_algorithm_iteration#filter) and [`std.math.isNaN`](std_math#isNaN) to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs: 
```
<range>.filter!(a=>!a.isNaN).minElement(<seed>);

```
 If you want to get NaN as a result if a NaN is present in the range, you can use [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold) and [`std.math.isNaN`](std_math#isNaN): 
```
<range>.fold!((a,b)=>a.isNaN || b.isNaN ? real.nan : a < b ? a : b);

```
 
See Also:

[`maxElement`](#maxElement), [`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minCount`](#minCount), [`minIndex`](#minIndex), [`minPos`](#minPos)

 
Examples:


```
import std.range : enumerate;
import std.typecons : tuple;

writeln([2, 7, 1, 3].minElement); // 1

// allows to get the index of an element too
writeln([5, 3, 7, 9].enumerate.minElement!"a.value"); // tuple(1, 3)

// any custom accessor can be passed
writeln([[0, 4], [1, 2]].minElement!"a[1]"); // [1, 2]

// can be seeded
int[] arr;
writeln(arr.minElement(1)); // 1

```
 
  auto **maxElement**(alias map = (a) => a, Range)(Range r)  
 Constraints: if (isInputRange!Range && !isInfinite!Range);   
  
auto **maxElement**(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Range r, RangeElementType seed)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void)); 
 
Iterates the passed range and returns the maximal element. A custom mapping function can be passed to `map`. In other languages this is sometimes called `argmax`. 



Complexity
 O(n) Exactly `n - 1` comparisons are needed. 
 
Parameters:


|  |  |
| --- | --- |
| map | custom accessor for the comparison key |
| Range `r` | range from which the maximum element will be selected |
| RangeElementType `seed` | custom seed to use as initial element |


 
Returns:
The maximal element of the passed-in range. 
 
Note
 If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.minElement`](std_algorithm_searching#minElement) for examples on how to cope with NaNs. 
 
See Also:

[`minElement`](#minElement), [`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`maxCount`](#maxCount), [`maxIndex`](#maxIndex), [`maxPos`](#maxPos)

 
Examples:


```
import std.range : enumerate;
import std.typecons : tuple;
writeln([2, 1, 4, 3].maxElement); // 4

// allows to get the index of an element too
writeln([2, 1, 4, 3].enumerate.maxElement!"a.value"); // tuple(2, 4)

// any custom accessor can be passed
writeln([[0, 4], [1, 2]].maxElement!"a[1]"); // [0, 4]

// can be seeded
int[] arr;
writeln(arr.minElement(1)); // 1

```
 
  Range **minPos**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front))));   
  
Range **maxPos**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); 
 
Computes a subrange of `range` starting at the first occurrence of `range`'s minimum (respectively maximum) and with the same ending as `range`, or the empty range if `range` itself is empty. 


Formally, the minimum is a value `x` in `range` such that `pred(a, x)` is `false` for all values `a` in `range`. Conversely, the maximum is a value `x` in `range` such that `pred(x, a)` is `false` for all values `a` in `range` (note the swapped arguments to `pred`).   
  
 These functions may be used for computing arbitrary extrema by choosing `pred` appropriately. For corrrect functioning, `pred` must be a strict partial order, i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and irreflexive (`pred(a, a)` is `false`). 

 
Parameters:


|  |  |
| --- | --- |
| pred | The ordering predicate to use to determine the extremum (minimum or maximum) element. |
| Range `range` | The [forward range](std_range_primitives#isForwardRange) to search. |


 
Returns:
The position of the minimum (respectively maximum) element of forward range `range`, i.e. a subrange of `range` starting at the position of its smallest (respectively largest) element and with the same ending as `range`. 
 
Limitations
 If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. 
 
See Also:

[`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`minCount`](#minCount), [`minIndex`](#minIndex), [`minElement`](#minElement)

 
Examples:


```
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
// Minimum is 1 and first occurs in position 3
writeln(a.minPos); // [1, 2, 4, 1, 1, 2]
// Maximum is 4 and first occurs in position 2
writeln(a.maxPos); // [4, 1, 2, 4, 1, 1, 2]

```
 
  ptrdiff\_t **minIndex**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); 
 
Computes the index of the first occurrence of `range`'s minimum element. 



Parameters:


|  |  |
| --- | --- |
| pred | The ordering predicate to use to determine the minimum element. |
| Range `range` | The [input range](std_range_primitives#isInputRange) to search. |


 
Complexity
 Ο(`range.length`) Exactly `range.length - 1` comparisons are needed. 
 
Returns:
The index of the first encounter of the minimum element in `range`. If the `range` is empty, -1 is returned. 
 
Limitations
 If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. 
 
See Also:

[`maxIndex`](#maxIndex), [`std.algorithm.comparison.min`](std_algorithm_comparison#min), [`minCount`](#minCount), [`minElement`](#minElement), [`minPos`](#minPos)

 
Examples:


```
int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2];

// Minimum is 1 and first occurs in position 3
writeln(a.minIndex); // 3
// Get maximum index with minIndex
writeln(a.minIndex!"a > b"); // 2

// Range is empty, so return value is -1
int[] b;
writeln(b.minIndex); // -1

// Works with more custom types
struct Dog { int age; }
Dog[] dogs = [Dog(10), Dog(5), Dog(15)];
writeln(dogs.minIndex!"a.age < b.age"); // 1

```
 
  ptrdiff\_t **maxIndex**(alias pred = "a < b", Range)(Range range)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front)))); 
 
Computes the index of the first occurrence of `range`'s maximum element. 



Complexity
 Ο(`range`) Exactly `range.length - 1` comparisons are needed. 
 
Parameters:


|  |  |
| --- | --- |
| pred | The ordering predicate to use to determine the maximum element. |
| Range `range` | The [input range](std_range_primitives#isInputRange) to search. |


 
Returns:
The index of the first encounter of the maximum in `range`. If the `range` is empty, -1 is returned. 
 
Limitations
 If at least one of the arguments is NaN, the result is an unspecified value. See [`std.algorithm.searching.maxElement`](std_algorithm_searching#maxElement) for examples on how to cope with NaNs. 
 
See Also:

[`minIndex`](#minIndex), [`std.algorithm.comparison.max`](std_algorithm_comparison#max), [`maxCount`](#maxCount), [`maxElement`](#maxElement), [`maxPos`](#maxPos)

 
Examples:


```
// Maximum is 4 and first occurs in position 2
int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2];
writeln(a.maxIndex); // 2

// Empty range
int[] b;
writeln(b.maxIndex); // -1

// Works with more custom types
struct Dog { int age; }
Dog[] dogs = [Dog(10), Dog(15), Dog(5)];
writeln(dogs.maxIndex!"a.age < b.age"); // 1

```
 
  template **skipOver**(alias pred = (a, b) => a == b) 
Skip over the initial portion of the first given range (`haystack`) that matches any of the additionally given ranges (`needles`) fully, or if no second range is given skip over the elements that fulfill pred. Do nothing if there is no match. 



Parameters:


|  |  |
| --- | --- |
| pred | The predicate that determines whether elements from each respective range match. Defaults to equality `"a == b"`. |


 
Examples:


```
import std.algorithm.comparison : equal;

auto s1 = "Hello world";
assert(!skipOver(s1, "Ha"));
writeln(s1); // "Hello world"
assert(skipOver(s1, "Hell") && s1 == "o world", s1);

string[]  r1 = ["abc", "def", "hij"];
dstring[] r2 = ["abc"d];
assert(!skipOver!((a, b) => a.equal(b))(r1, ["def"d]), r1[0]);
writeln(r1); // ["abc", "def", "hij"]
assert(skipOver!((a, b) => a.equal(b))(r1, r2));
writeln(r1); // ["def", "hij"]

```
 
 
Examples:


```
import std.ascii : isWhite;
import std.range.primitives : empty;

auto s2 = "\t\tvalue";
auto s3 = "";
auto s4 = "\t\t\t";
assert(s2.skipOver!isWhite && s2 == "value");
assert(!s3.skipOver!isWhite);
assert(s4.skipOver!isWhite && s3.empty);

```
 
 
Examples:
Variadic skipOver 
```
auto s = "Hello world";
assert(!skipOver(s, "hello", "HellO"));
writeln(s); // "Hello world"

// the range is skipped over the longest matching needle is skipped
assert(skipOver(s, "foo", "hell", "Hello "));
writeln(s); // "world"

```
 
 
Examples:


```
import std.algorithm.comparison : equal;

auto s1 = "Hello world";
assert(!skipOver(s1, 'a'));
writeln(s1); // "Hello world"
assert(skipOver(s1, 'H') && s1 == "ello world");

string[] r = ["abc", "def", "hij"];
dstring e = "abc"d;
assert(!skipOver!((a, b) => a.equal(b))(r, "def"d));
writeln(r); // ["abc", "def", "hij"]
assert(skipOver!((a, b) => a.equal(b))(r, e));
writeln(r); // ["def", "hij"]

auto s2 = "";
assert(!s2.skipOver('a'));

```
 
 
Examples:
Partial instantiation 
```
import std.ascii : isWhite;
import std.range.primitives : empty;

alias whitespaceSkiper = skipOver!isWhite;

auto s2 = "\t\tvalue";
auto s3 = "";
auto s4 = "\t\t\t";
assert(whitespaceSkiper(s2) && s2 == "value");
assert(!whitespaceSkiper(s2));
assert(whitespaceSkiper(s4) && s3.empty);

```
 
 
bool **skipOver**(Haystack, Needles...)(ref Haystack haystack, Needles needles)  
 Constraints: if (is(typeof(binaryFun!pred(haystack.front, needles[0].front))) && isForwardRange!Haystack && allSatisfy!(isInputRange, Needles) && !is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Needles))) == void));   
  
bool **skipOver**(R)(ref R r1)  
 Constraints: if (isForwardRange!R && ifTestable!(typeof(r1.front), unaryFun!pred));   
  
bool **skipOver**(R, Es...)(ref R r, Es es)  
 Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(r.front, es[0])))); 
 

Parameters:


|  |  |
| --- | --- |
| Haystack `haystack` | The [forward range](std_range_primitives#isForwardRange) to move forward. |
| Needles `needles` | The [input ranges](std_range_primitives#isInputRange) representing the prefix of `r1` to skip over. |
| Es `es` | The element to match. |


 
Returns:

`true` if the prefix of `haystack` matches any range of `needles` fully or `pred` evaluates to true, and `haystack` has been advanced to the point past this segment; otherwise false, and `haystack` is left in its original position. 
 
Note
 By definition, empty ranges are matched fully and if `needles` contains an empty range, `skipOver` will return `true`.
    uint **startsWith**(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese)  
 Constraints: if (isInputRange!Range && (Needles.length > 1) && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[0])) : bool) && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[1..$])) : uint));   
  
bool **startsWith**(alias pred = "a == b", R1, R2)(R1 doesThisStart, R2 withThis)  
 Constraints: if (isInputRange!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(doesThisStart.front, withThis.front)) : bool));   
  
bool **startsWith**(alias pred = "a == b", R, E)(R doesThisStart, E withThis)  
 Constraints: if (isInputRange!R && is(typeof(binaryFun!pred(doesThisStart.front, withThis)) : bool));   
  
bool **startsWith**(alias pred, R)(R doesThisStart)  
 Constraints: if (isInputRange!R && ifTestable!(typeof(doesThisStart.front), unaryFun!pred)); 
 
Checks whether the given [input range](std_range_primitives#isInputRange) starts with (one of) the given needle(s) or, if no needles are given, if its front element fulfils predicate `pred`. 



Parameters:


|  |  |
| --- | --- |
| pred | Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given. |
| Range `doesThisStart` | The input range to check. |
| Needles `withOneOfThese` | The needles against which the range is to be checked, which may be individual elements or input ranges of elements. |
| R2 `withThis` | The single needle to check, which may be either a single element or an input range of elements. |


 
Returns:
0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with `withOneOfThese[0]`, 2 if it starts with `withOneOfThese[1]`, and so on. In the case where `doesThisStart` starts with multiple of the ranges or elements in `withOneOfThese`, then the shortest one matches (if there are two which match which are of the same length (e.g. `"a"` and `'a'`), then the left-most of them in the argument list matches). In the case when no needle parameters are given, return `true` iff front of `doesThisStart` fulfils predicate `pred`.
 
Examples:


```
import std.ascii : isAlpha;

assert("abc".startsWith!(a => a.isAlpha));
assert("abc".startsWith!isAlpha);
assert(!"1ab".startsWith!(a => a.isAlpha));
assert(!"".startsWith!(a => a.isAlpha));

import std.algorithm.comparison : among;
assert("abc".startsWith!(a => a.among('a', 'b') != 0));
assert(!"abc".startsWith!(a => a.among('b', 'c') != 0));

assert(startsWith("abc", ""));
assert(startsWith("abc", "a"));
assert(!startsWith("abc", "b"));
writeln(startsWith("abc", 'a', "b")); // 1
writeln(startsWith("abc", "b", "a")); // 2
writeln(startsWith("abc", "a", "a")); // 1
writeln(startsWith("abc", "ab", "a")); // 2
writeln(startsWith("abc", "x", "a", "b")); // 2
writeln(startsWith("abc", "x", "aa", "ab")); // 3
writeln(startsWith("abc", "x", "aaa", "sab")); // 0
writeln(startsWith("abc", "x", "aaa", "a", "sab")); // 3

import std.typecons : Tuple;
alias C = Tuple!(int, "x", int, "y");
assert(startsWith!"a.x == b"([ C(1,1), C(1,2), C(2,2) ], [1, 1]));
writeln(startsWith!"a.x == b"([C(1, 1), C(2, 1), C(2, 2)], [1, 1], [1, 2], [1, 3])); // 2

```
 
  alias **OpenRight** = std.typecons.Flag!"openRight".Flag;  
Interval option specifier for `until` (below) and others. 


If set to `OpenRight.yes`, then the interval is open to the right (last element is not included).   
  
 Otherwise if set to `OpenRight.no`, then the interval is closed to the right (last element included).

  Until!(pred, Range, Sentinel) **until**(alias pred = "a == b", Range, Sentinel)(Range range, Sentinel sentinel, OpenRight openRight = Yes.openRight)  
 Constraints: if (!is(Sentinel == OpenRight));   
  
Until!(pred, Range, void) **until**(alias pred, Range)(Range range, OpenRight openRight = Yes.openRight);   
  
struct **Until**(alias pred, Range, Sentinel) if (isInputRange!Range);  
Lazily iterates `range` until the element `e` for which `pred(e, sentinel)` is true. 


This is similar to `takeWhile` in other languages. 

 
Parameters:


|  |  |
| --- | --- |
| pred | Predicate to determine when to stop. |
| Range `range` | The [input range](std_range_primitives#isInputRange) to iterate over. |
| Sentinel `sentinel` | The element to stop at. |
| OpenRight `openRight` | Determines whether the element for which the given predicate is true should be included in the resulting range (`No.openRight`), or not (`Yes.openRight`). |


 
Returns:
An [input range](std_range_primitives#isInputRange) that iterates over the original range's elements, but ends when the specified predicate becomes true. If the original range is a [forward range](std_range_primitives#isForwardRange) or higher, this range will be a forward range.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.typecons : No;
int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5];
assert(equal(a.until(7), [1, 2, 4]));
assert(equal(a.until(7, No.openRight), [1, 2, 4, 7]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_algorithm_searching.html>

std.csv
=======

 Implements functionality to read Comma Separated Values and its variants from an [input range](std_range_primitives#isInputRange) of `dchar`. 


Comma Separated Values provide a simple means to transfer and store tabular data. It has been common for programs to use their own variant of the CSV format. This parser will loosely follow the [RFC-4180](http://tools.ietf.org/html/rfc4180). CSV input should adhere to the following criteria (differences from RFC-4180 in parentheses):   
  
 * A record is separated by a new line (CRLF,LF,CR)
* A final record may end with a new line
* A header may be provided as the first record in input
* A record has fields separated by a comma (customizable)
* A field containing new lines, commas, or double quotes should be enclosed in double quotes (customizable)
* Double quotes in a field are escaped with a double quote
* Each record should contain the same number of fields

 

 
Example


```
import std.algorithm;
import std.array;
import std.csv;
import std.stdio;
import std.typecons;

void main()
{
    auto text = "Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n";

    foreach (record; csvReader!(Tuple!(string, string, int))(text))
    {
        writefln("%s works as a %s and earns &dollar;%d per year",
                 record[0], record[1], record[2]);
    }

    // To read the same string from the file "filename.csv":

    auto file = File("filename.csv", "r");
    foreach (record;
        file.byLine.joiner("\n").csvReader!(Tuple!(string, string, int)))
    {
        writefln("%s works as a %s and earns &dollar;%d per year",
                 record[0], record[1], record[2]);
    }
}
}

```
 When an input contains a header the `Contents` can be specified as an associative array. Passing null to signify that a header is present. 
```
auto text = "Name,Occupation,Salary\r"
    "Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n";

foreach (record; csvReader!(string[string])
        (text, null))
{
    writefln("%s works as a %s and earns &dollar;%s per year.",
             record["Name"], record["Occupation"],
             record["Salary"]);
}

// To read the same string from the file "filename.csv":

auto file = File("filename.csv", "r");

foreach (record; csvReader!(string[string])
        (file.byLine.joiner("\n"), null))
{
    writefln("%s works as a %s and earns &dollar;%s per year.",
             record["Name"], record["Occupation"],
             record["Salary"]);
}

```
 This module allows content to be iterated by record stored in a struct, class, associative array, or as a range of fields. Upon detection of an error an CSVException is thrown (can be disabled). csvNextToken has been made public to allow for attempted recovery. Disabling exceptions will lift many restrictions specified above. A quote can appear in a field if the field was not quoted. If in a quoted field any quote by itself, not at the end of a field, will end processing for that field. The field is ended when there is no input, even if the quote was not closed. 
See Also:

[Wikipedia Comma-separated values](http://en.wikipedia.org/wiki/Comma-separated_values) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Jesse Phillips 
 
Source
 [std/csv.d](https://github.com/dlang/phobos/blob/master/std/csv.d)

 
class **CSVException**: object.Exception;  
Exception containing the row and column for when an exception was thrown. 


Numbering of both row and col start at one and corresponds to the location in the file rather than any specified header. Special consideration should be made when there is failure to match the header see  [`HeaderMismatchException`](#%20HeaderMismatchException) for details.   
  
 When performing type conversions, [`std.conv.ConvException`](std_conv#ConvException) is stored in the `next` field.

 
Examples:


```
import std.exception : collectException;
import std.algorithm.searching : count;
string text = "a,b,c\nHello,65";
auto ex = collectException!CSVException(csvReader(text).count);
// "(Row: 0, Col: 0) Row 2's length 2 does not match previous length of 3."
writeln(ex.toString);

```
 
 
Examples:


```
import std.exception : collectException;
import std.algorithm.searching : count;
import std.typecons : Tuple;
string text = "a,b\nHello,65";
auto ex = collectException!CSVException(csvReader!(Tuple!(string,int))(text).count);
// "(Row: 1, Col: 2) Unexpected 'b' when converting from type string to type int"
writeln(ex.toString);

```
 
 
size\_t **row**;  size\_t **col**;    class **IncompleteCellException**: std.csv.CSVException;  
Exception thrown when a Token is identified to not be completed: a quote is found in an unquoted field, data continues after a closing quote, or the quoted field was not closed before data was empty.



Examples:


```
import std.exception : assertThrown;
string text = "a,\"b,c\nHello,65,2.5";
assertThrown!IncompleteCellException(text.csvReader(["a","b","c"]));

```
 
 
dstring **partialData**;  
Data pulled from input before finding a problem 


This field is populated when using [`csvReader`](#csvReader) but not by [`csvNextToken`](#csvNextToken) as this data will have already been fed to the output range.

    class **HeaderMismatchException**: std.csv.CSVException;  
Exception thrown under different conditions based on the type of  `Contents`. 


Structure, Class, and Associative Array * When a header is provided but a matching column is not found

   
  
 Other * When a header is provided but a matching column is not found
* Order did not match that found in the input

   
  
 Since a row and column is not meaningful when a column specified by the header is not found in the data, both row and col will be zero. Otherwise row is always one and col is the first instance found in header that occurred before the previous starting at one.

 
Examples:


```
import std.exception : assertThrown;
string text = "a,b,c\nHello,65,2.5";
assertThrown!HeaderMismatchException(text.csvReader(["b","c","invalid"]));

```
 
  enum **Malformed**: int;  
Determines the behavior for when an error is detected. 


Disabling exception will follow these rules: * A quote can appear in a field if the field was not quoted.
* If in a quoted field any quote by itself, not at the end of a field, will end processing for that field.
* The field is ended when there is no input, even if the quote was not closed.
* If the given header does not match the order in the input, the content will return as it is found in the input.
* If the given header contains columns not found in the input they will be ignored.


 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.searching : count;
import std.exception : assertThrown;

string text = "a,b,c\nHello,65,\"2.5";
assertThrown!IncompleteCellException(text.csvReader.count);

// ignore the exceptions and try to handle invalid CSV
auto firstLine = text.csvReader!(string, Malformed.ignore)(null).front;
assert(firstLine.equal(["Hello", "65", "2.5"]));

```
 
 
**ignore** 
No exceptions are thrown due to incorrect CSV.

  **throwException** 
Use exceptions when input has incorrect CSV.

    auto **csvReader**(Contents = string, Malformed ErrorLevel = Malformed.throwException, Range, Separator = char)(Range input, Separator delimiter = ',', Separator quote = '"')  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar)) && isSomeChar!Separator && !is(Contents T : T[U], U : string));   
  
auto **csvReader**(Contents = string, Malformed ErrorLevel = Malformed.throwException, Range, Header, Separator = char)(Range input, Header header, Separator delimiter = ',', Separator quote = '"')  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar)) && isSomeChar!Separator && isForwardRange!Header && isSomeString!(ElementType!Header));   
  
auto **csvReader**(Contents = string, Malformed ErrorLevel = Malformed.throwException, Range, Header, Separator = char)(Range input, Header header, Separator delimiter = ',', Separator quote = '"')  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar)) && isSomeChar!Separator && is(Header : typeof(null))); 
 
Returns an [input range](std_range_primitives#isInputRange) for iterating over records found in `input`. 


An optional `header` can be provided. The first record will be read in as the header. If `Contents` is a struct then the header provided is expected to correspond to the fields in the struct. When `Contents` is not a type which can contain the entire record, the `header` must be provided in the same order as the input or an exception is thrown. 

 
Returns:
An input range R as defined by [`std.range.primitives.isInputRange`](std_range_primitives#isInputRange). When `Contents` is a struct, class, or an associative array, the element type of R is `Contents`, otherwise the element type of R is itself a range with element type `Contents`. If a `header` argument is provided, the returned range provides a `header` field for accessing the header from the input in array form. 
 
Throws:

[`CSVException`](#CSVException) When a quote is found in an unquoted field, data continues after a closing quote, the quoted field was not closed before data was empty, a conversion failed, or when the row's length does not match the previous length. [`HeaderMismatchException`](#HeaderMismatchException) when a header is provided but a matching column is not found or the order did not match that found in the input. Read the exception documentation for specific details of when the exception is thrown for different types of `Contents`.
 
Examples:
The `Contents` of the input can be provided if all the records are the same type such as all integer data: 
```
import std.algorithm.comparison : equal;
string text = "76,26,22";
auto records = text.csvReader!int;
assert(records.equal!equal([
    [76, 26, 22],
]));

```
 
 
Examples:
Using a struct with modified delimiter: 
```
import std.algorithm.comparison : equal;
string text = "Hello;65;2.5\nWorld;123;7.5";
struct Layout
{
    string name;
    int value;
    double other;
}

auto records = text.csvReader!Layout(';');
assert(records.equal([
    Layout("Hello", 65, 2.5),
    Layout("World", 123, 7.5),
]));

```
 
 
Examples:
Specifying `ErrorLevel` as [`Malformed.ignore`](#Malformed.ignore) will lift restrictions on the format. This example shows that an exception is not thrown when finding a quote in a field not quoted. 
```
string text = "A \" is now part of the data";
auto records = text.csvReader!(string, Malformed.ignore);
auto record = records.front;

writeln(record.front); // text

```
 
 
Examples:
Read only column "b" 
```
import std.algorithm.comparison : equal;
string text = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
auto records = text.csvReader!int(["b"]);

assert(records.equal!equal([
    [65],
    [123],
]));

```
 
 
Examples:
Read while rearranging the columns by specifying a header with a different order" 
```
import std.algorithm.comparison : equal;
string text = "a,b,c\nHello,65,2.5\nWorld,123,7.5";
struct Layout
{
    int value;
    double other;
    string name;
}

auto records = text.csvReader!Layout(["b","c","a"]);
assert(records.equal([
    Layout(65, 2.5, "Hello"),
    Layout(123, 7.5, "World")
]));

```
 
 
Examples:
The header can also be left empty if the input contains a header row and all columns should be iterated. The header from the input can always be accessed from the `header` field. 
```
string text = "a,b,c\nHello,65,63.63";
auto records = text.csvReader(null);

writeln(records.header); // ["a", "b", "c"]

```
 
  void **csvNextToken**(Range, Malformed ErrorLevel = Malformed.throwException, Separator, Output)(ref Range input, ref Output ans, Separator sep, Separator quote, bool startQuoted = false)  
 Constraints: if (isSomeChar!Separator && isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar)) && isOutputRange!(Output, dchar)); 
 
Lower level control over parsing CSV 


This function consumes the input. After each call the input will start with either a delimiter or record break (\n, \r\n, \r) which must be removed for subsequent calls. 

 
Parameters:


|  |  |
| --- | --- |
| Range `input` | Any CSV input |
| Output `ans` | The first field in the input |
| Separator `sep` | The character to represent a comma in the specification |
| Separator `quote` | The character to represent a quote in the specification |
| bool `startQuoted` | Whether the input should be considered to already be in quotes |


 
Throws:

[`IncompleteCellException`](#IncompleteCellException) When a quote is found in an unquoted field, data continues after a closing quote, or the quoted field was not closed before data was empty.
 
Examples:


```
import std.array : appender;
import std.range.primitives : popFront;

string str = "65,63\n123,3673";

auto a = appender!(char[])();

csvNextToken(str,a,',','"');
writeln(a.data); // "65"
writeln(str); // ",63\n123,3673"

str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
writeln(a.data); // "63"
writeln(str); // "\n123,3673"

str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
writeln(a.data); // "123"
writeln(str); // ",3673"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_csv.html>

std.datetime
============

 

| Functionality | Symbols |
| --- | --- |
| Points in Time | [Date](std_datetime_date#Date) [TimeOfDay](std_datetime_date#TimeOfDay) [DateTime](std_datetime_date#DateTime) [SysTime](std_datetime_systime#SysTime) |
| Timezones | [TimeZone](std_datetime_timezone#TimeZone) [UTC](std_datetime_timezone#UTC) [LocalTime](std_datetime_timezone#LocalTime) [PosixTimeZone](std_datetime_timezone#PosixTimeZone) [WindowsTimeZone](std_datetime_timezone#WindowsTimeZone) [SimpleTimeZone](std_datetime_timezone#SimpleTimeZone) |
| Intervals and Ranges of Time | [Interval](std_datetime_interval#Interval) [PosInfInterval](std_datetime_interval#PosInfInterval) [NegInfInterval](std_datetime_interval#NegInfInterval) |
| Durations of Time | [Duration](core_time#Duration) [weeks](core_time#weeks) [days](core_time#days) [hours](core_time#hours) [minutes](core_time#minutes) [seconds](core_time#seconds) [msecs](core_time#msecs) [usecs](core_time#usecs) [hnsecs](core_time#hnsecs) [nsecs](core_time#nsecs) |
| Time Measurement and Benchmarking | [MonoTime](core_time#MonoTime) [StopWatch](std_datetime_stopwatch#StopWatch) [benchmark](std_datetime_stopwatch#benchmark) |


Phobos provides the following functionality for time: This functionality is separated into the following modules   
  
 * [`std.datetime.date`](std_datetime_date) for points in time without timezones.
* [`std.datetime.timezone`](std_datetime_timezone) for classes which represent timezones.
* [`std.datetime.systime`](std_datetime_systime) for a point in time with a timezone.
* [`std.datetime.interval`](std_datetime_interval) for types which represent series of points in time.
* [`std.datetime.stopwatch`](std_datetime_stopwatch) for measuring time.

 

 
See Also:

 [Introduction to std.datetime](https://dlang.org/intro-to-datetime.html)  
 [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601)  
  [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
  [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones)  
 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi 
 
Source
 [std/datetime/package.d](https://github.com/dlang/phobos/blob/master/std/datetime/package.d)

 
Examples:
Get the current time from the system clock 
```
import std.datetime.systime : SysTime, Clock;

SysTime currentTime = Clock.currTime();

```
 
 
Examples:
Construct a specific point in time without timezone information and get its ISO string. 
```
import std.datetime.date : DateTime;

auto dt = DateTime(2018, 1, 1, 12, 30, 10);
writeln(dt.toISOString()); // "20180101T123010"
writeln(dt.toISOExtString()); // "2018-01-01T12:30:10"

```
 
 
Examples:
Construct a specific point in time in the UTC timezone and add two days. 
```
import std.datetime.systime : SysTime;
import std.datetime.timezone : UTC;
import core.time : days;

auto st = SysTime(DateTime(2018, 1, 1, 12, 30, 10), UTC());
writeln(st.toISOExtString()); // "2018-01-01T12:30:10Z"
st += 2.days;
writeln(st.toISOExtString()); // "2018-01-03T12:30:10Z"

```
 


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime.html>

std.datetime.stopwatch
======================

 Module containing some basic benchmarking and timing functionality. 


 For convenience, this module publicly imports [`core.time`](core_time).   
  
 

| Category | Functions |
| --- | --- |
| Main functionality | [`StopWatch`](#StopWatch) [`benchmark`](#benchmark) |
| Flags | [`AutoStart`](#AutoStart) |

   
  
 Unlike the other modules in std.datetime, this module is not currently publicly imported in std.datetime.package, because the old versions of this functionality which use [`core.time.TickDuration`](core_time#TickDuration) are in std.datetime.package and would conflict with the symbols in this module. After the old symbols have gone through the deprecation cycle and have been fully removed, then this module will be publicly imported in std.datetime.package. The old, deprecated symbols has been removed from the documentation in December 2019 and currently scheduled to be fully removed from Phobos after 2.094.   
  
 So, for now, when using std.datetime.stopwatch, if other modules from std.datetime are needed, then either import them individually rather than importing std.datetime, or use selective or static imports to import std.datetime.stopwatch. e.g.   
  
 
```
import std.datetime;
import std.datetime.stopwatch : benchmark, StopWatch;

```
   
  
 The compiler will then know to use the symbols from std.datetime.stopwatch rather than the deprecated ones from std.datetime.package. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi 
 
Source
 [std/datetime/stopwatch.d](https://github.com/dlang/phobos/blob/master/std/datetime/stopwatch.d)

 
alias **AutoStart** = std.typecons.Flag!"autoStart".Flag;  
Used by StopWatch to indicate whether it should start immediately upon construction. 


If set to `AutoStart.no`, then the StopWatch is not started when it is constructed.   
  
 Otherwise, if set to `AutoStart.yes`, then the StopWatch is started when it is constructed.

  struct **StopWatch**;  
StopWatch is used to measure time just like one would do with a physical stopwatch, including stopping, restarting, and/or resetting it. 


[`core.time.MonoTime`](core_time#MonoTime) is used to hold the time, and it uses the system's monotonic clock, which is high precision and never counts backwards (unlike the wall clock time, which *can* count backwards, which is why [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime) should not be used for timing).   
  
 Note that the precision of StopWatch differs from system to system. It is impossible for it to be the same for all systems, since the precision of the system clock and other system-dependent and situation-dependent factors (such as the overhead of a context switch between threads) varies from system to system and can affect StopWatch's accuracy.

 
Examples:
Measure a time in milliseconds, microseconds, or nanoseconds 
```
auto sw = StopWatch(AutoStart.no);
sw.start();
// ... Insert operations to be timed here ...
sw.stop();

long msecs = sw.peek.total!"msecs";
long usecs = sw.peek.total!"usecs";
long nsecs = sw.peek.total!"nsecs";

assert(usecs >= msecs * 1000);
assert(nsecs >= usecs * 1000);

```
 
 
Examples:


```
import core.thread : Thread;

auto sw = StopWatch(AutoStart.yes);

Duration t1 = sw.peek();
Thread.sleep(usecs(1));
Duration t2 = sw.peek();
assert(t2 > t1);

Thread.sleep(usecs(1));
sw.stop();

Duration t3 = sw.peek();
assert(t3 > t2);
Duration t4 = sw.peek();
writeln(t3); // t4

sw.start();
Thread.sleep(usecs(1));

Duration t5 = sw.peek();
assert(t5 > t4);

// If stopping or resetting the StopWatch is not required, then
// MonoTime can easily be used by itself without StopWatch.
auto before = MonoTime.currTime;
// do stuff...
auto timeElapsed = MonoTime.currTime - before;

```
 
 
nothrow @nogc @safe this(AutoStart autostart);  
Constructs a StopWatch. Whether it starts immediately depends on the [`AutoStart`](#AutoStart) argument. 


If `StopWatch.init` is used, then the constructed StopWatch isn't running (and can't be, since no constructor ran).

 
Examples:


```
import core.thread : Thread;

{
    auto sw = StopWatch(AutoStart.yes);
    assert(sw.running);
    Thread.sleep(usecs(1));
    assert(sw.peek() > Duration.zero);
}
{
    auto sw = StopWatch(AutoStart.no);
    assert(!sw.running);
    Thread.sleep(usecs(1));
    writeln(sw.peek()); // Duration.zero
}
{
    StopWatch sw;
    assert(!sw.running);
    Thread.sleep(usecs(1));
    writeln(sw.peek()); // Duration.zero
}

writeln(StopWatch.init); // StopWatch(AutoStart.no)
assert(StopWatch.init != StopWatch(AutoStart.yes));

```
 
  nothrow @nogc @safe void **reset**();  
Resets the StopWatch. 


The StopWatch can be reset while it's running, and resetting it while it's running will not cause it to stop.

 
Examples:


```
import core.thread : Thread;

auto sw = StopWatch(AutoStart.yes);
Thread.sleep(usecs(1));
sw.stop();
assert(sw.peek() > Duration.zero);
sw.reset();
writeln(sw.peek()); // Duration.zero

```
 
  nothrow @nogc @safe void **start**();  
Starts the StopWatch. 


start should not be called if the StopWatch is already running.

 
Examples:


```
import core.thread : Thread;

StopWatch sw;
assert(!sw.running);
writeln(sw.peek()); // Duration.zero
sw.start();
assert(sw.running);
Thread.sleep(usecs(1));
assert(sw.peek() > Duration.zero);

```
 
  nothrow @nogc @safe void **stop**();  
Stops the StopWatch. 


stop should not be called if the StopWatch is not running.

 
Examples:


```
import core.thread : Thread;

auto sw = StopWatch(AutoStart.yes);
assert(sw.running);
Thread.sleep(usecs(1));
immutable t1 = sw.peek();
assert(t1 > Duration.zero);

sw.stop();
assert(!sw.running);
immutable t2 = sw.peek();
assert(t2 >= t1);
immutable t3 = sw.peek();
writeln(t2); // t3

```
 
  const nothrow @nogc @safe Duration **peek**();  
Peek at the amount of time that the the StopWatch has been running. 


This does not include any time during which the StopWatch was stopped but does include *all* of the time that it was running and not just the time since it was started last.   
  
 Calling [`reset`](#reset) will reset this to `Duration.zero`.

 
Examples:


```
import core.thread : Thread;

auto sw = StopWatch(AutoStart.no);
writeln(sw.peek()); // Duration.zero
sw.start();

Thread.sleep(usecs(1));
assert(sw.peek() >= usecs(1));

Thread.sleep(usecs(1));
assert(sw.peek() >= usecs(2));

sw.stop();
immutable stopped = sw.peek();
Thread.sleep(usecs(1));
writeln(sw.peek()); // stopped

sw.start();
Thread.sleep(usecs(1));
assert(sw.peek() > stopped);

```
 
  nothrow @nogc @safe void **setTimeElapsed**(Duration timeElapsed);  
Sets the total time which the StopWatch has been running (i.e. what peek returns). 


The StopWatch does not have to be stopped for setTimeElapsed to be called, nor will calling it cause the StopWatch to stop.

 
Examples:


```
import core.thread : Thread;

StopWatch sw;
sw.setTimeElapsed(hours(1));

// As discussed in MonoTime's documentation, converting between
// Duration and ticks is not exact, though it will be close.
// How exact it is depends on the frequency/resolution of the
// system's monotonic clock.
assert(abs(sw.peek() - hours(1)) < usecs(1));

sw.start();
Thread.sleep(usecs(1));
assert(sw.peek() > hours(1) + usecs(1));

```
 
  const pure nothrow @nogc @property @safe bool **running**();  
Returns whether this StopWatch is currently running.



Examples:


```
StopWatch sw;
assert(!sw.running);
sw.start();
assert(sw.running);
sw.stop();
assert(!sw.running);

```
 
    Duration[fun.length] **benchmark**(fun...)(uint n);  
Benchmarks code for speed assessment and comparison. 



Parameters:


|  |  |
| --- | --- |
| fun | aliases of callable objects (e.g. function names). Each callable object should take no arguments. |
| uint `n` | The number of times each function is to be executed. |


 
Returns:
The amount of time (as a [`core.time.Duration`](core_time#Duration)) that it took to call each function `n` times. The first value is the length of time that it took to call `fun[0]` `n` times. The second value is the length of time it took to call `fun[1]` `n` times. Etc.
 
Examples:


```
import std.conv : to;

int a;
void f0() {}
void f1() { auto b = a; }
void f2() { auto b = to!string(a); }
auto r = benchmark!(f0, f1, f2)(10_000);
Duration f0Result = r[0]; // time f0 took to run 10,000 times
Duration f1Result = r[1]; // time f1 took to run 10,000 times
Duration f2Result = r[2]; // time f2 took to run 10,000 times

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime_stopwatch.html>

std.compiler
============

 Identify the compiler used and its various features. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Alex Rønne Petersen 
 
Source
 [std/compiler.d](https://github.com/dlang/phobos/blob/master/std/compiler.d)

 
immutable string **name**;  
Vendor specific string naming the compiler, for example: "Digital Mars D".

  enum **Vendor**: int;  
Master list of D compiler vendors.

 
**unknown** 
Compiler vendor could not be detected

  **digitalMars** 
Digital Mars D (DMD)

  **gnu** 
GNU D Compiler (GDC)

  **llvm** 
LLVM D Compiler (LDC)

  **dotNET** 
D.NET

  **sdc** 
Stupid D Compiler (SDC)

    immutable Vendor **vendor**;  
Which vendor produced this compiler.

  immutable uint **version\_major**;   
  
immutable uint **version\_minor**;  
The vendor specific version number, as in version\_major.version\_minor

  immutable uint **D\_major**;  
The version of the D Programming Language Specification supported by the compiler.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_compiler.html>

std.conv
========

 A one-stop shop for converting values from one type to another. 


 

| Category | Functions |
| --- | --- |
| Generic | [`asOriginalType`](#asOriginalType) [`castFrom`](#castFrom) [`emplace`](#emplace) [`parse`](#parse) [`to`](#to) [`toChars`](#toChars) |
| Strings | [`text`](#text) [`wtext`](#wtext) [`dtext`](#dtext) [`hexString`](#hexString) |
| Numeric | [`octal`](#octal) [`roundTo`](#roundTo) [`signed`](#signed) [`unsigned`](#unsigned) |
| Exceptions | [`ConvException`](#ConvException) [`ConvOverflowException`](#ConvOverflowException) |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), Shin Fujishiro, Adam D. Ruppe, Kenji Hara 
 
Source
 [std/conv.d](https://github.com/dlang/phobos/blob/master/std/conv.d)

 
class **ConvException**: object.Exception;  
Thrown on conversion errors.



Examples:


```
import std.exception : assertThrown;
assertThrown!ConvException(to!int("abc"));

```
 
  class **ConvOverflowException**: std.conv.ConvException;  
Thrown on conversion overflow errors.



Examples:


```
import std.exception : assertThrown;
assertThrown!ConvOverflowException(to!ubyte(1_000_000));

```
 
  template **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
```


 
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

```
 
 
Examples:
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;
writeln(to!long(a)); // a
assertThrown!ConvOverflowException(to!byte(a));

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

```
 
 
Examples:
When converting strings to numeric types, note that the 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);
writeln(str); // "2A"
auto i = to!int(str, 16);
writeln(i); // 42

```
 
 
Examples:
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;
writeln(to!int(to!float(a))); // a
writeln(to!int(to!float(-a))); // -a

```
 
 
Examples:
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`](#ConvException) is thrown. 
```
import std.exception : assertThrown;

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

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

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

```
 
 
Examples:
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);
writeln(b); // [1.0f, 2, 3]
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
writeln(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);

```
 
 
Examples:
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);

```
 
 
Examples:
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));

```
 
 
Examples:
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 [`std.format.formatValue`](std_format#formatValue) on how toString should be defined. 
```
// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
writeln(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
writeln(to!string(cast(char*)null)); // ""
writeln(to!string("foo\0".ptr)); // "foo"

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

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

```
 
  template **roundTo**(Target) 
Rounded conversion from floating point to integral. 


Rounded conversions do not work with non-integral target types.

 
Examples:


```
writeln(roundTo!int(3.14)); // 3
writeln(roundTo!int(3.49)); // 3
writeln(roundTo!int(3.5)); // 4
writeln(roundTo!int(3.999)); // 4
writeln(roundTo!int(-3.14)); // -3
writeln(roundTo!int(-3.49)); // -3
writeln(roundTo!int(-3.5)); // -4
writeln(roundTo!int(-3.999)); // -4
writeln(roundTo!(const int)(to!(const double)(-3.999))); // -4

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source)  
 Constraints: if (isInputRange!Source && isSomeChar!(ElementType!Source) && is(immutable(Target) == immutable(bool))); 
 
The `parse` family of functions works quite like the `to` family, except that: 1. It only works with character ranges as input.
2. It takes the input by reference. (This means that rvalues - such as string literals - are not accepted: use `to` instead.)
3. It advances the input to the position following the conversion.
4. It does not throw if it could not convert the entire input.

 


This overload converts a character input range to a `bool`. 

 
Parameters:


|  |  |
| --- | --- |
| Target | the type to convert to |
| Source `source` | the lvalue of an [input range](std_range_primitives#isInputRange) |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* A `bool` if `doCount` is set to `No.doCount`
* A `tuple` containing a `bool` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) if the range does not represent a `bool`. 
 
Note
 All character input range conversions using [`to`](#to) are forwarded to `parse` and do not require lvalues.
 
Examples:


```
import std.typecons : Flag, Yes, No;
auto s = "true";
bool b = parse!bool(s);
assert(b);
auto s2 = "true";
bool b2 = parse!(bool, string, No.doCount)(s2);
assert(b2);
auto s3 = "true";
auto b3 = parse!(bool, string, Yes.doCount)(s3);
assert(b3.data && b3.count == 4);
auto s4 = "falSE";
auto b4 = parse!(bool, string, Yes.doCount)(s4);
assert(!b4.data && b4.count == 5);

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)  
 Constraints: if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum));   
  
auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source, uint radix)  
 Constraints: if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum)); 
 
Parses a character [input range](std_range_primitives#isInputRange) to an integral value. 



Parameters:


|  |  |
| --- | --- |
| Target | the integral type to convert to |
| Source `s` | the lvalue of an input range |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* A number of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing a number of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) If an overflow occurred during conversion or if no character of the input was meaningfully converted.
 
Examples:


```
import std.typecons : Flag, Yes, No;
string s = "123";
auto a = parse!int(s);
writeln(a); // 123

string s1 = "123";
auto a1 = parse!(int, string, Yes.doCount)(s1);
assert(a1.data == 123 && a1.count == 3);

// parse only accepts lvalues
static assert(!__traits(compiles, parse!int("123")));

```
 
 
Examples:


```
import std.string : tr;
import std.typecons : Flag, Yes, No;
string test = "123 \t  76.14";
auto a = parse!uint(test);
writeln(a); // 123
assert(test == " \t  76.14"); // parse bumps string
test = tr(test, " \t\n\r", "", "d"); // skip ws
writeln(test); // "76.14"
auto b = parse!double(test);
writeln(b); // 76.14
writeln(test); // ""

string test2 = "123 \t  76.14";
auto a2 = parse!(uint, string, Yes.doCount)(test2);
assert(a2.data == 123 && a2.count == 3);
assert(test2 == " \t  76.14");// parse bumps string
test2 = tr(test2, " \t\n\r", "", "d"); // skip ws
writeln(test2); // "76.14"
auto b2 = parse!(double, string, Yes.doCount)(test2);
assert(b2.data == 76.14 && b2.count == 5);
writeln(test2); // ""

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)  
 Constraints: if (isSomeString!Source && !is(Source == enum) && is(Target == enum)); 
 
Takes a string representing an `enum` type and returns that type. 



Parameters:


|  |  |
| --- | --- |
| Target | the `enum` type to convert to |
| Source `s` | the lvalue of the range to parse |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* An `enum` of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing an `enum` of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) if type `Target` does not have a member represented by `s`.
 
Examples:


```
import std.typecons : Flag, Yes, No, tuple;
enum EnumType : bool { a = true, b = false, c = a }

auto str = "a";
writeln(parse!EnumType(str)); // EnumType.a
auto str2 = "a";
writeln(parse!(EnumType, string, No.doCount)(str2)); // EnumType.a
auto str3 = "a";
writeln(parse!(EnumType, string, Yes.doCount)(str3)); // tuple(EnumType.a, 1)

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source)  
 Constraints: if (isInputRange!Source && isSomeChar!(ElementType!Source) && !is(Source == enum) && isFloatingPoint!Target && !is(Target == enum)); 
 
Parses a character range to a floating point number. 



Parameters:


|  |  |
| --- | --- |
| Target | a floating point type |
| Source `source` | the lvalue of the range to parse |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* A floating point number of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing a floating point number of·type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) if `source` is empty, if no number could be parsed, or if an overflow occurred.
 
Examples:


```
import std.math : approxEqual;
import std.typecons : Flag, Yes, No;
import std.math : isNaN, isInfinity;
auto str = "123.456";
assert(parse!double(str).approxEqual(123.456));
auto str2 = "123.456";
assert(parse!(double, string, No.doCount)(str2).approxEqual(123.456));
auto str3 = "123.456";
auto r = parse!(double, string, Yes.doCount)(str3);
assert(r.data.approxEqual(123.456));
writeln(r.count); // 7
auto str4 = "-123.456";
r = parse!(double, string, Yes.doCount)(str4);
assert(r.data.approxEqual(-123.456));
writeln(r.count); // 8
auto str5 = "+123.456";
r = parse!(double, string, Yes.doCount)(str5);
assert(r.data.approxEqual(123.456));
writeln(r.count); // 8
auto str6 = "inf0";
r = parse!(double, string, Yes.doCount)(str6);
assert(isInfinity(r.data) && r.count == 3 && str6 == "0");
auto str7 = "-0";
auto r2 = parse!(float, string, Yes.doCount)(str7);
assert(r2.data.approxEqual(0.0) && r2.count == 2);
auto str8 = "nan";
auto r3 = parse!(real, string, Yes.doCount)(str8);
assert(isNaN(r3.data) && r3.count == 3);

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)  
 Constraints: if (isSomeString!Source && !is(Source == enum) && (staticIndexOf!(immutable(Target), immutable(dchar), immutable(ElementEncodingType!Source)) >= 0));   
  
auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)  
 Constraints: if (!isSomeString!Source && isInputRange!Source && isSomeChar!(ElementType!Source) && isSomeChar!Target && (Target.sizeof >= ElementType!Source.sizeof) && !is(Target == enum)); 
 
Parsing one character off a range returns the first element and calls `popFront`. 



Parameters:


|  |  |
| --- | --- |
| Target | the type to convert to |
| Source `s` | the lvalue of an [input range](std_range_primitives#isInputRange) |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* A character of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing a character of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) if the range is empty.
 
Examples:


```
import std.typecons : Flag, Yes, No;
auto s = "Hello, World!";
char first = parse!char(s);
writeln(first); // 'H'
writeln(s); // "ello, World!"
char second = parse!(char, string, No.doCount)(s);
writeln(second); // 'e'
writeln(s); // "llo, World!"
auto third = parse!(char, string, Yes.doCount)(s);
assert(third.data == 'l' && third.count == 1);
writeln(s); // "lo, World!"

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)  
 Constraints: if (isInputRange!Source && isSomeChar!(ElementType!Source) && is(immutable(Target) == immutable(typeof(null)))); 
 
Parsing a character range to `typeof(null)` returns `null` if the range spells `"null"`. This function is case insensitive. 



Parameters:


|  |  |
| --- | --- |
| Target | the type to convert to |
| Source `s` | the lvalue of an [input range](std_range_primitives#isInputRange) |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:

* `null` if `doCount` is set to `No.doCount`
* A `tuple` containing `null` and a `size_t` if `doCount` is set to `Yes.doCount`

 
 
Throws:
A [`ConvException`](#ConvException) if the range doesn't represent `null`.
 
Examples:


```
import std.exception : assertThrown;
import std.typecons : Flag, Yes, No;

alias NullType = typeof(null);
auto s1 = "null";
assert(parse!NullType(s1) is null);
writeln(s1); // ""

auto s2 = "NUll"d;
assert(parse!NullType(s2) is null);
writeln(s2); // ""

auto s3 = "nuLlNULl";
assert(parse!(NullType, string, No.doCount)(s3) is null);
auto r = parse!(NullType, string, Yes.doCount)(s3);
assert(r.data is null && r.count == 4);

auto m = "maybe";
assertThrown!ConvException(parse!NullType(m));
assertThrown!ConvException(parse!(NullType, string, Yes.doCount)(m));
assert(m == "maybe");  // m shouldn't change on failure

auto s = "NULL";
assert(parse!(const NullType)(s) is null);

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')  
 Constraints: if (isSomeString!Source && !is(Source == enum) && isDynamicArray!Target && !is(Target == enum));   
  
auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')  
 Constraints: if (isExactSomeString!Source && isStaticArray!Target && !is(Target == enum)); 
 
Parses an array from a string given the left bracket (default  `'['`), right bracket (default `']'`), and element separator (by default `','`). A trailing separator is allowed. 



Parameters:


|  |  |
| --- | --- |
| Source `s` | The string to parse |
| dchar `lbracket` | the character that starts the array |
| dchar `rbracket` | the character that ends the array |
| dchar `comma` | the character that separates the elements of the array |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:
* An array of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing an array of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
Examples:


```
import std.typecons : Flag, Yes, No;
auto s1 = `[['h', 'e', 'l', 'l', 'o'], "world"]`;
auto a1 = parse!(string[])(s1);
writeln(a1); // ["hello", "world"]

auto s2 = `["aaa", "bbb", "ccc"]`;
auto a2 = parse!(string[])(s2);
writeln(a2); // ["aaa", "bbb", "ccc"]

auto s3 = `[['h', 'e', 'l', 'l', 'o'], "world"]`;
auto len3 = s3.length;
auto a3 = parse!(string[], string, Yes.doCount)(s3);
writeln(a3.data); // ["hello", "world"]
writeln(a3.count); // len3

```
 
  auto **parse**(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar keyval = ':', dchar comma = ',')  
 Constraints: if (isSomeString!Source && !is(Source == enum) && isAssociativeArray!Target && !is(Target == enum)); 
 
Parses an associative array from a string given the left bracket (default  `'['`), right bracket (default `']'`), key-value separator (default  `':'`), and element seprator (by default `','`). 



Parameters:


|  |  |
| --- | --- |
| Source `s` | the string to parse |
| dchar `lbracket` | the character that starts the associative array |
| dchar `rbracket` | the character that ends the associative array |
| dchar `keyval` | the character that associates the key with the value |
| dchar `comma` | the character that separates the elements of the associative array |
| doCount | the flag for deciding to report the number of consumed characters |


 
Returns:
* An associative array of type `Target` if `doCount` is set to `No.doCount`
* A `tuple` containing an associative array of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`

 
Examples:


```
import std.typecons : Flag, Yes, No, tuple;
import std.range.primitives : save;
import std.array : assocArray;
auto s1 = "[1:10, 2:20, 3:30]";
auto copyS1 = s1.save;
auto aa1 = parse!(int[int])(s1);
writeln(aa1); // [1:10, 2:20, 3:30]
// parse!(int[int], string, Yes.doCount)(copyS1)
writeln(tuple([1:10, 2:20, 3:30], copyS1.length));

auto s2 = `["aaa":10, "bbb":20, "ccc":30]`;
auto copyS2 = s2.save;
auto aa2 = parse!(int[string])(s2);
writeln(aa2); // ["aaa":10, "bbb":20, "ccc":30]
assert(tuple(["aaa":10, "bbb":20, "ccc":30], copyS2.length) ==
    parse!(int[string], string, Yes.doCount)(copyS2));

auto s3 = `["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]]`;
auto copyS3 = s3.save;
auto aa3 = parse!(int[][string])(s3);
writeln(aa3); // ["aaa":[1], "bbb":[2, 3], "ccc":[4, 5, 6]]
assert(tuple(["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]], copyS3.length) ==
    parse!(int[][string], string, Yes.doCount)(copyS3));

auto s4 = `[]`;
int[int] emptyAA;
writeln(tuple(emptyAA, s4.length)); // parse!(int[int], string, Yes.doCount)(s4)

```
 
  string **text**(T...)(T args)  
 Constraints: if (T.length > 0);   
  
wstring **wtext**(T...)(T args)  
 Constraints: if (T.length > 0);   
  
dstring **dtext**(T...)(T args)  
 Constraints: if (T.length > 0); 
 
Convenience functions for converting one or more arguments of any type into text (the three character widths).



Examples:


```
writeln(text(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"c
writeln(wtext(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"w
writeln(dtext(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"d

```
 
  template **octal**(string num) if (isOctalLiteral(num))  
  
template **octal**(alias decimalInteger) if (is(typeof(decimalInteger)) && isIntegral!(typeof(decimalInteger))) 
The `octal` facility provides a means to declare a number in base 8. Using `octal!177` or `octal!"177"` for 127 represented in octal (same as 0177 in C). 


The rules for strings are the usual for literals: If it can fit in an `int`, it is an `int`. Otherwise, it is a `long`. But, if the user specifically asks for a `long` with the `L` suffix, always give the `long`. Give an unsigned iff it is asked for with the `U` or `u` suffix. Octals created from integers preserve the type of the passed-in integral. 

 
See Also:

[`parse`](#parse) for parsing octal strings at runtime.
 
Examples:


```
// same as 0177
auto x = octal!177;
// octal is a compile-time device
enum y = octal!160;
// Create an unsigned octal
auto z = octal!"1_000_000u";

```
 
  pure nothrow @safe T\* **emplace**(T)(T\* chunk);  
Given a pointer `chunk` to uninitialized memory (but already typed as `T`), constructs an object of non-`class` type `T` at that address. If `T` is a class, initializes the class reference to null. 



Returns:
A pointer to the newly constructed object (which is the same as `chunk`).
 
Examples:


```
static struct S
{
    int i = 42;
}
S[2] s2 = void;
emplace(&s2);
assert(s2[0].i == 42 && s2[1].i == 42);

```
 
 
Examples:


```
interface I {}
class K : I {}

K k = void;
emplace(&k);
assert(k is null);

I i = void;
emplace(&i);
assert(i is null);

```
 
  T\* **emplace**(T, Args...)(T\* chunk, auto ref Args args)  
 Constraints: if (is(T == struct) || Args.length == 1); 
 
Given a pointer `chunk` to uninitialized memory (but already typed as a non-class type `T`), constructs an object of type `T` at that address from arguments `args`. If `T` is a class, initializes the class reference to `args[0]`. 


This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 

 
Returns:
A pointer to the newly constructed object (which is the same as `chunk`).
 
Examples:


```
int a;
int b = 42;
writeln(*emplace!int(&a, b)); // 42

```
 
  T **emplace**(T, Args...)(T chunk, auto ref Args args)  
 Constraints: if (is(T == class)); 
 
Given a raw memory area `chunk` (but already typed as a class type `T`), constructs an object of `class` type `T` at that address. The constructor is passed the arguments `Args`. 


If `T` is an inner class whose `outer` field can be used to access an instance of the enclosing class, then `Args` must not be empty, and the first member of it must be a valid initializer for that `outer` field. Correct initialization of this field is essential to access members of the outer class inside `T` methods. 

 
Note
 This function is `@safe` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
The newly constructed object.
 
Examples:


```
() @safe {
    class SafeClass
    {
        int x;
        @safe this(int x) { this.x = x; }
    }

    auto buf = new void[__traits(classInstanceSize, SafeClass)];
    auto support = (() @trusted => cast(SafeClass)(buf.ptr))();
    auto safeClass = emplace!SafeClass(support, 5);
    writeln(safeClass.x); // 5

    class UnsafeClass
    {
        int x;
        @system this(int x) { this.x = x; }
    }

    auto buf2 = new void[__traits(classInstanceSize, UnsafeClass)];
    auto support2 = (() @trusted => cast(UnsafeClass)(buf2.ptr))();
    static assert(!__traits(compiles, emplace!UnsafeClass(support2, 5)));
    static assert(!__traits(compiles, emplace!UnsafeClass(buf2, 5)));
}();

```
 
  T **emplace**(T, Args...)(void[] chunk, auto ref Args args)  
 Constraints: if (is(T == class)); 
 
Given a raw memory area `chunk`, constructs an object of `class` type `T` at that address. The constructor is passed the arguments `Args`. 


If `T` is an inner class whose `outer` field can be used to access an instance of the enclosing class, then `Args` must not be empty, and the first member of it must be a valid initializer for that `outer` field. Correct initialization of this field is essential to access members of the outer class inside `T` methods. 

 
Preconditions
 `chunk` must be at least as large as `T` needs and should have an alignment multiple of `T`'s alignment. (The size of a `class` instance is obtained by using `_traits(classInstanceSize, T)`). 
 
Note
 This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
The newly constructed object.
 
Examples:


```
static class C
{
    int i;
    this(int i){this.i = i;}
}
auto buf = new void[__traits(classInstanceSize, C)];
auto c = emplace!C(buf, 5);
writeln(c.i); // 5

```
 
  T\* **emplace**(T, Args...)(void[] chunk, auto ref Args args)  
 Constraints: if (!is(T == class)); 
 
Given a raw memory area `chunk`, constructs an object of non-`class` type `T` at that address. The constructor is passed the arguments `args`, if any. 



Preconditions
 `chunk` must be at least as large as `T` needs and should have an alignment multiple of `T`'s alignment. 
 
Note
 This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
A pointer to the newly constructed object.
 
Examples:


```
struct S
{
    int a, b;
}
auto buf = new void[S.sizeof];
S s;
s.a = 42;
s.b = 43;
auto s1 = emplace!S(buf, s);
assert(s1.a == 42 && s1.b == 43);

```
 
  auto **unsigned**(T)(T x)  
 Constraints: if (isIntegral!T);   
  
auto **unsigned**(T)(T x)  
 Constraints: if (isSomeChar!T); 
 
Returns the corresponding unsigned value for `x` (e.g. if `x` has type `int`, it returns `cast(uint) x`). The advantage compared to the cast is that you do not need to rewrite the cast if `x` later changes type (e.g from `int` to `long`). 


Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use [`std.traits.Unsigned`](std_traits#Unsigned).

 
Examples:


```
import std.traits : Unsigned;
immutable int s = 42;
auto u1 = unsigned(s); //not qualified
static assert(is(typeof(u1) == uint));
Unsigned!(typeof(s)) u2 = unsigned(s); //same qualification
static assert(is(typeof(u2) == immutable uint));
immutable u3 = unsigned(s); //explicitly qualified

```
 
  auto **signed**(T)(T x)  
 Constraints: if (isIntegral!T); 
 
Returns the corresponding signed value for `x` (e.g. if `x` has type `uint`, it returns `cast(int) x`). The advantage compared to the cast is that you do not need to rewrite the cast if `x` later changes type (e.g from `uint` to `ulong`). 


Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use [`std.traits.Signed`](std_traits#Signed).

 
Examples:


```
import std.traits : Signed;

immutable uint u = 42;
auto s1 = signed(u); //not qualified
static assert(is(typeof(s1) == int));
Signed!(typeof(u)) s2 = signed(u); //same qualification
static assert(is(typeof(s2) == immutable int));
immutable s3 = signed(u); //explicitly qualified

```
 
  OriginalType!E **asOriginalType**(E)(E value)  
 Constraints: if (is(E == enum)); 
 
Returns the representation of an enumerated value, i.e. the value converted to the base type of the enumeration.



Examples:


```
enum A { a = 42 }
static assert(is(typeof(A.a.asOriginalType) == int));
writeln(A.a.asOriginalType); // 42
enum B : double { a = 43 }
static assert(is(typeof(B.a.asOriginalType) == double));
writeln(B.a.asOriginalType); // 43

```
 
  template **castFrom**(From) 
A wrapper on top of the built-in cast operator that allows one to restrict casting of the original type of the value. 


A common issue with using a raw cast is that it may silently continue to compile even if the value's type has changed during refactoring, which breaks the initial assumption about the cast. 

 
Parameters:


|  |  |
| --- | --- |
| From | The type to cast from. The programmer must ensure it is legal to make this cast. |


 
Examples:


```
// Regular cast, which has been verified to be legal by the programmer:
{
    long x;
    auto y = cast(int) x;
}

// However this will still compile if 'x' is changed to be a pointer:
{
    long* x;
    auto y = cast(int) x;
}

// castFrom provides a more reliable alternative to casting:
{
    long x;
    auto y = castFrom!long.to!int(x);
}

// Changing the type of 'x' will now issue a compiler error,
// allowing bad casts to be caught before it's too late:
{
    long* x;
    static assert(
        !__traits(compiles, castFrom!long.to!int(x))
    );

    // if cast is still needed, must be changed to:
    auto y = castFrom!(long*).to!int(x);
}

```
 
 
ref @system auto **to**(To, T)(auto ref T value);  

Parameters:


|  |  |
| --- | --- |
| To | The type to cast to. |
| T `value` | The value to cast. It must be of type `From`, otherwise a compile-time error is emitted. |


 
Returns:
the value after the cast, returned by reference if possible.
    template **hexString**(string hexData) if (hexData.isHexLiteral)  
  
template **hexString**(wstring hexData) if (hexData.isHexLiteral)  
  
template **hexString**(dstring hexData) if (hexData.isHexLiteral) 
Converts a hex literal to a string at compile time. 


Takes a string made of hexadecimal digits and returns the matching string by converting each pair of digits to a character. The input string can also include white characters, which can be used to keep the literal string readable in the source code.   
  
 The function is intended to replace the hexadecimal literal strings starting with `'x'`, which could be removed to simplify the core language. 

 
Parameters:


|  |  |
| --- | --- |
| hexData | string to be converted. |


 
Returns:
a `string`, a `wstring` or a `dstring`, according to the type of hexData.
 
Examples:


```
// conversion at compile time
auto string1 = hexString!"304A314B";
writeln(string1); // "0J1K"
auto string2 = hexString!"304A314B"w;
writeln(string2); // "0J1K"w
auto string3 = hexString!"304A314B"d;
writeln(string3); // "0J1K"d

```
 
  pure nothrow @nogc @safe auto **toChars**(ubyte radix = 10, Char = char, LetterCase letterCase = LetterCase.lower, T)(T value)  
 Constraints: if ((radix == 2 || radix == 8 || radix == 10 || radix == 16) && (is(immutable(T) == immutable(uint)) || is(immutable(T) == immutable(ulong)) || radix == 10 && (is(immutable(T) == immutable(int)) || is(immutable(T) == immutable(long))))); 
 
Convert integer to a range of characters. Intended to be lightweight and fast. 



Parameters:


|  |  |
| --- | --- |
| radix | 2, 8, 10, 16 |
| Char | character type for output |
| letterCase | lower for deadbeef, upper for DEADBEEF |
| T `value` | integer to convert. Can be uint or ulong. If radix is 10, can also be int or long. |


 
Returns:
Random access range with slicing and everything
 
Examples:


```
import std.algorithm.comparison : equal;

assert(toChars(1).equal("1"));
assert(toChars(1_000_000).equal("1000000"));

assert(toChars!(2)(2U).equal("10"));
assert(toChars!(16)(255U).equal("ff"));
assert(toChars!(16, char, LetterCase.upper)(255U).equal("FF"));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_conv.html>

std.demangle
============

 Demangle D mangled names. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Thomas Kühne, Frits van Bommel 
 
Source
 [std/demangle.d](https://github.com/dlang/phobos/blob/master/std/demangle.d) 
 
pure nothrow @safe string **demangle**(string name);  
Demangle D mangled names. 



Parameters:


|  |  |
| --- | --- |
| string `name` | the mangled name |


 
Returns:
A `string`. If it is not a D mangled name, it returns its argument name.
 
Examples:


```
// int b in module a
writeln(demangle("_D1a1bi")); // "int a.b"
// char array foo in module test
writeln(demangle("_D4test3fooAa")); // "char[] test.foo"

```
 
 
Examples:
This program reads standard in and writes it to standard out, pretty-printing any found D mangled names. 
```
import std.ascii : isAlphaNum;
import std.algorithm.iteration : chunkBy, joiner, map;
import std.algorithm.mutation : copy;
import std.conv : to;
import std.demangle : demangle;
import std.functional : pipe;
import std.stdio : stdin, stdout;

void main()
{
    stdin.byLineCopy
        .map!(
            l => l.chunkBy!(a => isAlphaNum(a) || a == '_')
                  .map!(a => a[1].pipe!(to!string, demangle)).joiner
        )
        .copy(stdout.lockingTextWriter);
}

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_demangle.html>

std.container.binaryheap
========================

 This module provides a `BinaryHeap` (aka priority queue) adaptor that makes a binary heap out of any user-provided random-access range. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/binaryheap.d](https://github.com/dlang/phobos/blob/master/std/container/binaryheap.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:
[Andrei Alexandrescu](http://erdani.com)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : take;
auto maxHeap = heapify([4, 7, 3, 1, 5]);
assert(maxHeap.take(3).equal([7, 5, 4]));

auto minHeap = heapify!"a > b"([4, 7, 3, 1, 5]);
assert(minHeap.take(3).equal([1, 3, 4]));

```
 
 
struct **BinaryHeap**(Store, alias less = "a < b") if (isRandomAccessRange!Store || isRandomAccessRange!(typeof(Store.init[])));  
Implements a [binary heap](http://en.wikipedia.org/wiki/Binary_heap) container on top of a given random-access range type (usually `T[]`) or a random-access container type (usually `Array!T`). The documentation of `BinaryHeap` will refer to the underlying range or container as the *store* of the heap. 


The binary heap induces structure over the underlying store such that accessing the largest element (by using the `front` property) is a Ο(`1`) operation and extracting it (by using the `removeFront()` method) is done fast in Ο(`log n`) time.   
  
 If `less` is the less-than operator, which is the default option, then `BinaryHeap` defines a so-called max-heap that optimizes extraction of the *largest* elements. To define a min-heap, instantiate BinaryHeap with `"a > b"` as its predicate.   
  
 Simply extracting elements from a `BinaryHeap` container is tantamount to lazily fetching elements of `Store` in descending order. Extracting elements from the `BinaryHeap` to completion leaves the underlying store sorted in ascending order but, again, yields elements in descending order.   
  
 If `Store` is a range, the `BinaryHeap` cannot grow beyond the size of that range. If `Store` is a container that supports `insertBack`, the `BinaryHeap` may grow by adding elements to the container.

 
Examples:
Example from "Introduction to Algorithms" Cormen et al, p 146 
```
import std.algorithm.comparison : equal;
int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
auto h = heapify(a);
// largest element
writeln(h.front); // 16
// a has the heap property
assert(equal(a, [ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ]));

```
 
 
Examples:

`BinaryHeap` implements the standard input range interface, allowing lazy iteration of the underlying range in descending order. 
```
import std.algorithm.comparison : equal;
import std.range : take;
int[] a = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7];
auto top5 = heapify(a).take(5);
assert(top5.equal([16, 14, 10, 9, 8]));

```
 
 
this(Store s, size\_t initialSize = size\_t.max);  
Converts the store `s` into a heap. If `initialSize` is specified, only the first `initialSize` elements in `s` are transformed into a heap, after which the heap can grow up to `r.length` (if `Store` is a range) or indefinitely (if `Store` is a container with `insertBack`). Performs Ο(`min(r.length, initialSize)`) evaluations of `less`.

  void **acquire**(Store s, size\_t initialSize = size\_t.max);  
Takes ownership of a store. After this, manipulating `s` may make the heap work incorrectly.

  void **assume**(Store s, size\_t initialSize = size\_t.max);  
Takes ownership of a store assuming it already was organized as a heap.

  auto **release**();  
Clears the heap. Returns the portion of the store from `0` up to `length`, which satisfies the [heap property](https://en.wikipedia.org/wiki/Heap_(data_structure)).

  @property bool **empty**();  
Returns `true` if the heap is empty, `false` otherwise.

  @property BinaryHeap **dup**();  
Returns a duplicate of the heap. The `dup` method is available only if the underlying store supports it.

  @property size\_t **length**();  
Returns the length of the heap.

  @property size\_t **capacity**();  
Returns the capacity of the heap, which is the length of the underlying store (if the store is a range) or the capacity of the underlying store (if the store is a container).

  @property ElementType!Store **front**();  
Returns a copy of the front of the heap, which is the largest element according to `less`.

  void **clear**();  
Clears the heap by detaching it from the underlying store.

  size\_t **insert**(ElementType!Store value);  
Inserts `value` into the store. If the underlying store is a range and `length == capacity`, throws an exception.

  void **removeFront**();   
  
alias **popFront** = removeFront;  
Removes the largest element from the heap.

  ElementType!Store **removeAny**();  
Removes the largest element from the heap and returns a copy of it. The element still resides in the heap's store. For performance reasons you may want to use `removeFront` with heaps of objects that are expensive to copy.

  void **replaceFront**(ElementType!Store value);  
Replaces the largest element in the store with `value`.

  bool **conditionalInsert**(ElementType!Store value);  
If the heap has room to grow, inserts `value` into the store and returns `true`. Otherwise, if `less(value, front)`, calls `replaceFront(value)` and returns again `true`. Otherwise, leaves the heap unaffected and returns `false`. This method is useful in scenarios where the smallest `k` elements of a set of candidates must be collected.

  bool **conditionalSwap**(ref ElementType!Store value);  
Swapping is allowed if the heap is full. If `less(value, front)`, the method exchanges store.front and value and returns `true`. Otherwise, it leaves the heap unaffected and returns `false`.

    BinaryHeap!(Store, less) **heapify**(alias less = "a < b", Store)(Store s, size\_t initialSize = size\_t.max);  
Convenience function that returns a `BinaryHeap!Store` object initialized with `s` and `initialSize`.



Examples:


```
import std.conv : to;
import std.range.primitives;
{
    // example from "Introduction to Algorithms" Cormen et al., p 146
    int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
    auto h = heapify(a);
    h = heapify!"a < b"(a);
    writeln(h.front); // 16
    writeln(a); // [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
    auto witness = [ 16, 14, 10, 9, 8, 7, 4, 3, 2, 1 ];
    for (; !h.empty; h.removeFront(), witness.popFront())
    {
        assert(!witness.empty);
        writeln(witness.front); // h.front
    }
    assert(witness.empty);
}
{
    int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
    int[] b = new int[a.length];
    BinaryHeap!(int[]) h = BinaryHeap!(int[])(b, 0);
    foreach (e; a)
    {
        h.insert(e);
    }
    writeln(b); // [16, 14, 10, 8, 7, 3, 9, 1, 4, 2]
}

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_binaryheap.html>

std.complex
===========

 This module contains the [`Complex`](#Complex) type, which is used to represent complex numbers, along with related mathematical operations and functions. 


[`Complex`](#Complex) will eventually [replace](https://dlang.org/deprecate.html) the built-in types `cfloat`, `cdouble`, `creal`, `ifloat`, `idouble`, and `ireal`. 

 
Authors:
Lars Tandle Kyllingstad, Don Clugston 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt) 
 
Source
 [std/complex.d](https://github.com/dlang/phobos/blob/master/std/complex.d)

 
pure nothrow @nogc @safe auto **complex**(R)(const R re)  
 Constraints: if (is(R : double));   
  
pure nothrow @nogc @safe auto **complex**(R, I)(const R re, const I im)  
 Constraints: if (is(R : double) && is(I : double)); 
 
Helper function that returns a complex number with the specified real and imaginary parts. 



Parameters:


|  |  |
| --- | --- |
| R | (template parameter) type of real part of complex number |
| I | (template parameter) type of imaginary part of complex number |
| R `re` | real part of complex number to be constructed |
| I `im` | (optional) imaginary part of complex number, 0 if omitted. |


 
Returns:

`Complex` instance with real and imaginary parts set to the values provided as input. If neither `re` nor `im` are floating-point numbers, the return type will be `Complex!double`. Otherwise, the return type is deduced using `std.traits.CommonType!(R, I)`.
 
Examples:


```
auto a = complex(1.0);
static assert(is(typeof(a) == Complex!double));
writeln(a.re); // 1.0
writeln(a.im); // 0.0

auto b = complex(2.0L);
static assert(is(typeof(b) == Complex!real));
writeln(b.re); // 2.0L
writeln(b.im); // 0.0L

auto c = complex(1.0, 2.0);
static assert(is(typeof(c) == Complex!double));
writeln(c.re); // 1.0
writeln(c.im); // 2.0

auto d = complex(3.0, 4.0L);
static assert(is(typeof(d) == Complex!real));
writeln(d.re); // 3.0
writeln(d.im); // 4.0L

auto e = complex(1);
static assert(is(typeof(e) == Complex!double));
writeln(e.re); // 1
writeln(e.im); // 0

auto f = complex(1L, 2);
static assert(is(typeof(f) == Complex!double));
writeln(f.re); // 1L
writeln(f.im); // 2

auto g = complex(3, 4.0L);
static assert(is(typeof(g) == Complex!real));
writeln(g.re); // 3
writeln(g.im); // 4.0L

```
 
  struct **Complex**(T) if (isFloatingPoint!T);  
A complex number parametrised by a type `T`, which must be either `float`, `double` or `real`.

 
T **re**;  
The real part of the number.

  T **im**;  
The imaginary part of the number.

  const @safe string **toString**();   
  
const void **toString**(Writer, Char)(scope Writer w, ref scope const FormatSpec!Char formatSpec)  
 Constraints: if (isOutputRange!(Writer, const(Char)[])); 
 
Converts the complex number to a string representation. 


The second form of this function is usually not called directly; instead, it is used via [`std.string.format`](std_string#format), as shown in the examples below. Supported format characters are 'e', 'f', 'g', 'a', and 's'.   
  
 See the [`std.format`](std_format) and [`std.string.format`](std_string#format) documentation for more information.

 
Examples:


```
auto c = complex(1.2, 3.4);

// Vanilla toString formatting:
writeln(c.toString()); // "1.2+3.4i"

// Formatting with std.string.format specs: the precision and width
// specifiers apply to both the real and imaginary parts of the
// complex number.
import std.format : format;
writeln(format("%.2f", c)); // "1.20+3.40i"
writeln(format("%4.1f", c)); // " 1.2+ 3.4i"

```
 
  this(R : T)(Complex!R z);   
  
this(Rx : T, Ry : T)(const Rx x, const Ry y);   
  
this(R : T)(const R r);  
Construct a complex number with the specified real and imaginary parts. In the case where a single argument is passed that is not complex, the imaginary part of the result will be zero.

    pure nothrow @nogc @safe T **abs**(T)(Complex!T z);  

Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |


 
Returns:
The absolute value (or modulus) of `z`.
 
Examples:


```
static import std.math;
writeln(abs(complex(1.0))); // 1.0
writeln(abs(complex(0.0, 1.0))); // 1.0
writeln(abs(complex(1.0L, -2.0L))); // std.math.sqrt(5.0L)

```
 
  pure nothrow @nogc @safe T **sqAbs**(T)(Complex!T z);   
  
pure nothrow @nogc @safe T **sqAbs**(T)(const T x)  
 Constraints: if (isFloatingPoint!T); 
 

Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |
| T `x` | A real number. |


 
Returns:
The squared modulus of `z`. For genericity, if called on a real number, returns its square.
 
Examples:


```
import std.math;
writeln(sqAbs(complex(0.0))); // 0.0
writeln(sqAbs(complex(1.0))); // 1.0
writeln(sqAbs(complex(0.0, 1.0))); // 1.0
assert(approxEqual(sqAbs(complex(1.0L, -2.0L)), 5.0L));
assert(approxEqual(sqAbs(complex(-3.0L, 1.0L)), 10.0L));
assert(approxEqual(sqAbs(complex(1.0f,-1.0f)), 2.0f));

```
 
  pure nothrow @nogc @safe T **arg**(T)(Complex!T z);  

Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |


 
Returns:
The argument (or phase) of `z`.
 
Examples:


```
import std.math;
writeln(arg(complex(1.0))); // 0.0
writeln(arg(complex(0.0L, 1.0L))); // PI_2
writeln(arg(complex(1.0L, 1.0L))); // PI_4

```
 
  pure nothrow @nogc @safe T **norm**(T)(Complex!T z);  
Extracts the norm of a complex number. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number |


 
Returns:
The squared magnitude of `z`.
 
Examples:


```
import std.math : isClose, PI;
writeln(norm(complex(3.0, 4.0))); // 25.0
writeln(norm(fromPolar(5.0, 0.0))); // 25.0
assert(isClose(norm(fromPolar(5.0L, PI / 6)), 25.0L));
assert(isClose(norm(fromPolar(5.0L, 13 * PI / 6)), 25.0L));

```
 
  pure nothrow @nogc @safe Complex!T **conj**(T)(Complex!T z);  

Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |


 
Returns:
The complex conjugate of `z`.
 
Examples:


```
writeln(conj(complex(1.0))); // complex(1.0)
writeln(conj(complex(1.0, 2.0))); // complex(1.0, -2.0)

```
 
  Complex!T **proj**(T)(Complex!T z);  
Returns the projection of `z` onto the Riemann sphere. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number |


 
Returns:
The projection of `z` onto the Riemann sphere.
 
Examples:


```
writeln(proj(complex(1.0))); // complex(1.0)
writeln(proj(complex(double.infinity, 5.0))); // complex(double.infinity, 0.0)
writeln(proj(complex(5.0, -double.infinity))); // complex(double.infinity, -0.0)

```
 
  pure nothrow @nogc @safe Complex!(CommonType!(T, U)) **fromPolar**(T, U)(const T modulus, const U argument);  
Constructs a complex number given its absolute value and argument. 



Parameters:


|  |  |
| --- | --- |
| T `modulus` | The modulus |
| U `argument` | The argument |


 
Returns:
The complex number with the given modulus and argument.
 
Examples:


```
import std.math;
auto z = fromPolar(std.math.sqrt(2.0), PI_4);
assert(approxEqual(z.re, 1.0L, real.epsilon));
assert(approxEqual(z.im, 1.0L, real.epsilon));

```
 
  pure nothrow @nogc @safe Complex!T **sin**(T)(Complex!T z);   
  
pure nothrow @nogc @safe Complex!T **cos**(T)(Complex!T z);   
  
pure nothrow @nogc @safe Complex!T **tan**(T)(Complex!T z);  
Trigonometric functions on complex numbers. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |


 
Returns:
The sine, cosine and tangent of `z`, respectively.
 
Examples:


```
static import std.math;
writeln(sin(complex(0.0))); // 0.0
writeln(sin(complex(2.0, 0))); // std.math.sin(2.0)

```
 
 
Examples:


```
static import std.math;
writeln(cos(complex(0.0))); // 1.0
writeln(cos(complex(1.3, 0.0))); // std.math.cos(1.3)
writeln(cos(complex(0.0, 5.2))); // std.math.cosh(5.2)

```
 
 
Examples:


```
static import std.math;
assert(ceqrel(tan(complex(1.0, 0.0)), complex(std.math.tan(1.0), 0.0)) >= double.mant_dig - 2);
assert(ceqrel(tan(complex(0.0, 1.0)), complex(0.0, std.math.tanh(1.0))) >= double.mant_dig - 2);

```
 
  pure nothrow @nogc @trusted Complex!real **expi**(real y);  

Parameters:


|  |  |
| --- | --- |
| real `y` | A real number. |


 
Returns:
The value of cos(y) + i sin(y). 
 
Note
 `expi` is included here for convenience and for easy migration of code.
 
Examples:


```
import std.math : cos, sin;
writeln(expi(0.0L)); // 1.0L
writeln(expi(1.3e5L)); // complex(cos(1.3e5L), sin(1.3e5L))

```
 
  pure nothrow @nogc @safe Complex!real **coshisinh**(real y);  

Parameters:


|  |  |
| --- | --- |
| real `y` | A real number. |


 
Returns:
The value of cosh(y) + i sinh(y) 
 
Note
 `coshisinh` is included here for convenience and for easy migration of code.
 
Examples:


```
import std.math : cosh, sinh;
writeln(coshisinh(3.0L)); // complex(cosh(3.0L), sinh(3.0L))

```
 
  pure nothrow @nogc @safe Complex!T **sqrt**(T)(Complex!T z);  

Parameters:


|  |  |
| --- | --- |
| Complex!T `z` | A complex number. |


 
Returns:
The square root of `z`.
 
Examples:


```
static import std.math;
writeln(sqrt(complex(0.0))); // 0.0
writeln(sqrt(complex(1.0L, 0))); // std.math.sqrt(1.0L)
writeln(sqrt(complex(-1.0L, 0))); // complex(0, 1.0L)
writeln(sqrt(complex(-8.0, -6.0))); // complex(1.0, -3.0)

```
 
  pure nothrow @nogc @trusted Complex!T **exp**(T)(Complex!T x);  
Calculates ex. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `x` | A complex number |


 
Returns:
The complex base e exponential of `x` 

Special Values| x | exp(x) |
| (±0, +0) | (1, +0) |
| (any, +∞) | (NAN, NAN) |
| (any, NAN)  | (NAN, NAN) |
| (+∞, +0) | (+∞, +0) |
| (-∞, any) | (±0, cis(x.im)) |
| (+∞, any) | (±∞, cis(x.im)) |
| (-∞, +∞) | (±0, ±0) |
| (+∞, +∞) | (±∞, NAN) |
| (-∞, NAN) | (±0, ±0) |
| (+∞, NAN) | (±∞, NAN) |
| (NAN, +0) | (NAN, +0) |
| (NAN, any) | (NAN, NAN) |
| (NAN, NAN) | (NAN, NAN) |



 
Examples:


```
import std.math : isClose, PI;

writeln(exp(complex(0.0, 0.0))); // complex(1.0, 0.0)

auto a = complex(2.0, 1.0);
writeln(exp(conj(a))); // conj(exp(a))

auto b = exp(complex(0.0L, 1.0L) * PI);
assert(isClose(b, -1.0L, 0.0, 1e-15));

```
 
  pure nothrow @nogc @safe Complex!T **log**(T)(Complex!T x);  
Calculate the natural logarithm of x. The branch cut is along the negative axis. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `x` | A complex number |


 
Returns:
The complex natural logarithm of `x` 

Special Values| x | log(x) |
| (-0, +0) | (-∞, π) |
| (+0, +0) | (-∞, +0) |
| (any, +∞) | (+∞, π/2) |
| (any, NAN) | (NAN, NAN) |
| (-∞, any) | (+∞, π) |
| (+∞, any) | (+∞, +0) |
| (-∞, +∞) | (+∞, 3π/4) |
| (+∞, +∞) | (+∞, π/4) |
| (±∞, NAN) | (+∞, NAN) |
| (NAN, any) | (NAN, NAN) |
| (NAN, +∞) | (+∞, NAN) |
| (NAN, NAN) | (NAN, NAN) |



 
Examples:


```
import std.math : sqrt, PI, isClose;

auto a = complex(2.0, 1.0);
writeln(log(conj(a))); // conj(log(a))

auto b = 2.0 * log10(complex(0.0, 1.0));
auto c = 4.0 * log10(complex(sqrt(2.0) / 2, sqrt(2.0) / 2));
assert(isClose(b, c, 0.0, 1e-15));

writeln(log(complex(-1.0L, 0.0L))); // complex(0.0L, PI)
writeln(log(complex(-1.0L, -0.0L))); // complex(0.0L, -PI)

```
 
  pure nothrow @nogc @safe Complex!T **log10**(T)(Complex!T x);  
Calculate the base-10 logarithm of x. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `x` | A complex number |


 
Returns:
The complex base 10 logarithm of `x`

 
Examples:


```
import std.math : LN10, PI, isClose, sqrt;

auto a = complex(2.0, 1.0);
writeln(log10(a)); // log(a) / log(complex(10.0))

auto b = log10(complex(0.0, 1.0)) * 2.0;
auto c = log10(complex(sqrt(2.0) / 2, sqrt(2.0) / 2)) * 4.0;
assert(isClose(b, c, 0.0, 1e-15));

assert(ceqrel(log10(complex(-100.0L, 0.0L)), complex(2.0L, PI / LN10)) >= real.mant_dig - 1);
assert(ceqrel(log10(complex(-100.0L, -0.0L)), complex(2.0L, -PI / LN10)) >= real.mant_dig - 1);

```
 
  pure nothrow @nogc @safe Complex!T **pow**(T, Int)(Complex!T x, const Int n)  
 Constraints: if (isIntegral!Int);   
  
pure nothrow @nogc @trusted Complex!T **pow**(T)(Complex!T x, const T n);   
  
pure nothrow @nogc @trusted Complex!T **pow**(T)(Complex!T x, Complex!T y);   
  
pure nothrow @nogc @trusted Complex!T **pow**(T)(const T x, Complex!T n);  
Calculates xn. The branch cut is on the negative axis. 



Parameters:


|  |  |
| --- | --- |
| Complex!T `x` | base |
| Int `n` | exponent |


 
Returns:

`x` raised to the power of `n`

 
Examples:


```
import std.math : isClose;

auto a = complex(1.0, 2.0);
writeln(pow(a, 2)); // a * a
writeln(pow(a, 3)); // a * a * a
writeln(pow(a, -2)); // 1.0 / (a * a)
assert(isClose(pow(a, -3), 1.0 / (a * a * a)));

auto b = complex(2.0);
assert(ceqrel(pow(b, 3), exp(3 * log(b))) >= double.mant_dig - 1);

```
 
 
Examples:


```
import std.math : isClose;
writeln(pow(complex(0.0), 2.0)); // complex(0.0)
writeln(pow(complex(5.0), 2.0)); // complex(25.0)

auto a = pow(complex(-1.0, 0.0), 0.5);
assert(isClose(a, complex(0.0, +1.0), 0.0, 1e-16));

auto b = pow(complex(-1.0, -0.0), 0.5);
assert(isClose(b, complex(0.0, -1.0), 0.0, 1e-16));

```
 
 
Examples:


```
import std.math : isClose, exp, PI;
auto a = complex(0.0);
auto b = complex(2.0);
writeln(pow(a, b)); // complex(0.0)

auto c = complex(0.0L, 1.0L);
assert(isClose(pow(c, c), exp((-PI) / 2)));

```
 
 
Examples:


```
import std.math : isClose;
writeln(pow(2.0, complex(0.0))); // complex(1.0)
writeln(pow(2.0, complex(5.0))); // complex(32.0)

auto a = pow(-2.0, complex(-1.0));
assert(isClose(a, complex(-0.5), 0.0, 1e-16));

auto b = pow(-0.5, complex(-1.0));
assert(isClose(b, complex(-2.0), 0.0, 1e-15));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_complex.html>

std.container.dlist
===================

 This module implements a generic doubly-linked list container. It can be used as a queue, dequeue or stack. 


This module is a submodule of [`std.container`](std_container). 

 
Source
 [std/container/dlist.d](https://github.com/dlang/phobos/blob/master/std/container/dlist.d) 
 
License:
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE\_1\_0.txt or copy at [boost.org/LICENSE\_1\_0.txt](http://boost.org/LICENSE_1_0.txt)). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.container : DList;

auto s = DList!int(1, 2, 3);
assert(equal(s[], [1, 2, 3]));

s.removeFront();
assert(equal(s[], [2, 3]));
s.removeBack();
assert(equal(s[], [2]));

s.insertFront([4, 5]);
assert(equal(s[], [4, 5, 2]));
s.insertBack([6, 7]);
assert(equal(s[], [4, 5, 2, 6, 7]));

// If you want to apply range operations, simply slice it.
import std.algorithm.searching : countUntil;
import std.range : popFrontN, popBackN, walkLength;

auto sl = DList!int([1, 2, 3, 4, 5]);
writeln(countUntil(sl[], 2)); // 1

auto r = sl[];
popFrontN(r, 2);
popBackN(r, 2);
assert(r.equal([3]));
writeln(walkLength(r)); // 1

// DList.Range can be used to remove elements from the list it spans
auto nl = DList!int([1, 2, 3, 4, 5]);
for (auto rn = nl[]; !rn.empty;)
    if (rn.front % 2 == 0)
        nl.popFirstOf(rn);
    else
        rn.popFront();
assert(equal(nl[], [1, 3, 5]));
auto rs = nl[];
rs.popFront();
nl.remove(rs);
assert(equal(nl[], [1]));

```
 
 
struct **DList**(T);  
Implements a doubly-linked list. 


`DList` uses reference semantics.

 
this(U)(U[] values...)  
 Constraints: if (isImplicitlyConvertible!(U, T)); 
 
Constructor taking a number of nodes

  this(Stuff)(Stuff stuff)  
 Constraints: if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T)); 
 
Constructor taking an [input range](std_range_primitives#isInputRange)

  const bool **opEquals**()(ref const DList rhs)  
 Constraints: if (is(typeof(front == front))); 
 
Comparison for equality. 



Complexity
 Ο(`min(n, n1)`) where `n1` is the number of elements in `rhs`.
  struct **Range**;  
Defines the container's primary range, which embodies a bidirectional range.

  const nothrow @property bool **empty**();  
Property returning `true` if and only if the container has no elements. 



Complexity
 Ο(`1`)

  void **clear**();  
Removes all contents from the `DList`. 



Postcondition
 `empty` 
 
Complexity
 Ο(`1`)

  @property DList **dup**();  
Duplicates the container. The elements themselves are not transitively duplicated. 



Complexity
 Ο(`n`).
  Range **opSlice**();  
Returns a range that iterates over all elements of the container, in forward order. 



Complexity
 Ο(`1`)

  inout @property ref inout(T) **front**();  
Forward to `opSlice().front`. 



Complexity
 Ο(`1`)

  inout @property ref inout(T) **back**();  
Forward to `opSlice().back`. 



Complexity
 Ο(`1`)

  DList **opBinary**(string op, Stuff)(Stuff rhs)  
 Constraints: if (op == "~" && is(typeof(insertBack(rhs)))); 
 
Returns a new `DList` that's the concatenation of `this` and its argument `rhs`.

  DList **opBinaryRight**(string op, Stuff)(Stuff lhs)  
 Constraints: if (op == "~" && is(typeof(insertFront(lhs)))); 
 
Returns a new `DList` that's the concatenation of the argument `lhs` and `this`.

  DList **opOpAssign**(string op, Stuff)(Stuff rhs)  
 Constraints: if (op == "~" && is(typeof(insertBack(rhs)))); 
 
Appends the contents of the argument `rhs` into `this`.

  size\_t **insertFront**(Stuff)(Stuff stuff);   
  
size\_t **insertBack**(Stuff)(Stuff stuff);   
  
alias **insert** = insertBack;   
  
alias **stableInsert** = insert;   
  
alias **stableInsertFront** = insertFront;   
  
alias **stableInsertBack** = insertBack;  
Inserts `stuff` to the front/back of the container. `stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Returns:
The number of elements inserted 
 
Complexity
 Ο(`log(n)`)

  size\_t **insertBefore**(Stuff)(Range r, Stuff stuff);   
  
alias **stableInsertBefore** = insertBefore;   
  
size\_t **insertAfter**(Stuff)(Range r, Stuff stuff);   
  
alias **stableInsertAfter** = insertAfter;  
Inserts `stuff` after range `r`, which must be a non-empty range previously extracted from this container. 


`stuff` can be a value convertible to `T` or a range of objects convertible to `T`. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 

 
Returns:
The number of values inserted. 
 
Complexity
 Ο(`k + m`), where `k` is the number of elements in `r` and `m` is the length of `stuff`.
  T **removeAny**();   
  
alias **stableRemoveAny** = removeAny;  
Picks one value in an unspecified position in the container, removes it from the container, and returns it. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Precondition
 `!empty` 
 
Returns:
The element removed. 
 
Complexity
 Ο(`1`).
  void **removeFront**();   
  
alias **stableRemoveFront** = removeFront;   
  
void **removeBack**();   
  
alias **stableRemoveBack** = removeBack;  
Removes the value at the front/back of the container. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Precondition
 `!empty` 
 
Complexity
 Ο(`1`).
  size\_t **removeFront**(size\_t howMany);   
  
alias **stableRemoveFront** = removeFront;   
  
size\_t **removeBack**(size\_t howMany);   
  
alias **stableRemoveBack** = removeBack;  
Removes `howMany` values at the front or back of the container. Unlike the unparameterized versions above, these functions do not throw if they could not remove `howMany` elements. Instead, if `howMany > n`, all elements are removed. The returned value is the effective number of elements removed. The stable version behaves the same, but guarantees that ranges iterating over the container are never invalidated. 



Returns:
The number of elements removed 
 
Complexity
 Ο(`howMany`).
  Range **remove**(Range r);   
  
Range **linearRemove**(Range r);   
  
alias **stableRemove** = remove;  
Removes all elements belonging to `r`, which must be a range obtained originally from this container. 



Returns:
A range spanning the remaining elements in the container that initially were right after `r`. 
 
Complexity
 Ο(`1`)

  void **popFirstOf**(ref Range r);  
Removes first element of `r`, wich must be a range obtained originally from this container, from both DList instance and range `r`. 



Compexity
 Ο(`1`)

  void **popLastOf**(ref Range r);  
Removes last element of `r`, wich must be a range obtained originally from this container, from both DList instance and range `r`. 



Compexity
 Ο(`1`)

  Range **linearRemove**(Take!Range r);   
  
alias **stableLinearRemove** = linearRemove;  
`linearRemove` functions as `remove`, but also accepts ranges that are result the of a `take` operation. This is a convenient way to remove a fixed amount of elements from the range. 



Complexity
 Ο(`r.walkLength`)

  bool **linearRemoveElement**(T value);  
Removes the first occurence of an element from the list in linear time. 



Returns:
True if the element existed and was successfully removed, false otherwise. 
 
Parameters:


|  |  |
| --- | --- |
| T `value` | value of the node to be removed |


 
Complexity
 Ο(`n`)

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_container_dlist.html>

std.bigint
==========

 Arbitrary-precision ('bignum') arithmetic. 


Performance is optimized for numbers below ~1000 decimal digits. For X86 machines, highly optimised assembly routines are used.   
  
 The following algorithms are currently implemented: * Karatsuba multiplication
* Squaring is optimized independently of multiplication
* Divide-and-conquer division
* Binary exponentiation

   
  
 For very large numbers, consider using the [GMP library](http://gmplib.org) instead. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Don Clugston 
 
Source
 [std/bigint.d](https://github.com/dlang/phobos/blob/master/std/bigint.d)

 
struct **BigInt**;  
A struct representing an arbitrary precision integer. 


All arithmetic operations are supported, except unsigned shift right (`>>>`). Bitwise operations (`|`, `&`, `^`, `~`) are supported, and behave as if BigInt was an infinite length 2's complement number.   
  
 BigInt implements value semantics using copy-on-write. This means that assignment is cheap, but operations such as x++ will cause heap allocation. (But note that for most bigint operations, heap allocation is inevitable anyway.)

 
Examples:


```
BigInt a = "9588669891916142";
BigInt b = "7452469135154800";
auto c = a * b;
writeln(c); // BigInt("71459266416693160362545788781600")
auto d = b * a;
writeln(d); // BigInt("71459266416693160362545788781600")
writeln(d); // c
d = c * BigInt("794628672112");
writeln(d); // BigInt("56783581982794522489042432639320434378739200")
auto e = c + d;
writeln(e); // BigInt("56783581982865981755459125799682980167520800")
auto f = d + c;
writeln(f); // e
auto g = f - c;
writeln(g); // d
g = f - d;
writeln(g); // c
e = 12345678;
g = c + e;
auto h = g / b;
auto i = g % b;
writeln(h); // a
writeln(i); // e
BigInt j = "-0x9A56_57f4_7B83_AB78";
BigInt k = j;
j ^^= 11;
writeln(k^^11); // j

```
 
 
this(Range)(Range s)  
 Constraints: if (isBidirectionalRange!Range && isSomeChar!(ElementType!Range) && !isInfinite!Range && !isNarrowString!Range);   
  
pure this(Range)(Range s)  
 Constraints: if (isNarrowString!Range); 
 
Construct a `BigInt` from a decimal or hexadecimal string. The number must be in the form of a decimal or hex literal. It may have a leading `+` or `-` sign, followed by `0x` or `0X` if hexadecimal. Underscores are permitted in any location after the `0x` and/or the sign of the number. 



Parameters:


|  |  |
| --- | --- |
| Range `s` | a finite bidirectional range of any character type |


 
Throws:

[`std.conv.ConvException`](std_conv#ConvException) if the string doesn't represent a valid number
  this(Range)(bool isNegative, Range magnitude)  
 Constraints: if (isInputRange!Range && isUnsigned!(ElementType!Range) && (hasLength!Range || isForwardRange!Range) && !isInfinite!Range); 
 
Construct a `BigInt` from a sign and a magnitude. 


The magnitude is an [input range](std_range_primitives#isInputRange) of unsigned integers that satisfies either [`std.range.primitives.hasLength`](std_range_primitives#hasLength) or [`std.range.primitives.isForwardRange`](std_range_primitives#isForwardRange). The first (leftmost) element of the magnitude is considered the most significant. 

 
Parameters:


|  |  |
| --- | --- |
| bool `isNegative` | true for negative, false for non-negative (ignored when magnitude is zero) |
| Range `magnitude` | a finite range of unsigned integers |


 
Examples:


```
ubyte[] magnitude = [1, 2, 3, 4, 5, 6];
auto b1 = BigInt(false, magnitude);
writeln(cast(long)b1); // 0x01_02_03_04_05_06L
auto b2 = BigInt(true, magnitude);
writeln(cast(long)b2); // -0x01_02_03_04_05_06L

```
 
  pure nothrow @safe this(T)(T x)  
 Constraints: if (isIntegral!T); 
 
Construct a `BigInt` from a built-in integral type.



Examples:


```
ulong data = 1_000_000_000_000;
auto bigData = BigInt(data);
writeln(bigData); // BigInt("1_000_000_000_000")

```
 
  pure nothrow @safe this(T)(T x)  
 Constraints: if (is(immutable(T) == immutable(BigInt))); 
 
Construct a `BigInt` from another `BigInt`.



Examples:


```
const(BigInt) b1 = BigInt("1_234_567_890");
BigInt b2 = BigInt(b1);
writeln(b2); // BigInt("1_234_567_890")

```
 
  pure nothrow @safe BigInt **opAssign**(T)(T x)  
 Constraints: if (isIntegral!T); 
 
Assignment from built-in integer types.



Examples:


```
auto b = BigInt("123");
b = 456;
writeln(b); // BigInt("456")

```
 
  pure @nogc @safe BigInt **opAssign**(T : BigInt)(T x);  
Assignment from another BigInt.



Examples:


```
auto b1 = BigInt("123");
auto b2 = BigInt("456");
b2 = b1;
writeln(b2); // BigInt("123")

```
 
  pure nothrow @safe BigInt **opOpAssign**(string op, T)(T y)  
 Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "/" || op == "%" || op == ">>" || op == "<<" || op == "^^" || op == "|" || op == "&" || op == "^") && isIntegral!T); 
 
Implements assignment operators from built-in integers of the form `BigInt op= integer`.



Examples:


```
auto b = BigInt("1_000_000_000");

b += 12345;
writeln(b); // BigInt("1_000_012_345")

b /= 5;
writeln(b); // BigInt("200_002_469")

```
 
  pure nothrow @safe BigInt **opOpAssign**(string op, T)(T y)  
 Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt)); 
 
Implements assignment operators of the form `BigInt op= BigInt`.



Examples:


```
auto x = BigInt("123");
auto y = BigInt("321");
x += y;
writeln(x); // BigInt("444")

```
 
  const pure nothrow @safe BigInt **opBinary**(string op, T)(T y)  
 Constraints: if ((op == "+" || op == "\*" || op == "-" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt)); 
 
Implements binary operators between `BigInt`s.



Examples:


```
auto x = BigInt("123");
auto y = BigInt("456");
BigInt z = x * y;
writeln(z); // BigInt("56088")

```
 
  const pure nothrow @safe BigInt **opBinary**(string op, T)(T y)  
 Constraints: if ((op == "+" || op == "\*" || op == "-" || op == "/" || op == "|" || op == "&" || op == "^" || op == ">>" || op == "<<" || op == "^^") && isIntegral!T); 
 
Implements binary operators between `BigInt`'s and built-in integers.



Examples:


```
auto x = BigInt("123");
x *= 300;
writeln(x); // BigInt("36900")

```
 
  const pure nothrow @safe auto **opBinary**(string op, T)(T y)  
 Constraints: if (op == "%" && isIntegral!T); 
 
Implements a narrowing remainder operation with built-in integer types. 


This binary operator returns a narrower, built-in integer type where applicable, according to the following table.   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| `BigInt` | `%` | `uint` | → | `long` |
| `BigInt` | `%` | `long` | → | `long` |
| `BigInt` | `%` | `ulong` | → | `BigInt` |
| `BigInt` | `%` | other type | → | `int` |



 
Examples:


```
auto  x  = BigInt("1_000_000_500");
long  l  = 1_000_000L;
ulong ul = 2_000_000UL;
int   i  = 500_000;
short s  = 30_000;

assert(is(typeof(x % l)  == long)   && x % l  == 500L);
assert(is(typeof(x % ul) == BigInt) && x % ul == BigInt(500));
assert(is(typeof(x % i)  == int)    && x % i  == 500);
assert(is(typeof(x % s)  == int)    && x % s  == 10500);

```
 
  const pure nothrow @safe BigInt **opBinaryRight**(string op, T)(T y)  
 Constraints: if ((op == "+" || op == "\*" || op == "|" || op == "&" || op == "^") && isIntegral!T);   
  
const pure nothrow @safe BigInt **opBinaryRight**(string op, T)(T y)  
 Constraints: if (op == "-" && isIntegral!T);   
  
const pure nothrow @safe T **opBinaryRight**(string op, T)(T x)  
 Constraints: if ((op == "%" || op == "/") && isIntegral!T); 
 
Implements operators with built-in integers on the left-hand side and `BigInt` on the right-hand side.



Examples:


```
auto x = BigInt("100");
BigInt y = 123 + x;
writeln(y); // BigInt("223")

BigInt z = 123 - x;
writeln(z); // BigInt("23")

// Dividing a built-in integer type by BigInt always results in
// something that fits in a built-in type, so the built-in type is
// returned, not BigInt.
assert(is(typeof(1000 / x) == int));
writeln(1000 / x); // 10

```
 
  const pure nothrow @safe BigInt **opUnary**(string op)()  
 Constraints: if (op == "+" || op == "-" || op == "~");   
  
pure nothrow @safe BigInt **opUnary**(string op)()  
 Constraints: if (op == "++" || op == "--"); 
 
Implements `BigInt` unary operators.



Examples:


```
auto x = BigInt("1234");
writeln(-x); // BigInt("-1234")

++x;
writeln(x); // BigInt("1235")

```
 
  const pure @nogc @safe bool **opEquals**()(auto ref const BigInt y);   
  
const pure nothrow @nogc @safe bool **opEquals**(T)(const T y)  
 Constraints: if (isIntegral!T);   
  
const nothrow @nogc bool **opEquals**(T)(const T y)  
 Constraints: if (isFloatingPoint!T); 
 
Implements `BigInt` equality test with other `BigInt`'s and built-in numeric types.



Examples:


```
// Note that when comparing a BigInt to a float or double the
// full precision of the BigInt is always considered, unlike
// when comparing an int to a float or a long to a double.
assert(BigInt(123456789) != cast(float) 123456789);

```
 
  const pure nothrow @nogc @safe T **opCast**(T : bool)();  
Implements casting to `bool`.



Examples:


```
// Non-zero values are regarded as true
auto x = BigInt("1");
auto y = BigInt("10");
assert(x);
assert(y);

// Zero value is regarded as false
auto z = BigInt("0");
assert(!z);

```
 
  const pure @safe T **opCast**(T : ulong)();  
Implements casting to integer types. 



Throws:

[`std.conv.ConvOverflowException`](std_conv#ConvOverflowException) if the number exceeds the target type's range.
 
Examples:


```
import std.conv : to, ConvOverflowException;
import std.exception : assertThrown;

writeln(BigInt("0").to!int); // 0

writeln(BigInt("0").to!ubyte); // 0
writeln(BigInt("255").to!ubyte); // 255
assertThrown!ConvOverflowException(BigInt("256").to!ubyte);
assertThrown!ConvOverflowException(BigInt("-1").to!ubyte);

```
 
  const nothrow @nogc @safe T **opCast**(T)()  
 Constraints: if (isFloatingPoint!T); 
 
Implements casting to floating point types.



Examples:


```
writeln(0x1.abcd_e8p+124f); // cast(float)BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000")
// cast(double)BigInt("0x1abc_def1_2345_6000_0000_0000_0000_0000")
writeln(0x1.abcd_ef12_3456p+124);
// cast(real)BigInt("0x1abc_def1_2345_6000_0000_0000_0000_0000")
writeln(0x1.abcd_ef12_3456p+124L);

writeln(-0x1.3456_78p+108f); // cast(float)BigInt("-0x1345_6780_0000_0000_0000_0000_0000")
// cast(double)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000")
writeln(-0x1.3456_78ab_cdefp+108);
// cast(real)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000")
writeln(-0x1.3456_78ab_cdefp+108L);

```
 
 
Examples:
Rounding when casting to floating point 
```
// BigInts whose values cannot be exactly represented as float/double/real
// are rounded when cast to float/double/real. When cast to float or
// double or 64-bit real the rounding is strictly defined. When cast
// to extended-precision real the rounding rules vary by environment.

// BigInts that fall somewhere between two non-infinite floats/doubles
// are rounded to the closer value when cast to float/double.
writeln(0x1.aaa_aaep+28f); // cast(float)BigInt(0x1aaa_aae7)
writeln(0x1.aaa_ab0p+28f); // cast(float)BigInt(0x1aaa_aaff)
writeln(-0x1.aaaaaep+28f); // cast(float)BigInt(-0x1aaa_aae7)
writeln(-0x1.aaaab0p+28f); // cast(float)BigInt(-0x1aaa_aaff)

writeln(0x1.aaa_aaaa_aaaa_aa00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aa77)
writeln(0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aaff)
writeln(-0x1.aaa_aaaa_aaaa_aa00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa77)
writeln(-0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aaff)

// BigInts that fall exactly between two non-infinite floats/doubles
// are rounded away from zero when cast to float/double. (Note that
// in most environments this is NOT the same rounding rule rule used
// when casting int/long to float/double.)
writeln(0x1.aaa_ab0p+28f); // cast(float)BigInt(0x1aaa_aaf0)
writeln(-0x1.aaaab0p+28f); // cast(float)BigInt(-0x1aaa_aaf0)

writeln(0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(0x1aaa_aaaa_aaaa_aa80)
writeln(-0x1.aaa_aaaa_aaaa_ab00p+60); // cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa80)

// BigInts that are bounded on one side by the largest positive or
// most negative finite float/double and on the other side by infinity
// or -infinity are rounded as if in place of infinity was the value
// `2^^(T.max_exp)` when cast to float/double.
// cast(float)BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999")
writeln(float.infinity);
// cast(float)BigInt("-999_999_999_999_999_999_999_999_999_999_999_999_999")
writeln(-float.infinity);

assert(double.infinity > cast(double) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999"));
assert(real.infinity > cast(real) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999"));

```
 
  const pure nothrow @nogc T **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(BigInt))); 
 
Implements casting to/from qualified `BigInt`'s. 



Warning
 Casting to/from `const` or `immutable` may break type system guarantees. Use with care.
 
Examples:


```
const(BigInt) x = BigInt("123");
BigInt y = cast() x;    // cast away const
writeln(y); // x

```
 
  const pure nothrow @nogc @safe int **opCmp**(ref const BigInt y);   
  
const pure nothrow @nogc @safe int **opCmp**(T)(const T y)  
 Constraints: if (isIntegral!T);   
  
const nothrow @nogc @safe int **opCmp**(T)(const T y)  
 Constraints: if (isFloatingPoint!T);   
  
const pure nothrow @nogc @safe int **opCmp**(T : BigInt)(const T y);  
Implements 3-way comparisons of `BigInt` with `BigInt` or `BigInt` with built-in numeric types.



Examples:


```
auto x = BigInt("100");
auto y = BigInt("10");
int z = 50;
const int w = 200;

assert(y < x);
assert(x > z);
assert(z > y);
assert(x < w);

```
 
 
Examples:


```
auto x = BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000");
BigInt y = x - 1;
BigInt z = x + 1;

double d = 0x1.abcde8p124;
assert(y < d);
assert(z > d);
assert(x >= d && x <= d);

// Note that when comparing a BigInt to a float or double the
// full precision of the BigInt is always considered, unlike
// when comparing an int to a float or a long to a double.
assert(BigInt(123456789) < cast(float) 123456789);

```
 
  const pure nothrow @nogc @safe long **toLong**();  

Returns:
The value of this `BigInt` as a `long`, or `long.max`/`long.min` if outside the representable range.
 
Examples:


```
auto b = BigInt("12345");
long l = b.toLong();
writeln(l); // 12345

```
 
  const pure nothrow @nogc @safe int **toInt**();  

Returns:
The value of this `BigInt` as an `int`, or `int.max`/`int.min` if outside the representable range.
 
Examples:


```
auto big = BigInt("5_000_000");
auto i = big.toInt();
writeln(i); // 5_000_000

// Numbers that are too big to fit into an int will be clamped to int.max.
auto tooBig = BigInt("5_000_000_000");
i = tooBig.toInt();
writeln(i); // int.max

```
 
  const pure nothrow @nogc @property @safe size\_t **uintLength**();  
Number of significant `uint`s which are used in storing this number. The absolute value of this `BigInt` is always < 232\*uintLength

  const pure nothrow @nogc @property @safe size\_t **ulongLength**();  
Number of significant `ulong`s which are used in storing this number. The absolute value of this `BigInt` is always < 264\*ulongLength

  const void **toString**(Writer)(ref scope Writer sink, string formatString);   
  
const void **toString**(Writer)(ref scope Writer sink, ref scope const FormatSpec!char f);   
  
const void **toString**(scope void delegate(const(char)[]) sink, string formatString);   
  
const void **toString**(scope void delegate(const(char)[]) sink, ref scope const FormatSpec!char f);  
Convert the `BigInt` to `string`, passing it to the given sink. 



Parameters:


|  |  |
| --- | --- |
| Writer `sink` | An OutputRange for accepting possibly piecewise segments of the formatted string. |
| string `formatString` | A format string specifying the output format. 

 Available output formats:| "d" |  Decimal |
| "o" |  Octal |
| "x" |  Hexadecimal, lower case |
| "X" |  Hexadecimal, upper case |
| "s" |  Default formatting (same as "d")  |
| null | Default formatting (same as "d")  |

 |


 
Examples:

`toString` is rarely directly invoked; the usual way of using it is via [`std.format.format`](std_format#format): 
```
import std.format : format;

auto x = BigInt("1_000_000");
x *= 12345;

writeln(format("%d", x)); // "12345000000"
writeln(format("%x", x)); // "2_dfd1c040"
writeln(format("%X", x)); // "2_DFD1C040"
writeln(format("%o", x)); // "133764340100"

```
 
  const pure nothrow @nogc @safe size\_t **toHash**();  

Returns:
A unique hash of the `BigInt`'s value suitable for use in a hash table.
 
Examples:

`toHash` is rarely directly invoked; it is implicitly used when BigInt is used as the key of an associative array. 
```
string[BigInt] aa;
aa[BigInt(123)] = "abc";
aa[BigInt(456)] = "def";

writeln(aa[BigInt(123)]); // "abc"
writeln(aa[BigInt(456)]); // "def"

```
 
  const T **getDigit**(T = ulong)(size\_t n)  
 Constraints: if (is(T == ulong) || is(T == uint)); 
 
Gets the nth number in the underlying representation that makes up the whole `BigInt`. 



Parameters:


|  |  |
| --- | --- |
| T | the type to view the underlying representation as |
| size\_t `n` | The nth number to retrieve. Must be less than [`ulongLength`](#ulongLength) or [`uintLength`](#uintLength) with respect to `T`. |


 
Returns:
The nth `ulong` in the representation of this `BigInt`.
 
Examples:


```
auto a = BigInt("1000");
writeln(a.ulongLength()); // 1
writeln(a.getDigit(0)); // 1000

writeln(a.uintLength()); // 1
writeln(a.getDigit!uint(0)); // 1000

auto b = BigInt("2_000_000_000_000_000_000_000_000_000");
writeln(b.ulongLength()); // 2
writeln(b.getDigit(0)); // 4584946418820579328
writeln(b.getDigit(1)); // 108420217

writeln(b.uintLength()); // 3
writeln(b.getDigit!uint(0)); // 3489660928
writeln(b.getDigit!uint(1)); // 1067516025
writeln(b.getDigit!uint(2)); // 108420217

```
 
    pure nothrow @safe string **toDecimalString**(const(BigInt) x);  

Parameters:


|  |  |
| --- | --- |
| const(BigInt) `x` | The `BigInt` to convert to a decimal `string`. |


 
Returns:
A `string` that represents the `BigInt` as a decimal number.
 
Examples:


```
auto x = BigInt("123");
x *= 1000;
x += 456;

auto xstr = x.toDecimalString();
writeln(xstr); // "123456"

```
 
  @safe string **toHex**(const(BigInt) x);  

Parameters:


|  |  |
| --- | --- |
| const(BigInt) `x` | The `BigInt` to convert to a hexadecimal `string`. |


 
Returns:
A `string` that represents the `BigInt` as a hexadecimal (base 16) number in upper case.
 
Examples:


```
auto x = BigInt("123");
x *= 1000;
x += 456;

auto xstr = x.toHex();
writeln(xstr); // "1E240"

```
 
  Unsigned!T **absUnsign**(T)(T x)  
 Constraints: if (isIntegral!T); 
 
Returns the absolute value of x converted to the corresponding unsigned type. 



Parameters:


|  |  |
| --- | --- |
| T `x` | The integral value to return the absolute value of. |


 
Returns:
The absolute value of x.
 
Examples:


```
writeln((-1).absUnsign); // 1
writeln(1.absUnsign); // 1

```
 
  pure nothrow @safe void **divMod**(const BigInt dividend, const BigInt divisor, out BigInt quotient, out BigInt remainder);  
Finds the quotient and remainder for the given dividend and divisor in one operation. 



Parameters:


|  |  |
| --- | --- |
| BigInt `dividend` | the [`BigInt`](#BigInt) to divide |
| BigInt `divisor` | the [`BigInt`](#BigInt) to divide the dividend by |
| BigInt `quotient` | is set to the result of the division |
| BigInt `remainder` | is set to the remainder of the division |


 
Examples:


```
auto a = BigInt(123);
auto b = BigInt(25);
BigInt q, r;

divMod(a, b, q, r);

writeln(q); // 4
writeln(r); // 23
writeln(q * b + r); // a

```
 
  pure nothrow @safe BigInt **powmod**(BigInt base, BigInt exponent, BigInt modulus);  
Fast power modulus calculation for [`BigInt`](#BigInt) operands. 



Parameters:


|  |  |
| --- | --- |
| BigInt `base` | the [`BigInt`](#BigInt) is basic operands. |
| BigInt `exponent` | the [`BigInt`](#BigInt) is power exponent of base. |
| BigInt `modulus` | the [`BigInt`](#BigInt) is modules to be modular of base ^ exponent. |


 
Returns:
The power modulus value of (base ^ exponent) % modulus.
 
Examples:
for powmod 
```
BigInt base = BigInt("123456789012345678901234567890");
BigInt exponent = BigInt("1234567890123456789012345678901234567");
BigInt modulus = BigInt("1234567");

BigInt result = powmod(base, exponent, modulus);
writeln(result); // 359079

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_bigint.html>

std.datetime.timezone
=====================

  

| Category | Functions |
| --- | --- |
| Time zones | [`TimeZone`](#TimeZone) [`UTC`](#UTC) [`LocalTime`](#LocalTime) [`PosixTimeZone`](#PosixTimeZone) [`WindowsTimeZone`](#WindowsTimeZone) [`SimpleTimeZone`](#SimpleTimeZone) |
| Utilities | [`clearTZEnvVar`](#clearTZEnvVar) [`parseTZConversions`](#parseTZConversions) [`setTZEnvVar`](#setTZEnvVar) [`TZConversions`](#TZConversions) |

 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/datetime/timezone.d](https://github.com/dlang/phobos/blob/master/std/datetime/timezone.d)

 
abstract class **TimeZone**;  
Represents a time zone. It is used with [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime) to indicate the time zone of a [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime).

 
const nothrow @property @safe string **name**();  
The name of the time zone. Exactly how the time zone name is formatted depends on the derived class. In the case of [`PosixTimeZone`](#PosixTimeZone), it's the TZ Database name, whereas with [`WindowsTimeZone`](#WindowsTimeZone), it's the name that Windows chose to give the registry key for that time zone (typically the name that they give [`stdTime`](#stdTime) if the OS is in English). For other time zone types, what it is depends on how they're implemented. 



See Also:

[Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
 [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones)

  const nothrow @property @safe string **stdName**();  
Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST is *not* in effect (e.g. PST). It is not necessarily unique. 


However, on Windows, it may be the unabbreviated name (e.g. Pacific Standard Time). Regardless, it is not the same as name.

  const nothrow @property @safe string **dstName**();  
Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST *is* in effect (e.g. PDT). It is not necessarily unique. 


However, on Windows, it may be the unabbreviated name (e.g. Pacific Daylight Time). Regardless, it is not the same as name.

  abstract const nothrow @property @safe bool **hasDST**();  
Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST.

  abstract const nothrow @safe bool **dstInEffect**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is effect in this time zone at the given point in time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be checked for DST in this time zone. |


  abstract const nothrow @safe long **utcToTZ**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


  abstract const nothrow @safe long **tzToUTC**(long adjTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). 



Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


  const nothrow @safe Duration **utcOffsetAt**(long stdTime);  
Returns what the offset from UTC is at the given std time. It includes the DST offset in effect at that time (if any). 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. |


  protected immutable pure @safe this(string name, string stdName, string dstName);  

Parameters:


|  |  |
| --- | --- |
| string `name` | The name of the time zone. |
| string `stdName` | The abbreviation for the time zone during std time. |
| string `dstName` | The abbreviation for the time zone during DST. |


    class **LocalTime**: std.datetime.timezone.TimeZone;  
A TimeZone which represents the current local time zone on the system running your program. 


This uses the underlying C calls to adjust the time rather than using specific D code based off of system settings to calculate the time such as [`PosixTimeZone`](#PosixTimeZone) and [`WindowsTimeZone`](#WindowsTimeZone) do. That also means that it will use whatever the current time zone is on the system, even if the system's time zone changes while the program is running.

 
static pure nothrow @trusted immutable(LocalTime) **opCall**();  
[`LocalTime`](#LocalTime) is a singleton class. [`LocalTime`](#LocalTime) returns its only instance.

  const nothrow @property @safe string **name**();  
In principle, this is the name of the local time zone. However, this always returns the empty string. This is because time zones cannot be uniquely identified by the attributes given by the OS (such as the `stdName` and `dstName`), and neither Posix systems nor Windows systems provide an easy way to get the TZ Database name of the local time zone. 



See Also:

[Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
 [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones)

  const nothrow @property @trusted string **stdName**();  
Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST is *not* in effect (e.g. PST). It is not necessarily unique. 


However, on Windows, it may be the unabbreviated name (e.g. Pacific Standard Time). Regardless, it is not the same as name.   
  
 This property is overridden because the local time of the system could change while the program is running and we need to determine it dynamically rather than it being fixed like it would be with most time zones.

  const nothrow @property @trusted string **dstName**();  
Typically, the abbreviation (generally 3 or 4 letters) for the time zone when DST *is* in effect (e.g. PDT). It is not necessarily unique. 


However, on Windows, it may be the unabbreviated name (e.g. Pacific Daylight Time). Regardless, it is not the same as name.   
  
 This property is overridden because the local time of the system could change while the program is running and we need to determine it dynamically rather than it being fixed like it would be with most time zones.

  const nothrow @property @trusted bool **hasDST**();  
Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST.

  const nothrow @trusted bool **dstInEffect**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be checked for DST in this time zone. |


  const nothrow @trusted long **utcToTZ**(long stdTime);  
Returns hnsecs in the local time zone using the standard C function calls on Posix systems and the standard Windows system calls on Windows systems to adjust the time to the appropriate time zone from std time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


 
See Also:
`TimeZone.utcToTZ`
  const nothrow @trusted long **tzToUTC**(long adjTime);  
Returns std time using the standard C function calls on Posix systems and the standard Windows system calls on Windows systems to adjust the time to UTC from the appropriate time zone. 



See Also:

`TimeZone.tzToUTC` 
 
Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


    class **UTC**: std.datetime.timezone.TimeZone;  
A [`TimeZone`](#TimeZone) which represents UTC.

 
static pure nothrow @safe immutable(UTC) **opCall**();  
`UTC` is a singleton class. `UTC` returns its only instance.

  const nothrow @property @safe bool **hasDST**();  
Always returns false.

  const nothrow @safe bool **dstInEffect**(long stdTime);  
Always returns false.

  const nothrow @safe long **utcToTZ**(long stdTime);  
Returns the given hnsecs without changing them at all. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


 
See Also:
`TimeZone.utcToTZ`
  const nothrow @safe long **tzToUTC**(long adjTime);  
Returns the given hnsecs without changing them at all. 



See Also:

`TimeZone.tzToUTC` 
 
Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


  const nothrow @safe Duration **utcOffsetAt**(long stdTime);  
Returns a [`core.time.Duration`](core_time#Duration) of 0. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. |


    class **SimpleTimeZone**: std.datetime.timezone.TimeZone;  
Represents a time zone with an offset (in minutes, west is negative) from UTC but no DST. 


It's primarily used as the time zone in the result of [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime)'s `fromISOString`, `fromISOExtString`, and `fromSimpleString`.   
  
 `name` and `dstName` are always the empty string since this time zone has no DST, and while it may be meant to represent a time zone which is in the TZ Database, obviously it's not likely to be following the exact rules of any of the time zones in the TZ Database, so it makes no sense to set it.

 
const nothrow @property @safe bool **hasDST**();  
Always returns false.

  const nothrow @safe bool **dstInEffect**(long stdTime);  
Always returns false.

  const nothrow @safe long **utcToTZ**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


  const nothrow @safe long **tzToUTC**(long adjTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). 



Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


  const nothrow @safe Duration **utcOffsetAt**(long stdTime);  
Returns utcOffset as a [`core.time.Duration`](core_time#Duration). 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time for which to get the offset from UTC for this time zone. |


  immutable pure @safe this(Duration utcOffset, string stdName = "");  

Parameters:


|  |  |
| --- | --- |
| Duration `utcOffset` | This time zone's offset from UTC with west of UTC being negative (it is added to UTC to get the adjusted time). |
| string `stdName` | The `stdName` for this time zone. |


  const pure nothrow @property @safe Duration **utcOffset**();  
The amount of time the offset from UTC is (negative is west of UTC, positive is east).

    class **PosixTimeZone**: std.datetime.timezone.TimeZone;  
Represents a time zone from a TZ Database time zone file. Files from the TZ Database are how Posix systems hold their time zone information. Unfortunately, Windows does not use the TZ Database. To use the TZ Database, use `PosixTimeZone` (which reads its information from the TZ Database files on disk) on Windows by providing the TZ Database files and telling `PosixTimeZone.getTimeZone` where the directory holding them is. 


To get a `PosixTimeZone`, call `PosixTimeZone.getTimeZone` (which allows specifying the location the time zone files). 

 
Note
 Unless your system's local time zone deals with leap seconds (which is highly unlikely), then the only way to get a time zone which takes leap seconds into account is to use `PosixTimeZone` with a time zone whose name starts with "right/". Those time zone files do include leap seconds, and `PosixTimeZone` will take them into account (though posix systems which use a "right/" time zone as their local time zone will *not* take leap seconds into account even though they're in the file). 
 
See Also:

[Home of the TZ Database files](http://www.iana.org/time-zones)  
 [Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
 [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones)

 
const nothrow @property @safe bool **hasDST**();  
Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST.

  const nothrow @safe bool **dstInEffect**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be checked for DST in this time zone. |


  const nothrow @safe long **utcToTZ**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


  const nothrow @safe long **tzToUTC**(long adjTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). 



Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


  enum string **defaultTZDatabaseDir**;  
The default directory where the TZ Database files are stored. It's empty for Windows, since Windows doesn't have them. You can also use the TZDatabaseDir version to pass an arbitrary path at compile-time, rather than hard-coding it here. Android concatenates all time zone data into a single file called tzdata and stores it in the directory below.

  static @trusted immutable(PosixTimeZone) **getTimeZone**(string name, string tzDatabaseDir = defaultTZDatabaseDir);  
Returns a [`TimeZone`](#TimeZone) with the give name per the TZ Database. The time zone information is fetched from the TZ Database time zone files in the given directory. 



See Also:

[Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
 [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 
 
Parameters:


|  |  |
| --- | --- |
| string `name` | The TZ Database name of the desired time zone |
| string `tzDatabaseDir` | The directory where the TZ Database files are located. Because these files are not located on Windows systems, provide them and give their location here to use [`PosixTimeZone`](#PosixTimeZone)s. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given time zone could not be found or `FileException` if the TZ Database file could not be opened.
 
Examples:


```
version (Posix)
{
    auto tz = PosixTimeZone.getTimeZone("America/Los_Angeles");

    writeln(tz.name); // "America/Los_Angeles"
    writeln(tz.stdName); // "PST"
    writeln(tz.dstName); // "PDT"
}

```
 
  static @safe string[] **getInstalledTZNames**(string subName = "", string tzDatabaseDir = defaultTZDatabaseDir);  
Returns a list of the names of the time zones installed on the system. 


Providing a sub-name narrows down the list of time zones (which can number in the thousands). For example, passing in "America" as the sub-name returns only the time zones which begin with "America". 

 
Parameters:


|  |  |
| --- | --- |
| string `subName` | The first part of the desired time zones. |
| string `tzDatabaseDir` | The directory where the TZ Database files are located. |


 
Throws:

`FileException` if it fails to read from disk.
    class **WindowsTimeZone**: std.datetime.timezone.TimeZone;  
This class is Windows-Only. 


Represents a time zone from the Windows registry. Unfortunately, Windows does not use the TZ Database. To use the TZ Database, use [`PosixTimeZone`](#PosixTimeZone) (which reads its information from the TZ Database files on disk) on Windows by providing the TZ Database files and telling `PosixTimeZone.getTimeZone` where the directory holding them is.   
  
 The TZ Database files and Windows' time zone information frequently do not match. Windows has many errors with regards to when DST switches occur (especially for historical dates). Also, the TZ Database files include far more time zones than Windows does. So, for accurate time zone information, use the TZ Database files with [`PosixTimeZone`](#PosixTimeZone) rather than `WindowsTimeZone`. However, because `WindowsTimeZone` uses Windows system calls to deal with the time, it's far more likely to match the behavior of other Windows programs. Be aware of the differences when selecting a method.   
  
 `WindowsTimeZone` does not exist on Posix systems.   
  
 To get a `WindowsTimeZone`, call `WindowsTimeZone.getTimeZone`. 

 
See Also:
[Home of the TZ Database files](http://www.iana.org/time-zones)
 
const nothrow @property @safe bool **hasDST**();  
Whether this time zone has Daylight Savings Time at any point in time. Note that for some time zone types it may not have DST for current dates but will still return true for `hasDST` because the time zone did at some point have DST.

  const nothrow @safe bool **dstInEffect**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and returns whether DST is in effect in this time zone at the given point in time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be checked for DST in this time zone. |


  const nothrow @safe long **utcToTZ**(long stdTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in UTC time (i.e. std time) and converts it to this time zone's time. 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The UTC time that needs to be adjusted to this time zone's time. |


  const nothrow @safe long **tzToUTC**(long adjTime);  
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D. in this time zone's time and converts it to UTC (i.e. std time). 



Parameters:


|  |  |
| --- | --- |
| long `adjTime` | The time in this time zone that needs to be adjusted to UTC time. |


  static @safe immutable(WindowsTimeZone) **getTimeZone**(string name);  
Returns a [`TimeZone`](#TimeZone) with the given name per the Windows time zone names. The time zone information is fetched from the Windows registry. 



See Also:

[Wikipedia entry on TZ Database](http://en.wikipedia.org/wiki/Tz_database)  
 [List of Time Zones](http://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 
 
Parameters:


|  |  |
| --- | --- |
| string `name` | The TZ Database name of the desired time zone. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given time zone could not be found. 
 
Example


```
auto tz = WindowsTimeZone.getTimeZone("Pacific Standard Time");

```
  static @safe string[] **getInstalledTZNames**();  
Returns a list of the names of the time zones installed on the system. The list returned by WindowsTimeZone contains the Windows TZ names, not the TZ Database names. However, `TimeZone.getinstalledTZNames` will return the TZ Database names which are equivalent to the Windows TZ names.

    nothrow @safe void **setTZEnvVar**(string tzDatabaseName);  
This function is Posix-Only. 


Sets the local time zone on Posix systems with the TZ Database name by setting the TZ environment variable.   
  
 Unfortunately, there is no way to do it on Windows using the TZ Database name, so this function only exists on Posix systems.

  nothrow @safe void **clearTZEnvVar**();  
This function is Posix-Only. 


Clears the TZ environment variable.

  struct **TZConversions**;   
  
pure @safe TZConversions **parseTZConversions**(string windowsZonesXMLText);  
Provides the conversions between the IANA time zone database time zone names (which POSIX systems use) and the time zone names that Windows uses. 


Windows uses a different set of time zone names than the IANA time zone database does, and how they correspond to one another changes over time (particularly when Microsoft updates Windows). [windowsZones.xml](http://unicode.org/cldr/data/common/supplemental/windowsZones.xml) provides the current conversions (which may or may not match up with what's on a particular Windows box depending on how up-to-date it is), and parseTZConversions reads in those conversions from windowsZones.xml so that a D program can use those conversions.   
  
 However, it should be noted that the time zone information on Windows is frequently less accurate than that in the IANA time zone database, and if someone really wants accurate time zone information, they should use the IANA time zone database files with [`PosixTimeZone`](#PosixTimeZone) on Windows rather than [`WindowsTimeZone`](#WindowsTimeZone), whereas [`WindowsTimeZone`](#WindowsTimeZone) makes more sense when trying to match what Windows will think the time is in a specific time zone.   
  
 Also, the IANA time zone database has a lot more time zones than Windows does. 

 
Parameters:


|  |  |
| --- | --- |
| string `windowsZonesXMLText` | The text from [windowsZones.xml](http://unicode.org/cldr/data/common/supplemental/windowsZones.xml) |


 
Throws:
 Exception if there is an error while parsing the given XML. 
```
    // Parse the conversions from a local file.
    auto text = std.file.readText("path/to/windowsZones.xml");
    auto conversions = parseTZConversions(text);

    // Alternatively, grab the XML file from the web at runtime
    // and parse it so that it's guaranteed to be up-to-date, though
    // that has the downside that the code needs to worry about the
    // site being down or unicode.org changing the URL.
    auto url = "http://unicode.org/cldr/data/common/supplemental/windowsZones.xml";
    auto conversions2 = parseTZConversions(std.net.curl.get(url));

```
 
 
string[][string] **toWindows**;  
The key is the Windows time zone name, and the value is a list of IANA TZ database names which are close (currently only ever one, but it allows for multiple in case it's ever necessary).

  string[][string] **fromWindows**;  
The key is the IANA time zone database name, and the value is a list of Windows time zone names which are close (usually only one, but it could be multiple).

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime_timezone.html>

std.digest.crc
==============

 Cyclic Redundancy Check (32-bit) implementation. 




| Category | Functions |
| --- | --- |
| Template API | [*CRC*](#CRC) [*CRC32*](#CRC32) [*CRC64ECMA*](#CRC64ECMA) [*CRC64ISO*](#CRC64ISO) |
| OOP API | [*CRC32Digest*](#CRC32Digest) [*CRC64ECMADigest*](#CRC64ECMADigest) [*CRC64ISODigest*](#CRC64ISODigest) |
| Helpers | [*crcHexString*](#crcHexString) [*crc32Of*](#crc32Of) [*crc64ECMAOf*](#crc64ECMAOf) [*crc64ISOOf*](#crc64ISOOf) |

    
  
 This module conforms to the APIs defined in `std.digest`. To understand the differences between the template and the OOP API, see [`std.digest`](std_digest).   
  
 This module publicly imports [`std.digest`](std_digest) and can be used as a stand-alone module. 

 
Note
 CRCs are usually printed with the MSB first. When using [`std.digest.toHexString`](std_digest#toHexString) the result will be in an unexpected order. Use [`std.digest.toHexString`](std_digest#toHexString)'s optional order parameter to specify decreasing order for the correct result. The [`crcHexString`](#crcHexString) alias can also be used for this purpose. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Pavel "EvilOne" Minayev, Alex Rønne Petersen, Johannes Pfau 
 
References
 [Wikipedia on CRC](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) 
 
Source
 [std/digest/crc.d](https://github.com/dlang/phobos/blob/master/std/digest/crc.d) 
 
Standards:
Implements the 'common' IEEE CRC32 variant (LSB-first order, Initial value uint.max, complement result) 
 
CTFE
 Digests do not work in CTFE
 
Examples:


```
//Template API
import std.digest.crc;

ubyte[4] hash = crc32Of("The quick brown fox jumps over the lazy dog");
writeln(crcHexString(hash)); // "414FA339"

//Feeding data
ubyte[1024] data;
CRC32 crc;
crc.put(data[]);
crc.start(); //Start again
crc.put(data[]);
hash = crc.finish();

```
 
 
Examples:


```
//OOP API
import std.digest.crc;

auto crc = new CRC32Digest();
ubyte[] hash = crc.digest("The quick brown fox jumps over the lazy dog");
assert(crcHexString(hash) == "414FA339"); //352441c2

//Feeding data
ubyte[1024] data;
crc.put(data[]);
crc.reset(); //Start again
crc.put(data[]);
hash = crc.finish();

```
 
 
alias **CRC32** = CRC!(32u, 3988292384LU).CRC;  
Template API CRC32 implementation. See `std.digest` for differences between template and OOP API.

  alias **CRC64ECMA** = CRC!(64u, 14514072000185962306LU).CRC;  
Template API CRC64-ECMA implementation. See `std.digest` for differences between template and OOP API.

  alias **CRC64ISO** = CRC!(64u, 15564440312192434176LU).CRC;  
Template API CRC64-ISO implementation. See `std.digest` for differences between template and OOP API.

  struct **CRC**(uint N, ulong P) if (N == 32 || N == 64);  
Generic Template API used for CRC32 and CRC64 implementations. 


The N parameter indicate the size of the hash in bits. The parameter P specify the polynomial to be used for reduction.   
  
 You may want to use the CRC32, CRC65ECMA and CRC64ISO aliases for convenience.   
  
 See `std.digest` for differences between template and OOP API.

 
Examples:


```
//Simple example, hashing a string using crc32Of helper function
ubyte[4] hash32 = crc32Of("abc");
//Let's get a hash string
writeln(crcHexString(hash32)); // "352441C2"
// Repeat for CRC64
ubyte[8] hash64ecma = crc64ECMAOf("abc");
writeln(crcHexString(hash64ecma)); // "2CD8094A1A277627"
ubyte[8] hash64iso = crc64ISOOf("abc");
writeln(crcHexString(hash64iso)); // "3776C42000000000"

```
 
 
Examples:


```
ubyte[1024] data;
//Using the basic API
CRC32 hash32;
CRC64ECMA hash64ecma;
CRC64ISO hash64iso;
//Initialize data here...
hash32.put(data);
ubyte[4] result32 = hash32.finish();
hash64ecma.put(data);
ubyte[8] result64ecma = hash64ecma.finish();
hash64iso.put(data);
ubyte[8] result64iso = hash64iso.finish();

```
 
 
Examples:


```
//Let's use the template features:
//Note: When passing a CRC32 to a function, it must be passed by reference!
void doSomething(T)(ref T hash)
if (isDigest!T)
{
  hash.put(cast(ubyte) 0);
}
CRC32 crc32;
crc32.start();
doSomething(crc32);
writeln(crcHexString(crc32.finish())); // "D202EF8D"
// repeat for CRC64
CRC64ECMA crc64ecma;
crc64ecma.start();
doSomething(crc64ecma);
writeln(crcHexString(crc64ecma.finish())); // "1FADA17364673F59"
CRC64ISO crc64iso;
crc64iso.start();
doSomething(crc64iso);
writeln(crcHexString(crc64iso.finish())); // "6F90000000000000"

```
 
 
pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`.

  pure nothrow @nogc @safe void **start**();  
Used to initialize the CRC32 digest. 



Note
 For this CRC32 Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. 
 Generic code which deals with different Digest types should always call start though.  pure nothrow @nogc @safe R **finish**();  
Returns the finished CRC hash. This also calls [`start`](#start) to reset the internal state.

  const pure nothrow @nogc @safe R **peek**();  
Works like `finish` but does not reset the internal state, so it's possible to continue putting data into this CRC after a call to peek.

    ubyte[4] **crc32Of**(T...)(T data);  
This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the CRC32 implementation. 



Parameters:


|  |  |
| --- | --- |
| T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. |


 
Returns:
CRC32 of data
 
Examples:


```
ubyte[] data = [4,5,7,25];
writeln(data.crc32Of); // [167, 180, 199, 131]

import std.utf : byChar;
writeln("hello"d.byChar.crc32Of); // [134, 166, 16, 54]

ubyte[4] hash = "abc".crc32Of();
writeln(hash); // digest!CRC32("ab", "c")

import std.range : iota;
enum ubyte S = 5, F = 66;
writeln(iota(S, F).crc32Of); // [59, 140, 234, 154]

```
 
  ubyte[8] **crc64ECMAOf**(T...)(T data);  
This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the CRC64-ECMA implementation. 



Parameters:


|  |  |
| --- | --- |
| T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. |


 
Returns:
CRC64-ECMA of data
 
Examples:


```
ubyte[] data = [4,5,7,25];
writeln(data.crc64ECMAOf); // [58, 142, 220, 214, 118, 98, 105, 69]

import std.utf : byChar;
writeln("hello"d.byChar.crc64ECMAOf); // [177, 55, 185, 219, 229, 218, 30, 155]

ubyte[8] hash = "abc".crc64ECMAOf();
writeln("abc".crc64ECMAOf); // [39, 118, 39, 26, 74, 9, 216, 44]
writeln(hash); // digest!CRC64ECMA("ab", "c")

import std.range : iota;
enum ubyte S = 5, F = 66;
writeln(iota(S, F).crc64ECMAOf); // [6, 184, 91, 238, 46, 213, 127, 188]

```
 
  ubyte[8] **crc64ISOOf**(T...)(T data);  
This is a convenience alias for [`std.digest.digest.digest`](std_digest_digest#digest) using the CRC64-ISO implementation. 



Parameters:


|  |  |
| --- | --- |
| T `data` | `InputRange` of `ElementType` implicitly convertible to `ubyte`, `ubyte[]` or `ubyte[num]` or one or more arrays of any type. |


 
Returns:
CRC64-ISO of data
 
Examples:


```
ubyte[] data = [4,5,7,25];
writeln(data.crc64ISOOf); // [0, 0, 0, 80, 137, 232, 203, 120]

import std.utf : byChar;
writeln("hello"d.byChar.crc64ISOOf); // [0, 0, 16, 216, 226, 238, 62, 60]

ubyte[8] hash = "abc".crc64ISOOf();
writeln("abc".crc64ISOOf); // [0, 0, 0, 0, 32, 196, 118, 55]
writeln(hash); // digest!CRC64ISO("ab", "c")

import std.range : iota;
enum ubyte S = 5, F = 66;

writeln(iota(S, F).crc64ISOOf); // [21, 185, 116, 95, 219, 11, 54, 7]

```
 
  alias **crcHexString** = **crcHexString**;   
  
alias **crcHexString** = std.digest.toHexString!(Order.decreasing, 16LU, LetterCase.upper).toHexString;  
producing the usual CRC32 string output.

  alias **CRC32Digest** = std.digest.WrapperDigest!(CRC!(32u, 3988292384LU)).WrapperDigest;  
OOP API CRC32 implementation. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!CRC32`, see there for more information.

  alias **CRC64ECMADigest** = std.digest.WrapperDigest!(CRC!(64u, 14514072000185962306LU)).WrapperDigest;  
OOP API CRC64-ECMA implementation. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.digest.WrapperDigest](std_digest_digest#WrapperDigest)!CRC64ECMA`, see there for more information.

  alias **CRC64ISODigest** = std.digest.WrapperDigest!(CRC!(64u, 15564440312192434176LU)).WrapperDigest;  
OOP API CRC64-ISO implementation. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.digest.WrapperDigest](std_digest_digest#WrapperDigest)!CRC64ISO`, see there for more information.

 
Examples:


```
//Simple example, hashing a string using Digest.digest helper function
auto crc = new CRC32Digest();
ubyte[] hash = crc.digest("abc");
//Let's get a hash string
writeln(crcHexString(hash)); // "352441C2"

```
 
 
Examples:


```
//Let's use the OOP features:
void test(Digest dig)
{
 dig.put(cast(ubyte) 0);
}
auto crc = new CRC32Digest();
test(crc);

//Let's use a custom buffer:
ubyte[4] buf;
ubyte[] result = crc.finish(buf[]);
writeln(crcHexString(result)); // "D202EF8D"

```
 
 
Examples:


```
//Simple example
auto hash = new CRC32Digest();
hash.put(cast(ubyte) 0);
ubyte[] result = hash.finish();

```
 
 
Examples:


```
//using a supplied buffer
ubyte[4] buf;
auto hash = new CRC32Digest();
hash.put(cast(ubyte) 0);
ubyte[] result = hash.finish(buf[]);
//The result is now in result (and in buf. If you pass a buffer which is bigger than
//necessary, result will have the correct length, but buf will still have it's original
//length)

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_crc.html>

std.digest.hmac
===============

 This package implements the hash-based message authentication code (HMAC) algorithm as defined in [RFC2104](http://tools.ietf.org/html/rfc2104). See also the corresponding [Wikipedia article](http://en.wikipedia.org/wiki/Hash-based_message_authentication_code). 



License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Source
 [std/digest/hmac.d](https://github.com/dlang/phobos/blob/master/std/digest/hmac.d)

 
Examples:
Template API HMAC implementation. This implements an HMAC over the digest H. If H doesn't provide information about the block size, it can be supplied explicitly using the second overload. This type conforms to [`std.digest.isDigest`](std_digest#isDigest). Compute HMAC over an input string 
```
import std.ascii : LetterCase;
import std.digest : toHexString;
import std.digest.sha : SHA1;
import std.string : representation;

auto secret = "secret".representation;
assert("The quick brown fox jumps over the lazy dog"
        .representation
        .hmac!SHA1(secret)
        .toHexString!(LetterCase.lower) == "198ea1ea04c435c1246b586a06d5cf11c3ffcda6");

```
 
 
struct **HMAC**(H, size\_t hashBlockSize) if (hashBlockSize % 8 == 0);   
  
template **hmac**(H) if (isDigest!H && hasBlockSize!H)  
  
auto **hmac**(H, size\_t blockSize)(scope const(ubyte)[] secret)  
 Constraints: if (isDigest!H); 
 
Overload of HMAC to be used if H doesn't provide information about its block size.



Examples:


```
import std.digest.sha : SHA1;
import std.string : representation;
string data1 = "Hello, world", data2 = "Hola mundo";
auto hmac = HMAC!SHA1("My s3cR3T keY".representation);
auto digest = hmac.put(data1.representation)
                  .put(data2.representation)
                  .finish();
static immutable expected = [
    197, 57, 52, 3, 13, 194, 13,
    36, 117, 228, 8, 11, 111, 51,
    165, 3, 123, 31, 251, 113];
writeln(digest); // expected

```
 
 
this(scope const(ubyte)[] secret);  
Constructs the HMAC digest using the specified secret.



Examples:


```
import std.digest.sha : SHA1;
import std.string : representation;
auto hmac = HMAC!SHA1("My s3cR3T keY".representation);
hmac.put("Hello, world".representation);
static immutable expected = [
    130, 32, 235, 44, 208, 141,
    150, 232, 211, 214, 162, 195,
    188, 127, 52, 89, 100, 68, 90, 216];
writeln(hmac.finish()); // expected

```
 
  ref HMAC!(H, blockSize) **start**() return;  
Reinitializes the digest, making it ready for reuse. 



Note
 The constructor leaves the digest in an initialized state, so that this method only needs to be called if an unfinished digest is to be reused. 
 
Returns:
A reference to the digest for convenient chaining.
 
Examples:


```
import std.digest.sha : SHA1;
import std.string : representation;
string data1 = "Hello, world", data2 = "Hola mundo";
auto hmac = HMAC!SHA1("My s3cR3T keY".representation);
hmac.put(data1.representation);
hmac.start();                   // reset digest
hmac.put(data2.representation); // start over
static immutable expected = [
    122, 151, 232, 240, 249, 80,
    19, 178, 186, 77, 110, 23, 208,
    52, 11, 88, 34, 151, 192, 255];
writeln(hmac.finish()); // expected

```
 
  ref HMAC!(H, blockSize) **put**(in ubyte[] data...) return;  
Feeds a piece of data into the hash computation. This method allows the type to be used as an [`std.range.OutputRange`](std_range#OutputRange). 



Returns:
A reference to the digest for convenient chaining.
 
Examples:


```
import std.digest.hmac, std.digest.sha;
import std.string : representation;
string data1 = "Hello, world", data2 = "Hola mundo";
auto hmac = HMAC!SHA1("My s3cR3T keY".representation);
hmac.put(data1.representation)
    .put(data2.representation);
static immutable expected = [
    197, 57, 52, 3, 13, 194, 13,
    36, 117, 228, 8, 11, 111, 51,
    165, 3, 123, 31, 251, 113];
writeln(hmac.finish()); // expected

```
 
  DigestType!H **finish**();  
Resets the digest and returns the finished hash.



Examples:


```
import std.digest.sha : SHA1;
import std.string : representation;
string data1 = "Hello, world", data2 = "Hola mundo";
auto hmac = HMAC!SHA1("My s3cR3T keY".representation);
auto digest = hmac.put(data1.representation)
                  .put(data2.representation)
                  .finish();
static immutable expected = [
    197, 57, 52, 3, 13, 194, 13,
    36, 117, 228, 8, 11, 111, 51,
    165, 3, 123, 31, 251, 113];
writeln(digest); // expected

```
 
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_hmac.html>

std.digest
==========

 This module describes the digest APIs used in Phobos. All digests follow these APIs. Additionally, this module contains useful helper methods which can be used with every digest type. 




| Category | Functions |
| --- | --- |
| Template API | [*isDigest*](#isDigest) [*DigestType*](#DigestType) [*hasPeek*](#hasPeek) [*hasBlockSize*](#hasBlockSize) [*ExampleDigest*](#ExampleDigest) [*digest*](#digest) [*hexDigest*](#hexDigest) [*makeDigest*](#makeDigest) |
| OOP API | [*Digest*](#Digest) |
| Helper functions | [*toHexString*](#toHexString) [*secureEqual*](#secureEqual) |
| Implementation helpers | [*digestLength*](#digestLength) [*WrapperDigest*](#WrapperDigest) |

 
APIs
 There are two APIs for digests: The template API and the OOP API. The template API uses structs and template helpers like [`isDigest`](#isDigest). The OOP API implements digests as classes inheriting the [`Digest`](#Digest) interface. All digests are named so that the template API struct is called "**x**" and the OOP API class is called "**x**Digest". For example we have `MD5` <--> `MD5Digest`, `CRC32` <--> `CRC32Digest`, etc. 
 The template API is slightly more efficient. It does not have to allocate memory dynamically, all memory is allocated on the stack. The OOP API has to allocate in the finish method if no buffer was provided. If you provide a buffer to the OOP APIs finish function, it doesn't allocate, but the [`Digest`](#Digest) classes still have to be created using `new` which allocates them using the GC. The OOP API is useful to change the digest function and/or digest backend at 'runtime'. The benefit here is that switching e.g. Phobos MD5Digest and an OpenSSLMD5Digest implementation is ABI compatible. If just one specific digest type and backend is needed, the template API is usually a good fit. In this simplest case, the template API can even be used without templates: Just use the "**x**" structs directly. 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Johannes Pfau 
 
Source
 [std/digest/package.d](https://github.com/dlang/phobos/blob/master/std/digest/package.d) 
 
CTFE
 Digests do not work in CTFE 
 
TODO
 Digesting single bits (as opposed to bytes) is not implemented. This will be done as another template constraint helper (hasBitDigesting!T) and an additional interface (BitDigest)
 
Examples:


```
import std.digest.crc;

//Simple example
char[8] hexHash = hexDigest!CRC32("The quick brown fox jumps over the lazy dog");
writeln(hexHash); // "39A34F41"

//Simple example, using the API manually
CRC32 context = makeDigest!CRC32();
context.put(cast(ubyte[])"The quick brown fox jumps over the lazy dog");
ubyte[4] hash = context.finish();
writeln(toHexString(hash)); // "39A34F41"

```
 
 
Examples:


```
//Generating the hashes of a file, idiomatic D way
import std.digest.crc, std.digest.md, std.digest.sha;
import std.stdio;

// Digests a file and prints the result.
void digestFile(Hash)(string filename)
if (isDigest!Hash)
{
    auto file = File(filename);
    auto result = digest!Hash(file.byChunk(4096 * 1024));
    writefln("%s (%s) = %s", Hash.stringof, filename, toHexString(result));
}

void main(string[] args)
{
    foreach (name; args[1 .. $])
    {
        digestFile!MD5(name);
        digestFile!SHA1(name);
        digestFile!CRC32(name);
    }
}

```
 
 
Examples:


```
//Generating the hashes of a file using the template API
import std.digest.crc, std.digest.md, std.digest.sha;
import std.stdio;
// Digests a file and prints the result.
void digestFile(Hash)(ref Hash hash, string filename)
if (isDigest!Hash)
{
    File file = File(filename);

    //As digests imlement OutputRange, we could use std.algorithm.copy
    //Let's do it manually for now
    foreach (buffer; file.byChunk(4096 * 1024))
        hash.put(buffer);

    auto result = hash.finish();
    writefln("%s (%s) = %s", Hash.stringof, filename, toHexString(result));
}

void uMain(string[] args)
{
    MD5 md5;
    SHA1 sha1;
    CRC32 crc32;

    md5.start();
    sha1.start();
    crc32.start();

    foreach (arg; args[1 .. $])
    {
        digestFile(md5, arg);
        digestFile(sha1, arg);
        digestFile(crc32, arg);
    }
}

```
 
 
Examples:


```
import std.digest.crc, std.digest.md, std.digest.sha;
import std.stdio;

// Digests a file and prints the result.
void digestFile(Digest hash, string filename)
{
    File file = File(filename);

    //As digests implement OutputRange, we could use std.algorithm.copy
    //Let's do it manually for now
    foreach (buffer; file.byChunk(4096 * 1024))
      hash.put(buffer);

    ubyte[] result = hash.finish();
    writefln("%s (%s) = %s", typeid(hash).toString(), filename, toHexString(result));
}

void umain(string[] args)
{
    auto md5 = new MD5Digest();
    auto sha1 = new SHA1Digest();
    auto crc32 = new CRC32Digest();

    foreach (arg; args[1 .. $])
    {
      digestFile(md5, arg);
      digestFile(sha1, arg);
      digestFile(crc32, arg);
    }
}

```
 
 
struct **ExampleDigest**;  
This documents the general structure of a Digest in the template API. All digest implementations should implement the following members and therefore pass the [`isDigest`](#isDigest) test. 



Note

* A digest must be a struct (value type) to pass the [`isDigest`](#isDigest) test.
* A digest passing the [`isDigest`](#isDigest) test is always an `OutputRange`

 
Examples:


```
//Using the OutputRange feature
import std.algorithm.mutation : copy;
import std.digest.md;
import std.range : repeat;

auto oneMillionRange = repeat!ubyte(cast(ubyte)'a', 1000000);
auto ctx = makeDigest!MD5();
copy(oneMillionRange, &ctx); //Note: You must pass a pointer to copy!
writeln(ctx.finish().toHexString()); // "7707D6AE4E027C70EEA2A935C2296F21"

```
 
 
@trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. The following usages of `put` must work for any type which passes [`isDigest`](#isDigest): 



Example


```
ExampleDigest dig;
dig.put(cast(ubyte) 0); //single ubyte
dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic
ubyte[10] buf;
dig.put(buf); //buffer

```
  @trusted void **start**();  
This function is used to (re)initialize the digest. It must be called before using the digest and it also works as a 'reset' function if the digest has already processed data.

  @trusted ubyte[16] **finish**();  
The finish function returns the final hash sum and resets the Digest. 



Note
 The actual type returned by finish depends on the digest implementation. `ubyte[16]` is just used as an example. It is guaranteed that the type is a static array of ubytes. 
 * Use [`DigestType`](#DigestType) to obtain the actual return type.
* Use [`digestLength`](#digestLength) to obtain the length of the ubyte array.

    enum bool **isDigest**(T);  
Use this to check if a type is a digest. See [`ExampleDigest`](#ExampleDigest) to see what a type must provide to pass this check. 



Note
 This is very useful as a template constraint (see examples) 
 
Bugs:
* Does not yet verify that put takes scope parameters.
* Should check that finish() returns a ubyte[num] array

 
Examples:


```
import std.digest.crc;
static assert(isDigest!CRC32);

```
 
 
Examples:


```
import std.digest.crc;
void myFunction(T)()
if (isDigest!T)
{
    T dig;
    dig.start();
    auto result = dig.finish();
}
myFunction!CRC32();

```
 
  template **DigestType**(T) 
Use this template to get the type which is returned by a digest's [`finish`](#finish) method.



Examples:


```
import std.digest.crc;
assert(is(DigestType!(CRC32) == ubyte[4]));

```
 
 
Examples:


```
import std.digest.crc;
CRC32 dig;
dig.start();
DigestType!CRC32 result = dig.finish();

```
 
  enum bool **hasPeek**(T);  
Used to check if a digest supports the `peek` method. Peek has exactly the same function signatures as finish, but it doesn't reset the digest's internal state. 



Note

* This is very useful as a template constraint (see examples)
* This also checks if T passes [`isDigest`](#isDigest)

 
Examples:


```
import std.digest.crc, std.digest.md;
assert(!hasPeek!(MD5));
assert(hasPeek!CRC32);

```
 
 
Examples:


```
import std.digest.crc;
void myFunction(T)()
if (hasPeek!T)
{
    T dig;
    dig.start();
    auto result = dig.peek();
}
myFunction!CRC32();

```
 
  template **hasBlockSize**(T) if (isDigest!T) 
Checks whether the digest has a `blockSize` member, which contains the digest's internal block size in bits. It is primarily used by [`std.digest.hmac.HMAC`](std_digest_hmac#HMAC).



Examples:


```
import std.digest.hmac, std.digest.md;
static assert(hasBlockSize!MD5        && MD5.blockSize      == 512);
static assert(hasBlockSize!(HMAC!MD5) && HMAC!MD5.blockSize == 512);

```
 
  DigestType!Hash **digest**(Hash, Range)(auto ref Range range)  
 Constraints: if (!isArray!Range && isDigestibleRange!Range); 
 
This is a convenience function to calculate a hash using the template API. Every digest passing the [`isDigest`](#isDigest) test can be used with this function. 



Parameters:


|  |  |
| --- | --- |
| Range `range` | an `InputRange` with `ElementType` `ubyte`, `ubyte[]` or `ubyte[num]` |


 
Examples:


```
import std.digest.md;
import std.range : repeat;
auto testRange = repeat!ubyte(cast(ubyte)'a', 100);
auto md5 = digest!MD5(testRange);

```
 
  DigestType!Hash **digest**(Hash, T...)(scope const T data)  
 Constraints: if (allSatisfy!(isArray, typeof(data))); 
 
This overload of the digest function handles arrays. 



Parameters:


|  |  |
| --- | --- |
| T `data` | one or more arrays of any type |


 
Examples:


```
import std.digest.crc, std.digest.md, std.digest.sha;
auto md5   = digest!MD5(  "The quick brown fox jumps over the lazy dog");
auto sha1  = digest!SHA1( "The quick brown fox jumps over the lazy dog");
auto crc32 = digest!CRC32("The quick brown fox jumps over the lazy dog");
writeln(toHexString(crc32)); // "39A34F41"

```
 
 
Examples:


```
import std.digest.crc;
auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog");
writeln(toHexString(crc32)); // "39A34F41"

```
 
  char[digestLength!Hash \* 2] **hexDigest**(Hash, Order order = Order.increasing, Range)(ref Range range)  
 Constraints: if (!isArray!Range && isDigestibleRange!Range); 
 
This is a convenience function similar to [`digest`](#digest), but it returns the string representation of the hash. Every digest passing the [`isDigest`](#isDigest) test can be used with this function. 



Parameters:


|  |  |
| --- | --- |
| order | the order in which the bytes are processed (see [`toHexString`](#toHexString)) |
| Range `range` | an `InputRange` with `ElementType` `ubyte`, `ubyte[]` or `ubyte[num]` |


 
Examples:


```
import std.digest.md;
import std.range : repeat;
auto testRange = repeat!ubyte(cast(ubyte)'a', 100);
writeln(hexDigest!MD5(testRange)); // "36A92CC94A9E0FA21F625F8BFB007ADF"

```
 
  char[digestLength!Hash \* 2] **hexDigest**(Hash, Order order = Order.increasing, T...)(scope const T data)  
 Constraints: if (allSatisfy!(isArray, typeof(data))); 
 
This overload of the hexDigest function handles arrays. 



Parameters:


|  |  |
| --- | --- |
| order | the order in which the bytes are processed (see [`toHexString`](#toHexString)) |
| T `data` | one or more arrays of any type |


 
Examples:


```
import std.digest.crc;
// "414FA339"
writeln(hexDigest!(CRC32, Order.decreasing)("The quick brown fox jumps over the lazy dog"));

```
 
 
Examples:


```
import std.digest.crc;
// "414FA339"
writeln(hexDigest!(CRC32, Order.decreasing)("The quick ", "brown ", "fox jumps over the lazy dog"));

```
 
  Hash **makeDigest**(Hash)();  
This is a convenience function which returns an initialized digest, so it's not necessary to call start manually.



Examples:


```
import std.digest.md;
auto md5 = makeDigest!MD5();
md5.put(0);
writeln(toHexString(md5.finish())); // "93B885ADFE0DA089CDF634904FD59F71"

```
 
  interface **Digest**;  
This describes the OOP API. To understand when to use the template API and when to use the OOP API, see the module documentation at the top of this page. 


The Digest interface is the base interface which is implemented by all digests. 

 
Note
 A Digest implementation is always an `OutputRange`

 
Examples:


```
//Using the OutputRange feature
import std.algorithm.mutation : copy;
import std.digest.md;
import std.range : repeat;

auto oneMillionRange = repeat!ubyte(cast(ubyte)'a', 1000000);
auto ctx = new MD5Digest();
copy(oneMillionRange, ctx);
writeln(ctx.finish().toHexString()); // "7707D6AE4E027C70EEA2A935C2296F21"

```
 
 
Examples:


```
import std.digest.crc, std.digest.md, std.digest.sha;
ubyte[] md5   = (new MD5Digest()).digest("The quick brown fox jumps over the lazy dog");
ubyte[] sha1  = (new SHA1Digest()).digest("The quick brown fox jumps over the lazy dog");
ubyte[] crc32 = (new CRC32Digest()).digest("The quick brown fox jumps over the lazy dog");
writeln(crcHexString(crc32)); // "414FA339"

```
 
 
Examples:


```
import std.digest.crc;
ubyte[] crc32 = (new CRC32Digest()).digest("The quick ", "brown ", "fox jumps over the lazy dog");
writeln(crcHexString(crc32)); // "414FA339"

```
 
 
Examples:


```
void test(Digest dig)
{
    dig.put(cast(ubyte) 0); //single ubyte
    dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic
    ubyte[10] buf;
    dig.put(buf); //buffer
}

```
 
 
abstract nothrow @trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. 



Example


```
void test(Digest dig)
{
    dig.put(cast(ubyte) 0); //single ubyte
    dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic
    ubyte[10] buf;
    dig.put(buf); //buffer
}

```
  abstract nothrow @trusted void **reset**();  
Resets the internal state of the digest. 



Note
 [`finish`](#finish) calls this internally, so it's not necessary to call `reset` manually after a call to [`finish`](#finish).
  abstract const nothrow @property @trusted size\_t **length**();  
This is the length in bytes of the hash value which is returned by [`finish`](#finish). It's also the required size of a buffer passed to [`finish`](#finish).

  abstract nothrow @trusted ubyte[] **finish**();   
  
abstract nothrow ubyte[] **finish**(ubyte[] buf);  
The finish function returns the hash value. It takes an optional buffer to copy the data into. If a buffer is passed, it must be at least [`length`](#length) bytes big.

  final nothrow @trusted ubyte[] **digest**(scope const(void[])[] data...);  
This is a convenience function to calculate the hash of a value using the OOP API.

    enum **Order**: bool;  
See [`toHexString`](#toHexString)



Examples:


```
import std.digest.crc : CRC32;

auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog");
writeln(crc32.toHexString!(Order.decreasing)); // "414FA339"
writeln(crc32.toHexString!(LetterCase.lower, Order.decreasing)); // "414fa339"

```
 
 
**increasing** **decreasing**   char[num \* 2] **toHexString**(Order order = Order.increasing, size\_t num, LetterCase letterCase = LetterCase.upper)(const ubyte[num] digest);   
  
char[num \* 2] **toHexString**(LetterCase letterCase, Order order = Order.increasing, size\_t num)(in ubyte[num] digest);   
  
string **toHexString**(Order order = Order.increasing, LetterCase letterCase = LetterCase.upper)(in ubyte[] digest);   
  
string **toHexString**(LetterCase letterCase, Order order = Order.increasing)(in ubyte[] 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.
 
Examples:


```
import std.digest.crc;
//Test with template API:
auto crc32 = digest!CRC32("The quick ", "brown ", "fox jumps over the lazy dog");
//Lower case variant:
writeln(toHexString!(LetterCase.lower)(crc32)); // "39a34f41"
//Usually CRCs are printed in this order, though:
writeln(toHexString!(Order.decreasing)(crc32)); // "414FA339"
writeln(toHexString!(LetterCase.lower, Order.decreasing)(crc32)); // "414fa339"

```
 
 
Examples:


```
import std.digest.crc;
// With OOP API
auto crc32 = (new CRC32Digest()).digest("The quick ", "brown ", "fox jumps over the lazy dog");
//Usually CRCs are printed in this order, though:
writeln(toHexString!(Order.decreasing)(crc32)); // "414FA339"

```
 
  class **WrapperDigest**(T) if (isDigest!T): Digest;  
Wraps a template API hash struct into a Digest interface. Modules providing digest implementations will usually provide an alias for this template (e.g. MD5Digest, SHA1Digest, ...).



Examples:


```
import std.digest.md;
//Simple example
auto hash = new WrapperDigest!MD5();
hash.put(cast(ubyte) 0);
auto result = hash.finish();

```
 
 
Examples:


```
//using a supplied buffer
import std.digest.md;
ubyte[16] buf;
auto hash = new WrapperDigest!MD5();
hash.put(cast(ubyte) 0);
auto result = hash.finish(buf[]);
//The result is now in result (and in buf). If you pass a buffer which is bigger than
//necessary, result will have the correct length, but buf will still have it's original
//length

```
 
 
this();  
Initializes the digest.

  nothrow @trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`.

  nothrow @trusted void **reset**();  
Resets the internal state of the digest. 



Note
 [`finish`](#finish) calls this internally, so it's not necessary to call `reset` manually after a call to [`finish`](#finish).
  const pure nothrow @property @trusted size\_t **length**();  
This is the length in bytes of the hash value which is returned by [`finish`](#finish). It's also the required size of a buffer passed to [`finish`](#finish).

  nothrow ubyte[] **finish**(ubyte[] buf);   
  
nothrow @trusted ubyte[] **finish**();  
The finish function returns the hash value. It takes an optional buffer to copy the data into. If a buffer is passed, it must have a length at least [`length`](#length) bytes. 



Example


```

import std.digest.md;
ubyte[16] buf;
auto hash = new WrapperDigest!MD5();
hash.put(cast(ubyte) 0);
auto result = hash.finish(buf[]);
//The result is now in result (and in buf). If you pass a buffer which is bigger than
//necessary, result will have the correct length, but buf will still have it's original
//length

```
  const @trusted ubyte[] **peek**(ubyte[] buf);   
  
const @trusted ubyte[] **peek**();  
Works like `finish` but does not reset the internal state, so it's possible to continue putting data into this WrapperDigest after a call to peek. 


These functions are only available if `hasPeek!T` is true.

    bool **secureEqual**(R1, R2)(R1 r1, R2 r2)  
 Constraints: if (isInputRange!R1 && isInputRange!R2 && !isInfinite!R1 && !isInfinite!R2 && (isIntegral!(ElementEncodingType!R1) || isSomeChar!(ElementEncodingType!R1)) && !is(CommonType!(ElementEncodingType!R1, ElementEncodingType!R2) == void)); 
 
Securely compares two digest representations while protecting against timing attacks. Do not use `==` to compare digest representations. 


The attack happens as follows:   
  
 1. An attacker wants to send harmful data to your server, which requires a integrity HMAC SHA1 token signed with a secret.
2. The length of the token is known to be 40 characters long due to its format, so the attacker first sends `"0000000000000000000000000000000000000000"`, then `"1000000000000000000000000000000000000000"`, and so on.
3. The given HMAC token is compared with the expected token using the `==` string comparison, which returns `false` as soon as the first wrong element is found. If a wrong element is found, then a rejection is sent back to the sender.
4. Eventually, the attacker is able to determine the first character in the correct token because the sever takes slightly longer to return a rejection. This is due to the comparison moving on to second item in the two arrays, seeing they are different, and then sending the rejection.
5. It may seem like too small of a difference in time for the attacker to notice, but security researchers have shown that differences as small as  [20µs can be reliably distinguished](http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf) even with network inconsistencies.
6. Repeat the process for each character until the attacker has the whole correct token and the server accepts the harmful data. This can be done in a week with the attacker pacing the attack to 10 requests per second with only one client.

   
  
 This function defends against this attack by always comparing every single item in the array if the two arrays are the same length. Therefore, this function is always Ο(`n`) for ranges of the same length.   
  
 This attack can also be mitigated via rate limiting and banning IPs which have too many rejected requests. However, this does not completely solve the problem, as the attacker could be in control of a bot net. To fully defend against the timing attack, rate limiting, banning IPs, and using this function should be used together. 

 
Parameters:


|  |  |
| --- | --- |
| R1 `r1` | A digest representation |
| R2 `r2` | A digest representation |


 
Returns:

`true` if both representations are equal, `false` otherwise 
 
See Also:

[The Wikipedia article on timing attacks](https://en.wikipedia.org/wiki/Timing_attack).
 
Examples:


```
import std.digest.hmac : hmac;
import std.digest.sha : SHA1;
import std.string : representation;

// a typical HMAC data integrity verification
auto secret = "A7GZIP6TAQA6OHM7KZ42KB9303CEY0MOV5DD6NTV".representation;
auto data = "data".representation;

auto hex1 = data.hmac!SHA1(secret).toHexString;
auto hex2 = data.hmac!SHA1(secret).toHexString;
auto hex3 = "data1".representation.hmac!SHA1(secret).toHexString;

assert( secureEqual(hex1[], hex2[]));
assert(!secureEqual(hex1[], hex3[]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest.html>

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*](#MD5) |
| OOP API | [*MD5Digest*](#MD5Digest) |
| Helpers | [*md5Of*](#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`](std_digest).   
  
 This module publicly imports [`std.digest`](std_digest) and can be used as a stand-alone module. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
CTFE
 Digests do not work in CTFE 
 
Authors:
Piotr Szturmaj, Kai Nacke, Johannes Pfau   
 The routines and algorithms are derived from the *RSA Data Security, Inc. MD5 Message-Digest Algorithm*. 
 
References
 [Wikipedia on MD5](http://en.wikipedia.org/wiki/Md5) 
 
Source
 [std/digest/md.d](https://github.com/dlang/phobos/blob/master/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();

```
 
 
Examples:


```
//OOP API
import std.digest.md;

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

//Feeding data
ubyte[1024] data;
md5.put(data[]);
md5.reset(); //Start again
md5.put(data[]);
hash = md5.finish();

```
 
 
struct **MD5**;  
Template API MD5 implementation. See `std.digest` for differences between template and OOP API.



Examples:


```
//Simple example, hashing a string using md5Of helper function
ubyte[16] hash = md5Of("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "900150983CD24FB0D6963F7D28E17F72"

```
 
 
Examples:


```
//Using the basic API
MD5 hash;
hash.start();
ubyte[1024] data;
//Initialize data here...
hash.put(data);
ubyte[16] result = hash.finish();

```
 
 
Examples:


```
//Let's use the template features:
void doSomething(T)(ref T hash)
if (isDigest!T)
{
    hash.put(cast(ubyte) 0);
}
MD5 md5;
md5.start();
doSomething(md5);
writeln(toHexString(md5.finish())); // "93B885ADFE0DA089CDF634904FD59F71"

```
 
 
pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. 



Example


```
MD5 dig;
dig.put(cast(ubyte) 0); //single ubyte
dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic
ubyte[10] buf;
dig.put(buf); //buffer

```
  pure nothrow @nogc @safe void **start**();  
Used to (re)initialize the MD5 digest. 



Note
 For this MD5 Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. 
 Generic code which deals with different Digest types should always call start though. 
Example


```
MD5 digest;
//digest.start(); //Not necessary
digest.put(0);

```
  pure nothrow @nogc @trusted ubyte[16] **finish**();  
Returns the finished MD5 hash. This also calls [`start`](#start) to reset the internal state.



Examples:


```
//Simple example
MD5 hash;
hash.start();
hash.put(cast(ubyte) 0);
ubyte[16] result = hash.finish();

```
 
    auto **md5Of**(T...)(T data);  
This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the MD5 implementation.



Examples:


```
ubyte[16] hash = md5Of("abc");
writeln(hash); // digest!MD5("abc")

```
 
  alias **MD5Digest** = std.digest.WrapperDigest!(MD5).WrapperDigest;  
OOP API MD5 implementation. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!MD5`, see there for more information.

 
Examples:


```
//Simple example, hashing a string using Digest.digest helper function
auto md5 = new MD5Digest();
ubyte[] hash = md5.digest("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "900150983CD24FB0D6963F7D28E17F72"

```
 
 
Examples:


```
//Let's use the OOP features:
void test(Digest dig)
{
 dig.put(cast(ubyte) 0);
}
auto md5 = new MD5Digest();
test(md5);

//Let's use a custom buffer:
ubyte[16] buf;
ubyte[] result = md5.finish(buf[]);
writeln(toHexString(result)); // "93B885ADFE0DA089CDF634904FD59F71"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_md.html>

std.array
=========

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




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


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

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/array.d](https://github.com/dlang/phobos/blob/master/std/array.d)

 
ForeachType!Range[] **array**(Range)(Range r)  
 Constraints: if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range);   
  
ForeachType!(PointerTarget!Range)[] **array**(Range)(Range r)  
 Constraints: if (isPointer!Range && isIterable!(PointerTarget!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.

 

 
Parameters:


|  |  |
| --- | --- |
| Range `r` | range (or aggregate with `opApply` function) whose elements are copied into the allocated array |


 
Returns:
allocated and initialized array
 
Examples:


```
auto a = array([1, 2, 3, 4, 5][]);
writeln(a); // [1, 2, 3, 4, 5]

```
 
  CopyTypeQualifiers!(ElementType!String, dchar)[] **array**(String)(scope String str)  
 Constraints: if (isAutodecodableString!String); 
 
Convert a narrow autodecoding string to an array type that fully supports random access. This is handled as a special case and always returns an array of `dchar` 



NOTE
 This function is never used when autodecoding is turned off. 
 
Parameters:


|  |  |
| --- | --- |
| String `str` | `isNarrowString` to be converted to an array of `dchar` |


 
Returns:
a `dchar[]`, `const(dchar)[]`, or `immutable(dchar)[]` depending on the constness of the input.
 
Examples:


```
import std.range.primitives : isRandomAccessRange;
import std.traits : isAutodecodableString;

// note that if autodecoding is turned off, `array` will not transcode these.
static if (isAutodecodableString!string)
    writeln("Hello D".array); // "Hello D"d
else
    writeln("Hello D".array); // "Hello D"

static if (isAutodecodableString!wstring)
    writeln("Hello D"w.array); // "Hello D"d
else
    writeln("Hello D"w.array); // "Hello D"w

static assert(isRandomAccessRange!dstring == true);

```
 
  auto **assocArray**(Range)(Range r)  
 Constraints: if (isInputRange!Range);   
  
auto **assocArray**(Keys, Values)(Keys keys, Values values)  
 Constraints: if (isInputRange!Values && isInputRange!Keys); 
 
Returns a newly allocated associative array from a range of key/value tuples or from a range of keys and a range of values. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | An [input range](std_range_primitives#isInputRange) of tuples of keys and values. |
| Keys `keys` | An [input range](std_range_primitives#isInputRange) of keys |
| Values `values` | An [input range](std_range_primitives#isInputRange) of values |


 
Returns:
A newly allocated associative array out of elements of the input range, which must be a range of tuples (Key, Value) or a range of keys and a range of values. If given two ranges of unequal lengths after the elements of the shorter are exhausted the remaining elements of the longer will not be considered. Returns a null associative array reference when given an empty range. 
 
Duplicates
 Associative arrays have unique keys. If r contains duplicate keys, then the result will contain the value of the last pair for that key in r. 
 
See Also:

[`std.typecons.Tuple`](std_typecons#Tuple), [`std.range.zip`](std_range#zip)

 
Examples:


```
import std.range : repeat, zip;
import std.typecons : tuple;
import std.range.primitives : autodecodeStrings;
auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap
static assert(is(typeof(a) == string[int]));
writeln(a); // [0:"a", 1:"b", 2:"c"]

auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
static assert(is(typeof(b) == string[string]));
writeln(b); // ["foo":"bar", "baz":"quux"]

static if (autodecodeStrings)
    alias achar = dchar;
else
    alias achar = immutable(char);
auto c = assocArray("ABCD", true.repeat);
static assert(is(typeof(c) == bool[achar]));
bool[achar] expected = ['D':true, 'A':true, 'B':true, 'C':true];
writeln(c); // expected

```
 
  auto **byPair**(AA)(AA aa)  
 Constraints: if (isAssociativeArray!AA); 
 
Construct a range iterating over an associative array by key/value tuples. 



Parameters:


|  |  |
| --- | --- |
| AA `aa` | The associative array to iterate over. |


 
Returns:
A [forward range](std_range_primitives#isForwardRange) of Tuple's of key and value pairs from the given associative array. The members of each pair can be accessed by name (`.key` and `.value`). or by integer index (0 and 1 respectively).
 
Examples:


```
import std.algorithm.sorting : sort;
import std.typecons : tuple, Tuple;

auto aa = ["a": 1, "b": 2, "c": 3];
Tuple!(string, int)[] pairs;

// Iteration over key/value pairs.
foreach (pair; aa.byPair)
{
    if (pair.key == "b")
        pairs ~= tuple("B", pair.value);
    else
        pairs ~= pair;
}

// Iteration order is implementation-dependent, so we should sort it to get
// a fixed order.
pairs.sort();
assert(pairs == [
    tuple("B", 2),
    tuple("a", 1),
    tuple("c", 3)
]);

```
 
  nothrow @system auto **uninitializedArray**(T, I...)(I sizes)  
 Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I) && hasIndirections!(ElementEncodingType!T));   
  
nothrow @trusted auto **uninitializedArray**(T, I...)(I sizes)  
 Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I) && !hasIndirections!(ElementEncodingType!T)); 
 
Returns a new array of type `T` allocated on the garbage collected heap without initializing its elements. This can be a useful optimization if every element will be immediately initialized. `T` may be a multidimensional array. In this case sizes may be specified for any number of dimensions from 0 to the number in `T`. 


uninitializedArray is `nothrow` and weakly `pure`.   
  
 uninitializedArray is `@system` if the uninitialized element type has pointers. 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of the resulting array elements |
| I `sizes` | The length dimension(s) of the resulting array |


 
Returns:
An array of `T` with `I.length` dimensions.
 
Examples:


```
double[] arr = uninitializedArray!(double[])(100);
writeln(arr.length); // 100

double[][] matrix = uninitializedArray!(double[][])(42, 31);
writeln(matrix.length); // 42
writeln(matrix[0].length); // 31

char*[] ptrs = uninitializedArray!(char*[])(100);
writeln(ptrs.length); // 100

```
 
  nothrow @trusted auto **minimallyInitializedArray**(T, I...)(I sizes)  
 Constraints: if (isDynamicArray!T && allSatisfy!(isIntegral, I)); 
 
Returns a new array of type `T` allocated on the garbage collected heap. 


Partial initialization is done for types with indirections, for preservation of memory safety. Note that elements will only be initialized to 0, but not necessarily the element type's `.init`.   
  
 minimallyInitializedArray is `nothrow` and weakly `pure`. 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of the array elements |
| I `sizes` | The length dimension(s) of the resulting array |


 
Returns:
An array of `T` with `I.length` dimensions.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : repeat;

auto arr = minimallyInitializedArray!(int[])(42);
writeln(arr.length); // 42

// Elements aren't necessarily initialized to 0, so don't do this:
// assert(arr.equal(0.repeat(42)));
// If that is needed, initialize the array normally instead:
auto arr2 = new int[42];
assert(arr2.equal(0.repeat(42)));

```
 
  @trusted CommonType!(T[], U[]) **overlap**(T, U)(T[] a, U[] b)  
 Constraints: if (is(typeof(a.ptr < b.ptr) == bool)); 
 
Returns the overlapping portion, if any, of two arrays. Unlike `equal`, `overlap` only compares the pointers and lengths in the ranges, not the values referred by them. If `r1` and `r2` have an overlapping slice, returns that slice. Otherwise, returns the null slice. 



Parameters:


|  |  |
| --- | --- |
| T[] `a` | The first array to compare |
| U[] `b` | The second array to compare |


 
Returns:
The overlapping portion of the two arrays.
 
Examples:


```
int[] a = [ 10, 11, 12, 13, 14 ];
int[] b = a[1 .. 3];
writeln(overlap(a, b)); // [11, 12]
b = b.dup;
// overlap disappears even though the content is the same
assert(overlap(a, b).empty);

static test()() @nogc
{
    auto a = "It's three o'clock"d;
    auto b = a[5 .. 10];
    return b.overlap(a);
}

//works at compile-time
static assert(test == "three"d);

```
 
  void **insertInPlace**(T, U...)(ref T[] array, size\_t pos, U stuff)  
 Constraints: if (!isSomeString!(T[]) && allSatisfy!(isInputRangeOrConvertible!T, U) && (U.length > 0));   
  
void **insertInPlace**(T, U...)(ref T[] array, size\_t pos, U stuff)  
 Constraints: if (isSomeString!(T[]) && allSatisfy!(isCharOrStringOrDcharRange, U)); 
 
Inserts `stuff` (which must be an input range or any number of implicitly convertible items) in `array` at position `pos`. 



Parameters:


|  |  |
| --- | --- |
| T[] `array` | The array that `stuff` will be inserted into. |
| size\_t `pos` | The position in `array` to insert the `stuff`. |
| U `stuff` | An [input range](std_range_primitives#isInputRange), or any number of implicitly convertible items to insert into `array`. |


 
Examples:


```
int[] a = [ 1, 2, 3, 4 ];
a.insertInPlace(2, [ 1, 2 ]);
writeln(a); // [1, 2, 1, 2, 3, 4]
a.insertInPlace(3, 10u, 11);
writeln(a); // [1, 2, 1, 10, 11, 2, 3, 4]

```
 
  pure nothrow @safe bool **sameHead**(T)(in T[] lhs, in T[] rhs);  
Returns whether the `front`s of `lhs` and `rhs` both refer to the same place in memory, making one of the arrays a slice of the other which starts at index `0`. 



Parameters:


|  |  |
| --- | --- |
| T[] `lhs` | the first array to compare |
| T[] `rhs` | the second array to compare |


 
Returns:

`true` if `lhs.ptr == rhs.ptr`, `false` otherwise.
 
Examples:


```
auto a = [1, 2, 3, 4, 5];
auto b = a[0 .. 2];

assert(a.sameHead(b));

```
 
  pure nothrow @trusted bool **sameTail**(T)(in T[] lhs, in T[] rhs);  
Returns whether the `back`s of `lhs` and `rhs` both refer to the same place in memory, making one of the arrays a slice of the other which end at index `$`. 



Parameters:


|  |  |
| --- | --- |
| T[] `lhs` | the first array to compare |
| T[] `rhs` | the second array to compare |


 
Returns:

`true` if both arrays are the same length and `lhs.ptr == rhs.ptr`, `false` otherwise.
 
Examples:


```
auto a = [1, 2, 3, 4, 5];
auto b = a[3..$];

assert(a.sameTail(b));

```
 
  ElementEncodingType!S[] **replicate**(S)(S s, size\_t n)  
 Constraints: if (isDynamicArray!S);   
  
ElementType!S[] **replicate**(S)(S s, size\_t n)  
 Constraints: if (isInputRange!S && !isDynamicArray!S); 
 

Parameters:


|  |  |
| --- | --- |
| S `s` | an [input range](std_range_primitives#isInputRange) or a dynamic array |
| size\_t `n` | number of times to repeat `s` |


 
Returns:
An array that consists of `s` repeated `n` times. This function allocates, fills, and returns a new array. 
 
See Also:
For a lazy version, refer to [`std.range.repeat`](std_range#repeat).
 
Examples:


```
auto a = "abc";
auto s = replicate(a, 3);

writeln(s); // "abcabcabc"

auto b = [1, 2, 3];
auto c = replicate(b, 3);

writeln(c); // [1, 2, 3, 1, 2, 3, 1, 2, 3]

auto d = replicate(b, 0);

writeln(d); // []

```
 
  pure @safe S[] **split**(S)(S s)  
 Constraints: if (isSomeString!S);   
  
auto **split**(Range, Separator)(Range range, Separator sep)  
 Constraints: if (isForwardRange!Range && (is(typeof(ElementType!Range.init == Separator.init)) || is(typeof(ElementType!Range.init == ElementType!Separator.init)) && isForwardRange!Separator));   
  
auto **split**(alias isTerminator, Range)(Range range)  
 Constraints: if (isForwardRange!Range && is(typeof(unaryFun!isTerminator(range.front)))); 
 
Eagerly splits `range` into an array, using `sep` as the delimiter. 


When no delimiter is provided, strings are split into an array of words, using whitespace as delimiter. Runs of whitespace are merged together (no empty words are produced).   
  
 The `range` must be a [forward range](std_range_primitives#isForwardRange). The separator can be a value of the same type as the elements in `range` or it can be another forward `range`. 

 
Parameters:


|  |  |
| --- | --- |
| S `s` | the string to split by word if no separator is given |
| Range `range` | the range to split |
| Separator `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:

[`std.algorithm.iteration.splitter`](std_algorithm_iteration#splitter) for a lazy version without allocating memory. [`std.regex.splitter`](std_regex#splitter) for a version that splits using a regular expression defined separator.
 
Examples:


```
import std.uni : isWhite;
writeln("Learning,D,is,fun".split(",")); // ["Learning", "D", "is", "fun"]
writeln("Learning D is fun".split!isWhite); // ["Learning", "D", "is", "fun"]
writeln("Learning D is fun".split(" D ")); // ["Learning", "is fun"]

```
 
 
Examples:


```
string str = "Hello World!";
writeln(str.split); // ["Hello", "World!"]

string str2 = "Hello\t\tWorld\t!";
writeln(str2.split); // ["Hello", "World", "!"]

```
 
 
Examples:


```
writeln(split("hello world")); // ["hello", "world"]
writeln(split("192.168.0.1", ".")); // ["192", "168", "0", "1"]

auto a = split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]);
writeln(a); // [[1], [4, 5, 1], [4, 5]]

```
 
  ElementEncodingType!(ElementType!RoR)[] **join**(RoR, R)(RoR ror, scope R sep)  
 Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)));   
  
ElementEncodingType!(ElementType!RoR)[] **join**(RoR, E)(RoR ror, scope E sep)  
 Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && (is(E : ElementType!(ElementType!RoR)) || !autodecodeStrings && isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!E));   
  
ElementEncodingType!(ElementType!RoR)[] **join**(RoR)(RoR ror)  
 Constraints: if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR))); 
 
Eagerly concatenates all of the ranges in `ror` together (with the GC) into one array using `sep` as the separator if present. 



Parameters:


|  |  |
| --- | --- |
| RoR `ror` | An [input range](std_range_primitives#isInputRange) of input ranges |
| R `sep` | An input range, or a single element, to join the ranges on |


 
Returns:
An array of elements 
 
See Also:
For a lazy version, see [`std.algorithm.iteration.joiner`](std_algorithm_iteration#joiner)

 
Examples:


```
writeln(join(["hello", "silly", "world"], " ")); // "hello silly world"
writeln(join(["hello", "silly", "world"])); // "hellosillyworld"

writeln(join([[1, 2, 3], [4, 5]], [72, 73])); // [1, 2, 3, 72, 73, 4, 5]
writeln(join([[1, 2, 3], [4, 5]])); // [1, 2, 3, 4, 5]

const string[] arr = ["apple", "banana"];
writeln(arr.join(",")); // "apple,banana"
writeln(arr.join()); // "applebanana"

```
 
  E[] **replace**(E, R1, R2)(E[] subject, R1 from, R2 to)  
 Constraints: if (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1)); 
 
Replace occurrences of `from` with `to` in `subject` in a new array. 



Parameters:


|  |  |
| --- | --- |
| E[] `subject` | the array to scan |
| R1 `from` | the item to replace |
| R2 `to` | the item to replace all instances of `from` with |


 
Returns:
A new array without changing the contents of `subject`, or the original array if no match is found. 
 
See Also:

[`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace.
 
Examples:


```
writeln("Hello Wörld".replace("o Wö", "o Wo")); // "Hello World"
writeln("Hello Wörld".replace("l", "h")); // "Hehho Wörhd"

```
 
  void **replaceInto**(E, Sink, R1, R2)(Sink sink, E[] subject, R1 from, R2 to)  
 Constraints: if (isOutputRange!(Sink, E) && (isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2) || is(Unqual!E : Unqual!R1))); 
 
Replace occurrences of `from` with `to` in `subject` and output the result into `sink`. 



Parameters:


|  |  |
| --- | --- |
| Sink `sink` | an [output range](std_range_primitives#isOutputRange) |
| E[] `subject` | the array to scan |
| R1 `from` | the item to replace |
| R2 `to` | the item to replace all instances of `from` with |


 
See Also:

[`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace.
 
Examples:


```
auto arr = [1, 2, 3, 4, 5];
auto from = [2, 3];
auto to = [4, 6];
auto sink = appender!(int[])();

replaceInto(sink, arr, from, to);

writeln(sink.data); // [1, 4, 6, 4, 5]

```
 
  T[] **replace**(T, Range)(T[] subject, size\_t from, size\_t to, Range stuff)  
 Constraints: if (isInputRange!Range && (is(ElementType!Range : T) || isSomeString!(T[]) && is(ElementType!Range : dchar))); 
 
Replaces elements from `array` with indices ranging from `from` (inclusive) to `to` (exclusive) with the range `stuff`. 



Parameters:


|  |  |
| --- | --- |
| T[] `subject` | the array to scan |
| size\_t `from` | the starting index |
| size\_t `to` | the ending index |
| Range `stuff` | the items to replace in-between `from` and `to` |


 
Returns:
A new array without changing the contents of `subject`. 
 
See Also:

[`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace.
 
Examples:


```
auto a = [ 1, 2, 3, 4 ];
auto b = a.replace(1, 3, [ 9, 9, 9 ]);
writeln(a); // [1, 2, 3, 4]
writeln(b); // [1, 9, 9, 9, 4]

```
 
  void **replaceInPlace**(T, Range)(ref T[] array, size\_t from, size\_t to, Range stuff)  
 Constraints: if (is(typeof(replace(array, from, to, stuff)))); 
 
Replaces elements from `array` with indices ranging from `from` (inclusive) to `to` (exclusive) with the range `stuff`. Expands or shrinks the array as needed. 



Parameters:


|  |  |
| --- | --- |
| T[] `array` | the array to scan |
| size\_t `from` | the starting index |
| size\_t `to` | the ending index |
| Range `stuff` | the items to replace in-between `from` and `to` |


 
Examples:


```
int[] a = [1, 4, 5];
replaceInPlace(a, 1u, 2u, [2, 3, 4]);
writeln(a); // [1, 2, 3, 4, 5]
replaceInPlace(a, 1u, 2u, cast(int[])[]);
writeln(a); // [1, 3, 4, 5]
replaceInPlace(a, 1u, 3u, a[2 .. 4]);
writeln(a); // [1, 4, 5, 5]

```
 
  E[] **replaceFirst**(E, R1, R2)(E[] subject, R1 from, R2 to)  
 Constraints: if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1])))); 
 
Replaces the first occurrence of `from` with `to` in `subject`. 



Parameters:


|  |  |
| --- | --- |
| E[] `subject` | the array to scan |
| R1 `from` | the item to replace |
| R2 `to` | the item to replace `from` with |


 
Returns:
A new array without changing the contents of `subject`, or the original array if no match is found.
 
Examples:


```
auto a = [1, 2, 2, 3, 4, 5];
auto b = a.replaceFirst([2], [1337]);
writeln(b); // [1, 1337, 2, 3, 4, 5]

auto s = "This is a foo foo list";
auto r = s.replaceFirst("foo", "silly");
writeln(r); // "This is a silly foo list"

```
 
  E[] **replaceLast**(E, R1, R2)(E[] subject, R1 from, R2 to)  
 Constraints: if (isDynamicArray!(E[]) && isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0..1]))) && isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0..1])))); 
 
Replaces the last occurrence of `from` with `to` in `subject`. 



Parameters:


|  |  |
| --- | --- |
| E[] `subject` | the array to scan |
| R1 `from` | the item to replace |
| R2 `to` | the item to replace `from` with |


 
Returns:
A new array without changing the contents of `subject`, or the original array if no match is found.
 
Examples:


```
auto a = [1, 2, 2, 3, 4, 5];
auto b = a.replaceLast([2], [1337]);
writeln(b); // [1, 2, 1337, 3, 4, 5]

auto s = "This is a foo foo list";
auto r = s.replaceLast("foo", "silly");
writeln(r); // "This is a foo silly list"

```
 
  inout(T)[] **replaceSlice**(T)(inout(T)[] s, in T[] slice, in T[] replacement);  
Creates a new array such that the items in `slice` are replaced with the items in `replacement`. `slice` and `replacement` do not need to be the same length. The result will grow or shrink based on the items given. 



Parameters:


|  |  |
| --- | --- |
| inout(T)[] `s` | the base of the new array |
| T[] `slice` | the slice of `s` to be replaced |
| T[] `replacement` | the items to replace `slice` with |


 
Returns:
A new array that is `s` with `slice` replaced by `replacement[]`. 
 
See Also:

[`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) for a lazy replace.
 
Examples:


```
auto a = [1, 2, 3, 4, 5];
auto b = replaceSlice(a, a[1 .. 4], [0, 0, 0]);

writeln(b); // [1, 0, 0, 0, 5]

```
 
  struct **Appender**(A) if (isDynamicArray!A);  
Implements an output range that appends data to an array. This is recommended over `array ~= data` when appending many elements because it is more efficient. `Appender` maintains its own array metadata locally, so it can avoid global locking for each append where [`capacity`](#capacity) is non-zero. 



Parameters:


|  |  |
| --- | --- |
| A | the array type to simulate. |


 
See Also:
[`appender`](#appender)
 
Examples:


```
auto app = appender!string();
string b = "abcdefg";
foreach (char c; b)
    app.put(c);
writeln(app[]); // "abcdefg"

int[] a = [ 1, 2 ];
auto app2 = appender(a);
app2.put(3);
app2.put([ 4, 5, 6 ]);
writeln(app2[]); // [1, 2, 3, 4, 5, 6]

```
 
 
pure nothrow @trusted this(A arr);  
Constructs an `Appender` with a given array. Note that this does not copy the data. If the array has a larger capacity as determined by `arr.capacity`, it will be used by the appender. After initializing an appender on an array, appending to the original array will reallocate.

  void **reserve**(size\_t newCapacity);  
Reserve at least newCapacity elements for appending. Note that more elements may be reserved than requested. If `newCapacity <= capacity`, then nothing is done. 



Parameters:


|  |  |
| --- | --- |
| size\_t `newCapacity` | the capacity the `Appender` should have |


  const pure nothrow @property @safe size\_t **capacity**();  

Returns:
the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate, `0` will be returned.
  inout pure nothrow @property @trusted inout(ElementEncodingType!A)[] **data**();  
Use opSlice() from now on. 



Returns:
The managed array.
  inout pure nothrow @property @trusted inout(ElementEncodingType!A)[] **opSlice**();  

Returns:
The managed array.
  void **put**(U)(U item)  
 Constraints: if (canPutItem!U); 
 
Appends `item` to the managed array. Performs encoding for `char` types if `A` is a differently typed `char` array. 



Parameters:


|  |  |
| --- | --- |
| U `item` | the single item to append |


  void **put**(Range)(Range items)  
 Constraints: if (canPutRange!Range); 
 
Appends an entire range to the managed array. Performs encoding for `char` elements if `A` is a differently typed `char` array. 



Parameters:


|  |  |
| --- | --- |
| Range `items` | the range of items to append |


  template **opOpAssign**(string op : "~") 
Appends to the managed array. 



See Also:
[`Appender.put`](#Appender.put)
  pure nothrow @trusted void **clear**();  
Clears the managed array. This allows the elements of the array to be reused for appending. 



Note
 clear is disabled for immutable or const element types, due to the possibility that `Appender` might overwrite immutable data.
  pure @trusted void **shrinkTo**(size\_t newlength);  
Shrinks the managed array to the given length. 



Throws:

`Exception` if newlength is greater than the current array length. 
 
Note
 shrinkTo is disabled for immutable or const element types.
  const string **toString**()();   
  
const void **toString**(Writer)(ref Writer w, ref scope const std.format.FormatSpec!char fmt)  
 Constraints: if (isOutputRange!(Writer, char)); 
 
Gives a string in the form of `Appender!(A)(data)`. 



Parameters:


|  |  |
| --- | --- |
| Writer `w` | A `char` accepting [output range](std_range_primitives#isOutputRange). |
| std.format.FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which controls how the array is formatted. |


 
Returns:
A `string` if `writer` is not set; `void` otherwise.
    struct **RefAppender**(A) if (isDynamicArray!A);  
A version of [`Appender`](#Appender) that can update an array in-place. It forwards all calls to an underlying appender implementation. Any calls made to the appender also update the pointer to the original array passed in. 



Tip
 Use the `arrayPtr` overload of [`appender`](#appender) for construction with type-inference. 
 
Parameters:


|  |  |
| --- | --- |
| A | The array type to simulate |


 
Examples:


```
int[] a = [1, 2];
auto app2 = appender(&a);
writeln(app2[]); // [1, 2]
writeln(a); // [1, 2]
app2 ~= 3;
app2 ~= [4, 5, 6];
writeln(app2[]); // [1, 2, 3, 4, 5, 6]
writeln(a); // [1, 2, 3, 4, 5, 6]

app2.reserve(5);
assert(app2.capacity >= 5);

```
 
 
this(A\* arr);  
Constructs a `RefAppender` with a given array reference. This does not copy the data. If the array has a larger capacity as determined by `arr.capacity`, it will be used by the appender. 



Note
 Do not use built-in appending (i.e. `~=`) on the original array until you are done with the appender, because subsequent calls to the appender will reallocate the array data without those appends. 
 
Parameters:


|  |  |
| --- | --- |
| A\* `arr` | Pointer to an array. Must not be null. |


  void **opDispatch**(string fn, Args...)(Args args)  
 Constraints: if (\_\_traits(compiles, (Appender!A a) => mixin("a." ~ fn ~ "(args)"))); 
 
Wraps remaining `Appender` methods such as [`put`](#put). 



Parameters:


|  |  |
| --- | --- |
| fn | Method name to call. |
| Args `args` | Arguments to pass to the method. |


  void **opOpAssign**(string op : "~", U)(U rhs)  
 Constraints: if (\_\_traits(compiles, (Appender!A a) { a.put(rhs); } )); 
 
Appends `rhs` to the managed array. 



Parameters:


|  |  |
| --- | --- |
| U `rhs` | Element or range. |


  const @property size\_t **capacity**();  
Returns the capacity of the array (the maximum number of elements the managed array can accommodate before triggering a reallocation). If any appending will reallocate, `capacity` returns `0`.

  inout @property inout(ElementEncodingType!A)[] **opSlice**();  

Returns:
the managed array.
    Appender!A **appender**(A)()  
 Constraints: if (isDynamicArray!A);   
  
Appender!(E[]) **appender**(A : E[], E)(auto ref A array);  
Convenience function that returns an [`Appender`](#Appender) instance, optionally initialized with `array`.



Examples:


```
auto w = appender!string;
// pre-allocate space for at least 10 elements (this avoids costly reallocations)
w.reserve(10);
assert(w.capacity >= 10);

w.put('a'); // single elements
w.put("bc"); // multiple elements

// use the append syntax
w ~= 'd';
w ~= "ef";

writeln(w[]); // "abcdef"

```
 
  RefAppender!(E[]) **appender**(P : E[]\*, E)(P arrayPtr);  
Convenience function that returns a [`RefAppender`](#RefAppender) instance initialized with `arrayPtr`. Don't use null for the array pointer, use the other version of `appender` instead.



Examples:


```
int[] a = [1, 2];
auto app2 = appender(&a);
writeln(app2[]); // [1, 2]
writeln(a); // [1, 2]
app2 ~= 3;
app2 ~= [4, 5, 6];
writeln(app2[]); // [1, 2, 3, 4, 5, 6]
writeln(a); // [1, 2, 3, 4, 5, 6]

app2.reserve(5);
assert(app2.capacity >= 5);

```
 
  T[n] **staticArray**(T, size\_t n)(auto ref T[n] a);   
  
auto **staticArray**(size\_t n, T)(scope T a)  
 Constraints: if (isInputRange!T);   
  
auto **staticArray**(size\_t n, T)(scope T a, out size\_t rangeLength)  
 Constraints: if (isInputRange!T);   
  
auto **staticArray**(Un : U[n], U, size\_t n, T)(scope T a)  
 Constraints: if (isInputRange!T && is(ElementType!T : U));   
  
auto **staticArray**(Un : U[n], U, size\_t n, T)(scope T a, out size\_t rangeLength)  
 Constraints: if (isInputRange!T && is(ElementType!T : U));   
  
auto **staticArray**(alias a)()  
 Constraints: if (isInputRange!(typeof(a)));   
  
auto **staticArray**(U, alias a)()  
 Constraints: if (isInputRange!(typeof(a))); 
 
Constructs a static array from `a`. The type of elements can be specified implicitly so that `[1, 2].staticArray` results in `int[2]`, or explicitly, e.g. `[1, 2].staticArray!float` returns `float[2]`. When `a` is a range whose length is not known at compile time, the number of elements must be given as template argument (e.g. `myrange.staticArray!2`). Size and type can be combined, if the source range elements are implicitly convertible to the requested element type (eg: `2.iota.staticArray!(long[2])`). When the range `a` is known at compile time, it can also be specified as a template argument to avoid having to specify the number of elements (e.g.: `staticArray!(2.iota)` or `staticArray!(double, 2.iota)`). 



Note
 `staticArray` returns by value, so expressions involving large arrays may be inefficient. 
 
Parameters:


|  |  |
| --- | --- |
| T[n] `a` | The input elements. If there are less elements than the specified length of the static array, the rest of it is default-initialized. If there are more than specified, the first elements up to the specified length are used. |
| size\_t `rangeLength` | outputs the number of elements used from `a` to it. Optional. |


 
Returns:
A static array constructed from `a`.
 
Examples:
static array from array literal 
```
auto a = [0, 1].staticArray;
static assert(is(typeof(a) == int[2]));
writeln(a); // [0, 1]

```
 
 
Examples:
static array from range + size 
```
import std.range : iota;

auto input = 3.iota;
auto a = input.staticArray!2;
static assert(is(typeof(a) == int[2]));
writeln(a); // [0, 1]
auto b = input.staticArray!(long[4]);
static assert(is(typeof(b) == long[4]));
writeln(b); // [0, 1, 2, 0]

```
 
 
Examples:
static array from CT range 
```
import std.range : iota;

enum a = staticArray!(2.iota);
static assert(is(typeof(a) == int[2]));
writeln(a); // [0, 1]

enum b = staticArray!(long, 2.iota);
static assert(is(typeof(b) == long[2]));
writeln(b); // [0, 1]

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_array.html>

std.concurrency
===============

 This is a low-level messaging API upon which more structured or restrictive APIs may be built. The general idea is that every messageable entity is represented by a common handle type called a Tid, which allows messages to be sent to logical threads that are executing in both the current process and in external processes using the same interface. This is an important aspect of scalability because it allows the components of a program to be spread across available resources with few to no changes to the actual implementation. 


A logical thread is an execution context that has its own stack and which runs asynchronously to other logical threads. These may be preemptively scheduled kernel threads, fibers (cooperative user-space threads), or some other concept with similar behavior.   
  
 The type of concurrency used when logical threads are created is determined by the Scheduler selected at initialization time. The default behavior is currently to create a new kernel thread per call to spawn, but other schedulers are available that multiplex fibers across the main thread or use some combination of the two approaches. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Sean Kelly, Alex Rønne Petersen, Martin Nowak 
 
Source
 [std/concurrency.d](https://github.com/dlang/phobos/blob/master/std/concurrency.d)

 
Examples:


```
__gshared string received;
static void spawnedFunc(Tid ownerTid)
{
    import std.conv : text;
    // Receive a message from the owner thread.
    receive((int i){
        received = text("Received the number ", i);

        // Send a message back to the owner thread
        // indicating success.
        send(ownerTid, true);
    });
}

// Start spawnedFunc in a new thread.
auto childTid = spawn(&spawnedFunc, thisTid);

// Send the number 42 to this new thread.
send(childTid, 42);

// Receive the result code.
auto wasSuccessful = receiveOnly!(bool);
assert(wasSuccessful);
writeln(received); // "Received the number 42"

```
 
 
class **MessageMismatch**: object.Exception;  
Thrown on calls to `receiveOnly` if a message other than the type the receiving thread expected is sent.

 
pure nothrow @nogc @safe this(string msg = "Unexpected message type");    class **OwnerTerminated**: object.Exception;  
Thrown on calls to `receive` if the thread that spawned the receiving thread has terminated and no more messages exist.

 
pure nothrow @nogc @safe this(Tid t, string msg = "Owner terminated");    class **LinkTerminated**: object.Exception;  
Thrown if a linked thread has terminated.

 
pure nothrow @nogc @safe this(Tid t, string msg = "Link terminated");    class **PriorityMessageException**: object.Exception;  
Thrown if a message was sent to a thread via [`std.concurrency.prioritySend`](std_concurrency#prioritySend) and the receiver does not have a handler for a message of this type.

 
this(Variant vals);  Variant **message**;  
The message that was sent.

    class **MailboxFull**: object.Exception;  
Thrown on mailbox crowding if the mailbox is configured with `OnCrowding.throwException`.

 
pure nothrow @nogc @safe this(Tid t, string msg = "Mailbox full");    class **TidMissingException**: object.Exception;  
Thrown when a Tid is missing, e.g. when `ownerTid` doesn't find an owner thread.

  struct **Tid**;  
An opaque type used to represent a logical thread.

 
void **toString**(scope void delegate(const(char)[]) sink);  
Generate a convenient string for identifying this Tid. This is only useful to see if Tid's that are currently executing are the same or different, e.g. for logging and debugging. It is potentially possible that a Tid executed in the future will have the same toString() output as another Tid that has already terminated.

    @property @safe Tid **thisTid**();  

Returns:
The [`Tid`](#Tid) of the caller's thread.
  @property Tid **ownerTid**();  
Return the Tid of the thread which spawned the caller's thread. 



Throws:
A `TidMissingException` exception if there is no owner thread.
  Tid **spawn**(F, T...)(F fn, T args)  
 Constraints: if (isSpawnable!(F, T)); 
 
Starts fn(args) in a new logical thread. 


Executes the supplied function in a new logical thread represented by `Tid`. The calling thread is designated as the owner of the new thread. When the owner thread terminates an `OwnerTerminated` message will be sent to the new thread, causing an `OwnerTerminated` exception to be thrown on `receive()`. 

 
Parameters:


|  |  |
| --- | --- |
| F `fn` | The function to execute. |
| T `args` | Arguments to the function. |


 
Returns:
A Tid representing the new logical thread. 
 
Notes
 `args` must not have unshared aliasing. In other words, all arguments to `fn` must either be `shared` or `immutable` or have no pointer indirection. This is necessary for enforcing isolation among threads.
 
Examples:


```
static void f(string msg)
{
    writeln(msg); // "Hello World"
}

auto tid = spawn(&f, "Hello World");

```
 
 
Examples:
Fails: char[] has mutable aliasing. 
```
string msg = "Hello, World!";

static void f1(string msg) {}
static assert(!__traits(compiles, spawn(&f1, msg.dup)));
static assert( __traits(compiles, spawn(&f1, msg.idup)));

static void f2(char[] msg) {}
static assert(!__traits(compiles, spawn(&f2, msg.dup)));
static assert(!__traits(compiles, spawn(&f2, msg.idup)));

```
 
 
Examples:
New thread with anonymous function 
```
spawn({
    ownerTid.send("This is so great!");
});
writeln(receiveOnly!string); // "This is so great!"

```
 
  Tid **spawnLinked**(F, T...)(F fn, T args)  
 Constraints: if (isSpawnable!(F, T)); 
 
Starts fn(args) in a logical thread and will receive a LinkTerminated message when the operation terminates. 


Executes the supplied function in a new logical thread represented by Tid. This new thread is linked to the calling thread so that if either it or the calling thread terminates a LinkTerminated message will be sent to the other, causing a LinkTerminated exception to be thrown on receive(). The owner relationship from spawn() is preserved as well, so if the link between threads is broken, owner termination will still result in an OwnerTerminated exception to be thrown on receive(). 

 
Parameters:


|  |  |
| --- | --- |
| F `fn` | The function to execute. |
| T `args` | Arguments to the function. |


 
Returns:
A Tid representing the new thread.
  void **send**(T...)(Tid tid, T vals);  
Places the values as a message at the back of tid's message queue. 


Sends the supplied value to the thread represented by tid. As with [`std.concurrency.spawn`](std_concurrency#spawn), `T` must not have unshared aliasing.

  void **prioritySend**(T...)(Tid tid, T vals);  
Places the values as a message on the front of tid's message queue. 


Send a message to `tid` but place it at the front of `tid`'s message queue instead of at the back. This function is typically used for out-of-band communication, to signal exceptional conditions, etc.

  void **receive**(T...)(T ops);  
Receives a message from another thread. 


Receive a message from another thread, or block if no messages of the specified types are available. This function works by pattern matching a message against a set of delegates and executing the first match found.   
  
 If a delegate that accepts a [`std.variant.Variant`](std_variant#Variant) is included as the last argument to `receive`, it will match any message that was not matched by an earlier delegate. If more than one argument is sent, the `Variant` will contain a [`std.typecons.Tuple`](std_typecons#Tuple) of all values sent. 

 
Parameters:


|  |  |
| --- | --- |
| T `ops` | Variadic list of function pointers and delegates. Entries in this list must not occlude later entries. |


 
Throws:

[`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated.
 
Examples:


```
import std.variant : Variant;

auto process = ()
{
    receive(
        (int i) { ownerTid.send(1); },
        (double f) { ownerTid.send(2); },
        (Variant v) { ownerTid.send(3); }
    );
};

{
    auto tid = spawn(process);
    send(tid, 42);
    writeln(receiveOnly!int); // 1
}

{
    auto tid = spawn(process);
    send(tid, 3.14);
    writeln(receiveOnly!int); // 2
}

{
    auto tid = spawn(process);
    send(tid, "something else");
    writeln(receiveOnly!int); // 3
}

```
 
  receiveOnlyRet!T **receiveOnly**(T...)();  
Receives only messages with arguments of the specified types. 



Parameters:


|  |  |
| --- | --- |
| T | Variadic list of types to be received. |


 
Returns:
The received message. If `T` has more than one entry, the message will be packed into a [`std.typecons.Tuple`](std_typecons#Tuple). 
 
Throws:

[`MessageMismatch`](#MessageMismatch) if a message of types other than `T` is received, [`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated.
 
Examples:


```
auto tid = spawn(
{
    assert(receiveOnly!int == 42);
});
send(tid, 42);

```
 
 
Examples:


```
auto tid = spawn(
{
    assert(receiveOnly!string == "text");
});
send(tid, "text");

```
 
 
Examples:


```
struct Record { string name; int age; }

auto tid = spawn(
{
    auto msg = receiveOnly!(double, Record);
    assert(msg[0] == 0.5);
    assert(msg[1].name == "Alice");
    assert(msg[1].age == 31);
});

send(tid, 0.5, Record("Alice", 31));

```
 
  bool **receiveTimeout**(T...)(Duration duration, T ops);  
Receives a message from another thread and gives up if no match arrives within a specified duration. 


Receive a message from another thread, or block until `duration` exceeds, if no messages of the specified types are available. This function works by pattern matching a message against a set of delegates and executing the first match found.   
  
 If a delegate that accepts a [`std.variant.Variant`](std_variant#Variant) is included as the last argument, it will match any message that was not matched by an earlier delegate. If more than one argument is sent, the `Variant` will contain a [`std.typecons.Tuple`](std_typecons#Tuple) of all values sent. 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | Duration, how long to wait. If `duration` is negative, won't wait at all. |
| T `ops` | Variadic list of function pointers and delegates. Entries in this list must not occlude later entries. |


 
Returns:

`true` if it received a message and `false` if it timed out waiting for one. 
 
Throws:

[`OwnerTerminated`](#OwnerTerminated) when the sending thread was terminated.
  enum **OnCrowding**: int;  
These behaviors may be specified when a mailbox is full.

 
**block** 
Wait until room is available.

  **throwException** 
Throw a MailboxFull exception.

  **ignore** 
Abort the send and return.

    pure @safe void **setMaxMailboxSize**(Tid tid, size\_t messages, OnCrowding doThis);  
Sets a maximum mailbox size. 


Sets a limit on the maximum number of user messages allowed in the mailbox. If this limit is reached, the caller attempting to add a new message will execute the behavior specified by doThis. If messages is zero, the mailbox is unbounded. 

 
Parameters:


|  |  |
| --- | --- |
| Tid `tid` | The Tid of the thread for which this limit should be set. |
| size\_t `messages` | The maximum number of messages or zero if no limit. |
| OnCrowding `doThis` | The behavior executed when a message is sent to a full mailbox. |


  void **setMaxMailboxSize**(Tid tid, size\_t messages, bool function(Tid) onCrowdingDoThis);  
Sets a maximum mailbox size. 


Sets a limit on the maximum number of user messages allowed in the mailbox. If this limit is reached, the caller attempting to add a new message will execute onCrowdingDoThis. If messages is zero, the mailbox is unbounded. 

 
Parameters:


|  |  |
| --- | --- |
| Tid `tid` | The Tid of the thread for which this limit should be set. |
| size\_t `messages` | The maximum number of messages or zero if no limit. |
| bool function(Tid) `onCrowdingDoThis` | The routine called when a message is sent to a full mailbox. |


  bool **register**(string name, Tid tid);  
Associates name with tid. 


Associates name with tid in a process-local map. When the thread represented by tid terminates, any names associated with it will be automatically unregistered. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | The name to associate with tid. |
| Tid `tid` | The tid register by name. |


 
Returns:
true if the name is available and tid is not known to represent a defunct thread.
  bool **unregister**(string name);  
Removes the registered name associated with a tid. 



Parameters:


|  |  |
| --- | --- |
| string `name` | The name to unregister. |


 
Returns:
true if the name is registered, false if not.
  Tid **locate**(string name);  
Gets the Tid associated with name. 



Parameters:


|  |  |
| --- | --- |
| string `name` | The name to locate within the registry. |


 
Returns:
The associated Tid or Tid.init if name is not registered.
  struct **ThreadInfo**;  
Encapsulates all implementation-level data needed for scheduling. 


When defining a Scheduler, an instance of this struct must be associated with each logical thread. It contains all implementation-level information needed by the internal API.

 
static nothrow @property ref auto **thisInfo**();  
Gets a thread-local instance of ThreadInfo. 


Gets a thread-local instance of ThreadInfo, which should be used as the default instance when info is requested for a thread not created by the Scheduler.

  void **cleanup**();  
Cleans up this ThreadInfo. 


This must be called when a scheduled thread terminates. It tears down the messaging system for the thread and notifies interested parties of the thread's termination.

    interface **Scheduler**;  
A Scheduler controls how threading is performed by spawn. 


Implementing a Scheduler allows the concurrency mechanism used by this module to be customized according to different needs. By default, a call to spawn will create a new kernel thread that executes the supplied routine and terminates when finished. But it is possible to create Schedulers that reuse threads, that multiplex Fibers (coroutines) across a single thread, or any number of other approaches. By making the choice of Scheduler a user-level option, std.concurrency may be used for far more types of application than if this behavior were predefined. 

 
Example


```
import std.concurrency;
import std.stdio;

void main()
{
    scheduler = new FiberScheduler;
    scheduler.start(
    {
        writeln("the rest of main goes here");
    });
}

```
 Some schedulers have a dispatching loop that must run if they are to work properly, so for the sake of consistency, when using a scheduler, start() must be called within main(). This yields control to the scheduler and will ensure that any spawned threads are executed in an expected manner. 
abstract void **start**(void delegate() op);  
Spawns the supplied op and starts the Scheduler. 


This is intended to be called at the start of the program to yield all scheduling to the active Scheduler instance. This is necessary for schedulers that explicitly dispatch threads rather than simply relying on the operating system to do so, and so start should always be called within main() to begin normal program execution. 

 
Parameters:


|  |  |
| --- | --- |
| void delegate() `op` | A wrapper for whatever the main thread would have done in the absence of a custom scheduler. It will be automatically executed via a call to spawn by the Scheduler. |


  abstract void **spawn**(void delegate() op);  
Assigns a logical thread to execute the supplied op. 


This routine is called by spawn. It is expected to instantiate a new logical thread and run the supplied operation. This thread must call thisInfo.cleanup() when the thread terminates if the scheduled thread is not a kernel thread--all kernel threads will have their ThreadInfo cleaned up automatically by a thread-local destructor. 

 
Parameters:


|  |  |
| --- | --- |
| void delegate() `op` | The function to execute. This may be the actual function passed by the user to spawn itself, or may be a wrapper function. |


  abstract nothrow void **yield**();  
Yields execution to another logical thread. 


This routine is called at various points within concurrency-aware APIs to provide a scheduler a chance to yield execution when using some sort of cooperative multithreading model. If this is not appropriate, such as when each logical thread is backed by a dedicated kernel thread, this routine may be a no-op.

  abstract nothrow @property ref ThreadInfo **thisInfo**();  
Returns an appropriate ThreadInfo instance. 


Returns an instance of ThreadInfo specific to the logical thread that is calling this routine or, if the calling thread was not create by this scheduler, returns ThreadInfo.thisInfo instead.

  abstract nothrow Condition **newCondition**(Mutex m);  
Creates a Condition variable analog for signaling. 


Creates a new Condition variable analog which is used to check for and to signal the addition of messages to a thread's message queue. Like yield, some schedulers may need to define custom behavior so that calls to Condition.wait() yield to another thread when no new messages are available instead of blocking. 

 
Parameters:


|  |  |
| --- | --- |
| Mutex `m` | The Mutex that will be associated with this condition. It will be locked prior to any operation on the condition, and so in some cases a Scheduler may need to hold this reference and unlock the mutex before yielding execution to another logical thread. |


    class **ThreadScheduler**: std.concurrency.Scheduler;  
An example Scheduler using kernel threads. 


This is an example Scheduler that mirrors the default scheduling behavior of creating one kernel thread per call to spawn. It is fully functional and may be instantiated and used, but is not a necessary part of the default functioning of this module.

 
void **start**(void delegate() op);  
This simply runs op directly, since no real scheduling is needed by this approach.

  void **spawn**(void delegate() op);  
Creates a new kernel thread and assigns it to run the supplied op.

  nothrow void **yield**();  
This scheduler does no explicit multiplexing, so this is a no-op.

  nothrow @property ref ThreadInfo **thisInfo**();  
Returns ThreadInfo.thisInfo, since it is a thread-local instance of ThreadInfo, which is the correct behavior for this scheduler.

  nothrow Condition **newCondition**(Mutex m);  
Creates a new Condition variable. No custom behavior is needed here.

    class **FiberScheduler**: std.concurrency.Scheduler;  
An example Scheduler using Fibers. 


This is an example scheduler that creates a new Fiber per call to spawn and multiplexes the execution of all fibers within the main thread.

 
void **start**(void delegate() op);  
This creates a new Fiber for the supplied op and then starts the dispatcher.

  nothrow void **spawn**(void delegate() op);  
This created a new Fiber for the supplied op and adds it to the dispatch list.

  nothrow void **yield**();  
If the caller is a scheduled Fiber, this yields execution to another scheduled Fiber.

  nothrow @property ref ThreadInfo **thisInfo**();  
Returns an appropriate ThreadInfo instance. 


Returns a ThreadInfo instance specific to the calling Fiber if the Fiber was created by this dispatcher, otherwise it returns ThreadInfo.thisInfo.

  nothrow Condition **newCondition**(Mutex m);  
Returns a Condition analog that yields when wait or notify is called. 



Bug
 For the default implementation, `notifyAll`will behave like `notify`. 
 
Parameters:


|  |  |
| --- | --- |
| Mutex `m` | A `Mutex` to use for locking if the condition needs to be waited on or notified from multiple `Thread`s. If `null`, no `Mutex` will be used and it is assumed that the `Condition` is only waited on/notified from one `Thread`. |


  protected nothrow void **create**(void delegate() op);  
Creates a new Fiber which calls the given delegate. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `op` | The delegate the fiber should call |


  class **InfoFiber**: core.thread.fiber.Fiber;  
Fiber which embeds a ThreadInfo

    Scheduler **scheduler**;  
Sets the Scheduler behavior within the program. 


This variable sets the Scheduler behavior within this program. Typically, when setting a Scheduler, scheduler.start() should be called in main. This routine will not return until program execution is complete.

  nothrow void **yield**();  
If the caller is a Fiber and is not a Generator, this function will call scheduler.yield() or Fiber.yield(), as appropriate.

  class **Generator**(T): Fiber, IsGenerator, InputRange!T;  
A Generator is a Fiber that periodically returns values of type T to the caller via yield. This is represented as an InputRange.



Examples:


```
auto tid = spawn({
    int i;
    while (i < 9)
        i = receiveOnly!int;

    ownerTid.send(i * 2);
});

auto r = new Generator!int({
    foreach (i; 1 .. 10)
        yield(i);
});

foreach (e; r)
    tid.send(e);

writeln(receiveOnly!int); // 18

```
 
 
this(void function() fn);  
Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void function() `fn` | The fiber function. |


 
In
 fn must not be null.
  this(void function() fn, size\_t sz);  
Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void function() `fn` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |


 
In
 fn must not be null.
  this(void function() fn, size\_t sz, size\_t guardPageSize);  
Initializes a generator object which is associated with a static D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void function() `fn` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |
| size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Refer to [`core.thread.Fiber`](core_thread#Fiber)'s documentation for more details. |


 
In
 fn must not be null.
  this(void delegate() dg);  
Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `dg` | The fiber function. |


 
In
 dg must not be null.
  this(void delegate() dg, size\_t sz);  
Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `dg` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |


 
In
 dg must not be null.
  this(void delegate() dg, size\_t sz, size\_t guardPageSize);  
Initializes a generator object which is associated with a dynamic D function. The function will be called once to prepare the range for iteration. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `dg` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |
| size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Refer to [`core.thread.Fiber`](core_thread#Fiber)'s documentation for more details. |


 
In
 dg must not be null.
  final @property bool **empty**();  
Returns true if the generator is empty.

  final void **popFront**();  
Obtains the next value from the underlying function.

  final @property T **front**();  
Returns the most recently generated value by shallow copy.

  final T **moveFront**();  
Returns the most recently generated value without executing a copy contructor. Will not compile for element types defining a postblit, because Generator does not return by reference.

    void **yield**(T)(ref T value);   
  
void **yield**(T)(T value);  
Yields a value of type T to the caller of the currently executing generator. 



Parameters:


|  |  |
| --- | --- |
| T `value` | The value to yield. |


 
Examples:


```
import std.range;

InputRange!int myIota = iota(10).inputRangeObject;

myIota.popFront();
myIota.popFront();
writeln(myIota.moveFront); // 2
writeln(myIota.front); // 2
myIota.popFront();
writeln(myIota.front); // 3

//can be assigned to std.range.interfaces.InputRange directly
myIota = new Generator!int(
{
    foreach (i; 0 .. 10) yield(i);
});

myIota.popFront();
myIota.popFront();
writeln(myIota.moveFront); // 2
writeln(myIota.front); // 2
myIota.popFront();
writeln(myIota.front); // 3

size_t[2] counter = [0, 0];
foreach (i, unused; myIota) counter[] += [1, i];

assert(myIota.empty);
writeln(counter); // [7, 21]

```
 
  ref auto **initOnce**(alias var)(lazy typeof(var) init);  
Initializes var with the lazy init value in a thread-safe manner. 


The implementation guarantees that all threads simultaneously calling initOnce with the same var argument block until var is fully initialized. All side-effects of init are globally visible afterwards. 

 
Parameters:


|  |  |
| --- | --- |
| var | The variable to initialize |
| typeof(var) `init` | The lazy initializer value |


 
Returns:
A reference to the initialized variable
 
Examples:
A typical use-case is to perform lazy but thread-safe initialization. 
```
static class MySingleton
{
    static MySingleton instance()
    {
        __gshared MySingleton inst;
        return initOnce!inst(new MySingleton);
    }
}

assert(MySingleton.instance !is null);

```
 
  ref auto **initOnce**(alias var)(lazy typeof(var) init, shared Mutex mutex);   
  
ref auto **initOnce**(alias var)(lazy typeof(var) init, Mutex mutex);  
Same as above, but takes a separate mutex instead of sharing one among all initOnce instances. 


This should be used to avoid dead-locks when the init expression waits for the result of another thread that might also call initOnce. Use with care. 

 
Parameters:


|  |  |
| --- | --- |
| var | The variable to initialize |
| typeof(var) `init` | The lazy initializer value |
| Mutex `mutex` | A mutex to prevent race conditions |


 
Returns:
A reference to the initialized variable
 
Examples:
Use a separate mutex when init blocks on another thread that might also call initOnce. 
```
import core.sync.mutex : Mutex;

static shared bool varA, varB;
static shared Mutex m;
m = new shared Mutex;

spawn({
    // use a different mutex for varB to avoid a dead-lock
    initOnce!varB(true, m);
    ownerTid.send(true);
});
// init depends on the result of the spawned thread
initOnce!varA(receiveOnly!bool);
writeln(varA); // true
writeln(varB); // true

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_concurrency.html>

std.digest.murmurhash
=====================

 Computes [MurmurHash](https://en.wikipedia.org/wiki/MurmurHash) hashes of arbitrary data. MurmurHash is a non-cryptographic hash function suitable for general hash-based lookup. It is optimized for x86 but can be used on all architectures. 


The current version is MurmurHash3, which yields a 32-bit or 128-bit hash value. The older MurmurHash 1 and 2 are currently not supported.   
  
 MurmurHash3 comes in three flavors, listed in increasing order of throughput: * `MurmurHash3!32` produces a 32-bit value and is optimized for 32-bit architectures
* `MurmurHash3!(128, 32)` produces a 128-bit value and is optimized for 32-bit architectures
* `MurmurHash3!(128, 64)` produces a 128-bit value and is optimized for 64-bit architectures

 

 
Note

* `MurmurHash3!(128, 32)` and `MurmurHash3!(128, 64)` produce different values.
* The current implementation is optimized for little endian architectures. It will exhibit different results on big endian architectures and a slightly less uniform distribution.

 This module conforms to the APIs defined in [`std.digest`](std_digest). This module publicly imports [`std.digest`](std_digest) and can be used as a stand-alone module. 
Source
 [std/digest/murmurhash.d](https://github.com/dlang/phobos/blob/master/std/digest/murmurhash.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Guillaume Chatelet 
 
References
 [Reference implementation](https://github.com/aappleby/smhasher)   
 [Wikipedia](https://en.wikipedia.org/wiki/MurmurHash)

 
struct **MurmurHash3**(uint size, uint opt = size\_t.sizeof == 8 ? 64 : 32);  
Implements the MurmurHash3 functions. You can specify the `size` of the hash in bit. For 128 bit hashes you can specify whether to optimize for 32 or 64 bit architectures. If you don't specify the `opt` value it will select the fastest version of the host platform. 


This hasher is compatible with the `Digest` API: * `void start()`
* `void put(scope const(ubyte)[] data...)`
* `ubyte[Element.sizeof] finish()`

   
  
 It also provides a faster, low level API working with data of size `Element.sizeof`: * `void putElements(scope const(Element[]) elements...)`
* `void putRemainder(scope const(ubyte[]) data...)`
* `void finalize()`
* `Element get()`
* `ubyte[Element.sizeof] getBytes()`


 
Examples:
The convenient digest template allows for quick hashing of any data. 
```
ubyte[4] hashed = digest!(MurmurHash3!32)([1, 2, 3, 4]);
writeln(hashed); // [0, 173, 69, 68]

```
 
 
Examples:
One can also hash ubyte data piecewise by instanciating a hasher and call the 'put' method. 
```
const(ubyte)[] data1 = [1, 2, 3];
const(ubyte)[] data2 = [4, 5, 6, 7];
// The incoming data will be buffered and hashed element by element.
MurmurHash3!32 hasher;
hasher.put(data1);
hasher.put(data2);
// The call to 'finish' ensures:
// - the remaining bits are processed
// - the hash gets finalized
auto hashed = hasher.finish();
writeln(hashed); // [181, 151, 88, 252]

```
 
 
alias **Element** = uint;  
The element type for 32-bit implementation.

  pure nothrow @nogc void **putElement**(uint block);  
Adds a single Element of data without increasing `element_count`. Make sure to increase `element_count` by `Element.sizeof` for each call to `putElement`.

  pure nothrow @nogc void **putRemainder**(scope const(ubyte[]) data...);  
Put remainder bytes. This must be called only once after `putElement` and before `finalize`.

  pure nothrow @nogc void **finalize**();  
Incorporate `element_count` and finalizes the hash.

  pure nothrow @nogc Element **get**();  
Returns the hash as an uint value.

  pure nothrow @nogc ubyte[4] **getBytes**();  
Returns the current hashed value as an ubyte array.

  pure nothrow @nogc void **putElements**(scope const(Element[]) elements...);  
Pushes an array of elements at once. It is more efficient to push as much data as possible in a single call. On platforms that do not support unaligned reads (MIPS or old ARM chips), the compiler may produce slower code to ensure correctness.

  pure nothrow void **put**(scope const(ubyte)[] data...);  
Adds data to the digester. This function can be called many times in a row after start but before finish.

  pure nothrow ubyte[Element.sizeof] **finish**();  
Finalizes the computation of the hash and returns the computed value. Note that `finish` can be called only once and that no subsequent calls to `put` is allowed.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_murmurhash.html>

std.digest.ripemd
=================

 Computes RIPEMD-160 hashes of arbitrary data. RIPEMD-160 hashes are 20 byte quantities that are like a checksum or CRC, but are more robust. 




| Category | Functions |
| --- | --- |
| Template API | [*RIPEMD160*](#RIPEMD160) |
| OOP API | [*RIPEMD160Digest*](#RIPEMD160Digest) |
| Helpers | [*ripemd160Of*](#ripemd160Of) |

  This module conforms to the APIs defined in [`std.digest`](std_digest). To understand the differences between the template and the OOP API, see [`std.digest`](std_digest).   
  
 This module publicly imports `std.digest` and can be used as a stand-alone module. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
CTFE
 Digests do not work in CTFE 
 
Authors:
Kai Nacke   
 The algorithm was designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel.   
 The D implementation is a direct translation of the ANSI C implementation by Antoon Bosselaers. 
 
References

* [The hash function RIPEMD-160](http://homes.esat.kuleuven.be/~bosselae/ripemd160.html)
* [Wikipedia on RIPEMD-160](http://en.wikipedia.org/wiki/RIPEMD-160)

 
Source
 [std/digest/ripemd.d](https://github.com/dlang/phobos/blob/master/std/digest/ripemd.d)

 
Examples:


```
//Template API
import std.digest.md;

ubyte[20] hash = ripemd160Of("abc");
writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC"

//Feeding data
ubyte[1024] data;
RIPEMD160 md;
md.start();
md.put(data[]);
md.start(); //Start again
md.put(data[]);
hash = md.finish();

```
 
 
Examples:


```
//OOP API
import std.digest.md;

auto md = new RIPEMD160Digest();
ubyte[] hash = md.digest("abc");
writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC"

//Feeding data
ubyte[1024] data;
md.put(data[]);
md.reset(); //Start again
md.put(data[]);
hash = md.finish();

```
 
 
struct **RIPEMD160**;  
Template API RIPEMD160 implementation. See `std.digest` for differences between template and OOP API.



Examples:


```
//Simple example, hashing a string using ripemd160Of helper function
ubyte[20] hash = ripemd160Of("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC"

```
 
 
Examples:


```
//Using the basic API
RIPEMD160 hash;
hash.start();
ubyte[1024] data;
//Initialize data here...
hash.put(data);
ubyte[20] result = hash.finish();

```
 
 
Examples:


```
//Let's use the template features:
void doSomething(T)(ref T hash)
if (isDigest!T)
{
    hash.put(cast(ubyte) 0);
}
RIPEMD160 md;
md.start();
doSomething(md);
writeln(toHexString(md.finish())); // "C81B94933420221A7AC004A90242D8B1D3E5070D"

```
 
 
Examples:


```
//Simple example
RIPEMD160 hash;
hash.start();
hash.put(cast(ubyte) 0);
ubyte[20] result = hash.finish();
writeln(toHexString(result)); // "C81B94933420221A7AC004A90242D8B1D3E5070D"

```
 
 
pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] data...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`. 



Example


```
RIPEMD160 dig;
dig.put(cast(ubyte) 0); //single ubyte
dig.put(cast(ubyte) 0, cast(ubyte) 0); //variadic
ubyte[10] buf;
dig.put(buf); //buffer

```
  pure nothrow @nogc @safe void **start**();  
Used to (re)initialize the RIPEMD160 digest. 



Note
 For this RIPEMD160 Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. 
 Generic code which deals with different Digest types should always call start though. 
Example


```
RIPEMD160 digest;
//digest.start(); //Not necessary
digest.put(0);

```
  pure nothrow @nogc @trusted ubyte[20] **finish**();  
Returns the finished RIPEMD160 hash. This also calls [`start`](#start) to reset the internal state. 



Example


```
//Simple example
RIPEMD160 hash;
hash.start();
hash.put(cast(ubyte) 0);
ubyte[20] result = hash.finish();
assert(toHexString(result) == "C81B94933420221A7AC004A90242D8B1D3E5070D");

```
    auto **ripemd160Of**(T...)(T data);  
This is a convenience alias for [`std.digest.digest`](std_digest#digest) using the RIPEMD160 implementation.



Examples:


```
ubyte[20] hash = ripemd160Of("abc");
writeln(hash); // digest!RIPEMD160("abc")

```
 
  alias **RIPEMD160Digest** = std.digest.WrapperDigest!(RIPEMD160).WrapperDigest;  
OOP API RIPEMD160 implementation. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!RIPEMD160`, see there for more information.

 
Examples:


```
//Simple example, hashing a string using Digest.digest helper function
auto md = new RIPEMD160Digest();
ubyte[] hash = md.digest("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "8EB208F7E05D987A9B044A8E98C6B087F15A0BFC"

```
 
 
Examples:


```
//Let's use the OOP features:
void test(Digest dig)
{
  dig.put(cast(ubyte) 0);
}
auto md = new RIPEMD160Digest();
test(md);

//Let's use a custom buffer:
ubyte[20] buf;
ubyte[] result = md.finish(buf[]);
writeln(toHexString(result)); // "C81B94933420221A7AC004A90242D8B1D3E5070D"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_ripemd.html>

std.digest.sha
==============

 Computes SHA1 and SHA2 hashes of arbitrary data. SHA hashes are 20 to 64 byte quantities (depending on the SHA algorithm) that are like a checksum or CRC, but are more robust. 




| Category | Functions |
| --- | --- |
| Template API | [*SHA1*](#SHA1) |
| OOP API | [*SHA1Digest*](#SHA1Digest) |
| Helpers | [*sha1Of*](#sha1Of) |

  SHA2 comes in several different versions, all supported by this module: SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256.   
  
 This module conforms to the APIs defined in [`std.digest`](std_digest). To understand the differences between the template and the OOP API, see [`std.digest`](std_digest).   
  
 This module publicly imports `std.digest` and can be used as a stand-alone module. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
CTFE
 Digests do not work in CTFE 
 
Authors:
The routines and algorithms are derived from the *Secure Hash Signature Standard (SHS) (FIPS PUB 180-2)*.   
 Kai Nacke, Johannes Pfau, Nick Sabalausky 
 
References

* [FIPS PUB180-2](http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf)
* [Fast implementation of SHA1](http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/)
* [Wikipedia article about SHA](http://en.wikipedia.org/wiki/Secure_Hash_Algorithm)

 
Source
 [std/digest/sha.d](https://github.com/dlang/phobos/blob/master/std/digest/sha.d)

 
Examples:


```
//Template API
import std.digest.sha;

ubyte[20] hash1 = sha1Of("abc");
writeln(toHexString(hash1)); // "A9993E364706816ABA3E25717850C26C9CD0D89D"

ubyte[28] hash224 = sha224Of("abc");
writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"

//Feeding data
ubyte[1024] data;
SHA1 sha1;
sha1.start();
sha1.put(data[]);
sha1.start(); //Start again
sha1.put(data[]);
hash1 = sha1.finish();

```
 
 
Examples:


```
//OOP API
import std.digest.sha;

auto sha1 = new SHA1Digest();
ubyte[] hash1 = sha1.digest("abc");
writeln(toHexString(hash1)); // "A9993E364706816ABA3E25717850C26C9CD0D89D"

auto sha224 = new SHA224Digest();
ubyte[] hash224 = sha224.digest("abc");
writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"

//Feeding data
ubyte[1024] data;
sha1.put(data[]);
sha1.reset(); //Start again
sha1.put(data[]);
hash1 = sha1.finish();

```
 
 
struct **SHA**(uint hashBlockSize, uint digestSize);  
Template API SHA1/SHA2 implementation. Supports: SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. 


The hashBlockSize and digestSize are in bits. However, it's likely easier to simply use the convenience aliases: SHA1, SHA224, SHA256, SHA384, SHA512, SHA512\_224 and SHA512\_256.   
  
 See `std.digest` for differences between template and OOP API.

 
Examples:


```
//Simple example, hashing a string using sha1Of helper function
ubyte[20] hash = sha1Of("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "A9993E364706816ABA3E25717850C26C9CD0D89D"

//The same, but using SHA-224
ubyte[28] hash224 = sha224Of("abc");
writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"

```
 
 
Examples:


```
//Using the basic API
SHA1 hash;
hash.start();
ubyte[1024] data;
//Initialize data here...
hash.put(data);
ubyte[20] result = hash.finish();

```
 
 
Examples:


```
//Let's use the template features:
//Note: When passing a SHA1 to a function, it must be passed by reference!
void doSomething(T)(ref T hash)
if (isDigest!T)
{
  hash.put(cast(ubyte) 0);
}
SHA1 sha;
sha.start();
doSomething(sha);
writeln(toHexString(sha.finish())); // "5BA93C9DB0CFF93F52B521D7420E43F6EDA2784F"

```
 
 
pure nothrow @nogc @safe void **start**();  
SHA initialization. Begins an SHA1/SHA2 operation. 



Note
 For this SHA Digest implementation calling start after default construction is not necessary. Calling start is only necessary to reset the Digest. 
 Generic code which deals with different Digest types should always call start though. 
Example


```
SHA1 digest;
//digest.start(); //Not necessary
digest.put(0);

```
  pure nothrow @nogc @trusted void **put**(scope const(ubyte)[] input...);  
Use this to feed the digest with data. Also implements the [`std.range.primitives.isOutputRange`](std_range_primitives#isOutputRange) interface for `ubyte` and `const(ubyte)[]`.

  pure nothrow @nogc @trusted ubyte[digestSize / 8] **finish**();  
Returns the finished SHA hash. This also calls [`start`](#start) to reset the internal state.



Examples:


```
//Simple example
SHA1 hash;
hash.start();
hash.put(cast(ubyte) 0);
ubyte[20] result = hash.finish();

```
 
    alias **SHA1** = SHA!(512u, 160u).SHA;  
SHA alias for SHA-1, hash is ubyte[20]

  alias **SHA224** = SHA!(512u, 224u).SHA;  
SHA alias for SHA-224, hash is ubyte[28]

  alias **SHA256** = SHA!(512u, 256u).SHA;  
SHA alias for SHA-256, hash is ubyte[32]

  alias **SHA384** = SHA!(1024u, 384u).SHA;  
SHA alias for SHA-384, hash is ubyte[48]

  alias **SHA512** = SHA!(1024u, 512u).SHA;  
SHA alias for SHA-512, hash is ubyte[64]

  alias **SHA512\_224** = SHA!(1024u, 224u).SHA;  
SHA alias for SHA-512/224, hash is ubyte[28]

  alias **SHA512\_256** = SHA!(1024u, 256u).SHA;  
SHA alias for SHA-512/256, hash is ubyte[32]

  auto **sha1Of**(T...)(T data);   
  
auto **sha224Of**(T...)(T data);   
  
auto **sha256Of**(T...)(T data);   
  
auto **sha384Of**(T...)(T data);   
  
auto **sha512Of**(T...)(T data);   
  
auto **sha512\_224Of**(T...)(T data);   
  
auto **sha512\_256Of**(T...)(T data);  
These are convenience aliases for [`std.digest.digest`](std_digest#digest) using the SHA implementation.



Examples:


```
ubyte[20] hash = sha1Of("abc");
writeln(hash); // digest!SHA1("abc")

ubyte[28] hash224 = sha224Of("abc");
writeln(hash224); // digest!SHA224("abc")

ubyte[32] hash256 = sha256Of("abc");
writeln(hash256); // digest!SHA256("abc")

ubyte[48] hash384 = sha384Of("abc");
writeln(hash384); // digest!SHA384("abc")

ubyte[64] hash512 = sha512Of("abc");
writeln(hash512); // digest!SHA512("abc")

ubyte[28] hash512_224 = sha512_224Of("abc");
writeln(hash512_224); // digest!SHA512_224("abc")

ubyte[32] hash512_256 = sha512_256Of("abc");
writeln(hash512_256); // digest!SHA512_256("abc")

```
 
  alias **SHA1Digest** = std.digest.WrapperDigest!(SHA!(512u, 160u)).WrapperDigest;   
  
alias **SHA224Digest** = std.digest.WrapperDigest!(SHA!(512u, 224u)).WrapperDigest;   
  
alias **SHA256Digest** = std.digest.WrapperDigest!(SHA!(512u, 256u)).WrapperDigest;   
  
alias **SHA384Digest** = std.digest.WrapperDigest!(SHA!(1024u, 384u)).WrapperDigest;   
  
alias **SHA512Digest** = std.digest.WrapperDigest!(SHA!(1024u, 512u)).WrapperDigest;   
  
alias **SHA512\_224Digest** = std.digest.WrapperDigest!(SHA!(1024u, 224u)).WrapperDigest;   
  
alias **SHA512\_256Digest** = std.digest.WrapperDigest!(SHA!(1024u, 256u)).WrapperDigest;  
OOP API SHA1 and SHA2 implementations. See `std.digest` for differences between template and OOP API. 


This is an alias for `[std.digest.WrapperDigest](std_digest#WrapperDigest)!SHA1`, see there for more information.

 
Examples:


```
//Simple example, hashing a string using Digest.digest helper function
auto sha = new SHA1Digest();
ubyte[] hash = sha.digest("abc");
//Let's get a hash string
writeln(toHexString(hash)); // "A9993E364706816ABA3E25717850C26C9CD0D89D"

//The same, but using SHA-224
auto sha224 = new SHA224Digest();
ubyte[] hash224 = sha224.digest("abc");
//Let's get a hash string
writeln(toHexString(hash224)); // "23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"

```
 
 
Examples:


```
//Let's use the OOP features:
void test(Digest dig)
{
  dig.put(cast(ubyte) 0);
}
auto sha = new SHA1Digest();
test(sha);

//Let's use a custom buffer:
ubyte[20] buf;
ubyte[] result = sha.finish(buf[]);
writeln(toHexString(result)); // "5BA93C9DB0CFF93F52B521D7420E43F6EDA2784F"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_digest_sha.html>

std.datetime.systime
====================

  

| Category | Functions |
| --- | --- |
| Types | [`Clock`](#Clock) [`SysTime`](#SysTime) [`DosFileTime`](#DosFileTime) |
| Conversion | [`parseRFC822DateTime`](#parseRFC822DateTime) [`DosFileTimeToSysTime`](#DosFileTimeToSysTime) [`FILETIMEToStdTime`](#FILETIMEToStdTime) [`FILETIMEToSysTime`](#FILETIMEToSysTime) [`stdTimeToFILETIME`](#stdTimeToFILETIME) [`stdTimeToUnixTime`](#stdTimeToUnixTime) [`SYSTEMTIMEToSysTime`](#SYSTEMTIMEToSysTime) [`SysTimeToDosFileTime`](#SysTimeToDosFileTime) [`SysTimeToFILETIME`](#SysTimeToFILETIME) [`SysTimeToSYSTEMTIME`](#SysTimeToSYSTEMTIME) [`unixTimeToStdTime`](#unixTimeToStdTime) |

 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/datetime/systime.d](https://github.com/dlang/phobos/blob/master/std/datetime/systime.d)

 
class **Clock**;  
Effectively a namespace to make it clear that the methods it contains are getting the time from the system clock. It cannot be instantiated.



Examples:
Get the current time as a [`SysTime`](#SysTime) 
```
import std.datetime.timezone : LocalTime;
SysTime today = Clock.currTime();
assert(today.timezone is LocalTime());

```
 
 
@safe SysTime **currTime**(ClockType clockType = ClockType.normal)(immutable TimeZone tz = LocalTime());  
Returns the current time in the given time zone. 



Parameters:


|  |  |
| --- | --- |
| clockType | The [`core.time.ClockType`](core_time#ClockType) indicates which system clock to use to get the current time. Very few programs need to use anything other than the default. |
| TimeZone `tz` | The time zone for the SysTime that's returned. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if it fails to get the time.
  @property @trusted long **currStdTime**(ClockType clockType = ClockType.normal)();  
Returns the number of hnsecs since midnight, January 1st, 1 A.D. for the current time. 



Parameters:


|  |  |
| --- | --- |
| clockType | The [`core.time.ClockType`](core_time#ClockType) indicates which system clock to use to get the current time. Very few programs need to use anything other than the default. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if it fails to get the time.
    struct **SysTime**;  
`SysTime` is the type used to get the current time from the system or doing anything that involves time zones. Unlike [`std.datetime.date.DateTime`](std_datetime_date#DateTime), the time zone is an integral part of `SysTime` (though for local time applications, time zones can be ignored and it will work, since it defaults to using the local time zone). It holds its internal time in std time (hnsecs since midnight, January 1st, 1 A.D. UTC), so it interfaces well with the system time. However, that means that, unlike [`std.datetime.date.DateTime`](std_datetime_date#DateTime), it is not optimized for calendar-based operations, and getting individual units from it such as years or days is going to involve conversions and be less efficient. 


For calendar-based operations that don't care about time zones, then [`std.datetime.date.DateTime`](std_datetime_date#DateTime) would be the type to use. For system time, use `SysTime`.   
  
 [`Clock.currTime`](#Clock.currTime) will return the current time as a `SysTime`. To convert a `SysTime` to a [`std.datetime.date.Date`](std_datetime_date#Date) or [`std.datetime.date.DateTime`](std_datetime_date#DateTime), simply cast it. To convert a [`std.datetime.date.Date`](std_datetime_date#Date) or [`std.datetime.date.DateTime`](std_datetime_date#DateTime) to a `SysTime`, use `SysTime`'s constructor, and pass in the intended time zone with it (or don't pass in a [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone), and the local time zone will be used). Be aware, however, that converting from a [`std.datetime.date.DateTime`](std_datetime_date#DateTime) to a `SysTime` will not necessarily be 100% accurate due to DST (one hour of the year doesn't exist and another occurs twice). To not risk any conversion errors, keep times as `SysTime`s. Aside from DST though, there shouldn't be any conversion problems.   
  
 For using time zones other than local time or UTC, use [`std.datetime.timezone.PosixTimeZone`](std_datetime_timezone#PosixTimeZone) on Posix systems (or on Windows, if providing the TZ Database files), and use [`std.datetime.timezone.WindowsTimeZone`](std_datetime_timezone#WindowsTimeZone) on Windows systems. The time in `SysTime` is kept internally in hnsecs from midnight, January 1st, 1 A.D. UTC. Conversion error cannot happen when changing the time zone of a `SysTime`. [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) is the [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) class which represents the local time, and `UTC` is the [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) class which represents UTC. `SysTime` uses [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) if no [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) is provided. For more details on time zones, see the documentation for [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone), [`std.datetime.timezone.PosixTimeZone`](std_datetime_timezone#PosixTimeZone), and [`std.datetime.timezone.WindowsTimeZone`](std_datetime_timezone#WindowsTimeZone).   
  
 `SysTime`'s range is from approximately 29,000 B.C. to approximately 29,000 A.D.

 
Examples:


```
import core.time : days, hours, seconds;
import std.datetime.date : DateTime;
import std.datetime.timezone : SimpleTimeZone, UTC;

// make a specific point in time in the UTC timezone
auto st = SysTime(DateTime(2018, 1, 1, 10, 30, 0), UTC());
// make a specific point in time in the New York timezone
auto ny = SysTime(
    DateTime(2018, 1, 1, 10, 30, 0),
    new immutable SimpleTimeZone(-5.hours, "America/New_York")
);

// ISO standard time strings
writeln(st.toISOString()); // "20180101T103000Z"
writeln(st.toISOExtString()); // "2018-01-01T10:30:00Z"

// add two days and 30 seconds
st += 2.days + 30.seconds;
writeln(st.toISOExtString()); // "2018-01-03T10:30:30Z"

```
 
 
nothrow @safe this(DateTime dateTime, immutable TimeZone tz = null);  

Parameters:


|  |  |
| --- | --- |
| DateTime `dateTime` | The [`std.datetime.date.DateTime`](std_datetime_date#DateTime) to use to set this [`SysTime`](#SysTime)'s internal std time. As [`std.datetime.date.DateTime`](std_datetime_date#DateTime) has no concept of time zone, tz is used as its time zone. |
| TimeZone `tz` | The [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) to use for this [`SysTime`](#SysTime). If null, [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) will be used. The given [`std.datetime.date.DateTime`](std_datetime_date#DateTime) is assumed to be in the given time zone. |


  @safe this(DateTime dateTime, Duration fracSecs, immutable TimeZone tz = null);  

Parameters:


|  |  |
| --- | --- |
| DateTime `dateTime` | The [`std.datetime.date.DateTime`](std_datetime_date#DateTime) to use to set this [`SysTime`](#SysTime)'s internal std time. As [`std.datetime.date.DateTime`](std_datetime_date#DateTime) has no concept of time zone, tz is used as its time zone. |
| Duration `fracSecs` | The fractional seconds portion of the time. |
| TimeZone `tz` | The [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) to use for this [`SysTime`](#SysTime). If null, [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) will be used. The given [`std.datetime.date.DateTime`](std_datetime_date#DateTime) is assumed to be in the given time zone. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if `fracSecs` is negative or if it's greater than or equal to one second.
  nothrow @safe this(Date date, immutable TimeZone tz = null);  

Parameters:


|  |  |
| --- | --- |
| Date `date` | The [`std.datetime.date.Date`](std_datetime_date#Date) to use to set this [`SysTime`](#SysTime)'s internal std time. As [`std.datetime.date.Date`](std_datetime_date#Date) has no concept of time zone, tz is used as its time zone. |
| TimeZone `tz` | The [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) to use for this [`SysTime`](#SysTime). If null, [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) will be used. The given [`std.datetime.date.Date`](std_datetime_date#Date) is assumed to be in the given time zone. |


  pure nothrow @safe this(long stdTime, immutable TimeZone tz = null);  

Note
 Whereas the other constructors take in the given date/time, assume that it's in the given time zone, and convert it to hnsecs in UTC since midnight, January 1st, 1 A.D. UTC - i.e. std time - this constructor takes a std time, which is specifically already in UTC, so no conversion takes place. Of course, the various getter properties and functions will use the given time zone's conversion function to convert the results to that time zone, but no conversion of the arguments to this constructor takes place. 
 
Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The number of hnsecs since midnight, January 1st, 1 A.D. UTC. |
| TimeZone `tz` | The [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) to use for this [`SysTime`](#SysTime). If null, [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) will be used. |


  pure nothrow ref scope @safe SysTime **opAssign**()(auto ref const(SysTime) rhs) return;  

Parameters:


|  |  |
| --- | --- |
| const(SysTime) `rhs` | The [`SysTime`](#SysTime) to assign to this one. |


 
Returns:
The `this` of this `SysTime`.
  const pure nothrow scope @safe bool **opEquals**()(auto ref const(SysTime) rhs);  
Checks for equality between this [`SysTime`](#SysTime) and the given [`SysTime`](#SysTime). 


Note that the time zone is ignored. Only the internal std times (which are in UTC) are compared.

  const pure nothrow scope @safe int **opCmp**()(auto ref const(SysTime) rhs);  
Compares this [`SysTime`](#SysTime) with the given [`SysTime`](#SysTime). 


Time zone is irrelevant when comparing [`SysTime`](#SysTime)s. 

 
Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const pure nothrow @nogc scope @safe size\_t **toHash**();  

Returns:
A hash of the [`SysTime`](#SysTime).
  const nothrow @property scope @safe short **year**();  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C.

  @property scope @safe void **year**(int **year**);  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year to set this [`SysTime`](#SysTime)'s year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the new year is not a leap year and the resulting date would be on February 29th.
 
Examples:


```
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).year); // 1999
writeln(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).year); // 2010
writeln(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).year); // -7

```
 
  const @property scope @safe ushort **yearBC**();  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if `isAD` is true.
 
Examples:


```
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(0, 1, 1, 12, 30, 33)).yearBC); // 1
writeln(SysTime(DateTime(-1, 1, 1, 10, 7, 2)).yearBC); // 2
writeln(SysTime(DateTime(-100, 1, 1, 4, 59, 0)).yearBC); // 101

```
 
  @property scope @safe void **yearBC**(int year);  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year B.C. to set this [`SysTime`](#SysTime)'s year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if a non-positive value is given.
  const nothrow @property scope @safe Month **month**();  
Month of a Gregorian Year.



Examples:


```
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).month); // 7
writeln(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).month); // 10
writeln(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).month); // 4

```
 
  @property scope @safe void **month**(Month **month**);  
Month of a Gregorian Year. 



Parameters:


|  |  |
| --- | --- |
| Month `month` | The month to set this [`SysTime`](#SysTime)'s month to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given month is not a valid month.
  const nothrow @property scope @safe ubyte **day**();  
Day of a Gregorian Month.



Examples:


```
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).day); // 6
writeln(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).day); // 4
writeln(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).day); // 5

```
 
  @property scope @safe void **day**(int **day**);  
Day of a Gregorian Month. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the month to set this [`SysTime`](#SysTime)'s day to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given day is not a valid day of the current month.
  const nothrow @property scope @safe ubyte **hour**();  
Hours past midnight.

  @property scope @safe void **hour**(int **hour**);  
Hours past midnight. 



Parameters:


|  |  |
| --- | --- |
| int `hour` | The hours to set this [`SysTime`](#SysTime)'s hour to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given hour are not a valid hour of the day.
  const nothrow @property scope @safe ubyte **minute**();  
Minutes past the current hour.

  @property scope @safe void **minute**(int **minute**);  
Minutes past the current hour. 



Parameters:


|  |  |
| --- | --- |
| int `minute` | The minute to set this [`SysTime`](#SysTime)'s minute to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given minute are not a valid minute of an hour.
  const nothrow @property scope @safe ubyte **second**();  
Seconds past the current minute.

  @property scope @safe void **second**(int **second**);  
Seconds past the current minute. 



Parameters:


|  |  |
| --- | --- |
| int `second` | The second to set this [`SysTime`](#SysTime)'s second to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given second are not a valid second of a minute.
  const nothrow @property scope @safe Duration **fracSecs**();  
Fractional seconds past the second (i.e. the portion of a [`SysTime`](#SysTime) which is less than a second).



Examples:


```
import core.time : msecs, usecs, hnsecs, nsecs;
import std.datetime.date : DateTime;

auto dt = DateTime(1982, 4, 1, 20, 59, 22);
writeln(SysTime(dt, msecs(213)).fracSecs); // msecs(213)
writeln(SysTime(dt, usecs(5202)).fracSecs); // usecs(5202)
writeln(SysTime(dt, hnsecs(1234567)).fracSecs); // hnsecs(1234567)

// SysTime and Duration both have a precision of hnsecs (100 ns),
// so nsecs are going to be truncated.
writeln(SysTime(dt, nsecs(123456789)).fracSecs); // nsecs(123456700)

```
 
  @property scope @safe void **fracSecs**(Duration **fracSecs**);  
Fractional seconds past the second (i.e. the portion of a [`SysTime`](#SysTime) which is less than a second). 



Parameters:


|  |  |
| --- | --- |
| Duration `fracSecs` | The duration to set this [`SysTime`](#SysTime)'s fractional seconds to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given duration is negative or if it's greater than or equal to one second.
 
Examples:


```
import core.time : Duration, msecs, hnsecs, nsecs;
import std.datetime.date : DateTime;

auto st = SysTime(DateTime(1982, 4, 1, 20, 59, 22));
writeln(st.fracSecs); // Duration.zero

st.fracSecs = msecs(213);
writeln(st.fracSecs); // msecs(213)

st.fracSecs = hnsecs(1234567);
writeln(st.fracSecs); // hnsecs(1234567)

// SysTime has a precision of hnsecs (100 ns), so nsecs are
// going to be truncated.
st.fracSecs = nsecs(123456789);
writeln(st.fracSecs); // hnsecs(1234567)

```
 
  const pure nothrow @nogc @property scope @safe long **stdTime**();  
The total hnsecs from midnight, January 1st, 1 A.D. UTC. This is the internal representation of [`SysTime`](#SysTime).

  pure nothrow @property scope @safe void **stdTime**(long **stdTime**);  
The total hnsecs from midnight, January 1st, 1 A.D. UTC. This is the internal representation of [`SysTime`](#SysTime). 



Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The number of hnsecs since January 1st, 1 A.D. UTC. |


  const pure nothrow @property scope @safe immutable(TimeZone) **timezone**();  
The current time zone of this [`SysTime`](#SysTime). Its internal time is always kept in UTC, so there are no conversion issues between time zones due to DST. Functions which return all or part of the time - such as hours - adjust the time to this [`SysTime`](#SysTime)'s time zone before returning.

  pure nothrow @property scope @safe void **timezone**(immutable TimeZone **timezone**);  
The current time zone of this [`SysTime`](#SysTime). It's internal time is always kept in UTC, so there are no conversion issues between time zones due to DST. Functions which return all or part of the time - such as hours - adjust the time to this [`SysTime`](#SysTime)'s time zone before returning. 



Parameters:


|  |  |
| --- | --- |
| TimeZone `timezone` | The [`std.datetime.timezone.TimeZone`](std_datetime_timezone#TimeZone) to set this [`SysTime`](#SysTime)'s time zone to. |


  const nothrow @property scope @safe bool **dstInEffect**();  
Returns whether DST is in effect for this [`SysTime`](#SysTime).

  const nothrow @property scope @safe Duration **utcOffset**();  
Returns what the offset from UTC is for this [`SysTime`](#SysTime). It includes the DST offset in effect at that time (if any).

  const pure nothrow scope @safe SysTime **toLocalTime**();  
Returns a [`SysTime`](#SysTime) with the same std time as this one, but with [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) as its time zone.

  const pure nothrow scope @safe SysTime **toUTC**();  
Returns a [`SysTime`](#SysTime) with the same std time as this one, but with `UTC` as its time zone.

  const pure nothrow scope @safe SysTime **toOtherTZ**(immutable TimeZone tz);  
Returns a [`SysTime`](#SysTime) with the same std time as this one, but with given time zone as its time zone.

  const pure nothrow scope @safe T **toUnixTime**(T = time\_t)()  
 Constraints: if (is(T == int) || is(T == long)); 
 
Converts this [`SysTime`](#SysTime) to unix time (i.e. seconds from midnight, January 1st, 1970 in UTC). 


The C standard does not specify the representation of time\_t, so it is implementation defined. On POSIX systems, unix time is equivalent to time\_t, but that's not necessarily true on other systems (e.g. it is not true for the Digital Mars C runtime). So, be careful when using unix time with C functions on non-POSIX systems.   
  
 By default, the return type is time\_t (which is normally an alias for int on 32-bit systems and long on 64-bit systems), but if a different size is required than either int or long can be passed as a template argument to get the desired size.   
  
 If the return type is int, and the result can't fit in an int, then the closest value that can be held in 32 bits will be used (so `int.max` if it goes over and `int.min` if it goes under). However, no attempt is made to deal with integer overflow if the return type is long. 

 
Parameters:


|  |  |
| --- | --- |
| T | The return type (int or long). It defaults to time\_t, which is normally 32 bits on a 32-bit system and 64 bits on a 64-bit system. |


 
Returns:
A signed integer representing the unix time which is equivalent to this SysTime.
 
Examples:


```
import core.time : hours;
import std.datetime.date : DateTime;
import std.datetime.timezone : SimpleTimeZone, UTC;

writeln(SysTime(DateTime(1970, 1, 1), UTC()).toUnixTime()); // 0

auto pst = new immutable SimpleTimeZone(hours(-8));
writeln(SysTime(DateTime(1970, 1, 1), pst).toUnixTime()); // 28800

auto utc = SysTime(DateTime(2007, 12, 22, 8, 14, 45), UTC());
writeln(utc.toUnixTime()); // 1_198_311_285

auto ca = SysTime(DateTime(2007, 12, 22, 8, 14, 45), pst);
writeln(ca.toUnixTime()); // 1_198_340_085

static void testScope(scope ref SysTime st) @safe
{
    auto result = st.toUnixTime();
}

```
 
  static pure nothrow @safe SysTime **fromUnixTime**(long unixTime, immutable TimeZone tz = LocalTime());  
Converts from unix time (i.e. seconds from midnight, January 1st, 1970 in UTC) to a [`SysTime`](#SysTime). 


The C standard does not specify the representation of time\_t, so it is implementation defined. On POSIX systems, unix time is equivalent to time\_t, but that's not necessarily true on other systems (e.g. it is not true for the Digital Mars C runtime). So, be careful when using unix time with C functions on non-POSIX systems. 

 
Parameters:


|  |  |
| --- | --- |
| long `unixTime` | Seconds from midnight, January 1st, 1970 in UTC. |
| TimeZone `tz` | The time zone for the SysTime that's returned. |


 
Examples:


```
import core.time : hours;
import std.datetime.date : DateTime;
import std.datetime.timezone : SimpleTimeZone, UTC;

assert(SysTime.fromUnixTime(0) ==
       SysTime(DateTime(1970, 1, 1), UTC()));

auto pst = new immutable SimpleTimeZone(hours(-8));
assert(SysTime.fromUnixTime(28800) ==
       SysTime(DateTime(1970, 1, 1), pst));

auto st1 = SysTime.fromUnixTime(1_198_311_285, UTC());
writeln(st1); // SysTime(DateTime(2007, 12, 22, 8, 14, 45), UTC())
assert(st1.timezone is UTC());
writeln(st1); // SysTime(DateTime(2007, 12, 22, 0, 14, 45), pst)

auto st2 = SysTime.fromUnixTime(1_198_311_285, pst);
writeln(st2); // SysTime(DateTime(2007, 12, 22, 8, 14, 45), UTC())
assert(st2.timezone is pst);
writeln(st2); // SysTime(DateTime(2007, 12, 22, 0, 14, 45), pst)

```
 
  const pure nothrow scope @safe timeval **toTimeVal**();  
Returns a `timeval` which represents this [`SysTime`](#SysTime). 


Note that like all conversions in std.datetime, this is a truncating conversion.   
  
 If `timeval.tv_sec` is int, and the result can't fit in an int, then the closest value that can be held in 32 bits will be used for `tv_sec`. (so `int.max` if it goes over and `int.min` if it goes under).

  const pure nothrow scope @safe timespec **toTimeSpec**();  
Returns a `timespec` which represents this [`SysTime`](#SysTime). 


This function is Posix-Only.

  const nothrow scope @safe tm **toTM**();  
Returns a `tm` which represents this [`SysTime`](#SysTime).

  nothrow ref scope @safe SysTime **add**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years" || units == "months"); 
 
Adds the given number of years or months to this [`SysTime`](#SysTime). A negative number will subtract. 


Note that if day overflow is allowed, and the date with the adjusted year/month overflows the number of days in the new month, then the month will be incremented by one, and the day set to the number of days overflowed. (e.g. if the day were 31 and the new month were June, then the month would be incremented to July, and the new day would be 1). If day overflow is not allowed, then the day will be set to the last valid day in the month (e.g. June 31st would become June 30th). 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`SysTime`](#SysTime). |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow, causing the month to increment. |


  nothrow ref scope @safe SysTime **roll**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years"); 
 
Adds the given number of years or months to this [`SysTime`](#SysTime). A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. Rolling a [`SysTime`](#SysTime) 12 months gets the exact same [`SysTime`](#SysTime). However, the days can still be affected due to the differing number of days in each month.   
  
 Because there are no units larger than years, there is no difference between adding and rolling years. 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`SysTime`](#SysTime). |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow, causing the month to increment. |


 
Examples:


```
import std.datetime.date : AllowDayOverflow, DateTime;

auto st1 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st1.roll!"months"(1);
writeln(st1); // SysTime(DateTime(2010, 2, 1, 12, 33, 33))

auto st2 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st2.roll!"months"(-1);
writeln(st2); // SysTime(DateTime(2010, 12, 1, 12, 33, 33))

auto st3 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st3.roll!"months"(1);
writeln(st3); // SysTime(DateTime(1999, 3, 1, 12, 33, 33))

auto st4 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st4.roll!"months"(1, AllowDayOverflow.no);
writeln(st4); // SysTime(DateTime(1999, 2, 28, 12, 33, 33))

auto st5 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st5.roll!"years"(1);
writeln(st5); // SysTime(DateTime(2001, 3, 1, 12, 30, 33))

auto st6 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st6.roll!"years"(1, AllowDayOverflow.no);
writeln(st6); // SysTime(DateTime(2001, 2, 28, 12, 30, 33))

```
 
  nothrow ref scope @safe SysTime **roll**(string units)(long value)  
 Constraints: if (units == "days"); 
 
Adds the given number of units to this [`SysTime`](#SysTime). A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. For instance, rolling a [`SysTime`](#SysTime) one year's worth of days gets the exact same [`SysTime`](#SysTime).   
  
 Accepted units are `"days"`, `"minutes"`, `"hours"`, `"minutes"`, `"seconds"`, `"msecs"`, `"usecs"`, and `"hnsecs"`.   
  
 Note that when rolling msecs, usecs or hnsecs, they all add up to a second. So, for example, rolling 1000 msecs is exactly the same as rolling 100,000 usecs. 

 
Parameters:


|  |  |
| --- | --- |
| units | The units to add. |
| long `value` | The number of units to add to this [`SysTime`](#SysTime). |


 
Examples:


```
import core.time : msecs, hnsecs;
import std.datetime.date : DateTime;

auto st1 = SysTime(DateTime(2010, 1, 1, 11, 23, 12));
st1.roll!"days"(1);
writeln(st1); // SysTime(DateTime(2010, 1, 2, 11, 23, 12))
st1.roll!"days"(365);
writeln(st1); // SysTime(DateTime(2010, 1, 26, 11, 23, 12))
st1.roll!"days"(-32);
writeln(st1); // SysTime(DateTime(2010, 1, 25, 11, 23, 12))

auto st2 = SysTime(DateTime(2010, 7, 4, 12, 0, 0));
st2.roll!"hours"(1);
writeln(st2); // SysTime(DateTime(2010, 7, 4, 13, 0, 0))

auto st3 = SysTime(DateTime(2010, 2, 12, 12, 0, 0));
st3.roll!"hours"(-1);
writeln(st3); // SysTime(DateTime(2010, 2, 12, 11, 0, 0))

auto st4 = SysTime(DateTime(2009, 12, 31, 0, 0, 0));
st4.roll!"minutes"(1);
writeln(st4); // SysTime(DateTime(2009, 12, 31, 0, 1, 0))

auto st5 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st5.roll!"minutes"(-1);
writeln(st5); // SysTime(DateTime(2010, 1, 1, 0, 59, 0))

auto st6 = SysTime(DateTime(2009, 12, 31, 0, 0, 0));
st6.roll!"seconds"(1);
writeln(st6); // SysTime(DateTime(2009, 12, 31, 0, 0, 1))

auto st7 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st7.roll!"seconds"(-1);
writeln(st7); // SysTime(DateTime(2010, 1, 1, 0, 0, 59))

auto dt = DateTime(2010, 1, 1, 0, 0, 0);
auto st8 = SysTime(dt);
st8.roll!"msecs"(1);
writeln(st8); // SysTime(dt, msecs(1))

auto st9 = SysTime(dt);
st9.roll!"msecs"(-1);
writeln(st9); // SysTime(dt, msecs(999))

auto st10 = SysTime(dt);
st10.roll!"hnsecs"(1);
writeln(st10); // SysTime(dt, hnsecs(1))

auto st11 = SysTime(dt);
st11.roll!"hnsecs"(-1);
writeln(st11); // SysTime(dt, hnsecs(9_999_999))

```
 
  const pure nothrow scope @safe SysTime **opBinary**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`SysTime`](#SysTime). 


The legal types of arithmetic for [`SysTime`](#SysTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| SysTime | + | Duration | --> | SysTime |
| SysTime | - | Duration | --> | SysTime |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`SysTime`](#SysTime). |


 
Examples:


```
import core.time : hours, seconds;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(2015, 12, 31, 23, 59, 59)) + seconds(1) ==
       SysTime(DateTime(2016, 1, 1, 0, 0, 0)));

assert(SysTime(DateTime(2015, 12, 31, 23, 59, 59)) + hours(1) ==
       SysTime(DateTime(2016, 1, 1, 0, 59, 59)));

assert(SysTime(DateTime(2016, 1, 1, 0, 0, 0)) - seconds(1) ==
       SysTime(DateTime(2015, 12, 31, 23, 59, 59)));

assert(SysTime(DateTime(2016, 1, 1, 0, 59, 59)) - hours(1) ==
       SysTime(DateTime(2015, 12, 31, 23, 59, 59)));

```
 
  pure nothrow ref scope @safe SysTime **opOpAssign**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`SysTime`](#SysTime), as well as assigning the result to this [`SysTime`](#SysTime). 


The legal types of arithmetic for [`SysTime`](#SysTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| SysTime | + | Duration | --> | SysTime |
| SysTime | - | Duration | --> | SysTime |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`SysTime`](#SysTime). |


  const pure nothrow scope @safe Duration **opBinary**(string op)(SysTime rhs)  
 Constraints: if (op == "-"); 
 
Gives the difference between two [`SysTime`](#SysTime)s. 


The legal types of arithmetic for [`SysTime`](#SysTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| SysTime | - | SysTime | --> | duration |



  const nothrow scope @safe int **diffMonths**(scope SysTime rhs);  
Returns the difference between the two [`SysTime`](#SysTime)s in months. 


To get the difference in years, subtract the year property of two [`SysTime`](#SysTime)s. To get the difference in days or weeks, subtract the [`SysTime`](#SysTime)s themselves and use the [`core.time.Duration`](core_time#Duration) that results. Because converting between months and smaller units requires a specific date (which [`core.time.Duration`](core_time#Duration)s don't have), getting the difference in months requires some math using both the year and month properties, so this is a convenience function for getting the difference in months.   
  
 Note that the number of days in the months or how far into the month either date is is irrelevant. It is the difference in the month property combined with the difference in years \* 12. So, for instance, December 31st and January 1st are one month apart just as December 1st and January 31st are one month apart. 

 
Parameters:


|  |  |
| --- | --- |
| SysTime `rhs` | The [`SysTime`](#SysTime) to subtract from this one. |


 
Examples:


```
import core.time;
import std.datetime.date : Date;

assert(SysTime(Date(1999, 2, 1)).diffMonths(
           SysTime(Date(1999, 1, 31))) == 1);

assert(SysTime(Date(1999, 1, 31)).diffMonths(
           SysTime(Date(1999, 2, 1))) == -1);

assert(SysTime(Date(1999, 3, 1)).diffMonths(
           SysTime(Date(1999, 1, 1))) == 2);

assert(SysTime(Date(1999, 1, 1)).diffMonths(
           SysTime(Date(1999, 3, 31))) == -2);

```
 
  const nothrow @property scope @safe bool **isLeapYear**();  
Whether this [`SysTime`](#SysTime) is in a leap year.

  const nothrow @property scope @safe DayOfWeek **dayOfWeek**();  
Day of the week this [`SysTime`](#SysTime) is on.

  const nothrow @property scope @safe ushort **dayOfYear**();  
Day of the year this [`SysTime`](#SysTime) is on.



Examples:


```
import core.time;
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1999, 1, 1, 12, 22, 7)).dayOfYear); // 1
writeln(SysTime(DateTime(1999, 12, 31, 7, 2, 59)).dayOfYear); // 365
writeln(SysTime(DateTime(2000, 12, 31, 21, 20, 0)).dayOfYear); // 366

```
 
  @property scope @safe void **dayOfYear**(int day);  
Day of the year. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the year to set which day of the year this [`SysTime`](#SysTime) is on. |


  const nothrow @property scope @safe int **dayOfGregorianCal**();  
The Xth day of the Gregorian Calendar that this [`SysTime`](#SysTime) is on.



Examples:


```
import core.time;
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1, 1, 1, 0, 0, 0)).dayOfGregorianCal); // 1
writeln(SysTime(DateTime(1, 12, 31, 23, 59, 59)).dayOfGregorianCal); // 365
writeln(SysTime(DateTime(2, 1, 1, 2, 2, 2)).dayOfGregorianCal); // 366

writeln(SysTime(DateTime(0, 12, 31, 7, 7, 7)).dayOfGregorianCal); // 0
writeln(SysTime(DateTime(0, 1, 1, 19, 30, 0)).dayOfGregorianCal); // -365
writeln(SysTime(DateTime(-1, 12, 31, 4, 7, 0)).dayOfGregorianCal); // -366

writeln(SysTime(DateTime(2000, 1, 1, 9, 30, 20)).dayOfGregorianCal); // 730_120
writeln(SysTime(DateTime(2010, 12, 31, 15, 45, 50)).dayOfGregorianCal); // 734_137

```
 
  nothrow @property scope @safe void **dayOfGregorianCal**(int days);  
The Xth day of the Gregorian Calendar that this [`SysTime`](#SysTime) is on. Setting this property does not affect the time portion of [`SysTime`](#SysTime). 



Parameters:


|  |  |
| --- | --- |
| int `days` | The day of the Gregorian Calendar to set this [`SysTime`](#SysTime) to. |


 
Examples:


```
import core.time;
import std.datetime.date : DateTime;

auto st = SysTime(DateTime(0, 1, 1, 12, 0, 0));
st.dayOfGregorianCal = 1;
writeln(st); // SysTime(DateTime(1, 1, 1, 12, 0, 0))

st.dayOfGregorianCal = 365;
writeln(st); // SysTime(DateTime(1, 12, 31, 12, 0, 0))

st.dayOfGregorianCal = 366;
writeln(st); // SysTime(DateTime(2, 1, 1, 12, 0, 0))

st.dayOfGregorianCal = 0;
writeln(st); // SysTime(DateTime(0, 12, 31, 12, 0, 0))

st.dayOfGregorianCal = -365;
writeln(st); // SysTime(DateTime(-0, 1, 1, 12, 0, 0))

st.dayOfGregorianCal = -366;
writeln(st); // SysTime(DateTime(-1, 12, 31, 12, 0, 0))

st.dayOfGregorianCal = 730_120;
writeln(st); // SysTime(DateTime(2000, 1, 1, 12, 0, 0))

st.dayOfGregorianCal = 734_137;
writeln(st); // SysTime(DateTime(2010, 12, 31, 12, 0, 0))

```
 
  const nothrow @property scope @safe ubyte **isoWeek**();  
The ISO 8601 week of the year that this [`SysTime`](#SysTime) is in. 



See Also:

[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date).
 
Examples:


```
import core.time;
import std.datetime.date : Date;

auto st = SysTime(Date(1999, 7, 6));
const cst = SysTime(Date(2010, 5, 1));
immutable ist = SysTime(Date(2015, 10, 10));

writeln(st.isoWeek); // 27
writeln(cst.isoWeek); // 17
writeln(ist.isoWeek); // 41

```
 
  const nothrow @property scope @safe SysTime **endOfMonth**();  
[`SysTime`](#SysTime) for the last day in the month that this Date is in. The time portion of endOfMonth is always 23:59:59.9999999.



Examples:


```
import core.time : msecs, usecs, hnsecs;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).endOfMonth ==
       SysTime(DateTime(1999, 1, 31, 23, 59, 59), hnsecs(9_999_999)));

assert(SysTime(DateTime(1999, 2, 7, 19, 30, 0), msecs(24)).endOfMonth ==
       SysTime(DateTime(1999, 2, 28, 23, 59, 59), hnsecs(9_999_999)));

assert(SysTime(DateTime(2000, 2, 7, 5, 12, 27), usecs(5203)).endOfMonth ==
       SysTime(DateTime(2000, 2, 29, 23, 59, 59), hnsecs(9_999_999)));

assert(SysTime(DateTime(2000, 6, 4, 12, 22, 9), hnsecs(12345)).endOfMonth ==
       SysTime(DateTime(2000, 6, 30, 23, 59, 59), hnsecs(9_999_999)));

```
 
  const nothrow @property scope @safe ubyte **daysInMonth**();  
The last day in the month that this [`SysTime`](#SysTime) is in.



Examples:


```
import core.time;
import std.datetime.date : DateTime;

writeln(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).daysInMonth); // 31
writeln(SysTime(DateTime(1999, 2, 7, 19, 30, 0)).daysInMonth); // 28
writeln(SysTime(DateTime(2000, 2, 7, 5, 12, 27)).daysInMonth); // 29
writeln(SysTime(DateTime(2000, 6, 4, 12, 22, 9)).daysInMonth); // 30

```
 
  const nothrow @property scope @safe bool **isAD**();  
Whether the current year is a date in A.D.



Examples:


```
import core.time;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(1, 1, 1, 12, 7, 0)).isAD);
assert(SysTime(DateTime(2010, 12, 31, 0, 0, 0)).isAD);
assert(!SysTime(DateTime(0, 12, 31, 23, 59, 59)).isAD);
assert(!SysTime(DateTime(-2010, 1, 1, 2, 2, 2)).isAD);

```
 
  const nothrow @property scope @safe long **julianDay**();  
The [Julian day](http://en.wikipedia.org/wiki/Julian_day) for this [`SysTime`](#SysTime) at the given time. For example, prior to noon, 1996-03-31 would be the Julian day number 2\_450\_173, so this function returns 2\_450\_173, while from noon onward, the Julian day number would be 2\_450\_174, so this function returns 2\_450\_174.

  const nothrow @property scope @safe long **modJulianDay**();  
The modified [Julian day](http://en.wikipedia.org/wiki/Julian_day) for any time on this date (since, the modified Julian day changes at midnight).

  const nothrow scope @safe Date **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(Date))); 
 
Returns a [`std.datetime.date.Date`](std_datetime_date#Date) equivalent to this [`SysTime`](#SysTime).

  const nothrow scope @safe DateTime **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(DateTime))); 
 
Returns a [`std.datetime.date.DateTime`](std_datetime_date#DateTime) equivalent to this [`SysTime`](#SysTime).

  const nothrow scope @safe TimeOfDay **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(TimeOfDay))); 
 
Returns a [`std.datetime.date.TimeOfDay`](std_datetime_date#TimeOfDay) equivalent to this [`SysTime`](#SysTime).

  const nothrow scope @safe string **toISOString**();   
  
const scope void **toISOString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`SysTime`](#SysTime) to a string with the format YYYYMMDDTHHMMSS.FFFFFFFTZ (where F is fractional seconds and TZ is time zone). 


Note that the number of digits in the fractional seconds varies with the number of fractional seconds. It's a maximum of 7 (which would be hnsecs), but only has as many as are necessary to hold the correct value (so no trailing zeroes), and if there are no fractional seconds, then there is no decimal point.   
  
 If this [`SysTime`](#SysTime)'s time zone is [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime), then TZ is empty. If its time zone is `UTC`, then it is "Z". Otherwise, it is the offset from UTC (e.g. +0100 or -0700). Note that the offset from UTC is *not* enough to uniquely identify the time zone.   
  
 Time zone offsets will be in the form +HHMM or -HHMM.   
  
 Warning: Previously, toISOString did the same as [`toISOExtString`](#toISOExtString) and generated +HH:MM or -HH:MM for the time zone when it was not [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) or [`std.datetime.timezone.UTC`](std_datetime_timezone#UTC), which is not in conformance with ISO 8601 for the non-extended string format. This has now been fixed. However, for now, fromISOString will continue to accept the extended format for the time zone so that any code which has been writing out the result of toISOString to read in later will continue to work. The current behavior will be kept until July 2019 at which point, fromISOString will be fixed to be standards compliant. 

 
Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
import core.time : msecs, hnsecs;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOString() ==
       "20100704T070612");

assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0), msecs(24)).toISOString() ==
       "19981225T021500.024");

assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOString() ==
       "00000105T230959");

assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2), hnsecs(520_920)).toISOString() ==
       "-00040105T000002.052092");

```
 
  const nothrow scope @safe string **toISOExtString**();   
  
const scope void **toISOExtString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`SysTime`](#SysTime) to a string with the format YYYY-MM-DDTHH:MM:SS.FFFFFFFTZ (where F is fractional seconds and TZ is the time zone). 


Note that the number of digits in the fractional seconds varies with the number of fractional seconds. It's a maximum of 7 (which would be hnsecs), but only has as many as are necessary to hold the correct value (so no trailing zeroes), and if there are no fractional seconds, then there is no decimal point.   
  
 If this [`SysTime`](#SysTime)'s time zone is [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime), then TZ is empty. If its time zone is `UTC`, then it is "Z". Otherwise, it is the offset from UTC (e.g. +01:00 or -07:00). Note that the offset from UTC is *not* enough to uniquely identify the time zone.   
  
 Time zone offsets will be in the form +HH:MM or -HH:MM. 

 
Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
import core.time : msecs, hnsecs;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOExtString() ==
       "2010-07-04T07:06:12");

assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0), msecs(24)).toISOExtString() ==
       "1998-12-25T02:15:00.024");

assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOExtString() ==
       "0000-01-05T23:09:59");

assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2), hnsecs(520_920)).toISOExtString() ==
       "-0004-01-05T00:00:02.052092");

```
 
  const nothrow scope @safe string **toSimpleString**();   
  
const scope void **toSimpleString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`SysTime`](#SysTime) to a string with the format YYYY-Mon-DD HH:MM:SS.FFFFFFFTZ (where F is fractional seconds and TZ is the time zone). 


Note that the number of digits in the fractional seconds varies with the number of fractional seconds. It's a maximum of 7 (which would be hnsecs), but only has as many as are necessary to hold the correct value (so no trailing zeroes), and if there are no fractional seconds, then there is no decimal point.   
  
 If this [`SysTime`](#SysTime)'s time zone is [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime), then TZ is empty. If its time zone is `UTC`, then it is "Z". Otherwise, it is the offset from UTC (e.g. +01:00 or -07:00). Note that the offset from UTC is *not* enough to uniquely identify the time zone.   
  
 Time zone offsets will be in the form +HH:MM or -HH:MM. 

 
Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
import core.time : msecs, hnsecs;
import std.datetime.date : DateTime;

assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toSimpleString() ==
       "2010-Jul-04 07:06:12");

assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0), msecs(24)).toSimpleString() ==
       "1998-Dec-25 02:15:00.024");

assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toSimpleString() ==
       "0000-Jan-05 23:09:59");

assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2), hnsecs(520_920)).toSimpleString() ==
        "-0004-Jan-05 00:00:02.052092");

```
 
  const nothrow scope @safe string **toString**();   
  
const scope void **toString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`SysTime`](#SysTime) to a string. 


This function exists to make it easy to convert a [`SysTime`](#SysTime) to a string for code that does not care what the exact format is - just that it presents the information in a clear manner. It also makes it easy to simply convert a [`SysTime`](#SysTime) to a string when using functions such as `to!string`, `format`, or `writeln` which use toString to convert user-defined types. So, it is unlikely that much code will call toString directly.   
  
 The format of the string is purposefully unspecified, and code that cares about the format of the string should use `toISOString`, `toISOExtString`, `toSimpleString`, or some other custom formatting function that explicitly generates the format that the code needs. The reason is that the code is then clear about what format it's using, making it less error-prone to maintain the code and interact with other software that consumes the generated strings. It's for this same reason that [`SysTime`](#SysTime) has no `fromString` function, whereas it does have `fromISOString`, `fromISOExtString`, and `fromSimpleString`.   
  
 The format returned by toString may or may not change in the future. 

 
Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
  @safe SysTime **fromISOString**(S)(scope const S isoString, immutable TimeZone tz = null)  
 Constraints: if (isSomeString!S); 
 
Creates a [`SysTime`](#SysTime) from a string with the format YYYYMMDDTHHMMSS.FFFFFFFTZ (where F is fractional seconds is the time zone). Whitespace is stripped from the given string. 


The exact format is exactly as described in `toISOString` except that trailing zeroes are permitted - including having fractional seconds with all zeroes. However, a decimal point with nothing following it is invalid. Also, while [`toISOString`](#toISOString) will never generate a string with more than 7 digits in the fractional seconds (because that's the limit with hecto-nanosecond precision), it will allow more than 7 digits in order to read strings from other sources that have higher precision (however, any digits beyond 7 will be truncated).   
  
 If there is no time zone in the string, then [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) is used. If the time zone is "Z", then `UTC` is used. Otherwise, a [`std.datetime.timezone.SimpleTimeZone`](std_datetime_timezone#SimpleTimeZone) which corresponds to the given offset from UTC is used. To get the returned [`SysTime`](#SysTime) to be a particular time zone, pass in that time zone and the [`SysTime`](#SysTime) to be returned will be converted to that time zone (though it will still be read in as whatever time zone is in its string).   
  
 The accepted formats for time zone offsets are +HH, -HH, +HHMM, and -HHMM.   
  
 Warning: Previously, [`toISOString`](#toISOString) did the same as [`toISOExtString`](#toISOExtString) and generated +HH:MM or -HH:MM for the time zone when it was not [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) or [`std.datetime.timezone.UTC`](std_datetime_timezone#UTC), which is not in conformance with ISO 8601 for the non-extended string format. This has now been fixed. However, for now, fromISOString will continue to accept the extended format for the time zone so that any code which has been writing out the result of toISOString to read in later will continue to work. The current behavior will be kept until July 2019 at which point, fromISOString will be fixed to be standards compliant. 

 
Parameters:


|  |  |
| --- | --- |
| S `isoString` | A string formatted in the ISO format for dates and times. |
| TimeZone `tz` | The time zone to convert the given time to (no conversion occurs if null). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`SysTime`](#SysTime) would not be valid.
  @safe SysTime **fromISOExtString**(S)(scope const S isoExtString, immutable TimeZone tz = null)  
 Constraints: if (isSomeString!S); 
 
Creates a [`SysTime`](#SysTime) from a string with the format YYYY-MM-DDTHH:MM:SS.FFFFFFFTZ (where F is fractional seconds is the time zone). Whitespace is stripped from the given string. 


The exact format is exactly as described in `toISOExtString` except that trailing zeroes are permitted - including having fractional seconds with all zeroes. However, a decimal point with nothing following it is invalid. Also, while [`toISOExtString`](#toISOExtString) will never generate a string with more than 7 digits in the fractional seconds (because that's the limit with hecto-nanosecond precision), it will allow more than 7 digits in order to read strings from other sources that have higher precision (however, any digits beyond 7 will be truncated).   
  
 If there is no time zone in the string, then [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) is used. If the time zone is "Z", then `UTC` is used. Otherwise, a [`std.datetime.timezone.SimpleTimeZone`](std_datetime_timezone#SimpleTimeZone) which corresponds to the given offset from UTC is used. To get the returned [`SysTime`](#SysTime) to be a particular time zone, pass in that time zone and the [`SysTime`](#SysTime) to be returned will be converted to that time zone (though it will still be read in as whatever time zone is in its string).   
  
 The accepted formats for time zone offsets are +HH, -HH, +HH:MM, and -HH:MM. 

 
Parameters:


|  |  |
| --- | --- |
| S `isoExtString` | A string formatted in the ISO Extended format for dates and times. |
| TimeZone `tz` | The time zone to convert the given time to (no conversion occurs if null). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`SysTime`](#SysTime) would not be valid.
  @safe SysTime **fromSimpleString**(S)(scope const S simpleString, immutable TimeZone tz = null)  
 Constraints: if (isSomeString!S); 
 
Creates a [`SysTime`](#SysTime) from a string with the format YYYY-MM-DD HH:MM:SS.FFFFFFFTZ (where F is fractional seconds is the time zone). Whitespace is stripped from the given string. 


The exact format is exactly as described in `toSimpleString` except that trailing zeroes are permitted - including having fractional seconds with all zeroes. However, a decimal point with nothing following it is invalid. Also, while [`toSimpleString`](#toSimpleString) will never generate a string with more than 7 digits in the fractional seconds (because that's the limit with hecto-nanosecond precision), it will allow more than 7 digits in order to read strings from other sources that have higher precision (however, any digits beyond 7 will be truncated).   
  
 If there is no time zone in the string, then [`std.datetime.timezone.LocalTime`](std_datetime_timezone#LocalTime) is used. If the time zone is "Z", then `UTC` is used. Otherwise, a [`std.datetime.timezone.SimpleTimeZone`](std_datetime_timezone#SimpleTimeZone) which corresponds to the given offset from UTC is used. To get the returned [`SysTime`](#SysTime) to be a particular time zone, pass in that time zone and the [`SysTime`](#SysTime) to be returned will be converted to that time zone (though it will still be read in as whatever time zone is in its string).   
  
 The accepted formats for time zone offsets are +HH, -HH, +HH:MM, and -HH:MM. 

 
Parameters:


|  |  |
| --- | --- |
| S `simpleString` | A string formatted in the way that `toSimpleString` formats dates and times. |
| TimeZone `tz` | The time zone to convert the given time to (no conversion occurs if null). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`SysTime`](#SysTime) would not be valid.
  static pure nothrow @property @safe SysTime **min**();  
Returns the [`SysTime`](#SysTime) farthest in the past which is representable by [`SysTime`](#SysTime). 


The [`SysTime`](#SysTime) which is returned is in UTC.

  static pure nothrow @property @safe SysTime **max**();  
Returns the [`SysTime`](#SysTime) farthest in the future which is representable by [`SysTime`](#SysTime). 


The [`SysTime`](#SysTime) which is returned is in UTC.

    pure nothrow @nogc @safe long **unixTimeToStdTime**(long unixTime);  
Converts from unix time (which uses midnight, January 1st, 1970 UTC as its epoch and seconds as its units) to "std time" (which uses midnight, January 1st, 1 A.D. UTC and hnsecs as its units). 


The C standard does not specify the representation of time\_t, so it is implementation defined. On POSIX systems, unix time is equivalent to time\_t, but that's not necessarily true on other systems (e.g. it is not true for the Digital Mars C runtime). So, be careful when using unix time with C functions on non-POSIX systems.   
  
 "std time"'s epoch is based on the Proleptic Gregorian Calendar per ISO 8601 and is what [`SysTime`](#SysTime) uses internally. However, holding the time as an integer in hnsecs since that epoch technically isn't actually part of the standard, much as it's based on it, so the name "std time" isn't particularly good, but there isn't an official name for it. C# uses "ticks" for the same thing, but they aren't actually clock ticks, and the term "ticks" *is* used for actual clock ticks for [`core.time.MonoTime`](core_time#MonoTime), so it didn't make sense to use the term ticks here. So, for better or worse, std.datetime uses the term "std time" for this. 

 
Parameters:


|  |  |
| --- | --- |
| long `unixTime` | The unix time to convert. |


 
See Also:
SysTime.fromUnixTime
 
Examples:


```
import std.datetime.date : DateTime;
import std.datetime.timezone : UTC;

// Midnight, January 1st, 1970
writeln(unixTimeToStdTime(0)); // 621_355_968_000_000_000L
assert(SysTime(unixTimeToStdTime(0)) ==
       SysTime(DateTime(1970, 1, 1), UTC()));

writeln(unixTimeToStdTime(int.max)); // 642_830_804_470_000_000L
assert(SysTime(unixTimeToStdTime(int.max)) ==
       SysTime(DateTime(2038, 1, 19, 3, 14, 07), UTC()));

writeln(unixTimeToStdTime(-127_127)); // 621_354_696_730_000_000L
assert(SysTime(unixTimeToStdTime(-127_127)) ==
       SysTime(DateTime(1969, 12, 30, 12, 41, 13), UTC()));

```
 
  pure nothrow @safe T **stdTimeToUnixTime**(T = time\_t)(long stdTime)  
 Constraints: if (is(T == int) || is(T == long)); 
 
Converts std time (which uses midnight, January 1st, 1 A.D. UTC as its epoch and hnsecs as its units) to unix time (which uses midnight, January 1st, 1970 UTC as its epoch and seconds as its units). 


The C standard does not specify the representation of time\_t, so it is implementation defined. On POSIX systems, unix time is equivalent to time\_t, but that's not necessarily true on other systems (e.g. it is not true for the Digital Mars C runtime). So, be careful when using unix time with C functions on non-POSIX systems.   
  
 "std time"'s epoch is based on the Proleptic Gregorian Calendar per ISO 8601 and is what [`SysTime`](#SysTime) uses internally. However, holding the time as an integer in hnescs since that epoch technically isn't actually part of the standard, much as it's based on it, so the name "std time" isn't particularly good, but there isn't an official name for it. C# uses "ticks" for the same thing, but they aren't actually clock ticks, and the term "ticks" *is* used for actual clock ticks for [`core.time.MonoTime`](core_time#MonoTime), so it didn't make sense to use the term ticks here. So, for better or worse, std.datetime uses the term "std time" for this.   
  
 By default, the return type is time\_t (which is normally an alias for int on 32-bit systems and long on 64-bit systems), but if a different size is required than either int or long can be passed as a template argument to get the desired size.   
  
 If the return type is int, and the result can't fit in an int, then the closest value that can be held in 32 bits will be used (so `int.max` if it goes over and `int.min` if it goes under). However, no attempt is made to deal with integer overflow if the return type is long. 

 
Parameters:


|  |  |
| --- | --- |
| T | The return type (int or long). It defaults to time\_t, which is normally 32 bits on a 32-bit system and 64 bits on a 64-bit system. |
| long `stdTime` | The std time to convert. |


 
Returns:
A signed integer representing the unix time which is equivalent to the given std time. 
 
See Also:
SysTime.toUnixTime
 
Examples:


```
// Midnight, January 1st, 1970 UTC
writeln(stdTimeToUnixTime(621_355_968_000_000_000L)); // 0

// 2038-01-19 03:14:07 UTC
writeln(stdTimeToUnixTime(642_830_804_470_000_000L)); // int.max

```
 
  @safe SysTime **SYSTEMTIMEToSysTime**(scope const SYSTEMTIME\* st, immutable TimeZone tz = LocalTime());  
This function is Windows-Only. 


Converts a `SYSTEMTIME` struct to a [`SysTime`](#SysTime). 

 
Parameters:


|  |  |
| --- | --- |
| SYSTEMTIME\* `st` | The `SYSTEMTIME` struct to convert. |
| TimeZone `tz` | The time zone that the time in the `SYSTEMTIME` struct is assumed to be (if the `SYSTEMTIME` was supplied by a Windows system call, the `SYSTEMTIME` will either be in local time or UTC, depending on the call). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given `SYSTEMTIME` will not fit in a [`SysTime`](#SysTime), which is highly unlikely to happen given that `SysTime.max` is in 29,228 A.D. and the maximum `SYSTEMTIME` is in 30,827 A.D.
  @safe SYSTEMTIME **SysTimeToSYSTEMTIME**(scope SysTime sysTime);  
This function is Windows-Only. 


Converts a [`SysTime`](#SysTime) to a `SYSTEMTIME` struct.   
  
 The `SYSTEMTIME` which is returned will be set using the given [`SysTime`](#SysTime)'s time zone, so to get the `SYSTEMTIME` in UTC, set the [`SysTime`](#SysTime)'s time zone to UTC. 

 
Parameters:


|  |  |
| --- | --- |
| SysTime `sysTime` | The [`SysTime`](#SysTime) to convert. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given [`SysTime`](#SysTime) will not fit in a `SYSTEMTIME`. This will only happen if the [`SysTime`](#SysTime)'s date is prior to 1601 A.D.
  @safe long **FILETIMEToStdTime**(scope const FILETIME\* ft);  
This function is Windows-Only. 


Converts a `FILETIME` struct to the number of hnsecs since midnight, January 1st, 1 A.D. 

 
Parameters:


|  |  |
| --- | --- |
| FILETIME\* `ft` | The `FILETIME` struct to convert. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given `FILETIME` cannot be represented as the return value.
  @safe SysTime **FILETIMEToSysTime**(scope const FILETIME\* ft, immutable TimeZone tz = LocalTime());  
This function is Windows-Only. 


Converts a `FILETIME` struct to a [`SysTime`](#SysTime). 

 
Parameters:


|  |  |
| --- | --- |
| FILETIME\* `ft` | The `FILETIME` struct to convert. |
| TimeZone `tz` | The time zone that the [`SysTime`](#SysTime) will be in (`FILETIME`s are in UTC). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given `FILETIME` will not fit in a [`SysTime`](#SysTime).
  @safe FILETIME **stdTimeToFILETIME**(long stdTime);  
This function is Windows-Only. 


Converts a number of hnsecs since midnight, January 1st, 1 A.D. to a `FILETIME` struct. 

 
Parameters:


|  |  |
| --- | --- |
| long `stdTime` | The number of hnsecs since midnight, January 1st, 1 A.D. UTC. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given value will not fit in a `FILETIME`.
  @safe FILETIME **SysTimeToFILETIME**(scope SysTime sysTime);  
This function is Windows-Only. 


Converts a [`SysTime`](#SysTime) to a `FILETIME` struct.   
  
 `FILETIME`s are always in UTC. 

 
Parameters:


|  |  |
| --- | --- |
| SysTime `sysTime` | The [`SysTime`](#SysTime) to convert. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given [`SysTime`](#SysTime) will not fit in a `FILETIME`.
  alias **DosFileTime** = uint;  
Type representing the DOS file date/time format.

  @safe SysTime **DosFileTimeToSysTime**(DosFileTime dft, immutable TimeZone tz = LocalTime());  
Converts from DOS file date/time to [`SysTime`](#SysTime). 



Parameters:


|  |  |
| --- | --- |
| DosFileTime `dft` | The DOS file time to convert. |
| TimeZone `tz` | The time zone which the DOS file time is assumed to be in. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the `DosFileTime` is invalid.
 
Examples:


```
import std.datetime.date : DateTime;

// SysTime(DateTime(1980, 1, 1, 0, 0, 0))
writeln(DosFileTimeToSysTime(0b00000000001000010000000000000000));
// SysTime(DateTime(2107, 12, 31, 23, 59, 58))
writeln(DosFileTimeToSysTime(0b11111111100111111011111101111101));
writeln(DosFileTimeToSysTime(0x3E3F8456)); // SysTime(DateTime(2011, 1, 31, 16, 34, 44))

```
 
  @safe DosFileTime **SysTimeToDosFileTime**(scope SysTime sysTime);  
Converts from [`SysTime`](#SysTime) to DOS file date/time. 



Parameters:


|  |  |
| --- | --- |
| SysTime `sysTime` | The [`SysTime`](#SysTime) to convert. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given [`SysTime`](#SysTime) cannot be converted to a `DosFileTime`.
 
Examples:


```
import std.datetime.date : DateTime;

// 0b00000000001000010000000000000000
writeln(SysTimeToDosFileTime(SysTime(DateTime(1980, 1, 1, 0, 0, 0))));
// 0b11111111100111111011111101111101
writeln(SysTimeToDosFileTime(SysTime(DateTime(2107, 12, 31, 23, 59, 58))));
writeln(SysTimeToDosFileTime(SysTime(DateTime(2011, 1, 31, 16, 34, 44)))); // 0x3E3F8456

```
 
  @safe SysTime **parseRFC822DateTime**()(scope const char[] value);   
  
SysTime **parseRFC822DateTime**(R)(scope R value)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && (is(immutable(ElementType!R) == immutable(char)) || is(immutable(ElementType!R) == immutable(ubyte)))); 
 
The given array of `char` or random-access range of `char` or `ubyte` is expected to be in the format specified in [RFC 5322](http://tools.ietf.org/html/rfc5322) section 3.3 with the grammar rule *date-time*. It is the date-time format commonly used in internet messages such as e-mail and HTTP. The corresponding [`SysTime`](#SysTime) will be returned. 


RFC 822 was the original spec (hence the function's name), whereas RFC 5322 is the current spec.   
  
 The day of the week is ignored beyond verifying that it's a valid day of the week, as the day of the week can be inferred from the date. It is not checked whether the given day of the week matches the actual day of the week of the given date (though it is technically invalid per the spec if the day of the week doesn't match the actual day of the week of the given date).   
  
 If the time zone is `"-0000"` (or considered to be equivalent to `"-0000"` by section 4.3 of the spec), a [`std.datetime.timezone.SimpleTimeZone`](std_datetime_timezone#SimpleTimeZone) with a utc offset of `0` is used rather than [`std.datetime.timezone.UTC`](std_datetime_timezone#UTC), whereas `"+0000"` uses [`std.datetime.timezone.UTC`](std_datetime_timezone#UTC).   
  
 Note that because [`SysTime`](#SysTime) does not currently support having a second value of 60 (as is sometimes done for leap seconds), if the date-time value does have a value of 60 for the seconds, it is treated as 59.   
  
 The one area in which this function violates RFC 5322 is that it accepts `"\n"` in folding whitespace in the place of `"\r\n"`, because the HTTP spec requires it. 

 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string doesn't follow the grammar for a date-time field or if the resulting [`SysTime`](#SysTime) is invalid.
 
Examples:


```
import core.time : hours;
import std.datetime.date : DateTime, DateTimeException;
import std.datetime.timezone : SimpleTimeZone, UTC;
import std.exception : assertThrown;

auto tz = new immutable SimpleTimeZone(hours(-8));
assert(parseRFC822DateTime("Sat, 6 Jan 1990 12:14:19 -0800") ==
       SysTime(DateTime(1990, 1, 6, 12, 14, 19), tz));

assert(parseRFC822DateTime("9 Jul 2002 13:11 +0000") ==
       SysTime(DateTime(2002, 7, 9, 13, 11, 0), UTC()));

auto badStr = "29 Feb 2001 12:17:16 +0200";
assertThrown!DateTimeException(parseRFC822DateTime(badStr));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime_systime.html>

std.experimental.allocator.building\_blocks
===========================================

 Assembling Your Own Allocator
-----------------------------

 

This package also implements untyped composable memory allocators. They are *untyped* because they deal exclusively in `void[]` and have no notion of what type the memory allocated would be destined for. They are *composable* because the included allocators are building blocks that can be assembled in complex nontrivial allocators.   
  
 Unlike the allocators for the C and C++ programming languages, which manage the allocated size internally, these allocators require that the client maintains (or knows *a priori*) the allocation size for each piece of memory allocated. Put simply, the client must pass the allocated size upon deallocation. Storing the size in the allocator has significant negative performance implications, and is virtually always redundant because client code needs knowledge of the allocated size in order to avoid buffer overruns. (See more discussion in a [proposal](#) for sized deallocation in C++.) For this reason, allocators herein traffic in `void[]` as opposed to `void*`.

   
  
 In order to be usable as an allocator, a type should implement the following methods with their respective semantics. Only `alignment` and `allocate` are required. If any of the other methods is missing, the allocator is assumed to not have that capability (for example some allocators do not offer manual deallocation of memory). Allocators should NOT implement unsupported methods to always fail. For example, an allocator that lacks the capability to implement `alignedAllocate` should not define it at all (as opposed to defining it to always return `null` or throw an exception). The missing implementation statically informs other components about the allocator's capabilities and allows them to make design decisions accordingly.

   
  
 

| Method name | Semantics |
| --- | --- |
  
  
| `uint alignment;`*Post:* `*result* > 0` | Returns the minimum alignment of all data returned by the allocator. An allocator may implement `alignment` as a statically-known `enum` value only. Applications that need dynamically-chosen alignment values should use the `alignedAllocate` and `alignedReallocate` APIs. |
  
  
| `size\_t goodAllocSize(size\_t n);`*Post:* `*result* >= n` | Allocators customarily allocate memory in discretely-sized chunks. Therefore, a request for `n` bytes may result in a larger allocation. The extra memory allocated goes unused and adds to the so-called [internal fragmentation](http://goo.gl/YoKffF). The function `goodAllocSize(n)` returns the actual number of bytes that would be allocated upon a request for `n` bytes. This module defines a default implementation that returns `n` rounded up to a multiple of the allocator's alignment. |
  
  
| `void[] allocate(size\_t s);`*Post:* `*result* is null || *result*.length == s` | If `s == 0`, the call may return any empty slice (including `null`). Otherwise, the call allocates `s` bytes of memory and returns the allocated block, or `null` if the request could not be satisfied. |
  
  
| `void[] alignedAllocate(size\_t s, uint a);`*Post:* `*result* is null || *result*.length == s` | Similar to `allocate`, with the additional guarantee that the memory returned is aligned to at least `a` bytes. `a` must be a power of 2. |
  
  
| `void[] allocateAll();` | Offers all of allocator's memory to the caller, so it's usually defined by fixed-size allocators. If the allocator is currently NOT managing any memory, then `allocateAll()` shall allocate and return all memory available to the allocator, and subsequent calls to all allocation primitives should not succeed (e.g. `allocate` shall return `null` etc). Otherwise, `allocateAll` only works on a best-effort basis, and the allocator is allowed to return `null` even if does have available memory. Memory allocated with `allocateAll` is not otherwise special (e.g. can be reallocated or deallocated with the usual primitives, if defined). |
  
  
| `bool expand(ref void[] b, size\_t delta);`*Post:* `!*result* || b.length == *old*(b).length + delta` | Expands `b` by `delta` bytes. If `delta == 0`, succeeds without changing `b`. If `b is null`, returns `false` (the null pointer cannot be expanded in place). Otherwise, `b` must be a buffer previously allocated with the same allocator. If expansion was successful, `expand` changes `b`'s length to `b.length + delta` and returns `true`. Upon failure, the call effects no change upon the allocator object, leaves `b` unchanged, and returns `false`. |
  
  
| `bool reallocate(ref void[] b, size\_t s);`*Post:* `!*result* || b.length == s` | Reallocates `b` to size `s`, possibly moving memory around. `b` must be `null` or a buffer allocated with the same allocator. If reallocation was successful, `reallocate` changes `b` appropriately and returns `true`. Upon failure, the call effects no change upon the allocator object, leaves `b` unchanged, and returns `false`. An allocator should implement `reallocate` if it can derive some advantage from doing so; otherwise, this module defines a `reallocate` free function implemented in terms of `expand`, `allocate`, and `deallocate`. |
  
  
| `bool alignedReallocate(ref void[] b, size\_t s, uint a);`*Post:* `!*result* || b.length == s` | Similar to `reallocate`, but guarantees the reallocated memory is aligned at `a` bytes. The buffer must have been originated with a call to `alignedAllocate`. `a` must be a power of 2 greater than `(void*).sizeof`. An allocator should implement `alignedReallocate` if it can derive some advantage from doing so; otherwise, this module defines a `alignedReallocate` free function implemented in terms of `expand`, `alignedAllocate`, and `deallocate`. |
  
  
| `Ternary owns(void[] b);` | Returns `Ternary.yes` if `b` has been allocated with this allocator. An allocator should define this method only if it can decide on ownership precisely and fast (in constant time, logarithmic time, or linear time with a low multiplication factor). Traditional allocators such as the C heap do not define such functionality. If `b is null`, the allocator shall return `Ternary.no`, i.e. no allocator owns the `null` slice. |
  
  
| `Ternary resolveInternalPointer(void\* p, ref void[] result);` | If `p` is a pointer somewhere inside a block allocated with this allocator, `result` holds a pointer to the beginning of the allocated block and returns `Ternary.yes`. Otherwise, `result` holds `null` and returns `Ternary.no`. If the pointer points immediately after an allocated block, the result is implementation defined. |
  
  
| `bool deallocate(void[] b);` | If `b is null`, does nothing and returns `true`. Otherwise, deallocates memory previously allocated with this allocator and returns `true` if successful, `false` otherwise. An implementation that would not support deallocation (i.e. would always return `false` should not define this primitive at all.) |
  
  
| `bool deallocateAll();`*Post:* `empty` | Deallocates all memory allocated with this allocator. If an allocator implements this method, it must specify whether its destructor calls it, too. |
  
  
| `Ternary empty();` | Returns `Ternary.yes` if and only if the allocator holds no memory (i.e. no allocation has occurred, or all allocations have been deallocated). |
  
  
| `static Allocator instance;`*Post:* `instance *is a valid* Allocator *object*` | Some allocators are *monostate*, i.e. have only an instance and hold only global state. (Notable examples are C's own `malloc`-based allocator and D's garbage-collected heap.) Such allocators must define a static `instance` instance that serves as the symbolic placeholder for the global instance of the allocator. An allocator should not hold state and define `instance` simultaneously. Depending on whether the allocator is thread-safe or not, this instance may be `shared`. |

   
  
 Sample Assembly
---------------

   
  
 The example below features an allocator modeled after [jemalloc](http://goo.gl/m7329l), which uses a battery of free-list allocators spaced so as to keep internal fragmentation to a minimum. The `FList` definitions specify no bounds for the freelist because the `Segregator` does all size selection in advance.   
  
 Sizes through 3584 bytes are handled via freelists of staggered sizes. Sizes from 3585 bytes through 4072 KB are handled by a `BitmappedBlock` with a block size of 4 KB. Sizes above that are passed direct to the `GCAllocator`.   
  
 
```
    alias FList = FreeList!(GCAllocator, 0, unbounded);
    alias A = Segregator!(
        8, FreeList!(GCAllocator, 0, 8),
        128, Bucketizer!(FList, 1, 128, 16),
        256, Bucketizer!(FList, 129, 256, 32),
        512, Bucketizer!(FList, 257, 512, 64),
        1024, Bucketizer!(FList, 513, 1024, 128),
        2048, Bucketizer!(FList, 1025, 2048, 256),
        3584, Bucketizer!(FList, 2049, 3584, 512),
        4072 * 1024, AllocatorList!(
            () => BitmappedBlock!(GCAllocator, 4096)(4072 * 1024)),
        GCAllocator
    );
    A tuMalloc;
    auto b = tuMalloc.allocate(500);
    assert(b.length == 500);
    auto c = tuMalloc.allocate(113);
    assert(c.length == 113);
    assert(tuMalloc.expand(c, 14));
    tuMalloc.deallocate(b);
    tuMalloc.deallocate(c);

```
   
  
 Allocating memory for sharing across threads
--------------------------------------------

   
  
 One allocation pattern used in multithreaded applications is to share memory across threads, and to deallocate blocks in a different thread than the one that allocated it.   
  
 All allocators in this module accept and return `void[]` (as opposed to `shared void[]`). This is because at the time of allocation, deallocation, or reallocation, the memory is effectively not `shared` (if it were, it would reveal a bug at the application level).   
  
 The issue remains of calling `a.deallocate(b)` from a different thread than the one that allocated `b`. It follows that both threads must have access to the same instance `a` of the respective allocator type. By definition of D, this is possible only if `a` has the `shared` qualifier. It follows that the allocator type must implement `allocate` and `deallocate` as `shared` methods. That way, the allocator commits to allowing usable `shared` instances.   
  
 Conversely, allocating memory with one non-`shared` allocator, passing it across threads (by casting the obtained buffer to `shared`), and later deallocating it in a different thread (either with a different allocator object or with the same allocator object after casting it to `shared`) is illegal.   
  
 Building Blocks
---------------

   
  
 The table below gives a synopsis of predefined allocator building blocks, with their respective modules. Either `import` the needed modules individually, or `import` `std.experimental.building_blocks`, which imports them all `public`ly. The building blocks can be assembled in unbounded ways and also combined with your own. For a collection of typical and useful preassembled allocators and for inspiration in defining more such assemblies, refer to [`std.experimental.allocator.showcase`](std_experimental_allocator_showcase).

   
  
 

| Allocator | Description |
| --- | --- |
  
  
| `[NullAllocator](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)``std.experimental.allocator.building\_blocks.null\_allocator` | Very good at doing absolutely nothing. A good starting point for defining other allocators or for studying the API. |
  
  
| `[GCAllocator](std_experimental_allocator_gc_allocator#GCAllocator)``std.experimental.allocator.gc\_allocator` | The system-provided garbage-collector allocator. This should be the default fallback allocator tapping into system memory. It offers manual `free` and dutifully collects litter. |
  
  
| `[Mallocator](std_experimental_allocator_mallocator#Mallocator)``std.experimental.allocator.mallocator` | The C heap allocator, a.k.a. `malloc`/`realloc`/`free`. Use sparingly and only for code that is unlikely to leak. |
  
  
| `[AlignedMallocator](std_experimental_allocator_mallocator#AlignedMallocator)``std.experimental.allocator.mallocator` | Interface to OS-specific allocators that support specifying alignment: [`posix_memalign`](http://man7.org/linux/man-pages/man3/posix_memalign.3.html) on Posix and [`__aligned_xxx`](http://msdn.microsoft.com/en-us/library/fs9stz4e(v=vs.80).aspx) on Windows. |
  
  
| `[AlignedBlockList](std_experimental_allocator_building_blocks_aligned_block_list#AlignedBlockList)``std.experimental.allocator.building\_blocks.aligned\_block\_list` | A wrapper around a list of allocators which allow for very fast deallocations. |
  
  
| `[AffixAllocator](std_experimental_allocator_building_blocks_affix_allocator#AffixAllocator)``std.experimental.allocator.building\_blocks.affix\_allocator` | Allocator that allows and manages allocating extra prefix and/or a suffix bytes for each block allocated. |
  
  
| `[BitmappedBlock](std_experimental_allocator_building_blocks_bitmapped_block#BitmappedBlock)``std.experimental.allocator.building\_blocks.bitmapped\_block` | Organizes one contiguous chunk of memory in equal-size blocks and tracks allocation status at the cost of one bit per block. |
  
  
| `[FallbackAllocator](std_experimental_allocator_building_blocks_fallback_allocator#FallbackAllocator)``std.experimental.allocator.building\_blocks.fallback\_allocator` | Allocator that combines two other allocators - primary and fallback. Allocation requests are first tried with primary, and upon failure are passed to the fallback. Useful for small and fast allocators fronting general-purpose ones. |
  
  
| `[FreeList](std_experimental_allocator_building_blocks_free_list#FreeList)``std.experimental.allocator.building\_blocks.free\_list` | Allocator that implements a [free list](http://wikipedia.org/wiki/Free_list) on top of any other allocator. The preferred size, tolerance, and maximum elements are configurable at compile- and run time. |
  
  
| `[SharedFreeList](std_experimental_allocator_building_blocks_free_list#SharedFreeList)``std.experimental.allocator.building\_blocks.free\_list` | Same features as `FreeList`, but packaged as a `shared` structure that is accessible to several threads. |
  
  
| `[FreeTree](std_experimental_allocator_building_blocks_free_tree#FreeTree)``std.experimental.allocator.building\_blocks.free\_tree` | Allocator similar to `FreeList` that uses a binary search tree to adaptively store not one, but many free lists. |
  
  
| `[Region](std_experimental_allocator_building_blocks_region#Region)``std.experimental.allocator.building\_blocks.region` | Region allocator organizes a chunk of memory as a simple bump-the-pointer allocator. |
  
  
| `[InSituRegion](std_experimental_allocator_building_blocks_region#InSituRegion)``std.experimental.allocator.building\_blocks.region` | Region holding its own allocation, most often on the stack. Has statically-determined size. |
  
  
| `[SbrkRegion](std_experimental_allocator_building_blocks_region#SbrkRegion)``std.experimental.allocator.building\_blocks.region` | Region using `[sbrk](https://en.wikipedia.org/wiki/Sbrk)` for allocating memory. |
  
  
| `[MmapAllocator](std_experimental_allocator_mmap_allocator#MmapAllocator)``std.experimental.allocator.mmap\_allocator` | Allocator using `[mmap](https://en.wikipedia.org/wiki/Mmap)` directly. |
  
  
| `[StatsCollector](std_experimental_allocator_building_blocks_stats_collector#StatsCollector)``std.experimental.allocator.building\_blocks.stats\_collector` | Collect statistics about any other allocator. |
  
  
| `[Quantizer](std_experimental_allocator_building_blocks_quantizer#Quantizer)``std.experimental.allocator.building\_blocks.quantizer` | Allocates in coarse-grained quantas, thus improving performance of reallocations by often reallocating in place. The drawback is higher memory consumption because of allocated and unused memory. |
  
  
| `[AllocatorList](std_experimental_allocator_building_blocks_allocator_list#AllocatorList)``std.experimental.allocator.building\_blocks.allocator\_list` | Given an allocator factory, lazily creates as many allocators as needed to satisfy allocation requests. The allocators are stored in a linked list. Requests for allocation are satisfied by searching the list in a linear manner. |
  
  
| `[Segregator](std_experimental_allocator_building_blocks_segregator#Segregator)``std.experimental.allocator.building\_blocks.segregator` | Segregates allocation requests by size and dispatches them to distinct allocators. |
  
  
| `[Bucketizer](std_experimental_allocator_building_blocks_bucketizer#Bucketizer)``std.experimental.allocator.building\_blocks.bucketizer` | Divides allocation sizes in discrete buckets and uses an array of allocators, one per bucket, to satisfy requests. |
  
  
| `[AscendingPageAllocator](std_experimental_allocator_building_blocks_ascending_page_allocator#AscendingPageAllocator)``std.experimental.allocator.building\_blocks.ascending\_page\_allocator` | A memory safe allocator where sizes are rounded to a multiple of the page size and allocations are satisfied at increasing addresses. |
  
  

 
Source
 [std/experimental/allocator/building\_blocks/package.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/package.d) 


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks.html>

std.experimental.allocator.building\_blocks.affix\_allocator
============================================================

 
Source
 [std/experimental/allocator/building\_blocks/affix\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/affix_allocator.d)

 
struct **AffixAllocator**(Allocator, Prefix, Suffix = void);  
Allocator that adds some extra data before (of type `Prefix`) and/or after (of type `Suffix`) any allocation made with its parent allocator. This is useful for uses where additional allocation-related information is needed, such as mutexes, reference counts, or walls for debugging memory corruption errors. 


If `Prefix` is not `void`, `Allocator` must guarantee an alignment at least as large as `Prefix.alignof`.   
  
 Suffixes are slower to get at because of alignment rounding, so prefixes should be preferred. However, small prefixes blunt the alignment so if a large alignment with a small affix is needed, suffixes should be chosen.   
  
 The following methods are defined if `Allocator` defines them, and forward to it: `deallocateAll`, `empty`, `owns`.

 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;
// One word before and after each allocation.
alias A = AffixAllocator!(Mallocator, size_t, size_t);
auto b = A.instance.allocate(11);
A.instance.prefix(b) = 0xCAFE_BABE;
A.instance.suffix(b) = 0xDEAD_BEEF;
assert(A.instance.prefix(b) == 0xCAFE_BABE
    && A.instance.suffix(b) == 0xDEAD_BEEF);

```
 
 
enum uint **alignment**;  
If `Prefix` is `void`, the alignment is that of the parent. Otherwise, the alignment is the same as the `Prefix`'s alignment.

  Allocator **\_parent**;  
If the parent allocator `Allocator` is stateful, an instance of it is stored as a member. Otherwise, `AffixAllocator` uses `Allocator.instance`. In either case, the name `_parent` is uniformly used for accessing the parent allocator.

  pure nothrow @nogc @safe Allocator **parent**();  
If the parent allocator `Allocator` is stateful, an instance of it is stored as a member. Otherwise, `AffixAllocator` uses `Allocator.instance`. In either case, the name `_parent` is uniformly used for accessing the parent allocator.

  size\_t **goodAllocSize**(size\_t);   
  
void[] **allocate**(size\_t);   
  
Ternary **owns**(void[]);   
  
bool **expand**(ref void[] b, size\_t delta);   
  
bool **reallocate**(ref void[] b, size\_t s);   
  
bool **deallocate**(void[] b);   
  
bool **deallocateAll**();   
  
Ternary **empty**();  
Standard allocator methods. Each is defined if and only if the parent allocator defines the homonym method (except for `goodAllocSize`, which may use the global default). Also, the methods will be  `shared` if the parent allocator defines them as such.

  static AffixAllocator **instance**;  
The `instance` singleton is defined if and only if the parent allocator has no state and defines its own `it` object.

  ref auto **prefix**(T)(T[] b);   
  
ref auto **suffix**(T)(T[] b);  
Affix access functions offering references to the affixes of a block `b` previously allocated with this allocator. `b` may not be null. They are defined if and only if the corresponding affix is not `void`. 


The qualifiers of the affix are not always the same as the qualifiers of the argument. This is because the affixes are not part of the data itself, but instead are just *associated* with the data and known to the allocator. The table below documents the type of `preffix(b)` and `affix(b)` depending on the type of `b`.   
  
 

Result of `prefix`/`suffix` depending on argument (`U` is any unqualified type, `Affix` is `Prefix` or `Suffix`)| Argument Type | Return | Comments |
  
  
| `shared(U)[]` | `ref shared Affix` | Data is shared across threads and the affix follows suit. |
  
  
| `immutable(U)[]` | `ref shared Affix` | Although the data is immutable, the allocator "knows" the underlying memory is mutable, so `immutable` is elided for the affix which is independent from the data itself. However, the result is `shared` because `immutable` is implicitly shareable so multiple threads may access and manipulate the affix for the same data. |
  
  
| `const(shared(U))[]` | `ref shared Affix` | The data is always shareable across threads. Even if the data is `const`, the affix is modifiable by the same reasoning as for `immutable`. |
  
  
| `const(U)[]` | `ref const Affix` | The input may have originated from `U[]` or `immutable(U)[]`, so it may be actually shared or not. Returning an unqualified affix may result in race conditions, whereas returning a `shared` affix may result in inadvertent sharing of mutable thread-local data across multiple threads. So the returned type is conservatively `ref const`. |
  
  
| `U[]` | `ref Affix` | Unqualified data has unqualified affixes. |

 

 
Precondition
 `b !is null` and `b` must have been allocated with this allocator.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_affix_allocator.html>

std.experimental.allocator.building\_blocks.aligned\_block\_list
================================================================

 `AlignedBlockList` represents a wrapper around a chain of allocators, allowing for fast deallocations and preserving a low degree of fragmentation by means of aligned allocations. 



Source
 [std/experimental/allocator/building\_blocks/aligned\_block\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/aligned_block_list.d)

 
struct **AlignedBlockList**(Allocator, ParentAllocator, ulong theAlignment = 1 << 21);  
`AlignedBlockList` represents a wrapper around a chain of allocators, allowing for fast deallocations and preserving a low degree of fragmentation. The allocator holds internally a doubly linked list of `Allocator` objects, which will serve allocations in a most-recently-used fashion. Most recent allocators used for `allocate` calls, will be moved to the front of the list. 


Although allocations are in theory served in linear searching time, `deallocate` calls take Ο(`1`) time, by using aligned allocations. `ParentAllocator` must implement `alignedAllocate` and it must be able to allocate `theAlignment` bytes at the same alignment. Each aligned allocation done by `ParentAllocator` will contain metadata for an `Allocator`, followed by its payload. 

 
Parameters:


|  |  |
| --- | --- |
| Allocator | the allocator which is used to manage each node; it must have a constructor which receives `ubyte[]` and it must not have any parent allocators, except for the `NullAllocator` |
| ParentAllocator | each node draws memory from the parent allocator; it must support `alignedAllocate` |
| theAlignment | alignment of each block and at the same time length of each node |


 
Examples:


```
import std.experimental.allocator.building_blocks.ascending_page_allocator : AscendingPageAllocator;
import std.experimental.allocator.building_blocks.segregator : Segregator;
import std.experimental.allocator.building_blocks.bitmapped_block : BitmappedBlock;
import std.typecons : Ternary;

/*
In this example we use 'AlignedBlockList' in conjunction with other allocators
in order to create a more complex allocator.

The 'SuperAllocator' uses a 'Segregator' to distribute allocations to sub-allocators,
based on the requested size.

Each sub-allocator is represented by an 'AlignedBlockList' of 'BitmappedBlocks'.
Each 'AlignedBlockList' draws memory from a root allocator which in this case is an 'AscendingPageAllocator'

Such an allocator not only provides good performance, but also a low degree of memory fragmentation.
*/
alias SuperAllocator = Segregator!(
    32,
    AlignedBlockList!(BitmappedBlock!32, AscendingPageAllocator*, 1 << 12),
    Segregator!(

    64,
    AlignedBlockList!(BitmappedBlock!64, AscendingPageAllocator*, 1 << 12),
    Segregator!(

    128,
    AlignedBlockList!(BitmappedBlock!128, AscendingPageAllocator*, 1 << 12),
    AscendingPageAllocator*
)));

SuperAllocator a;
auto pageAlloc = AscendingPageAllocator(128 * 4096);

// Set the parent allocator for all the sub allocators
a.allocatorForSize!256 = &pageAlloc;
a.allocatorForSize!128.parent = &pageAlloc;
a.allocatorForSize!64.parent = &pageAlloc;
a.allocatorForSize!32.parent = &pageAlloc;

enum testNum = 10;
void[][testNum] buf;

// Allocations of size 32 will go to the first 'AlignedBlockList'
foreach (j; 0 .. testNum)
{
    buf[j] = a.allocate(32);
    writeln(buf[j].length); // 32

    // This is owned by the first 'AlignedBlockList'
    writeln(a.allocatorForSize!32.owns(buf[j])); // Ternary.yes
}

// Free the memory
foreach (j; 0 .. testNum)
    assert(a.deallocate(buf[j]));

// Allocations of size 64 will go to the second 'AlignedBlockList'
foreach (j; 0 .. testNum)
{
    buf[j] = a.allocate(64);
    writeln(buf[j].length); // 64

    // This is owned by the second 'AlignedBlockList'
    writeln(a.allocatorForSize!64.owns(buf[j])); // Ternary.yes
}

// Free the memory
foreach (j; 0 .. testNum)
    assert(a.deallocate(buf[j]));

// Allocations of size 128 will go to the third 'AlignedBlockList'
foreach (j; 0 .. testNum)
{
    buf[j] = a.allocate(128);
    writeln(buf[j].length); // 128

    // This is owned by the third 'AlignedBlockList'
    writeln(a.allocatorForSize!128.owns(buf[j])); // Ternary.yes
}

// Free the memory
foreach (j; 0 .. testNum)
    assert(a.deallocate(buf[j]));

// Allocations which exceed 128, will go to the 'AscendingPageAllocator*'
void[] b = a.allocate(256);
writeln(b.length); // 256
a.deallocate(b);

```
 
 
void[] **allocate**(size\_t n);  
Returns a chunk of memory of size `n` It finds the first node in the `AlignedBlockNode` list which has available memory, and moves it to the front of the list. 


All empty nodes which cannot return new memory, are removed from the list. 

 
Parameters:


|  |  |
| --- | --- |
| size\_t `n` | bytes to allocate |


 
Returns:
A chunk of memory of the required length or `null` on failure or
  bool **deallocate**(void[] b);  
Deallocates the buffer `b` given as parameter. Deallocations take place in constant time, regardless of the number of nodes in the list. `b.ptr` is rounded down to the nearest multiple of the `alignment` to quickly find the corresponding `AlignedBlockNode`. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | buffer candidate for deallocation |


 
Returns:

`true` on success and `false` on failure
  Ternary **owns**(void[] b);  
Returns `Ternary.yes` if the buffer belongs to the parent allocator and `Ternary.no` otherwise. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | buffer tested if owned by this allocator |


 
Returns:

`Ternary.yes` if owned by this allocator and `Ternary.no` otherwise
    struct **SharedAlignedBlockList**(Allocator, ParentAllocator, ulong theAlignment = 1 << 21);  
`SharedAlignedBlockList` is the threadsafe version of `AlignedBlockList`. The `Allocator` template parameter must refer a shared allocator. Also, `ParentAllocator` must be a shared allocator, supporting `alignedAllocate`. 



Parameters:


|  |  |
| --- | --- |
| Allocator | the shared allocator which is used to manage each node; it must have a constructor which receives `ubyte[]` and it must not have any parent allocators, except for the `NullAllocator` |
| ParentAllocator | each node draws memory from the parent allocator; it must be shared and support `alignedAllocate` |
| theAlignment | alignment of each block and at the same time length of each node |


 
Examples:


```
import std.experimental.allocator.building_blocks.region : SharedRegion;
import std.experimental.allocator.building_blocks.ascending_page_allocator : SharedAscendingPageAllocator;
import std.experimental.allocator.building_blocks.null_allocator : NullAllocator;
import core.thread : ThreadGroup;

enum numThreads = 8;
enum size = 2048;
enum maxIter = 10;

/*
In this example we use 'SharedAlignedBlockList' together with 'SharedRegion',
in order to create a fast, thread-safe allocator.
*/
alias SuperAllocator = SharedAlignedBlockList!(
        SharedRegion!(NullAllocator, 1),
        SharedAscendingPageAllocator,
        4096);

SuperAllocator a;
// The 'SuperAllocator' will draw memory from a 'SharedAscendingPageAllocator'
a.parent = SharedAscendingPageAllocator(4096 * 1024);

// Launch 'numThreads', each performing allocations
void fun()
{
    foreach (i; 0 .. maxIter)
    {
        void[] b = a.allocate(size);
        writeln(b.length); // size
    }
}

auto tg = new ThreadGroup;
foreach (i; 0 .. numThreads)
{
    tg.create(&fun);
}
tg.joinAll();

```
 
 
void[] **allocate**(size\_t n);  
Returns a chunk of memory of size `n` It finds the first node in the `AlignedBlockNode` list which has available memory, and moves it to the front of the list. 


All empty nodes which cannot return new memory, are removed from the list. 

 
Parameters:


|  |  |
| --- | --- |
| size\_t `n` | bytes to allocate |


 
Returns:
A chunk of memory of the required length or `null` on failure or
  bool **deallocate**(void[] b);  
Deallocates the buffer `b` given as parameter. Deallocations take place in constant time, regardless of the number of nodes in the list. `b.ptr` is rounded down to the nearest multiple of the `alignment` to quickly find the corresponding `AlignedBlockNode`. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | buffer candidate for deallocation |


 
Returns:

`true` on success and `false` on failure
  Ternary **owns**(void[] b);  
Returns `Ternary.yes` if the buffer belongs to the parent allocator and `Ternary.no` otherwise. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | buffer tested if owned by this allocator |


 
Returns:

`Ternary.yes` if owned by this allocator and `Ternary.no` otherwise
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_aligned_block_list.html>

std.datetime.date
=================

  

| Category | Functions |
| --- | --- |
| Main date types | [`Date`](#Date) [`DateTime`](#DateTime) |
| Other date types | [`Month`](#Month) [`DayOfWeek`](#DayOfWeek) [`TimeOfDay`](#TimeOfDay) |
| Date checking | [`valid`](#valid) [`validTimeUnits`](#validTimeUnits) [`yearIsLeapYear`](#yearIsLeapYear) [`isTimePoint`](#isTimePoint) [`enforceValid`](#enforceValid) |
| Date conversion | [`daysToDayOfWeek`](#daysToDayOfWeek) [`monthsToMonth`](#monthsToMonth) |
| Time units | [`cmpTimeUnits`](#cmpTimeUnits) [`timeStrings`](#timeStrings) |
| Other | [`AllowDayOverflow`](#AllowDayOverflow) [`DateTimeException`](#DateTimeException) |

 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/datetime/date.d](https://github.com/dlang/phobos/blob/master/std/datetime/date.d)

 
alias **DateTimeException** = core.time.TimeException;  
Exception type used by std.datetime. It's an alias to [`core.time.TimeException`](core_time#TimeException). Either can be caught without concern about which module it came from.

  enum **Month**: ubyte;  
Represents the 12 months of the Gregorian year (January is 1).



Examples:


```
writeln(Date(2018, 10, 1).month); // Month.oct
writeln(DateTime(1, 1, 1).month); // Month.jan

```
 
 
**jan** **feb** **mar** **apr** **may** **jun** **jul** **aug** **sep** **oct** **nov** **dec**   enum **DayOfWeek**: ubyte;  
Represents the 7 days of the Gregorian week (Sunday is 0).



Examples:


```
writeln(Date(2018, 10, 1).dayOfWeek); // DayOfWeek.mon
writeln(DateTime(5, 5, 5).dayOfWeek); // DayOfWeek.thu

```
 
 
**sun** **mon** **tue** **wed** **thu** **fri** **sat**   alias **AllowDayOverflow** = std.typecons.Flag!"allowDayOverflow".Flag;  
In some date calculations, adding months or years can cause the date to fall on a day of the month which is not valid (e.g. February 29th 2001 or June 31st 2000). If overflow is allowed (as is the default), then the month will be incremented accordingly (so, February 29th 2001 would become March 1st 2001, and June 31st 2000 would become July 1st 2000). If overflow is not allowed, then the day will be adjusted to the last valid day in that month (so, February 29th 2001 would become February 28th 2001 and June 31st 2000 would become June 30th 2000). 


AllowDayOverflow only applies to calculations involving months or years.   
  
 If set to `AllowDayOverflow.no`, then day overflow is not allowed.   
  
 Otherwise, if set to `AllowDayOverflow.yes`, then day overflow is allowed.

  immutable string[] **timeStrings**;  
Array of the strings representing time units, starting with the smallest unit and going to the largest. It does not include `"nsecs"`. 


Includes `"hnsecs"` (hecto-nanoseconds (100 ns)), `"usecs"` (microseconds), `"msecs"` (milliseconds), `"seconds"`, `"minutes"`, `"hours"`, `"days"`, `"weeks"`, `"months"`, and `"years"`

  struct **DateTime**;  
Combines the [`std.datetime.date.Date`](std_datetime_date#Date) and [`std.datetime.date.TimeOfDay`](std_datetime_date#TimeOfDay) structs to give an object which holds both the date and the time. It is optimized for calendar-based operations and has no concept of time zone. For an object which is optimized for time operations based on the system time, use [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime) has a concept of time zone and has much higher precision (hnsecs). `DateTime` is intended primarily for calendar-based uses rather than precise time operations.



Examples:


```
import core.time : days, seconds;

auto dt = DateTime(2000, 6, 1, 10, 30, 0);

writeln(dt.date); // Date(2000, 6, 1)
writeln(dt.timeOfDay); // TimeOfDay(10, 30, 0)
writeln(dt.dayOfYear); // 153
writeln(dt.dayOfWeek); // DayOfWeek.thu

dt += 10.days + 100.seconds;
writeln(dt); // DateTime(2000, 6, 11, 10, 31, 40)

writeln(dt.toISOExtString()); // "2000-06-11T10:31:40"
writeln(dt.toISOString()); // "20000611T103140"
writeln(dt.toSimpleString()); // "2000-Jun-11 10:31:40"

writeln(DateTime.fromISOExtString("2018-01-01T12:00:00")); // DateTime(2018, 1, 1, 12, 0, 0)
writeln(DateTime.fromISOString("20180101T120000")); // DateTime(2018, 1, 1, 12, 0, 0)
writeln(DateTime.fromSimpleString("2018-Jan-01 12:00:00")); // DateTime(2018, 1, 1, 12, 0, 0)

```
 
 
pure nothrow @nogc @safe this(Date date, TimeOfDay tod = TimeOfDay.init);  

Parameters:


|  |  |
| --- | --- |
| Date `date` | The date portion of [`DateTime`](#DateTime). |
| TimeOfDay `tod` | The time portion of [`DateTime`](#DateTime). |


  pure @safe this(int year, int month, int day, int hour = 0, int minute = 0, int second = 0);  

Parameters:


|  |  |
| --- | --- |
| int `year` | The year portion of the date. |
| int `month` | The month portion of the date (January is 1). |
| int `day` | The day portion of the date. |
| int `hour` | The hour portion of the time; |
| int `minute` | The minute portion of the time; |
| int `second` | The second portion of the time; |


  const pure nothrow @nogc @safe int **opCmp**(DateTime rhs);  
Compares this [`DateTime`](#DateTime) with the given `DateTime.`. 



Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const pure nothrow @nogc @property @safe Date **date**();  
The date portion of [`DateTime`](#DateTime).

  pure nothrow @nogc @property @safe void **date**(Date **date**);  
The date portion of [`DateTime`](#DateTime). 



Parameters:


|  |  |
| --- | --- |
| Date `date` | The Date to set this [`DateTime`](#DateTime)'s date portion to. |


  const pure nothrow @nogc @property @safe TimeOfDay **timeOfDay**();  
The time portion of [`DateTime`](#DateTime).

  pure nothrow @nogc @property @safe void **timeOfDay**(TimeOfDay tod);  
The time portion of [`DateTime`](#DateTime). 



Parameters:


|  |  |
| --- | --- |
| TimeOfDay `tod` | The [`std.datetime.date.TimeOfDay`](std_datetime_date#TimeOfDay) to set this [`DateTime`](#DateTime)'s time portion to. |


  const pure nothrow @nogc @property @safe short **year**();  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C.

  pure @property @safe void **year**(int **year**);  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year to set this [`DateTime`](#DateTime)'s year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the new year is not a leap year and if the resulting date would be on February 29th.
 
Examples:


```
writeln(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).year); // 1999
writeln(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).year); // 2010
writeln(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).year); // -7

```
 
  const pure @property @safe short **yearBC**();  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if `isAD` is true.
 
Examples:


```
writeln(DateTime(Date(0, 1, 1), TimeOfDay(12, 30, 33)).yearBC); // 1
writeln(DateTime(Date(-1, 1, 1), TimeOfDay(10, 7, 2)).yearBC); // 2
writeln(DateTime(Date(-100, 1, 1), TimeOfDay(4, 59, 0)).yearBC); // 101

```
 
  pure @property @safe void **yearBC**(int year);  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year B.C. to set this [`DateTime`](#DateTime)'s year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if a non-positive value is given.
 
Examples:


```
auto dt = DateTime(Date(2010, 1, 1), TimeOfDay(7, 30, 0));
dt.yearBC = 1;
writeln(dt); // DateTime(Date(0, 1, 1), TimeOfDay(7, 30, 0))

dt.yearBC = 10;
writeln(dt); // DateTime(Date(-9, 1, 1), TimeOfDay(7, 30, 0))

```
 
  const pure nothrow @nogc @property @safe Month **month**();  
Month of a Gregorian Year.



Examples:


```
writeln(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).month); // 7
writeln(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).month); // 10
writeln(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).month); // 4

```
 
  pure @property @safe void **month**(Month **month**);  
Month of a Gregorian Year. 



Parameters:


|  |  |
| --- | --- |
| Month `month` | The month to set this [`DateTime`](#DateTime)'s month to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given month is not a valid month.
  const pure nothrow @nogc @property @safe ubyte **day**();  
Day of a Gregorian Month.



Examples:


```
writeln(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).day); // 6
writeln(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).day); // 4
writeln(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).day); // 5

```
 
  pure @property @safe void **day**(int **day**);  
Day of a Gregorian Month. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the month to set this [`DateTime`](#DateTime)'s day to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given day is not a valid day of the current month.
  const pure nothrow @nogc @property @safe ubyte **hour**();  
Hours past midnight.

  pure @property @safe void **hour**(int **hour**);  
Hours past midnight. 



Parameters:


|  |  |
| --- | --- |
| int `hour` | The hour of the day to set this [`DateTime`](#DateTime)'s hour to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given hour would result in an invalid [`DateTime`](#DateTime).
  const pure nothrow @nogc @property @safe ubyte **minute**();  
Minutes past the hour.

  pure @property @safe void **minute**(int **minute**);  
Minutes past the hour. 



Parameters:


|  |  |
| --- | --- |
| int `minute` | The minute to set this [`DateTime`](#DateTime)'s minute to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given minute would result in an invalid [`DateTime`](#DateTime).
  const pure nothrow @nogc @property @safe ubyte **second**();  
Seconds past the minute.

  pure @property @safe void **second**(int **second**);  
Seconds past the minute. 



Parameters:


|  |  |
| --- | --- |
| int `second` | The second to set this [`DateTime`](#DateTime)'s second to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given seconds would result in an invalid [`DateTime`](#DateTime).
  pure nothrow @nogc ref @safe DateTime **add**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years" || units == "months"); 
 
Adds the given number of years or months to this [`DateTime`](#DateTime), mutating it. A negative number will subtract. 


Note that if day overflow is allowed, and the date with the adjusted year/month overflows the number of days in the new month, then the month will be incremented by one, and the day set to the number of days overflowed. (e.g. if the day were 31 and the new month were June, then the month would be incremented to July, and the new day would be 1). If day overflow is not allowed, then the day will be set to the last valid day in the month (e.g. June 31st would become June 30th). 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`DateTime`](#DateTime). |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow, causing the month to increment. |


 
Returns:
A reference to the `DateTime` (`this`).
 
Examples:


```
auto dt1 = DateTime(2010, 1, 1, 12, 30, 33);
dt1.add!"months"(11);
writeln(dt1); // DateTime(2010, 12, 1, 12, 30, 33)

auto dt2 = DateTime(2010, 1, 1, 12, 30, 33);
dt2.add!"months"(-11);
writeln(dt2); // DateTime(2009, 2, 1, 12, 30, 33)

auto dt3 = DateTime(2000, 2, 29, 12, 30, 33);
dt3.add!"years"(1);
writeln(dt3); // DateTime(2001, 3, 1, 12, 30, 33)

auto dt4 = DateTime(2000, 2, 29, 12, 30, 33);
dt4.add!"years"(1, AllowDayOverflow.no);
writeln(dt4); // DateTime(2001, 2, 28, 12, 30, 33)

```
 
  pure nothrow @nogc ref @safe DateTime **roll**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years" || units == "months"); 
 
Adds the given number of years or months to this [`DateTime`](#DateTime), mutating it. A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. Rolling a [`DateTime`](#DateTime) 12 months gets the exact same [`DateTime`](#DateTime). However, the days can still be affected due to the differing number of days in each month.   
  
 Because there are no units larger than years, there is no difference between adding and rolling years. 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`DateTime`](#DateTime). |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow, causing the month to increment. |


 
Returns:
A reference to the `DateTime` (`this`).
 
Examples:


```
auto dt1 = DateTime(2010, 1, 1, 12, 33, 33);
dt1.roll!"months"(1);
writeln(dt1); // DateTime(2010, 2, 1, 12, 33, 33)

auto dt2 = DateTime(2010, 1, 1, 12, 33, 33);
dt2.roll!"months"(-1);
writeln(dt2); // DateTime(2010, 12, 1, 12, 33, 33)

auto dt3 = DateTime(1999, 1, 29, 12, 33, 33);
dt3.roll!"months"(1);
writeln(dt3); // DateTime(1999, 3, 1, 12, 33, 33)

auto dt4 = DateTime(1999, 1, 29, 12, 33, 33);
dt4.roll!"months"(1, AllowDayOverflow.no);
writeln(dt4); // DateTime(1999, 2, 28, 12, 33, 33)

auto dt5 = DateTime(2000, 2, 29, 12, 30, 33);
dt5.roll!"years"(1);
writeln(dt5); // DateTime(2001, 3, 1, 12, 30, 33)

auto dt6 = DateTime(2000, 2, 29, 12, 30, 33);
dt6.roll!"years"(1, AllowDayOverflow.no);
writeln(dt6); // DateTime(2001, 2, 28, 12, 30, 33)

```
 
  pure nothrow @nogc ref @safe DateTime **roll**(string units)(long value)  
 Constraints: if (units == "days");   
  
pure nothrow @nogc ref @safe DateTime **roll**(string units)(long value)  
 Constraints: if (units == "hours" || units == "minutes" || units == "seconds"); 
 
Adds the given number of units to this [`DateTime`](#DateTime), mutating it. A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. For instance, rolling a [`DateTime`](#DateTime) one year's worth of days gets the exact same [`DateTime`](#DateTime).   
  
 Accepted units are `"days"`, `"minutes"`, `"hours"`, `"minutes"`, and `"seconds"`. 

 
Parameters:


|  |  |
| --- | --- |
| units | The units to add. |
| long `value` | The number of units to add to this [`DateTime`](#DateTime). |


 
Returns:
A reference to the `DateTime` (`this`).
 
Examples:


```
auto dt1 = DateTime(2010, 1, 1, 11, 23, 12);
dt1.roll!"days"(1);
writeln(dt1); // DateTime(2010, 1, 2, 11, 23, 12)
dt1.roll!"days"(365);
writeln(dt1); // DateTime(2010, 1, 26, 11, 23, 12)
dt1.roll!"days"(-32);
writeln(dt1); // DateTime(2010, 1, 25, 11, 23, 12)

auto dt2 = DateTime(2010, 7, 4, 12, 0, 0);
dt2.roll!"hours"(1);
writeln(dt2); // DateTime(2010, 7, 4, 13, 0, 0)

auto dt3 = DateTime(2010, 1, 1, 0, 0, 0);
dt3.roll!"seconds"(-1);
writeln(dt3); // DateTime(2010, 1, 1, 0, 0, 59)

```
 
  const pure nothrow @nogc @safe DateTime **opBinary**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`DateTime`](#DateTime). 


The legal types of arithmetic for [`DateTime`](#DateTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| DateTime | + | Duration | --> | DateTime |
| DateTime | - | Duration | --> | DateTime |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`DateTime`](#DateTime). |


 
Examples:


```
import core.time : hours, seconds;

assert(DateTime(2015, 12, 31, 23, 59, 59) + seconds(1) ==
       DateTime(2016, 1, 1, 0, 0, 0));

assert(DateTime(2015, 12, 31, 23, 59, 59) + hours(1) ==
       DateTime(2016, 1, 1, 0, 59, 59));

assert(DateTime(2016, 1, 1, 0, 0, 0) - seconds(1) ==
       DateTime(2015, 12, 31, 23, 59, 59));

assert(DateTime(2016, 1, 1, 0, 59, 59) - hours(1) ==
       DateTime(2015, 12, 31, 23, 59, 59));

```
 
  pure nothrow @nogc ref @safe DateTime **opOpAssign**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a duration from this [`DateTime`](#DateTime), as well as assigning the result to this [`DateTime`](#DateTime). 


The legal types of arithmetic for [`DateTime`](#DateTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| DateTime | + | duration | --> | DateTime |
| DateTime | - | duration | --> | DateTime |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The duration to add to or subtract from this [`DateTime`](#DateTime). |


  const pure nothrow @nogc @safe Duration **opBinary**(string op)(DateTime rhs)  
 Constraints: if (op == "-"); 
 
Gives the difference between two [`DateTime`](#DateTime)s. 


The legal types of arithmetic for [`DateTime`](#DateTime) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| DateTime | - | DateTime | --> | duration |



  const pure nothrow @nogc @safe int **diffMonths**(DateTime rhs);  
Returns the difference between the two [`DateTime`](#DateTime)s in months. 


To get the difference in years, subtract the year property of two [`DateTime`](#DateTime)s. To get the difference in days or weeks, subtract the [`DateTime`](#DateTime)s themselves and use the [`core.time.Duration`](core_time#Duration) that results. Because converting between months and smaller units requires a specific date (which [`core.time.Duration`](core_time#Duration)s don't have), getting the difference in months requires some math using both the year and month properties, so this is a convenience function for getting the difference in months.   
  
 Note that the number of days in the months or how far into the month either date is is irrelevant. It is the difference in the month property combined with the difference in years \* 12. So, for instance, December 31st and January 1st are one month apart just as December 1st and January 31st are one month apart. 

 
Parameters:


|  |  |
| --- | --- |
| DateTime `rhs` | The [`DateTime`](#DateTime) to subtract from this one. |


 
Examples:


```
assert(DateTime(1999, 2, 1, 12, 2, 3).diffMonths(
           DateTime(1999, 1, 31, 23, 59, 59)) == 1);

assert(DateTime(1999, 1, 31, 0, 0, 0).diffMonths(
           DateTime(1999, 2, 1, 12, 3, 42)) == -1);

assert(DateTime(1999, 3, 1, 5, 30, 0).diffMonths(
           DateTime(1999, 1, 1, 2, 4, 7)) == 2);

assert(DateTime(1999, 1, 1, 7, 2, 4).diffMonths(
           DateTime(1999, 3, 31, 0, 30, 58)) == -2);

```
 
  const pure nothrow @nogc @property @safe bool **isLeapYear**();  
Whether this [`DateTime`](#DateTime) is in a leap year.

  const pure nothrow @nogc @property @safe DayOfWeek **dayOfWeek**();  
Day of the week this [`DateTime`](#DateTime) is on.

  const pure nothrow @nogc @property @safe ushort **dayOfYear**();  
Day of the year this [`DateTime`](#DateTime) is on.



Examples:


```
writeln(DateTime(Date(1999, 1, 1), TimeOfDay(12, 22, 7)).dayOfYear); // 1
writeln(DateTime(Date(1999, 12, 31), TimeOfDay(7, 2, 59)).dayOfYear); // 365
writeln(DateTime(Date(2000, 12, 31), TimeOfDay(21, 20, 0)).dayOfYear); // 366

```
 
  pure @property @safe void **dayOfYear**(int day);  
Day of the year. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the year to set which day of the year this [`DateTime`](#DateTime) is on. |


  const pure nothrow @nogc @property @safe int **dayOfGregorianCal**();  
The Xth day of the Gregorian Calendar that this [`DateTime`](#DateTime) is on.



Examples:


```
writeln(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)).dayOfGregorianCal); // 1
writeln(DateTime(Date(1, 12, 31), TimeOfDay(23, 59, 59)).dayOfGregorianCal); // 365
writeln(DateTime(Date(2, 1, 1), TimeOfDay(2, 2, 2)).dayOfGregorianCal); // 366

writeln(DateTime(Date(0, 12, 31), TimeOfDay(7, 7, 7)).dayOfGregorianCal); // 0
writeln(DateTime(Date(0, 1, 1), TimeOfDay(19, 30, 0)).dayOfGregorianCal); // -365
writeln(DateTime(Date(-1, 12, 31), TimeOfDay(4, 7, 0)).dayOfGregorianCal); // -366

writeln(DateTime(Date(2000, 1, 1), TimeOfDay(9, 30, 20)).dayOfGregorianCal); // 730_120
writeln(DateTime(Date(2010, 12, 31), TimeOfDay(15, 45, 50)).dayOfGregorianCal); // 734_137

```
 
  pure nothrow @nogc @property @safe void **dayOfGregorianCal**(int days);  
The Xth day of the Gregorian Calendar that this [`DateTime`](#DateTime) is on. Setting this property does not affect the time portion of [`DateTime`](#DateTime). 



Parameters:


|  |  |
| --- | --- |
| int `days` | The day of the Gregorian Calendar to set this [`DateTime`](#DateTime) to. |


 
Examples:


```
auto dt = DateTime(Date.init, TimeOfDay(12, 0, 0));
dt.dayOfGregorianCal = 1;
writeln(dt); // DateTime(Date(1, 1, 1), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = 365;
writeln(dt); // DateTime(Date(1, 12, 31), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = 366;
writeln(dt); // DateTime(Date(2, 1, 1), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = 0;
writeln(dt); // DateTime(Date(0, 12, 31), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = -365;
writeln(dt); // DateTime(Date(-0, 1, 1), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = -366;
writeln(dt); // DateTime(Date(-1, 12, 31), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = 730_120;
writeln(dt); // DateTime(Date(2000, 1, 1), TimeOfDay(12, 0, 0))

dt.dayOfGregorianCal = 734_137;
writeln(dt); // DateTime(Date(2010, 12, 31), TimeOfDay(12, 0, 0))

```
 
  const pure nothrow @property @safe ubyte **isoWeek**();  
The ISO 8601 week of the year that this [`DateTime`](#DateTime) is in. 



See Also:
[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date)
  const pure nothrow @property @safe short **isoWeekYear**();  
The year of the ISO 8601 week calendar that this [`DateTime`](#DateTime) is in. 



See Also:
[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date)
  const pure nothrow @property @safe DateTime **endOfMonth**();  
[`DateTime`](#DateTime) for the last day in the month that this [`DateTime`](#DateTime) is in. The time portion of endOfMonth is always 23:59:59.



Examples:


```
assert(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).endOfMonth ==
       DateTime(Date(1999, 1, 31), TimeOfDay(23, 59, 59)));

assert(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).endOfMonth ==
       DateTime(Date(1999, 2, 28), TimeOfDay(23, 59, 59)));

assert(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).endOfMonth ==
       DateTime(Date(2000, 2, 29), TimeOfDay(23, 59, 59)));

assert(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).endOfMonth ==
       DateTime(Date(2000, 6, 30), TimeOfDay(23, 59, 59)));

```
 
  const pure nothrow @nogc @property @safe ubyte **daysInMonth**();  
The last day in the month that this [`DateTime`](#DateTime) is in.



Examples:


```
writeln(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).daysInMonth); // 31
writeln(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).daysInMonth); // 28
writeln(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).daysInMonth); // 29
writeln(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).daysInMonth); // 30

```
 
  const pure nothrow @nogc @property @safe bool **isAD**();  
Whether the current year is a date in A.D.



Examples:


```
assert(DateTime(Date(1, 1, 1), TimeOfDay(12, 7, 0)).isAD);
assert(DateTime(Date(2010, 12, 31), TimeOfDay(0, 0, 0)).isAD);
assert(!DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 59)).isAD);
assert(!DateTime(Date(-2010, 1, 1), TimeOfDay(2, 2, 2)).isAD);

```
 
  const pure nothrow @nogc @property @safe long **julianDay**();  
The [Julian day](http://en.wikipedia.org/wiki/Julian_day) for this [`DateTime`](#DateTime) at the given time. For example, prior to noon, 1996-03-31 would be the Julian day number 2\_450\_173, so this function returns 2\_450\_173, while from noon onward, the julian day number would be 2\_450\_174, so this function returns 2\_450\_174.

  const pure nothrow @nogc @property @safe long **modJulianDay**();  
The modified [Julian day](http://en.wikipedia.org/wiki/Julian_day) for any time on this date (since, the modified Julian day changes at midnight).

  const pure nothrow @safe string **toISOString**();   
  
const void **toISOString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`DateTime`](#DateTime) to a string with the format `YYYYMMDDTHHMMSS`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOString() ==
       "20100704T070612");

assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOString() ==
       "19981225T021500");

assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOString() ==
       "00000105T230959");

assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOString() ==
       "-00040105T000002");

```
 
  const pure nothrow @safe string **toISOExtString**();   
  
const void **toISOExtString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`DateTime`](#DateTime) to a string with the format `YYYY-MM-DDTHH:MM:SS`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOExtString() ==
       "2010-07-04T07:06:12");

assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOExtString() ==
       "1998-12-25T02:15:00");

assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOExtString() ==
       "0000-01-05T23:09:59");

assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOExtString() ==
       "-0004-01-05T00:00:02");

```
 
  const pure nothrow @safe string **toSimpleString**();   
  
const void **toSimpleString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`DateTime`](#DateTime) to a string with the format `YYYY-Mon-DD HH:MM:SS`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toSimpleString() ==
       "2010-Jul-04 07:06:12");

assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toSimpleString() ==
       "1998-Dec-25 02:15:00");

assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toSimpleString() ==
       "0000-Jan-05 23:09:59");

assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toSimpleString() ==
       "-0004-Jan-05 00:00:02");

```
 
  const pure nothrow @safe string **toString**();   
  
const void **toString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`DateTime`](#DateTime) to a string. 


This function exists to make it easy to convert a [`DateTime`](#DateTime) to a string for code that does not care what the exact format is - just that it presents the information in a clear manner. It also makes it easy to simply convert a [`DateTime`](#DateTime) to a string when using functions such as `to!string`, `format`, or `writeln` which use toString to convert user-defined types. So, it is unlikely that much code will call toString directly.   
  
 The format of the string is purposefully unspecified, and code that cares about the format of the string should use `toISOString`, `toISOExtString`, `toSimpleString`, or some other custom formatting function that explicitly generates the format that the code needs. The reason is that the code is then clear about what format it's using, making it less error-prone to maintain the code and interact with other software that consumes the generated strings. It's for this same reason that [`DateTime`](#DateTime) has no `fromString` function, whereas it does have `fromISOString`, `fromISOExtString`, and `fromSimpleString`.   
  
 The format returned by toString may or may not change in the future.

  pure @safe DateTime **fromISOString**(S)(scope const S isoString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`DateTime`](#DateTime) from a string with the format YYYYMMDDTHHMMSS. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoString` | A string formatted in the ISO format for dates and times. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`DateTime`](#DateTime) would not be valid.
  pure @safe DateTime **fromISOExtString**(S)(scope const S isoExtString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`DateTime`](#DateTime) from a string with the format YYYY-MM-DDTHH:MM:SS. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoExtString` | A string formatted in the ISO Extended format for dates and times. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO Extended format or if the resulting [`DateTime`](#DateTime) would not be valid.
  pure @safe DateTime **fromSimpleString**(S)(scope const S simpleString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`DateTime`](#DateTime) from a string with the format YYYY-Mon-DD HH:MM:SS. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `simpleString` | A string formatted in the way that toSimpleString formats dates and times. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the correct format or if the resulting [`DateTime`](#DateTime) would not be valid.
  static pure nothrow @nogc @property @safe DateTime **min**();  
Returns the [`DateTime`](#DateTime) farthest in the past which is representable by [`DateTime`](#DateTime).

  static pure nothrow @nogc @property @safe DateTime **max**();  
Returns the [`DateTime`](#DateTime) farthest in the future which is representable by [`DateTime`](#DateTime).

    struct **Date**;  
Represents a date in the [Proleptic Gregorian Calendar](http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar) ranging from 32,768 B.C. to 32,767 A.D. Positive years are A.D. Non-positive years are B.C. 


Year, month, and day are kept separately internally so that `Date` is optimized for calendar-based operations.   
  
 `Date` uses the Proleptic Gregorian Calendar, so it assumes the Gregorian leap year calculations for its entire length. As per [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601), it treats 1 B.C. as year 0, i.e. 1 B.C. is 0, 2 B.C. is -1, etc. Use [`yearBC`](#yearBC) to use B.C. as a positive integer with 1 B.C. being the year prior to 1 A.D.   
  
 Year 0 is a leap year.

 
Examples:


```
import core.time : days;

auto d = Date(2000, 6, 1);

writeln(d.dayOfYear); // 153
writeln(d.dayOfWeek); // DayOfWeek.thu

d += 10.days;
writeln(d); // Date(2000, 6, 11)

writeln(d.toISOExtString()); // "2000-06-11"
writeln(d.toISOString()); // "20000611"
writeln(d.toSimpleString()); // "2000-Jun-11"

writeln(Date.fromISOExtString("2018-01-01")); // Date(2018, 1, 1)
writeln(Date.fromISOString("20180101")); // Date(2018, 1, 1)
writeln(Date.fromSimpleString("2018-Jan-01")); // Date(2018, 1, 1)

```
 
 
pure @safe this(int year, int month, int day);  

Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the resulting [`Date`](#Date) would not be valid. 
 
Parameters:


|  |  |
| --- | --- |
| int `year` | Year of the Gregorian Calendar. Positive values are A.D. Non-positive values are B.C. with year 0 being the year prior to 1 A.D. |
| int `month` | Month of the year (January is 1). |
| int `day` | Day of the month. |


  pure nothrow @nogc @safe this(int day);  

Parameters:


|  |  |
| --- | --- |
| int `day` | The Xth day of the Gregorian Calendar that the constructed [`Date`](#Date) will be for. |


  const pure nothrow @nogc @safe int **opCmp**(Date rhs);  
Compares this [`Date`](#Date) with the given [`Date`](#Date). 



Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const pure nothrow @nogc @property @safe short **year**();  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C.



Examples:


```
writeln(Date(1999, 7, 6).year); // 1999
writeln(Date(2010, 10, 4).year); // 2010
writeln(Date(-7, 4, 5).year); // -7

```
 
  pure @property @safe void **year**(int **year**);  
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive are B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year to set this Date's year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the new year is not a leap year and the resulting date would be on February 29th.
 
Examples:


```
writeln(Date(1999, 7, 6).year); // 1999
writeln(Date(2010, 10, 4).year); // 2010
writeln(Date(-7, 4, 5).year); // -7

```
 
  const pure @property @safe ushort **yearBC**();  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if `isAD` is true.
 
Examples:


```
writeln(Date(0, 1, 1).yearBC); // 1
writeln(Date(-1, 1, 1).yearBC); // 2
writeln(Date(-100, 1, 1).yearBC); // 101

```
 
  pure @property @safe void **yearBC**(int year);  
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year B.C. to set this [`Date`](#Date)'s year to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if a non-positive value is given.
 
Examples:


```
auto date = Date(2010, 1, 1);
date.yearBC = 1;
writeln(date); // Date(0, 1, 1)

date.yearBC = 10;
writeln(date); // Date(-9, 1, 1)

```
 
  const pure nothrow @nogc @property @safe Month **month**();  
Month of a Gregorian Year.



Examples:


```
writeln(Date(1999, 7, 6).month); // 7
writeln(Date(2010, 10, 4).month); // 10
writeln(Date(-7, 4, 5).month); // 4

```
 
  pure @property @safe void **month**(Month **month**);  
Month of a Gregorian Year. 



Parameters:


|  |  |
| --- | --- |
| Month `month` | The month to set this [`Date`](#Date)'s month to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given month is not a valid month or if the current day would not be valid in the given month.
  const pure nothrow @nogc @property @safe ubyte **day**();  
Day of a Gregorian Month.



Examples:


```
writeln(Date(1999, 7, 6).day); // 6
writeln(Date(2010, 10, 4).day); // 4
writeln(Date(-7, 4, 5).day); // 5

```
 
  pure @property @safe void **day**(int **day**);  
Day of a Gregorian Month. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the month to set this [`Date`](#Date)'s day to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given day is not a valid day of the current month.
  pure nothrow @nogc ref @safe Date **add**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years"); 
 
Adds the given number of years or months to this [`Date`](#Date), mutating it. A negative number will subtract. 


Note that if day overflow is allowed, and the date with the adjusted year/month overflows the number of days in the new month, then the month will be incremented by one, and the day set to the number of days overflowed. (e.g. if the day were 31 and the new month were June, then the month would be incremented to July, and the new day would be 1). If day overflow is not allowed, then the day will be set to the last valid day in the month (e.g. June 31st would become June 30th). 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`Date`](#Date). |
| AllowDayOverflow `allowOverflow` | Whether the day should be allowed to overflow, causing the month to increment. |


 
Returns:
A reference to the `Date` (`this`).
 
Examples:


```
auto d1 = Date(2010, 1, 1);
d1.add!"months"(11);
writeln(d1); // Date(2010, 12, 1)

auto d2 = Date(2010, 1, 1);
d2.add!"months"(-11);
writeln(d2); // Date(2009, 2, 1)

auto d3 = Date(2000, 2, 29);
d3.add!"years"(1);
writeln(d3); // Date(2001, 3, 1)

auto d4 = Date(2000, 2, 29);
d4.add!"years"(1, AllowDayOverflow.no);
writeln(d4); // Date(2001, 2, 28)

```
 
  pure nothrow @nogc ref @safe Date **roll**(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (units == "years"); 
 
Adds the given number of years or months to this [`Date`](#Date), mutating it. A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. Rolling a [`Date`](#Date) 12 months gets the exact same [`Date`](#Date). However, the days can still be affected due to the differing number of days in each month.   
  
 Because there are no units larger than years, there is no difference between adding and rolling years. 

 
Parameters:


|  |  |
| --- | --- |
| units | The type of units to add ("years" or "months"). |
| long `value` | The number of months or years to add to this [`Date`](#Date). |
| AllowDayOverflow `allowOverflow` | Whether the day should be allowed to overflow, causing the month to increment. |


 
Returns:
A reference to the `Date` (`this`).
 
Examples:


```
auto d1 = Date(2010, 1, 1);
d1.roll!"months"(1);
writeln(d1); // Date(2010, 2, 1)

auto d2 = Date(2010, 1, 1);
d2.roll!"months"(-1);
writeln(d2); // Date(2010, 12, 1)

auto d3 = Date(1999, 1, 29);
d3.roll!"months"(1);
writeln(d3); // Date(1999, 3, 1)

auto d4 = Date(1999, 1, 29);
d4.roll!"months"(1, AllowDayOverflow.no);
writeln(d4); // Date(1999, 2, 28)

auto d5 = Date(2000, 2, 29);
d5.roll!"years"(1);
writeln(d5); // Date(2001, 3, 1)

auto d6 = Date(2000, 2, 29);
d6.roll!"years"(1, AllowDayOverflow.no);
writeln(d6); // Date(2001, 2, 28)

```
 
  pure nothrow @nogc ref @safe Date **roll**(string units)(long days)  
 Constraints: if (units == "days"); 
 
Adds the given number of units to this [`Date`](#Date), mutating it. A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. For instance, rolling a [`Date`](#Date) one year's worth of days gets the exact same [`Date`](#Date).   
  
 The only accepted units are `"days"`. 

 
Parameters:


|  |  |
| --- | --- |
| units | The units to add. Must be `"days"`. |
| long `days` | The number of days to add to this [`Date`](#Date). |


 
Returns:
A reference to the `Date` (`this`).
 
Examples:


```
auto d = Date(2010, 1, 1);
d.roll!"days"(1);
writeln(d); // Date(2010, 1, 2)
d.roll!"days"(365);
writeln(d); // Date(2010, 1, 26)
d.roll!"days"(-32);
writeln(d); // Date(2010, 1, 25)

```
 
  const pure nothrow @nogc @safe Date **opBinary**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from 


The legal types of arithmetic for [`Date`](#Date) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Date | + | Duration | --> | Date |
| Date | - | Duration | --> | Date |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`Date`](#Date). |


 
Examples:


```
import core.time : days;

writeln(Date(2015, 12, 31) + days(1)); // Date(2016, 1, 1)
writeln(Date(2004, 2, 26) + days(4)); // Date(2004, 3, 1)

writeln(Date(2016, 1, 1) - days(1)); // Date(2015, 12, 31)
writeln(Date(2004, 3, 1) - days(4)); // Date(2004, 2, 26)

```
 
  pure nothrow @nogc ref @safe Date **opOpAssign**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`Date`](#Date), as well as assigning the result to this [`Date`](#Date). 


The legal types of arithmetic for [`Date`](#Date) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Date | + | Duration | --> | Date |
| Date | - | Duration | --> | Date |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`Date`](#Date). |


  const pure nothrow @nogc @safe Duration **opBinary**(string op)(Date rhs)  
 Constraints: if (op == "-"); 
 
Gives the difference between two [`Date`](#Date)s. 


The legal types of arithmetic for [`Date`](#Date) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Date | - | Date | --> | duration |



  const pure nothrow @nogc @safe int **diffMonths**(Date rhs);  
Returns the difference between the two [`Date`](#Date)s in months. 


To get the difference in years, subtract the year property of two [`Date`](#Date)s. To get the difference in days or weeks, subtract the [`Date`](#Date)s themselves and use the [`core.time.Duration`](core_time#Duration) that results. Because converting between months and smaller units requires a specific date (which [`core.time.Duration`](core_time#Duration)s don't have), getting the difference in months requires some math using both the year and month properties, so this is a convenience function for getting the difference in months.   
  
 Note that the number of days in the months or how far into the month either [`Date`](#Date) is is irrelevant. It is the difference in the month property combined with the difference in years \* 12. So, for instance, December 31st and January 1st are one month apart just as December 1st and January 31st are one month apart. 

 
Parameters:


|  |  |
| --- | --- |
| Date `rhs` | The [`Date`](#Date) to subtract from this one. |


 
Examples:


```
writeln(Date(1999, 2, 1).diffMonths(Date(1999, 1, 31))); // 1
writeln(Date(1999, 1, 31).diffMonths(Date(1999, 2, 1))); // -1
writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1))); // 2
writeln(Date(1999, 1, 1).diffMonths(Date(1999, 3, 31))); // -2

```
 
  const pure nothrow @nogc @property @safe bool **isLeapYear**();  
Whether this [`Date`](#Date) is in a leap year.

  const pure nothrow @nogc @property @safe DayOfWeek **dayOfWeek**();  
Day of the week this [`Date`](#Date) is on.

  const pure nothrow @nogc @property @safe ushort **dayOfYear**();  
Day of the year this [`Date`](#Date) is on.



Examples:


```
writeln(Date(1999, 1, 1).dayOfYear); // 1
writeln(Date(1999, 12, 31).dayOfYear); // 365
writeln(Date(2000, 12, 31).dayOfYear); // 366

```
 
  pure @property @safe void **dayOfYear**(int day);  
Day of the year. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the year to set which day of the year this [`Date`](#Date) is on. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given day is an invalid day of the year.
  const pure nothrow @nogc @property @safe int **dayOfGregorianCal**();  
The Xth day of the Gregorian Calendar that this [`Date`](#Date) is on.



Examples:


```
writeln(Date(1, 1, 1).dayOfGregorianCal); // 1
writeln(Date(1, 12, 31).dayOfGregorianCal); // 365
writeln(Date(2, 1, 1).dayOfGregorianCal); // 366

writeln(Date(0, 12, 31).dayOfGregorianCal); // 0
writeln(Date(0, 1, 1).dayOfGregorianCal); // -365
writeln(Date(-1, 12, 31).dayOfGregorianCal); // -366

writeln(Date(2000, 1, 1).dayOfGregorianCal); // 730_120
writeln(Date(2010, 12, 31).dayOfGregorianCal); // 734_137

```
 
  pure nothrow @nogc @property @safe void **dayOfGregorianCal**(int day);  
The Xth day of the Gregorian Calendar that this [`Date`](#Date) is on. 



Parameters:


|  |  |
| --- | --- |
| int `day` | The day of the Gregorian Calendar to set this [`Date`](#Date) to. |


 
Examples:


```
auto date = Date.init;
date.dayOfGregorianCal = 1;
writeln(date); // Date(1, 1, 1)

date.dayOfGregorianCal = 365;
writeln(date); // Date(1, 12, 31)

date.dayOfGregorianCal = 366;
writeln(date); // Date(2, 1, 1)

date.dayOfGregorianCal = 0;
writeln(date); // Date(0, 12, 31)

date.dayOfGregorianCal = -365;
writeln(date); // Date(-0, 1, 1)

date.dayOfGregorianCal = -366;
writeln(date); // Date(-1, 12, 31)

date.dayOfGregorianCal = 730_120;
writeln(date); // Date(2000, 1, 1)

date.dayOfGregorianCal = 734_137;
writeln(date); // Date(2010, 12, 31)

```
 
  const pure nothrow @property @safe auto **isoWeekAndYear**();  
The ISO 8601 week and year of the year that this [`Date`](#Date) is in. 



Returns:
An anonymous struct with the members `isoWeekYear` for the resulting year and `isoWeek` for the resulting ISO week. 
 
See Also:
[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date)
  const pure nothrow @property @safe ubyte **isoWeek**();  
The ISO 8601 week of the year that this [`Date`](#Date) is in. 



See Also:
[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date)
  const pure nothrow @property @safe short **isoWeekYear**();  
The year inside the ISO 8601 week calendar that this [`Date`](#Date) is in. 


May differ from [`year`](#year) between 28 December and 4 January. 

 
See Also:
[ISO Week Date](http://en.wikipedia.org/wiki/ISO_week_date)
  const pure nothrow @property @safe Date **endOfMonth**();  
[`Date`](#Date) for the last day in the month that this [`Date`](#Date) is in.



Examples:


```
writeln(Date(1999, 1, 6).endOfMonth); // Date(1999, 1, 31)
writeln(Date(1999, 2, 7).endOfMonth); // Date(1999, 2, 28)
writeln(Date(2000, 2, 7).endOfMonth); // Date(2000, 2, 29)
writeln(Date(2000, 6, 4).endOfMonth); // Date(2000, 6, 30)

```
 
  const pure nothrow @nogc @property @safe ubyte **daysInMonth**();  
The last day in the month that this [`Date`](#Date) is in.



Examples:


```
writeln(Date(1999, 1, 6).daysInMonth); // 31
writeln(Date(1999, 2, 7).daysInMonth); // 28
writeln(Date(2000, 2, 7).daysInMonth); // 29
writeln(Date(2000, 6, 4).daysInMonth); // 30

```
 
  const pure nothrow @nogc @property @safe bool **isAD**();  
Whether the current year is a date in A.D.



Examples:


```
assert(Date(1, 1, 1).isAD);
assert(Date(2010, 12, 31).isAD);
assert(!Date(0, 12, 31).isAD);
assert(!Date(-2010, 1, 1).isAD);

```
 
  const pure nothrow @nogc @property @safe long **julianDay**();  
The [Julian day](http://en.wikipedia.org/wiki/Julian_day) for this [`Date`](#Date) at noon (since the Julian day changes at noon).

  const pure nothrow @nogc @property @safe long **modJulianDay**();  
The modified [Julian day](http://en.wikipedia.org/wiki/Julian_day) for any time on this date (since, the modified Julian day changes at midnight).

  const pure nothrow @safe string **toISOString**();   
  
const void **toISOString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`Date`](#Date) to a string with the format `YYYYMMDD`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
writeln(Date(2010, 7, 4).toISOString()); // "20100704"
writeln(Date(1998, 12, 25).toISOString()); // "19981225"
writeln(Date(0, 1, 5).toISOString()); // "00000105"
writeln(Date(-4, 1, 5).toISOString()); // "-00040105"

```
 
  const pure nothrow @safe string **toISOExtString**();   
  
const void **toISOExtString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`Date`](#Date) to a string with the format `YYYY-MM-DD`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
writeln(Date(2010, 7, 4).toISOExtString()); // "2010-07-04"
writeln(Date(1998, 12, 25).toISOExtString()); // "1998-12-25"
writeln(Date(0, 1, 5).toISOExtString()); // "0000-01-05"
writeln(Date(-4, 1, 5).toISOExtString()); // "-0004-01-05"

```
 
  const pure nothrow @safe string **toSimpleString**();   
  
const void **toSimpleString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`Date`](#Date) to a string with the format `YYYY-Mon-DD`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
writeln(Date(2010, 7, 4).toSimpleString()); // "2010-Jul-04"
writeln(Date(1998, 12, 25).toSimpleString()); // "1998-Dec-25"
writeln(Date(0, 1, 5).toSimpleString()); // "0000-Jan-05"
writeln(Date(-4, 1, 5).toSimpleString()); // "-0004-Jan-05"

```
 
  const pure nothrow @safe string **toString**();   
  
const void **toString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`Date`](#Date) to a string. 


This function exists to make it easy to convert a [`Date`](#Date) to a string for code that does not care what the exact format is - just that it presents the information in a clear manner. It also makes it easy to simply convert a [`Date`](#Date) to a string when using functions such as `to!string`, `format`, or `writeln` which use toString to convert user-defined types. So, it is unlikely that much code will call toString directly.   
  
 The format of the string is purposefully unspecified, and code that cares about the format of the string should use `toISOString`, `toISOExtString`, `toSimpleString`, or some other custom formatting function that explicitly generates the format that the code needs. The reason is that the code is then clear about what format it's using, making it less error-prone to maintain the code and interact with other software that consumes the generated strings. It's for this same reason [`Date`](#Date) has no `fromString` function, whereas it does have `fromISOString`, `fromISOExtString`, and `fromSimpleString`.   
  
 The format returned by toString may or may not change in the future.

  pure @safe Date **fromISOString**(S)(scope const S isoString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`Date`](#Date) from a string with the format YYYYMMDD. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoString` | A string formatted in the ISO format for dates. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`Date`](#Date) would not be valid.
  pure @safe Date **fromISOExtString**(S)(scope const S isoExtString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`Date`](#Date) from a string with the format YYYY-MM-DD. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoExtString` | A string formatted in the ISO Extended format for dates. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO Extended format or if the resulting [`Date`](#Date) would not be valid.
  pure @safe Date **fromSimpleString**(S)(scope const S simpleString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`Date`](#Date) from a string with the format YYYY-Mon-DD. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `simpleString` | A string formatted in the way that toSimpleString formats dates. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the correct format or if the resulting [`Date`](#Date) would not be valid.
  static pure nothrow @nogc @property @safe Date **min**();  
Returns the [`Date`](#Date) farthest in the past which is representable by [`Date`](#Date).

  static pure nothrow @nogc @property @safe Date **max**();  
Returns the [`Date`](#Date) farthest in the future which is representable by [`Date`](#Date).

    struct **TimeOfDay**;  
Represents a time of day with hours, minutes, and seconds. It uses 24 hour time.



Examples:


```
import core.time : minutes, seconds;

auto t = TimeOfDay(12, 30, 0);

t += 10.minutes + 100.seconds;
writeln(t); // TimeOfDay(12, 41, 40)

writeln(t.toISOExtString()); // "12:41:40"
writeln(t.toISOString()); // "124140"

writeln(TimeOfDay.fromISOExtString("15:00:00")); // TimeOfDay(15, 0, 0)
writeln(TimeOfDay.fromISOString("015000")); // TimeOfDay(1, 50, 0)

```
 
 
pure @safe this(int hour, int minute, int second = 0);  

Parameters:


|  |  |
| --- | --- |
| int `hour` | Hour of the day [0 - 24). |
| int `minute` | Minute of the hour [0 - 60). |
| int `second` | Second of the minute [0 - 60). |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the resulting [`TimeOfDay`](#TimeOfDay) would be not be valid.
  const pure nothrow @nogc @safe int **opCmp**(TimeOfDay rhs);  
Compares this [`TimeOfDay`](#TimeOfDay) with the given [`TimeOfDay`](#TimeOfDay). 



Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const pure nothrow @nogc @property @safe ubyte **hour**();  
Hours past midnight.

  pure @property @safe void **hour**(int **hour**);  
Hours past midnight. 



Parameters:


|  |  |
| --- | --- |
| int `hour` | The hour of the day to set this [`TimeOfDay`](#TimeOfDay)'s hour to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given hour would result in an invalid [`TimeOfDay`](#TimeOfDay).
  const pure nothrow @nogc @property @safe ubyte **minute**();  
Minutes past the hour.

  pure @property @safe void **minute**(int **minute**);  
Minutes past the hour. 



Parameters:


|  |  |
| --- | --- |
| int `minute` | The minute to set this [`TimeOfDay`](#TimeOfDay)'s minute to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given minute would result in an invalid [`TimeOfDay`](#TimeOfDay).
  const pure nothrow @nogc @property @safe ubyte **second**();  
Seconds past the minute.

  pure @property @safe void **second**(int **second**);  
Seconds past the minute. 



Parameters:


|  |  |
| --- | --- |
| int `second` | The second to set this [`TimeOfDay`](#TimeOfDay)'s second to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given second would result in an invalid [`TimeOfDay`](#TimeOfDay).
  pure nothrow @nogc ref @safe TimeOfDay **roll**(string units)(long value)  
 Constraints: if (units == "hours");   
  
pure nothrow @nogc ref @safe TimeOfDay **roll**(string units)(long value)  
 Constraints: if (units == "minutes" || units == "seconds"); 
 
Adds the given number of units to this [`TimeOfDay`](#TimeOfDay), mutating it. A negative number will subtract. 


The difference between rolling and adding is that rolling does not affect larger units. For instance, rolling a [`TimeOfDay`](#TimeOfDay) one hours's worth of minutes gets the exact same [`TimeOfDay`](#TimeOfDay).   
  
 Accepted units are `"hours"`, `"minutes"`, and `"seconds"`. 

 
Parameters:


|  |  |
| --- | --- |
| units | The units to add. |
| long `value` | The number of units to add to this [`TimeOfDay`](#TimeOfDay). |


 
Returns:
A reference to the `TimeOfDay` (`this`).
 
Examples:


```
auto tod1 = TimeOfDay(7, 12, 0);
tod1.roll!"hours"(1);
writeln(tod1); // TimeOfDay(8, 12, 0)

auto tod2 = TimeOfDay(7, 12, 0);
tod2.roll!"hours"(-1);
writeln(tod2); // TimeOfDay(6, 12, 0)

auto tod3 = TimeOfDay(23, 59, 0);
tod3.roll!"minutes"(1);
writeln(tod3); // TimeOfDay(23, 0, 0)

auto tod4 = TimeOfDay(0, 0, 0);
tod4.roll!"minutes"(-1);
writeln(tod4); // TimeOfDay(0, 59, 0)

auto tod5 = TimeOfDay(23, 59, 59);
tod5.roll!"seconds"(1);
writeln(tod5); // TimeOfDay(23, 59, 0)

auto tod6 = TimeOfDay(0, 0, 0);
tod6.roll!"seconds"(-1);
writeln(tod6); // TimeOfDay(0, 0, 59)

```
 
  const pure nothrow @nogc @safe TimeOfDay **opBinary**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`TimeOfDay`](#TimeOfDay). 


The legal types of arithmetic for [`TimeOfDay`](#TimeOfDay) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TimeOfDay | + | Duration | --> | TimeOfDay |
| TimeOfDay | - | Duration | --> | TimeOfDay |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`TimeOfDay`](#TimeOfDay). |


 
Examples:


```
import core.time : hours, minutes, seconds;

writeln(TimeOfDay(12, 12, 12) + seconds(1)); // TimeOfDay(12, 12, 13)
writeln(TimeOfDay(12, 12, 12) + minutes(1)); // TimeOfDay(12, 13, 12)
writeln(TimeOfDay(12, 12, 12) + hours(1)); // TimeOfDay(13, 12, 12)
writeln(TimeOfDay(23, 59, 59) + seconds(1)); // TimeOfDay(0, 0, 0)

writeln(TimeOfDay(12, 12, 12) - seconds(1)); // TimeOfDay(12, 12, 11)
writeln(TimeOfDay(12, 12, 12) - minutes(1)); // TimeOfDay(12, 11, 12)
writeln(TimeOfDay(12, 12, 12) - hours(1)); // TimeOfDay(11, 12, 12)
writeln(TimeOfDay(0, 0, 0) - seconds(1)); // TimeOfDay(23, 59, 59)

```
 
  pure nothrow @nogc ref @safe TimeOfDay **opOpAssign**(string op)(Duration duration)  
 Constraints: if (op == "+" || op == "-"); 
 
Gives the result of adding or subtracting a [`core.time.Duration`](core_time#Duration) from this [`TimeOfDay`](#TimeOfDay), as well as assigning the result to this [`TimeOfDay`](#TimeOfDay). 


The legal types of arithmetic for [`TimeOfDay`](#TimeOfDay) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TimeOfDay | + | Duration | --> | TimeOfDay |
| TimeOfDay | - | Duration | --> | TimeOfDay |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `duration` | The [`core.time.Duration`](core_time#Duration) to add to or subtract from this [`TimeOfDay`](#TimeOfDay). |


  const pure nothrow @nogc @safe Duration **opBinary**(string op)(TimeOfDay rhs)  
 Constraints: if (op == "-"); 
 
Gives the difference between two [`TimeOfDay`](#TimeOfDay)s. 


The legal types of arithmetic for [`TimeOfDay`](#TimeOfDay) using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TimeOfDay | - | TimeOfDay | --> | duration |

 

 
Parameters:


|  |  |
| --- | --- |
| TimeOfDay `rhs` | The [`TimeOfDay`](#TimeOfDay) to subtract from this one. |


  const pure nothrow @safe string **toISOString**();   
  
const void **toISOString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`TimeOfDay`](#TimeOfDay) to a string with the format `HHMMSS`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
writeln(TimeOfDay(0, 0, 0).toISOString()); // "000000"
writeln(TimeOfDay(12, 30, 33).toISOString()); // "123033"

```
 
  const pure nothrow @safe string **toISOExtString**();   
  
const void **toISOExtString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this [`TimeOfDay`](#TimeOfDay) to a string with the format `HH:MM:SS`. If `writer` is set, the resulting string will be written directly to it. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
 
Examples:


```
writeln(TimeOfDay(0, 0, 0).toISOExtString()); // "00:00:00"
writeln(TimeOfDay(12, 30, 33).toISOExtString()); // "12:30:33"

```
 
  const pure nothrow @safe string **toString**();   
  
const void **toString**(W)(ref W writer)  
 Constraints: if (isOutputRange!(W, char)); 
 
Converts this TimeOfDay to a string. 


This function exists to make it easy to convert a [`TimeOfDay`](#TimeOfDay) to a string for code that does not care what the exact format is - just that it presents the information in a clear manner. It also makes it easy to simply convert a [`TimeOfDay`](#TimeOfDay) to a string when using functions such as `to!string`, `format`, or `writeln` which use toString to convert user-defined types. So, it is unlikely that much code will call toString directly.   
  
 The format of the string is purposefully unspecified, and code that cares about the format of the string should use `toISOString`, `toISOExtString`, or some other custom formatting function that explicitly generates the format that the code needs. The reason is that the code is then clear about what format it's using, making it less error-prone to maintain the code and interact with other software that consumes the generated strings. It's for this same reason that [`TimeOfDay`](#TimeOfDay) has no `fromString` function, whereas it does have `fromISOString` and `fromISOExtString`.   
  
 The format returned by toString may or may not change in the future. 

 
Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
  pure @safe TimeOfDay **fromISOString**(S)(scope const S isoString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`TimeOfDay`](#TimeOfDay) from a string with the format HHMMSS. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoString` | A string formatted in the ISO format for times. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO format or if the resulting [`TimeOfDay`](#TimeOfDay) would not be valid.
  pure @safe TimeOfDay **fromISOExtString**(S)(scope const S isoExtString)  
 Constraints: if (isSomeString!S); 
 
Creates a [`TimeOfDay`](#TimeOfDay) from a string with the format HH:MM:SS. Whitespace is stripped from the given string. 



Parameters:


|  |  |
| --- | --- |
| S `isoExtString` | A string formatted in the ISO Extended format for times. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given string is not in the ISO Extended format or if the resulting [`TimeOfDay`](#TimeOfDay) would not be valid.
  static pure nothrow @nogc @property @safe TimeOfDay **min**();  
Returns midnight.

  static pure nothrow @nogc @property @safe TimeOfDay **max**();  
Returns one second short of midnight.

    pure nothrow @nogc @safe bool **valid**(string units)(int value)  
 Constraints: if (units == "months" || units == "hours" || units == "minutes" || units == "seconds"); 
 
Returns whether the given value is valid for the given unit type when in a time point. Naturally, a duration is not held to a particular range, but the values in a time point are (e.g. a month must be in the range of 1 - 12 inclusive). 



Parameters:


|  |  |
| --- | --- |
| units | The units of time to validate. |
| int `value` | The number to validate. |


 
Examples:


```
assert(valid!"hours"(12));
assert(!valid!"hours"(32));
assert(valid!"months"(12));
assert(!valid!"months"(13));

```
 
  pure nothrow @nogc @safe bool **valid**(string units)(int year, int month, int day)  
 Constraints: if (units == "days"); 
 
Returns whether the given day is valid for the given year and month. 



Parameters:


|  |  |
| --- | --- |
| units | The units of time to validate. |
| int `year` | The year of the day to validate. |
| int `month` | The month of the day to validate (January is 1). |
| int `day` | The day to validate. |


 
Examples:


```
assert(valid!"days"(2016, 2, 29));
assert(!valid!"days"(2016, 2, 30));
assert(valid!"days"(2017, 2, 20));
assert(!valid!"days"(2017, 2, 29));

```
 
  pure @safe void **enforceValid**(string units)(int value, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)  
 Constraints: if (units == "months" || units == "hours" || units == "minutes" || units == "seconds"); 
 

Parameters:


|  |  |
| --- | --- |
| units | The units of time to validate. |
| int `value` | The number to validate. |
| string `file` | The file that the [`DateTimeException`](#DateTimeException) will list if thrown. |
| size\_t `line` | The line number that the [`DateTimeException`](#DateTimeException) will list if thrown. |


 
Throws:

[`DateTimeException`](#DateTimeException) if `valid!units(value)` is false.
 
Examples:


```
import std.exception : assertThrown, assertNotThrown;

assertNotThrown(enforceValid!"months"(10));
assertNotThrown(enforceValid!"seconds"(40));

assertThrown!DateTimeException(enforceValid!"months"(0));
assertThrown!DateTimeException(enforceValid!"hours"(24));
assertThrown!DateTimeException(enforceValid!"minutes"(60));
assertThrown!DateTimeException(enforceValid!"seconds"(60));

```
 
  pure @safe void **enforceValid**(string units)(int year, Month month, int day, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)  
 Constraints: if (units == "days"); 
 
Because the validity of the day number depends on both on the year and month of which the day is occurring, take all three variables to validate the day. 



Parameters:


|  |  |
| --- | --- |
| units | The units of time to validate. |
| int `year` | The year of the day to validate. |
| Month `month` | The month of the day to validate. |
| int `day` | The day to validate. |
| string `file` | The file that the [`DateTimeException`](#DateTimeException) will list if thrown. |
| size\_t `line` | The line number that the [`DateTimeException`](#DateTimeException) will list if thrown. |


 
Throws:

[`DateTimeException`](#DateTimeException) if `valid!"days"(year, month, day)` is false.
 
Examples:


```
import std.exception : assertThrown, assertNotThrown;

assertNotThrown(enforceValid!"days"(2000, Month.jan, 1));
// leap year
assertNotThrown(enforceValid!"days"(2000, Month.feb, 29));

assertThrown!DateTimeException(enforceValid!"days"(2001, Month.feb, 29));
assertThrown!DateTimeException(enforceValid!"days"(2000, Month.jan, 32));
assertThrown!DateTimeException(enforceValid!"days"(2000, Month.apr, 31));

```
 
  pure nothrow @nogc @safe int **daysToDayOfWeek**(DayOfWeek currDoW, DayOfWeek dow);  
Returns the number of days from the current day of the week to the given day of the week. If they are the same, then the result is 0. 



Parameters:


|  |  |
| --- | --- |
| DayOfWeek `currDoW` | The current day of the week. |
| DayOfWeek `dow` | The day of the week to get the number of days to. |


 
Examples:


```
writeln(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.mon)); // 0
writeln(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.sun)); // 6
writeln(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.wed)); // 2

```
 
  pure @safe int **monthsToMonth**(int currMonth, int month);  
Returns the number of months from the current months of the year to the given month of the year. If they are the same, then the result is 0. 



Parameters:


|  |  |
| --- | --- |
| int `currMonth` | The current month of the year. |
| int `month` | The month of the year to get the number of months to. |


 
Examples:


```
writeln(monthsToMonth(Month.jan, Month.jan)); // 0
writeln(monthsToMonth(Month.jan, Month.dec)); // 11
writeln(monthsToMonth(Month.jul, Month.oct)); // 3

```
 
  pure nothrow @nogc @safe bool **yearIsLeapYear**(int year);  
Whether the given Gregorian Year is a leap year. 



Parameters:


|  |  |
| --- | --- |
| int `year` | The year to to be tested. |


 
Examples:


```
foreach (year; [1, 2, 100, 2001, 2002, 2003, 2005, 2006, 2007, 2009, 2010])
{
    assert(!yearIsLeapYear(year));
    assert(!yearIsLeapYear(-year));
}

foreach (year; [0, 4, 8, 400, 800, 1600, 1996, 2000, 2004, 2008, 2012])
{
    assert(yearIsLeapYear(year));
    assert(yearIsLeapYear(-year));
}

```
 
  enum auto **isTimePoint**(T);  
Whether the given type defines all of the necessary functions for it to function as a time point. 


1. `T` must define a static property named `min` which is the smallest value of `T` as `Unqual!T`.
2. `T` must define a static property named `max` which is the largest value of `T` as `Unqual!T`.
3. `T` must define an `opBinary` for addition and subtraction that accepts [`core.time.Duration`](core_time#Duration) and returns `Unqual!T`.
4. `T` must define an `opOpAssign` for addition and subtraction that accepts [`core.time.Duration`](core_time#Duration) and returns `ref Unqual!T`.
5. `T` must define a `opBinary` for subtraction which accepts `T` and returns [`core.time.Duration`](core_time#Duration).


 
Examples:


```
import core.time : Duration;
import std.datetime.interval : Interval;
import std.datetime.systime : SysTime;

static assert(isTimePoint!Date);
static assert(isTimePoint!DateTime);
static assert(isTimePoint!SysTime);
static assert(isTimePoint!TimeOfDay);

static assert(!isTimePoint!int);
static assert(!isTimePoint!Duration);
static assert(!isTimePoint!(Interval!SysTime));

```
 
  pure nothrow @nogc @safe bool **validTimeUnits**(string[] units...);  
Whether all of the given strings are valid units of time. 


`"nsecs"` is not considered a valid unit of time. Nothing in std.datetime can handle precision greater than hnsecs, and the few functions in core.time which deal with "nsecs" deal with it explicitly.

 
Examples:


```
assert(validTimeUnits("msecs", "seconds", "minutes"));
assert(validTimeUnits("days", "weeks", "months"));
assert(!validTimeUnits("ms", "seconds", "minutes"));

```
 
  pure @safe int **cmpTimeUnits**(string lhs, string rhs);  
Compares two time unit strings. `"years"` are the largest units and `"hnsecs"` are the smallest. 



Returns:



|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |

 
 
Throws:

[`DateTimeException`](#DateTimeException) if either of the given strings is not a valid time unit string.
 
Examples:


```
import std.exception : assertThrown;

writeln(cmpTimeUnits("hours", "hours")); // 0
assert(cmpTimeUnits("hours", "weeks") < 0);
assert(cmpTimeUnits("months", "seconds") > 0);

assertThrown!DateTimeException(cmpTimeUnits("month", "second"));

```
 
  template **CmpTimeUnits**(string lhs, string rhs) if (validTimeUnits(lhs, rhs)) 
Compares two time unit strings at compile time. `"years"` are the largest units and `"hnsecs"` are the smallest. 


This template is used instead of `cmpTimeUnits` because exceptions can't be thrown at compile time and `cmpTimeUnits` must enforce that the strings it's given are valid time unit strings. This template uses a template constraint instead. 

 
Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


 
Examples:


```
static assert(CmpTimeUnits!("years", "weeks") > 0);
static assert(CmpTimeUnits!("days", "days") == 0);
static assert(CmpTimeUnits!("seconds", "hours") < 0);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime_date.html>

std.experimental.allocator.building\_blocks.allocator\_list
===========================================================

 
Source
 [std/experimental/allocator/building\_blocks/allocator\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/allocator_list.d)

 
struct **AllocatorList**(Factory, BookkeepingAllocator = GCAllocator);   
  
template **AllocatorList**(alias factoryFunction, BookkeepingAllocator = GCAllocator) 
Given an [object factory](https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)) of type `Factory` or a factory function `factoryFunction`, and optionally also `BookkeepingAllocator` as a supplemental allocator for bookkeeping, `AllocatorList` creates an allocator that lazily creates as many allocators are needed for satisfying client allocation requests. 


An embedded list builds a most-recently-used strategy: the most recent allocators used in calls to either `allocate`, `owns` (successful calls only), or `deallocate` are tried for new allocations in order of their most recent use. Thus, although core operations take in theory Ο(`k`) time for `k` allocators in current use, in many workloads the factor is sublinear. Details of the actual strategy may change in future releases.   
  
 `AllocatorList` is primarily intended for coarse-grained handling of allocators, i.e. the number of allocators in the list is expected to be relatively small compared to the number of allocations handled by each allocator. However, the per-allocator overhead is small so using `AllocatorList` with a large number of allocators should be satisfactory as long as the most-recently-used strategy is fast enough for the application.   
  
 `AllocatorList` makes an effort to return allocated memory back when no longer used. It does so by destroying empty allocators. However, in order to avoid thrashing (excessive creation/destruction of allocators under certain use patterns), it keeps unused allocators for a while. 

 
Parameters:


|  |  |
| --- | --- |
| factoryFunction | A function or template function (including function literals). New allocators are created by calling `factoryFunction(n)` with strictly positive numbers `n`. Delegates that capture their enviroment are not created amid concerns regarding garbage creation for the environment. When the factory needs state, a `Factory` object should be used. |
| BookkeepingAllocator | Allocator used for storing bookkeeping data. The size of bookkeeping data is proportional to the number of allocators. If `BookkeepingAllocator` is `NullAllocator`, then `AllocatorList` is "ouroboros-style", i.e. it keeps the bookkeeping data in memory obtained from the allocators themselves. Note that for ouroboros-style management, the size `n` passed to `make` will be occasionally different from the size requested by client code. |
| Factory | Type of a factory object that returns new allocators on a need basis. For an object `sweatshop` of type `Factory`, `sweatshop(n)` should return an allocator able to allocate at least `n` bytes (i.e. `Factory` must define `opCall(size_t)` to return an allocator object). Usually the capacity of allocators created should be much larger than `n` such that an allocator can be used for many subsequent allocations. `n` is passed only to ensure the minimum necessary for the next allocation. The factory object is allowed to hold state, which will be stored inside `AllocatorList` as a direct `public` member called `factory`. |


 
Examples:


```
import std.algorithm.comparison : max;
import std.experimental.allocator.building_blocks.free_list : ContiguousFreeList;
import std.experimental.allocator.building_blocks.null_allocator : NullAllocator;
import std.experimental.allocator.building_blocks.region : Region;
import std.experimental.allocator.building_blocks.segregator : Segregator;
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.experimental.allocator.mmap_allocator : MmapAllocator;

// Ouroboros allocator list based upon 4MB regions, fetched directly from
// mmap. All memory is released upon destruction.
alias A1 = AllocatorList!((n) => Region!MmapAllocator(max(n, 1024 * 4096)),
    NullAllocator);

// Allocator list based upon 4MB regions, fetched from the garbage
// collector. All memory is released upon destruction.
alias A2 = AllocatorList!((n) => Region!GCAllocator(max(n, 1024 * 4096)));

// Ouroboros allocator list based upon 4MB regions, fetched from the garbage
// collector. Memory is left to the collector.
alias A3 = AllocatorList!(
    (n) => Region!NullAllocator(new ubyte[max(n, 1024 * 4096)]),
    NullAllocator);

// Allocator list that creates one freelist for all objects
alias A4 =
    Segregator!(
        64, AllocatorList!(
            (n) => ContiguousFreeList!(NullAllocator, 0, 64)(
                cast(ubyte[])(GCAllocator.instance.allocate(4096)))),
        GCAllocator);

A4 a;
auto small = a.allocate(64);
assert(small);
a.deallocate(small);
auto b1 = a.allocate(1024 * 8192);
assert(b1 !is null); // still works due to overdimensioning
b1 = a.allocate(1024 * 10);
writeln(b1.length); // 1024 * 10

```
 
 
alias **Allocator** = typeof(Factory.init(1));  
Alias for `typeof(Factory()(1))`, i.e. the type of the individual allocators.

  BookkeepingAllocator **bkalloc**;  
If `BookkeepingAllocator` is not `NullAllocator`, `bkalloc` is defined and accessible.

  this(ref Factory plant);   
  
this(Factory plant);  
Constructs an `AllocatorList` given a factory object. This constructor is defined only if `Factory` has state.

  enum uint **alignment**;  
The alignment offered.

  void[] **allocate**(size\_t s);  
Allocate a block of size `s`. First tries to allocate from the existing list of already-created allocators. If neither can satisfy the request, creates a new allocator by calling `make(s)` and delegates the request to it. However, if the allocation fresh off a newly created allocator fails, subsequent calls to `allocate` will not cause more calls to  `make`.

  void[] **alignedAllocate**(size\_t s, uint theAlignment);  
Allocate a block of size `s` with alignment `a`. First tries to allocate from the existing list of already-created allocators. If neither can satisfy the request, creates a new allocator by calling `make(s + a - 1)` and delegates the request to it. However, if the allocation fresh off a newly created allocator fails, subsequent calls to `alignedAllocate` will not cause more calls to `make`.

  Ternary **owns**(void[] b);  
Defined only if `Allocator` defines `owns`. Tries each allocator in turn, in most-recently-used order. If the owner is found, it is moved to the front of the list as a side effect under the assumption it will be used soon. 



Returns:

`Ternary.yes` if one allocator was found to return `Ternary.yes`, `Ternary.no` if all component allocators returned `Ternary.no`, and `Ternary.unknown` if no allocator returned `Ternary.yes` and at least one returned `Ternary.unknown`.
  bool **expand**(ref void[] b, size\_t delta);  
Defined only if `Allocator.expand` is defined. Finds the owner of `b` and calls `expand` for it. The owner is not brought to the head of the list.

  bool **reallocate**(ref void[] b, size\_t s);  
Defined only if `Allocator.reallocate` is defined. Finds the owner of `b` and calls `reallocate` for it. If that fails, calls the global `reallocate`, which allocates a new block and moves memory.

  bool **deallocate**(void[] b);  
Defined if `Allocator.deallocate` and `Allocator.owns` are defined.

  bool **deallocateAll**();  
Defined only if `Allocator.owns` and `Allocator.deallocateAll` are defined.

  const pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if no allocators are currently active, `Ternary.no` otherwise. This methods never returns `Ternary.unknown`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_allocator_list.html>

std.experimental.allocator.building\_blocks.ascending\_page\_allocator
======================================================================

 
Source
 [std/experimental/allocator/building\_blocks/ascending\_page\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/ascending_page_allocator.d)

 
struct **AscendingPageAllocator**;  
`AscendingPageAllocator` is a fast and safe allocator that rounds all allocations to multiples of the system's page size. It reserves a range of virtual addresses (using `mmap` on Posix and `VirtualAlloc` on Windows) and allocates memory at consecutive virtual addresses. 


When a chunk of memory is requested, the allocator finds a range of virtual pages that satisfy the requested size, changing their protection to read/write using OS primitives (`mprotect` and `VirtualProtect`, respectively). The physical memory is allocated on demand, when the pages are accessed.   
  
 Deallocation removes any read/write permissions from the target pages and notifies the OS to reclaim the physical memory, while keeping the virtual memory.   
  
 Because the allocator does not reuse memory, any dangling references to deallocated memory will always result in deterministically crashing the process. 

 
See Also:

[Simple Fast and Safe Manual Memory Management](https://microsoft.com/en-us/research/wp-content/uploads/2017/03/kedia2017mem.pdf) for the general approach.
 
Examples:


```
import core.memory : pageSize;

size_t numPages = 100;
void[] buf;
void[] prevBuf = null;
AscendingPageAllocator a = AscendingPageAllocator(numPages * pageSize);

foreach (i; 0 .. numPages)
{
    // Allocation is rounded up to page size
    buf = a.allocate(pageSize - 100);
    writeln(buf.length); // pageSize - 100

    // Allocations are served at increasing addresses
    if (prevBuf)
        writeln(prevBuf.ptr + pageSize); // buf.ptr

    assert(a.deallocate(buf));
    prevBuf = buf;
}

```
 
 
nothrow @nogc this(size\_t n);  
Rounds the mapping size to the next multiple of the page size and calls the OS primitive responsible for creating memory mappings: `mmap` on POSIX and `VirtualAlloc` on Windows. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | mapping size in bytes |


  nothrow @nogc size\_t **goodAllocSize**(size\_t n);  
Rounds the requested size to the next multiple of the page size.

  nothrow @nogc void **deallocate**(void[] b);  
Decommit all physical memory associated with the buffer given as parameter, but keep the range of virtual addresses. 


On POSIX systems `deallocate` calls `mmap` with `MAP\_FIXED' a second time to decommit the memory. On Windows, it uses `VirtualFree` with `MEM_DECOMMIT`.

  nothrow @nogc Ternary **owns**(void[] buf);  
Returns `Ternary.yes` if the passed buffer is inside the range of virtual adresses. Does not guarantee that the passed buffer is still valid.

  nothrow @nogc bool **deallocateAll**();  
Removes the memory mapping causing all physical memory to be decommited and the virtual address space to be reclaimed.

  nothrow @nogc size\_t **getAvailableSize**();  
Returns the available size for further allocations in bytes.

  nothrow @nogc void[] **allocate**(size\_t n);  
Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | Bytes to allocate |


 
Returns:

`null` on failure or if the requested size exceeds the remaining capacity.
  nothrow @nogc void[] **alignedAllocate**(size\_t n, uint a);  
Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. 


The allocated memory is aligned to the specified alignment `a`. 

 
Parameters:


|  |  |
| --- | --- |
| size\_t `n` | Bytes to allocate |
| uint `a` | Alignment |


 
Returns:

`null` on failure or if the requested size exceeds the remaining capacity.
  nothrow @nogc bool **expand**(ref void[] b, size\_t delta);  
If the passed buffer is not the last allocation, then `delta` can be at most the number of bytes left on the last page. Otherwise, we can expand the last allocation until the end of the virtual address range.

  nothrow @nogc Ternary **empty**();  
Returns `Ternary.yes` if the allocator does not contain any alive objects and `Ternary.no` otherwise.

    struct **SharedAscendingPageAllocator**;  
`SharedAscendingPageAllocator` is the threadsafe version of `AscendingPageAllocator`.



Examples:


```
import core.memory : pageSize;
import core.thread : ThreadGroup;

enum numThreads = 100;
shared SharedAscendingPageAllocator a = SharedAscendingPageAllocator(pageSize * numThreads);

void fun()
{
    void[] b = a.allocate(pageSize);
    writeln(b.length); // pageSize

    assert(a.deallocate(b));
}

auto tg = new ThreadGroup;
foreach (i; 0 .. numThreads)
{
    tg.create(&fun);
}
tg.joinAll();

```
 
 
shared nothrow @nogc this(size\_t n);  
Rounds the mapping size to the next multiple of the page size and calls the OS primitive responsible for creating memory mappings: `mmap` on POSIX and `VirtualAlloc` on Windows. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | mapping size in bytes |


  shared nothrow @nogc size\_t **goodAllocSize**(size\_t n);  
Rounds the requested size to the next multiple of the page size.

  shared nothrow @nogc void **deallocate**(void[] b);  
Decommit all physical memory associated with the buffer given as parameter, but keep the range of virtual addresses. 


On POSIX systems `deallocate` calls `mmap` with `MAP\_FIXED' a second time to decommit the memory. On Windows, it uses `VirtualFree` with `MEM_DECOMMIT`.

  shared nothrow @nogc Ternary **owns**(void[] buf);  
Returns `Ternary.yes` if the passed buffer is inside the range of virtual adresses. Does not guarantee that the passed buffer is still valid.

  shared nothrow @nogc bool **deallocateAll**();  
Removes the memory mapping causing all physical memory to be decommited and the virtual address space to be reclaimed.

  shared nothrow @nogc size\_t **getAvailableSize**();  
Returns the available size for further allocations in bytes.

  shared nothrow @nogc void[] **allocate**(size\_t n);  
Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | Bytes to allocate |


 
Returns:

`null` on failure or if the requested size exceeds the remaining capacity.
  shared nothrow @nogc void[] **alignedAllocate**(size\_t n, uint a);  
Rounds the allocation size to the next multiple of the page size. The allocation only reserves a range of virtual pages but the actual physical memory is allocated on demand, when accessing the memory. 


The allocated memory is aligned to the specified alignment `a`. 

 
Parameters:


|  |  |
| --- | --- |
| size\_t `n` | Bytes to allocate |
| uint `a` | Alignment |


 
Returns:

`null` on failure or if the requested size exceeds the remaining capacity.
  shared nothrow @nogc bool **expand**(ref void[] b, size\_t delta);  
If the passed buffer is not the last allocation, then `delta` can be at most the number of bytes left on the last page. Otherwise, we can expand the last allocation until the end of the virtual address range.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_ascending_page_allocator.html>

std.experimental.allocator.building\_blocks.bucketizer
======================================================

 
Source
 [std/experimental/allocator/building\_blocks/bucketizer.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/bucketizer.d)

 
struct **Bucketizer**(Allocator, size\_t min, size\_t max, size\_t step);  
A `Bucketizer` uses distinct allocators for handling allocations of sizes in the intervals `[min, min + step - 1]`, `[min + step, min + 2 * step - 1]`, `[min + 2 * step, min + 3 * step - 1]`, `...`, `[max - step + 1, max]`. 


`Bucketizer` holds a fixed-size array of allocators and dispatches calls to them appropriately. The size of the array is `(max + 1 - min) / step`, which must be an exact division.   
  
 Allocations for sizes smaller than `min` or larger than `max` are illegal for `Bucketizer`. To handle them separately, `Segregator` may be of use.

 
Examples:


```
import std.algorithm.comparison : max;
import std.experimental.allocator.building_blocks.allocator_list : AllocatorList;
import std.experimental.allocator.building_blocks.free_list : FreeList;
import std.experimental.allocator.building_blocks.region : Region;
import std.experimental.allocator.common : unbounded;
import std.experimental.allocator.mallocator : Mallocator;
import std.typecons : Ternary;
Bucketizer!(
    FreeList!(
        AllocatorList!(
            (size_t n) => Region!Mallocator(max(n, 1024 * 1024))),
        0, unbounded),
    65, 512, 64) a;
auto b = a.allocate(400);
writeln(b.length); // 400
writeln(a.owns(b)); // Ternary.yes
a.deallocate(b);

```
 
 
Allocator[(max + 1 - min) / step] **buckets**;  
The array of allocators is publicly available for e.g. initialization and inspection.

  enum uint **alignment**;  
The alignment offered is the same as `Allocator.alignment`.

  const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t bytes);  
Rounds up to the maximum size of the bucket in which `bytes` falls.

  void[] **allocate**(size\_t bytes);  
Directs the call to either one of the `buckets` allocators.

  void[] **alignedAllocate**(size\_t bytes, uint alignment);  
Allocates the requested `bytes` of memory with specified `alignment`. Directs the call to either one of the `buckets` allocators. Defined only if `Allocator` defines `alignedAllocate`.

  bool **expand**(ref void[] b, size\_t delta);  
This method allows expansion within the respective bucket range. It succeeds if both `b.length` and `b.length + delta` fall in a range of the form `[min + k * step, min + (k + 1) * step - 1]`.

  bool **reallocate**(ref void[] b, size\_t size);  
This method allows reallocation within the respective bucket range. If both `b.length` and `size` fall in a range of the form `[min + k * step, min + (k + 1) * step - 1]`, then reallocation is in place. Otherwise, reallocation with moving is attempted.

  bool **alignedReallocate**(ref void[] b, size\_t size, uint a);  
Similar to `reallocate`, with alignment. Defined only if `Allocator` defines `alignedReallocate`.

  Ternary **owns**(void[] b);  
Defined only if `Allocator` defines `owns`. Finds the owner of `b` and forwards the call to it.

  bool **deallocate**(void[] b);  
This method is only defined if `Allocator` defines `deallocate`.

  bool **deallocateAll**();  
This method is only defined if all allocators involved define  `deallocateAll`, and calls it for each bucket in turn. Returns `true` if all allocators could deallocate all.

  Ternary **resolveInternalPointer**(const void\* p, ref void[] result);  
This method is only defined if all allocators involved define  `resolveInternalPointer`, and tries it for each bucket in turn.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_bucketizer.html>

std.encoding
============

 Classes and functions for handling and transcoding between various encodings. 


For cases where the encoding is known at compile-time, functions are provided for arbitrary encoding and decoding of characters, arbitrary transcoding between strings of different type, as well as validation and sanitization.   
  
 Encodings currently supported are UTF-8, UTF-16, UTF-32, ASCII, ISO-8859-1 (also known as LATIN-1), ISO-8859-2 (LATIN-2), WINDOWS-1250, WINDOWS-1251 and WINDOWS-1252.   
  
 

| Category | Functions |
| --- | --- |
| Decode | [`codePoints`](#codePoints) [`decode`](#decode) [`decodeReverse`](#decodeReverse) [`safeDecode`](#safeDecode) |
| Conversion | [`codeUnits`](#codeUnits) [`sanitize`](#sanitize) [`transcode`](#transcode) |
| Classification | [`canEncode`](#canEncode) [`isValid`](#isValid) [`isValidCodePoint`](#isValidCodePoint) [`isValidCodeUnit`](#isValidCodeUnit) |
| BOM | [`BOM`](#BOM) [`BOMSeq`](#BOMSeq) [`getBOM`](#getBOM) [`utfBOM`](#utfBOM) |
| Length & Index | [`firstSequence`](#firstSequence) [`encodedLength`](#encodedLength) [`index`](#index) [`lastSequence`](#lastSequence) [`validLength`](#validLength) |
| Encoding schemes | [`encodingName`](#encodingName) [`EncodingScheme`](#EncodingScheme) [`EncodingSchemeASCII`](#EncodingSchemeASCII) [`EncodingSchemeLatin1`](#EncodingSchemeLatin1) [`EncodingSchemeLatin2`](#EncodingSchemeLatin2) [`EncodingSchemeUtf16Native`](#EncodingSchemeUtf16Native) [`EncodingSchemeUtf32Native`](#EncodingSchemeUtf32Native) [`EncodingSchemeUtf8`](#EncodingSchemeUtf8) [`EncodingSchemeWindows1250`](#EncodingSchemeWindows1250) [`EncodingSchemeWindows1251`](#EncodingSchemeWindows1251) [`EncodingSchemeWindows1252`](#EncodingSchemeWindows1252) |
| Representation | [`AsciiChar`](#AsciiChar) [`AsciiString`](#AsciiString) [`Latin1Char`](#Latin1Char) [`Latin1String`](#Latin1String) [`Latin2Char`](#Latin2Char) [`Latin2String`](#Latin2String) [`Windows1250Char`](#Windows1250Char) [`Windows1250String`](#Windows1250String) [`Windows1251Char`](#Windows1251Char) [`Windows1251String`](#Windows1251String) [`Windows1252Char`](#Windows1252Char) [`Windows1252String`](#Windows1252String) |
| Exceptions | [`INVALID_SEQUENCE`](#INVALID_SEQUENCE) [`EncodingException`](#EncodingException) |

   
  
 For cases where the encoding is not known at compile-time, but is known at run-time, the abstract class [`EncodingScheme`](#EncodingScheme) and its subclasses is provided. To construct a run-time encoder/decoder, one does e.g.   
  
 
```
auto e = EncodingScheme.create("utf-8");

```
   
  
 This library supplies [`EncodingScheme`](#EncodingScheme) subclasses for ASCII, ISO-8859-1 (also known as LATIN-1), ISO-8859-2 (LATIN-2), WINDOWS-1250, WINDOWS-1251, WINDOWS-1252, UTF-8, and (on little-endian architectures) UTF-16LE and UTF-32LE; or (on big-endian architectures) UTF-16BE and UTF-32BE.   
  
 This library provides a mechanism whereby other modules may add [`EncodingScheme`](#EncodingScheme) subclasses for any other encoding. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Janice Caron 
 
Source
 [std/encoding.d](https://github.com/dlang/phobos/blob/master/std/encoding.d)

 
enum dchar **INVALID\_SEQUENCE**;  
Special value returned by `safeDecode`

  enum **AsciiChar**: ubyte;   
  
alias **AsciiString** = immutable(AsciiChar)[];  
Defines various character sets.

  enum **Latin1Char**: ubyte;  
Defines an Latin1-encoded character.

  alias **Latin1String** = immutable(Latin1Char)[];  
Defines an Latin1-encoded string (as an array of `immutable(Latin1Char)`).

  enum **Latin2Char**: ubyte;  
Defines a Latin2-encoded character.

  alias **Latin2String** = immutable(Latin2Char)[];  
Defines an Latin2-encoded string (as an array of  `immutable(Latin2Char)`).

  enum **Windows1250Char**: ubyte;  
Defines a Windows1250-encoded character.

  alias **Windows1250String** = immutable(Windows1250Char)[];  
Defines an Windows1250-encoded string (as an array of  `immutable(Windows1250Char)`).

  enum **Windows1251Char**: ubyte;  
Defines a Windows1251-encoded character.

  alias **Windows1251String** = immutable(Windows1251Char)[];  
Defines an Windows1251-encoded string (as an array of  `immutable(Windows1251Char)`).

  enum **Windows1252Char**: ubyte;  
Defines a Windows1252-encoded character.

  alias **Windows1252String** = immutable(Windows1252Char)[];  
Defines an Windows1252-encoded string (as an array of  `immutable(Windows1252Char)`).

  pure nothrow @nogc @safe bool **isValidCodePoint**(dchar c);  
Returns true if c is a valid code point 


Note that this includes the non-character code points U+FFFE and U+FFFF, since these are valid code points (even though they are not valid characters). 

 
Supersedes
 This function supersedes `std.utf.startsValidDchar()`. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be tested |


  @property string **encodingName**(T)();  
Returns the name of an encoding. 


The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252
 
Examples:


```
writeln(encodingName!(char)); // "UTF-8"
writeln(encodingName!(wchar)); // "UTF-16"
writeln(encodingName!(dchar)); // "UTF-32"
writeln(encodingName!(AsciiChar)); // "ASCII"
writeln(encodingName!(Latin1Char)); // "ISO-8859-1"
writeln(encodingName!(Latin2Char)); // "ISO-8859-2"
writeln(encodingName!(Windows1250Char)); // "windows-1250"
writeln(encodingName!(Windows1251Char)); // "windows-1251"
writeln(encodingName!(Windows1252Char)); // "windows-1252"

```
 
  bool **canEncode**(E)(dchar c);  
Returns true iff it is possible to represent the specified codepoint in the encoding. 


The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252
 
Examples:


```
assert( canEncode!(Latin1Char)('A'));
assert( canEncode!(Latin2Char)('A'));
assert(!canEncode!(AsciiChar)('\u00A0'));
assert( canEncode!(Latin1Char)('\u00A0'));
assert( canEncode!(Latin2Char)('\u00A0'));
assert( canEncode!(Windows1250Char)('\u20AC'));
assert(!canEncode!(Windows1250Char)('\u20AD'));
assert(!canEncode!(Windows1250Char)('\uFFFD'));
assert( canEncode!(Windows1251Char)('\u0402'));
assert(!canEncode!(Windows1251Char)('\u20AD'));
assert(!canEncode!(Windows1251Char)('\uFFFD'));
assert( canEncode!(Windows1252Char)('\u20AC'));
assert(!canEncode!(Windows1252Char)('\u20AD'));
assert(!canEncode!(Windows1252Char)('\uFFFD'));
assert(!canEncode!(char)(cast(dchar) 0x110000));

```
 
 
Examples:
How to check an entire string 
```
import std.algorithm.searching : find;
import std.utf : byDchar;

assert("The quick brown fox"
    .byDchar
    .find!(x => !canEncode!AsciiChar(x))
    .empty);

```
 
  bool **isValidCodeUnit**(E)(E c);  
Returns true if the code unit is legal. For example, the byte 0x80 would not be legal in ASCII, because ASCII code units must always be in the range 0x00 to 0x7F. 



Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| E `c` | the code unit to be tested |


 
Examples:


```
assert(!isValidCodeUnit(cast(char) 0xC0));
assert(!isValidCodeUnit(cast(char) 0xFF));
assert( isValidCodeUnit(cast(wchar) 0xD800));
assert(!isValidCodeUnit(cast(dchar) 0xD800));
assert(!isValidCodeUnit(cast(AsciiChar) 0xA0));
assert( isValidCodeUnit(cast(Windows1250Char) 0x80));
assert(!isValidCodeUnit(cast(Windows1250Char) 0x81));
assert( isValidCodeUnit(cast(Windows1251Char) 0x80));
assert(!isValidCodeUnit(cast(Windows1251Char) 0x98));
assert( isValidCodeUnit(cast(Windows1252Char) 0x80));
assert(!isValidCodeUnit(cast(Windows1252Char) 0x81));

```
 
  bool **isValid**(E)(const(E)[] s);  
Returns true if the string is encoded correctly 



Supersedes
 This function supersedes std.utf.validate(), however note that this function returns a bool indicating whether the input was valid or not, whereas the older function would throw an exception. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string to be tested |


 
Examples:


```
assert( isValid("\u20AC100"));
assert(!isValid(cast(char[3])[167, 133, 175]));

```
 
  size\_t **validLength**(E)(const(E)[] s);  
Returns the length of the longest possible substring, starting from the first code unit, which is validly encoded. 



Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string to be tested |


  immutable(E)[] **sanitize**(E)(immutable(E)[] s);  
Sanitizes a string by replacing malformed code unit sequences with valid code unit sequences. The result is guaranteed to be valid for this encoding. 


If the input string is already valid, this function returns the original, otherwise it constructs a new string by replacing all illegal code unit sequences with the encoding's replacement character, Invalid sequences will be replaced with the Unicode replacement character (U+FFFD) if the character repertoire contains it, otherwise invalid sequences will be replaced with '?'. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| immutable(E)[] `s` | the string to be sanitized |


 
Examples:


```
writeln(sanitize("hello \xF0\x80world")); // "hello \xEF\xBF\xBDworld"

```
 
  size\_t **firstSequence**(E)(const(E)[] s);  
Returns the length of the first encoded sequence. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string to be sliced |


 
Examples:


```
writeln(firstSequence("\u20AC1000")); // "\u20AC".length
writeln(firstSequence("hel")); // "h".length

```
 
  size\_t **lastSequence**(E)(const(E)[] s);  
Returns the length of the last encoded sequence. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string to be sliced |


 
Examples:


```
writeln(lastSequence("1000\u20AC")); // "\u20AC".length
writeln(lastSequence("hellö")); // "ö".length

```
 
  ptrdiff\_t **index**(E)(const(E)[] s, int n);  
Returns the array index at which the (n+1)th code point begins. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Supersedes
 This function supersedes std.utf.toUTFindex(). 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string to be counted |
| int `n` | the current code point index |


 
Examples:


```
writeln(index("\u20AC100", 1)); // 3
writeln(index("hällo", 2)); // 3

```
 
  dchar **decode**(S)(ref S s);  
Decodes a single code point. 


This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent.   
  
 The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Supersedes
 This function supersedes std.utf.decode(), however, note that the function codePoints() supersedes it more conveniently. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| S `s` | the string whose first code point is to be decoded |


  dchar **decodeReverse**(E)(ref const(E)[] s);  
Decodes a single code point from the end of a string. 


This function removes one or more code units from the end of a string, and returns the decoded code point which those code units represent.   
  
 The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| const(E)[] `s` | the string whose first code point is to be decoded |


  dchar **safeDecode**(S)(ref S s);  
Decodes a single code point. The input does not have to be valid. 


This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent.   
  
 This function will accept an invalidly encoded string as input. If an invalid sequence is found at the start of the string, this function will remove it, and return the value INVALID\_SEQUENCE. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| S `s` | the string whose first code point is to be decoded |


  size\_t **encodedLength**(E)(dchar c);  
Returns the number of code units required to encode a single code point. 


The input to this function MUST be a valid code point. This is enforced by the function's in-contract.   
  
 The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. 

 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |


  E[] **encode**(E)(dchar c);  
Encodes a single code point. 


This function encodes a single code point into one or more code units. It returns a string containing those code units.   
  
 The input to this function MUST be a valid code point. This is enforced by the function's in-contract.   
  
 The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. 

 
Supersedes
 This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |


  size\_t **encode**(E)(dchar c, E[] array);  
Encodes a single code point into an array. 


This function encodes a single code point into one or more code units The code units are stored in a user-supplied fixed-size array, which must be passed by reference.   
  
 The input to this function MUST be a valid code point. This is enforced by the function's in-contract.   
  
 The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. 

 
Supersedes
 This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |
| E[] `array` | the destination array |


 
Returns:
the number of code units written to the array
  void **encode**(E)(dchar c, void delegate(E) dg);  
Encodes a single code point to a delegate. 


This function encodes a single code point into one or more code units. The code units are passed one at a time to the supplied delegate.   
  
 The input to this function MUST be a valid code point. This is enforced by the function's in-contract.   
  
 The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. 

 
Supersedes
 This function supersedes std.utf.encode(), however, note that the function codeUnits() supersedes it more conveniently. 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |
| void delegate(E) `dg` | the delegate to invoke for each code unit |


  size\_t **encode**(Tgt, Src, R)(in Src[] s, R range);  
Encodes the contents of `s` in units of type `Tgt`, writing the result to an output range. 



Returns:
The number of `Tgt` elements written. 
 
Parameters:


|  |  |
| --- | --- |
| Tgt | Element type of `range`. |
| Src[] `s` | Input array. |
| R `range` | Output range. |


  CodePoints!E **codePoints**(E)(immutable(E)[] s);  
Returns a foreachable struct which can bidirectionally iterate over all code points in a string. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract.   
  
 You can foreach either with or without an index. If an index is specified, it will be initialized at each iteration with the offset into the string at which the code point begins. 

 
Supersedes
 This function supersedes std.utf.decode(). 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| immutable(E)[] `s` | the string to be decoded |


 
Example


```
string s = "hello world";
foreach (c;codePoints(s))
{
    // do something with c (which will always be a dchar)
}

```
 Note that, currently, foreach (c:codePoints(s)) is superior to foreach (c;s) in that the latter will fall over on encountering U+FFFF. 
Examples:


```
string s = "hello";
string t;
foreach (c;codePoints(s))
{
    t ~= cast(char) c;
}
writeln(s); // t

```
 
  CodeUnits!E **codeUnits**(E)(dchar c);  
Returns a foreachable struct which can bidirectionally iterate over all code units in a code point. 


The input to this function MUST be a valid code point. This is enforced by the function's in-contract.   
  
 The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type in the template parameter. 

 
Supersedes
 This function supersedes std.utf.encode(). 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |


 
Examples:


```
char[] a;
foreach (c;codeUnits!(char)(cast(dchar)'\u20AC'))
{
    a ~= c;
}
writeln(a.length); // 3
writeln(a[0]); // 0xE2
writeln(a[1]); // 0x82
writeln(a[2]); // 0xAC

```
 
  void **transcode**(Src, Dst)(Src[] s, out Dst[] r);  
Convert a string from one encoding to another. 



Supersedes
 This function supersedes std.utf.toUTF8(), std.utf.toUTF16() and std.utf.toUTF32() (but note that to!() supersedes it more conveniently). 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, ISO-8859-2, WINDOWS-1250, WINDOWS-1251, WINDOWS-1252 
 
Parameters:


|  |  |
| --- | --- |
| Src[] `s` | Source string. Must be validly encoded. This is enforced by the function's in-contract. |
| Dst[] `r` | Destination string |


 
See Also:
[`std.conv.to`](std_conv#to)
 
Examples:


```
wstring ws;
// transcode from UTF-8 to UTF-16
transcode("hello world",ws);
writeln(ws); // "hello world"w

Latin1String ls;
// transcode from UTF-16 to ISO-8859-1
transcode(ws, ls);
writeln(ls); // "hello world"

```
 
  class **EncodingException**: object.Exception;  
The base class for exceptions thrown by this module

  abstract class **EncodingScheme**;  
Abstract base class of all encoding schemes

 
void **register**(Klass : EncodingScheme)();  
Registers a subclass of EncodingScheme. 


This function allows user-defined subclasses of EncodingScheme to be declared in other modules. 

 
Parameters:


|  |  |
| --- | --- |
| Klass | The subclass of EncodingScheme to register. |


 
Example


```
class Amiga1251 : EncodingScheme
{
    shared static this()
    {
        EncodingScheme.register!Amiga1251;
    }
}

```
  static EncodingScheme **create**(string encodingName);  
Obtains a subclass of EncodingScheme which is capable of encoding and decoding the named encoding scheme. 


This function is only aware of EncodingSchemes which have been registered with the register() function. 

 
Example


```
auto scheme = EncodingScheme.create("Amiga-1251");

```
  abstract const string **toString**();  
Returns the standard name of the encoding scheme

  abstract const string[] **names**();  
Returns an array of all known names for this encoding scheme

  abstract const bool **canEncode**(dchar c);  
Returns true if the character c can be represented in this encoding scheme.

  abstract const size\_t **encodedLength**(dchar c);  
Returns the number of ubytes required to encode this code point. 


The input to this function MUST be a valid code point. 

 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |


 
Returns:
the number of ubytes required.
  abstract const size\_t **encode**(dchar c, ubyte[] buffer);  
Encodes a single code point into a user-supplied, fixed-size buffer. 


This function encodes a single code point into one or more ubytes. The supplied buffer must be code unit aligned. (For example, UTF-16LE or UTF-16BE must be wchar-aligned, UTF-32LE or UTF-32BE must be dchar-aligned, etc.)   
  
 The input to this function MUST be a valid code point. 

 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the code point to be encoded |
| ubyte[] `buffer` | the destination array |


 
Returns:
the number of ubytes written.
  abstract const dchar **decode**(ref const(ubyte)[] s);  
Decodes a single code point. 


This function removes one or more ubytes from the start of an array, and returns the decoded code point which those ubytes represent.   
  
 The input to this function MUST be validly encoded. 

 
Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the array whose first code point is to be decoded |


  abstract const dchar **safeDecode**(ref const(ubyte)[] s);  
Decodes a single code point. The input does not have to be valid. 


This function removes one or more ubytes from the start of an array, and returns the decoded code point which those ubytes represent.   
  
 This function will accept an invalidly encoded array as input. If an invalid sequence is found at the start of the string, this function will remove it, and return the value INVALID\_SEQUENCE. 

 
Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the array whose first code point is to be decoded |


  abstract const @property immutable(ubyte)[] **replacementSequence**();  
Returns the sequence of ubytes to be used to represent any character which cannot be represented in the encoding scheme. 


Normally this will be a representation of some substitution character, such as U+FFFD or '?'.

  bool **isValid**(const(ubyte)[] s);  
Returns true if the array is encoded correctly 



Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the array to be tested |


  size\_t **validLength**()(const(ubyte)[] s);  
Returns the length of the longest possible substring, starting from the first element, which is validly encoded. 



Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the array to be tested |


  immutable(ubyte)[] **sanitize**()(immutable(ubyte)[] s);  
Sanitizes an array by replacing malformed ubyte sequences with valid ubyte sequences. The result is guaranteed to be valid for this encoding scheme. 


If the input array is already valid, this function returns the original, otherwise it constructs a new array by replacing all illegal sequences with the encoding scheme's replacement sequence. 

 
Parameters:


|  |  |
| --- | --- |
| immutable(ubyte)[] `s` | the string to be sanitized |


  size\_t **firstSequence**()(const(ubyte)[] s);  
Returns the length of the first encoded sequence. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the array to be sliced |


  size\_t **count**()(const(ubyte)[] s);  
Returns the total number of code points encoded in a ubyte array. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the string to be counted |


  ptrdiff\_t **index**()(const(ubyte)[] s, size\_t n);  
Returns the array index at which the (n+1)th code point begins. 


The input to this function MUST be validly encoded. This is enforced by the function's in-contract. 

 
Parameters:


|  |  |
| --- | --- |
| const(ubyte)[] `s` | the string to be counted |
| size\_t `n` | the current code point index |


    class **EncodingSchemeASCII**: std.encoding.EncodingScheme;  
EncodingScheme to handle ASCII 


This scheme recognises the following names: "ANSI\_X3.4-1968", "ANSI\_X3.4-1986", "ASCII", "IBM367", "ISO646-US", "ISO\_646.irv:1991", "US-ASCII", "cp367", "csASCII" "iso-ir-6", "us"

  class **EncodingSchemeLatin1**: std.encoding.EncodingScheme;  
EncodingScheme to handle Latin-1 


This scheme recognises the following names: "CP819", "IBM819", "ISO-8859-1", "ISO\_8859-1", "ISO\_8859-1:1987", "csISOLatin1", "iso-ir-100", "l1", "latin1"

  class **EncodingSchemeLatin2**: std.encoding.EncodingScheme;  
EncodingScheme to handle Latin-2 


This scheme recognises the following names: "Latin 2", "ISO-8859-2", "ISO\_8859-2", "ISO\_8859-2:1999", "Windows-28592"

  class **EncodingSchemeWindows1250**: std.encoding.EncodingScheme;  
EncodingScheme to handle Windows-1250 


This scheme recognises the following names: "windows-1250"

  class **EncodingSchemeWindows1251**: std.encoding.EncodingScheme;  
EncodingScheme to handle Windows-1251 


This scheme recognises the following names: "windows-1251"

  class **EncodingSchemeWindows1252**: std.encoding.EncodingScheme;  
EncodingScheme to handle Windows-1252 


This scheme recognises the following names: "windows-1252"

  class **EncodingSchemeUtf8**: std.encoding.EncodingScheme;  
EncodingScheme to handle UTF-8 


This scheme recognises the following names: "UTF-8"

  class **EncodingSchemeUtf16Native**: std.encoding.EncodingScheme;  
EncodingScheme to handle UTF-16 in native byte order 


This scheme recognises the following names: "UTF-16LE" (little-endian architecture only) "UTF-16BE" (big-endian architecture only)

  class **EncodingSchemeUtf32Native**: std.encoding.EncodingScheme;  
EncodingScheme to handle UTF-32 in native byte order 


This scheme recognises the following names: "UTF-32LE" (little-endian architecture only) "UTF-32BE" (big-endian architecture only)

  enum **BOM**: int;  
Definitions of common Byte Order Marks. The elements of the `enum` can used as indices into `bomTable` to get matching `BOMSeq`.

 
**none** 
no BOM was found

  **utf32be** 
[0x00, 0x00, 0xFE, 0xFF]

  **utf32le** 
[0xFF, 0xFE, 0x00, 0x00]

  **utf1** 
[0xF7, 0x64, 0x4C]

  **utfebcdic** 
[0xDD, 0x73, 0x66, 0x73]

  **scsu** 
[0x0E, 0xFE, 0xFF]

  **bocu1** 
[0xFB, 0xEE, 0x28]

  **gb18030** 
[0x84, 0x31, 0x95, 0x33]

  **utf8** 
[0xEF, 0xBB, 0xBF]

  **utf16be** 
[0xFE, 0xFF]

  **utf16le** 
[0xFF, 0xFE]

    alias **BOMSeq** = std.typecons.Tuple!(BOM, "schema", ubyte[], "sequence").Tuple;  
The type stored inside `bomTable`.

  immutable Tuple!(BOM, "schema", ubyte[], "sequence")[] **bomTable**;  
Mapping of a byte sequence to **Byte Order Mark (BOM)**

  immutable(BOMSeq) **getBOM**(Range)(Range input)  
 Constraints: if (isForwardRange!Range && is(immutable(ElementType!Range) == immutable(ubyte))); 
 
Returns a `BOMSeq` for a given `input`. If no `BOM` is present the `BOMSeq` for `BOM.none` is returned. The `BOM` sequence at the beginning of the range will not be comsumed from the passed range. If you pass a reference type range make sure that `save` creates a deep copy. 



Parameters:


|  |  |
| --- | --- |
| Range `input` | The sequence to check for the `BOM` |


 
Returns:
the found `BOMSeq` corresponding to the passed `input`.
 
Examples:


```
import std.format : format;

auto ts = dchar(0x0000FEFF) ~ "Hello World"d;

auto entry = getBOM(cast(ubyte[]) ts);
version (BigEndian)
{
    writeln(entry.schema); // BOM.utf32be
}
else
{
    writeln(entry.schema); // BOM.utf32le
}

```
 
  enum dchar **utfBOM**;  
Constant defining a fully decoded BOM

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_encoding.html>

std.exception
=============

 This module defines functions related to exceptions and general error handling. It also defines functions intended to aid in unit testing. 


 

| Category | Functions |
| --- | --- |
| Assumptions | [`assertNotThrown`](#assertNotThrown) [`assertThrown`](#assertThrown) [`assumeUnique`](#assumeUnique) [`assumeWontThrow`](#assumeWontThrow) [`mayPointTo`](#mayPointTo) |
| Enforce | [`doesPointTo`](#doesPointTo) [`enforce`](#enforce) [`errnoEnforce`](#errnoEnforce) |
| Handlers | [`collectException`](#collectException) [`collectExceptionMsg`](#collectExceptionMsg) [`ifThrown`](#ifThrown) [`handle`](#handle) |
| Other | [`basicExceptionCtors`](#basicExceptionCtors) [`emptyExceptionMsg`](#emptyExceptionMsg) [`ErrnoException`](#ErrnoException) [`RangePrimitive`](#RangePrimitive) |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt) 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/exception.d](https://github.com/dlang/phobos/blob/master/std/exception.d)

 
Examples:
Synopis 
```
import core.stdc.stdlib : malloc, free;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map, splitter;
import std.algorithm.searching : endsWith;
import std.conv : ConvException, to;
import std.range : front, retro;

// use enforce like assert
int a = 3;
enforce(a > 2, "a needs to be higher than 2.");

// enforce can throw a custom exception
enforce!ConvException(a > 2, "a needs to be higher than 2.");

// enforce will return it's input
enum size = 42;
auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
scope(exit) free(memory.ptr);

// collectException can be used to test for exceptions
Exception e = collectException("abc".to!int);
assert(e.file.endsWith("conv.d"));

// and just for the exception message
string msg = collectExceptionMsg("abc".to!int);
writeln(msg); // "Unexpected 'a' when converting from type string to type int"

// assertThrown can be used to assert that an exception is thrown
assertThrown!ConvException("abc".to!int);

// ifThrown can be used to provide a default value if an exception is thrown
writeln("x".to!int().ifThrown(0)); // 0

// handle is a more advanced version of ifThrown for ranges
auto r = "12,1337z32,54".splitter(',').map!(a => to!int(a));
auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
assert(h.equal([12, 0, 54]));
assertThrown!ConvException(h.retro.equal([54, 0, 12]));

// basicExceptionCtors avoids the boilerplate when creating custom exceptions
static class MeaCulpa : Exception
{
    mixin basicExceptionCtors;
}
e = collectException((){throw new MeaCulpa("diagnostic message");}());
writeln(e.msg); // "diagnostic message"
writeln(e.file); // __FILE__
writeln(e.line); // __LINE__ - 3

// assumeWontThrow can be used to cast throwing code into `nothrow`
void exceptionFreeCode() nothrow
{
    // auto-decoding only throws if an invalid UTF char is given
    assumeWontThrow("abc".front);
}

// assumeUnique can be used to cast mutable instance to an `immutable` one
// use with care
char[] str = "  mutable".dup;
str[0 .. 2] = "im";
immutable res = assumeUnique(str);
writeln(res); // "immutable"

```
 
 
auto **assertNotThrown**(T : Throwable = Exception, E)(lazy E expression, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Asserts that the given expression does *not* throw the given type of `Throwable`. If a `Throwable` of the given type is thrown, it is caught and does not escape assertNotThrown. Rather, an `AssertError` is thrown. However, any other `Throwable`s will escape. 



Parameters:


|  |  |
| --- | --- |
| T | The `Throwable` to test for. |
| E `expression` | The expression to test. |
| string `msg` | Optional message to output on test failure. If msg is empty, and the thrown exception has a non-empty msg field, the exception's msg field will be output on test failure. |
| string `file` | The file where the error occurred. Defaults to `__FILE__`. |
| size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. |


 
Throws:

`AssertError` if the given `Throwable` is thrown. 
 
Returns:
the result of `expression`.
 
Examples:


```
import core.exception : AssertError;

import std.string;
assertNotThrown!StringException(enforce!StringException(true, "Error!"));

//Exception is the default.
assertNotThrown(enforce!StringException(true, "Error!"));

assert(collectExceptionMsg!AssertError(assertNotThrown!StringException(
           enforce!StringException(false, "Error!"))) ==
       `assertNotThrown failed: StringException was thrown: Error!`);

```
 
  void **assertThrown**(T : Throwable = Exception, E)(lazy E expression, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Asserts that the given expression throws the given type of `Throwable`. The `Throwable` is caught and does not escape assertThrown. However, any other `Throwable`s *will* escape, and if no `Throwable` of the given type is thrown, then an `AssertError` is thrown. 



Parameters:


|  |  |
| --- | --- |
| T | The `Throwable` to test for. |
| E `expression` | The expression to test. |
| string `msg` | Optional message to output on test failure. |
| string `file` | The file where the error occurred. Defaults to `__FILE__`. |
| size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. |


 
Throws:

`AssertError` if the given `Throwable` is not thrown.
 
Examples:


```
import core.exception : AssertError;
import std.string;

assertThrown!StringException(enforce!StringException(false, "Error!"));

//Exception is the default.
assertThrown(enforce!StringException(false, "Error!"));

assert(collectExceptionMsg!AssertError(assertThrown!StringException(
           enforce!StringException(true, "Error!"))) ==
       `assertThrown failed: No StringException was thrown.`);

```
 
  template **enforce**(E : Throwable = Exception) if (is(typeof(new E("", string.init, size\_t.init)) : Throwable) || is(typeof(new E(string.init, size\_t.init)) : Throwable))  
  
T **enforce**(T, Dg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)(T value, scope Dg dg)  
 Constraints: if (isSomeFunction!Dg && is(typeof(dg())) && is(typeof(() { if (!value) { } } )));   
  
T **enforce**(T)(T value, lazy Throwable ex);  
Enforces that the given value is true. If the given value is false, an exception is thrown. The * `msg` - error message as a `string`
* `dg` - custom delegate that return a string and is only called if an exception occurred
* `ex` - custom exception to be thrown. It is `lazy` and is only created if an exception occurred

 



Parameters:


|  |  |
| --- | --- |
| T `value` | The value to test. |
| E | Exception type to throw if the value evaluates to false. |
| const(char)[] msg | The error message to put in the exception if it is thrown. |
| Dg `dg` | The delegate to be called if the value evaluates to false. |
| Throwable `ex` | The exception to throw if the value evaluates to false. |
| string file | The source file of the caller. |
| size\_t line | The line number of the caller. |


 
Returns:

`value`, if `cast(bool) value` is true. Otherwise, depending on the chosen overload, `new Exception(msg)`, `dg()` or `ex` is thrown. 
 
Note
 `enforce` is used to throw exceptions and is therefore intended to aid in error handling. It is *not* intended for verifying the logic of your program. That is what `assert` is for. Also, do not use `enforce` inside of contracts (i.e. inside of `in` and `out` blocks and `invariant`s), because contracts are compiled out when compiling with *-release*. 
 If a delegate is passed, the safety and purity of this function are inferred from `Dg`'s safety and purity. 
Examples:


```
import core.stdc.stdlib : malloc, free;
import std.conv : ConvException, to;

// use enforce like assert
int a = 3;
enforce(a > 2, "a needs to be higher than 2.");

// enforce can throw a custom exception
enforce!ConvException(a > 2, "a needs to be higher than 2.");

// enforce will return it's input
enum size = 42;
auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
scope(exit) free(memory.ptr);

```
 
 
Examples:


```
assertNotThrown(enforce(true, new Exception("this should not be thrown")));
assertThrown(enforce(false, new Exception("this should be thrown")));

```
 
 
Examples:


```
writeln(enforce(123)); // 123

try
{
    enforce(false, "error");
    assert(false);
}
catch (Exception e)
{
    writeln(e.msg); // "error"
    writeln(e.file); // __FILE__
    writeln(e.line); // __LINE__ - 7
}

```
 
 
Examples:
Alias your own enforce function 
```
import std.conv : ConvException;
alias convEnforce = enforce!ConvException;
assertNotThrown(convEnforce(true));
assertThrown!ConvException(convEnforce(false, "blah"));

```
 
 
T **enforce**(T)(T value, lazy const(char)[] msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)  
 Constraints: if (is(typeof(() { if (!value) { } } ))); 
   alias **errnoEnforce** = enforce!(ErrnoException).enforce(T)(T value, lazy const(char)[] msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_) if (is(typeof(() { if (!value) { } } )));  
Enforces that the given value is true, throwing an `ErrnoException` if it is not. 



Parameters:


|  |  |
| --- | --- |
| T value | The value to test. |
| const(char)[] msg | The message to include in the `ErrnoException` if it is thrown. |


 
Returns:

`value`, if `cast(bool) value` is true. Otherwise, `new ErrnoException(msg)` is thrown. It is assumed that the last operation set `errno` to an error code corresponding with the failed condition.
 
Examples:


```
import core.stdc.stdio : fclose, fgets, fopen;
import std.file : thisExePath;
import std.string : toStringz;

auto f = fopen(thisExePath.toStringz, "r").errnoEnforce;
scope(exit) fclose(f);
char[100] buf;
auto line = fgets(buf.ptr, buf.length, f);
enforce(line !is null); // expect a non-empty line

```
 
  template **enforceEx**(E : Throwable) if (is(typeof(new E("", string.init, size\_t.init)))) 
Deprecated. Please use [`enforce`](#enforce) instead. This function will be removed 2.089. 


If `!value` is `false`, `value` is returned. Otherwise, `new E(msg, file, line)` is thrown. Or if `E` doesn't take a message and can be constructed with `new E(file, line)`, then `new E(file, line)` will be thrown. 

 
Example


```
auto f = enforceEx!FileMissingException(fopen("data.txt"));
auto line = readln(f);
enforceEx!DataCorruptionException(line.length);

```
 
T **enforceEx**(T)(T value, lazy string msg = "", string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Ditto

    T **collectException**(T = Exception, E)(lazy E expression, ref E result);  
Catches and returns the exception thrown from the given expression. If no exception is thrown, then null is returned and `result` is set to the result of the expression. 


Note that while `collectException` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectException` to collect non-`Exception`s unless you're sure that that's what you really want to do. 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of exception to catch. |
| E `expression` | The expression which may throw an exception. |
| E `result` | The result of the expression if no exception is thrown. |


 
Examples:


```
int b;
int foo() { throw new Exception("blah"); }
assert(collectException(foo(), b));

int[] a = new int[3];
import core.exception : RangeError;
assert(collectException!RangeError(a[4], b));

```
 
  T **collectException**(T : Throwable = Exception, E)(lazy E expression);  
Catches and returns the exception thrown from the given expression. If no exception is thrown, then null is returned. `E` can be `void`. 


Note that while `collectException` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectException` to collect non-`Exception`s unless you're sure that that's what you really want to do. 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of exception to catch. |
| E `expression` | The expression which may throw an exception. |


 
Examples:


```
int foo() { throw new Exception("blah"); }
writeln(collectException(foo()).msg); // "blah"

```
 
  string **collectExceptionMsg**(T = Exception, E)(lazy E expression);  
Catches the exception thrown from the given expression and returns the msg property of that exception. If no exception is thrown, then null is returned. `E` can be `void`. 


If an exception is thrown but it has an empty message, then `emptyExceptionMsg` is returned.   
  
 Note that while `collectExceptionMsg` *can* be used to collect any `Throwable` and not just `Exception`s, it is generally ill-advised to catch anything that is neither an `Exception` nor a type derived from `Exception`. So, do not use `collectExceptionMsg` to collect non-`Exception`s unless you're sure that that's what you really want to do. 

 
Parameters:


|  |  |
| --- | --- |
| T | The type of exception to catch. |
| E `expression` | The expression which may throw an exception. |


 
Examples:


```
void throwFunc() { throw new Exception("My Message."); }
writeln(collectExceptionMsg(throwFunc())); // "My Message."

void nothrowFunc() {}
assert(collectExceptionMsg(nothrowFunc()) is null);

void throwEmptyFunc() { throw new Exception(""); }
writeln(collectExceptionMsg(throwEmptyFunc())); // emptyExceptionMsg

```
 
  enum string **emptyExceptionMsg**;  
Value that collectExceptionMsg returns when it catches an exception with an empty exception message.

  pure nothrow immutable(T)[] **assumeUnique**(T)(T[] array);   
  
pure nothrow immutable(T)[] **assumeUnique**(T)(ref T[] array);   
  
pure nothrow immutable(T[U]) **assumeUnique**(T, U)(ref T[U] array);  
Casts a mutable array to an immutable array in an idiomatic manner. Technically, `assumeUnique` just inserts a cast, but its name documents assumptions on the part of the caller. `assumeUnique(arr)` should only be called when there are no more active mutable aliases to elements of  `arr`. To strengthen this assumption, `assumeUnique(arr)` also clears `arr` before returning. Essentially  `assumeUnique(arr)` indicates commitment from the caller that there is no more mutable access to any of `arr`'s elements (transitively), and that all future accesses will be done through the immutable array returned by `assumeUnique`. 


Typically, `assumeUnique` is used to return arrays from functions that have allocated and built them. 

 
Parameters:


|  |  |
| --- | --- |
| T[] `array` | The array to cast to immutable. |


 
Returns:
The immutable array. 
 
Example
 
```
string letters()
{
  char[] result = new char['z' - 'a' + 1];
  foreach (i, ref e; result)
  {
    e = cast(char)('a' + i);
  }
  return assumeUnique(result);
}

```
 The use in the example above is correct because `result` was private to `letters` and is inaccessible in writing after the function returns. The following example shows an incorrect use of `assumeUnique`. 
Bad
 
```
private char[] buffer;
string letters(char first, char last)
{
  if (first >= last) return null; // fine
  auto sneaky = buffer;
  sneaky.length = last - first + 1;
  foreach (i, ref e; sneaky)
  {
    e = cast(char)('a' + i);
  }
  return assumeUnique(sneaky); // BAD
}

```
 The example above wreaks havoc on client code because it is modifying arrays that callers considered immutable. To obtain an immutable array from the writable array `buffer`, replace the last line with: 
```
return to!(string)(sneaky); // not that sneaky anymore

```
 The call will duplicate the array appropriately. Note that checking for uniqueness during compilation is possible in certain cases, especially when a function is marked as a pure function. The following example does not need to call assumeUnique because the compiler can infer the uniqueness of the array in the pure function: 
```
string letters() pure
{
  char[] result = new char['z' - 'a' + 1];
  foreach (i, ref e; result)
  {
    e = cast(char)('a' + i);
  }
  return result;
}

```
 For more on infering uniqueness see the **unique** and **lent** keywords in the [ArchJava](http://www.cs.cmu.edu/~aldrich/papers/aldrich-dissertation.pdf) language. The downside of using `assumeUnique`'s convention-based usage is that at this time there is no formal checking of the correctness of the assumption; on the upside, the idiomatic use of `assumeUnique` is simple and rare enough to be tolerable. 
Examples:


```
int[] arr = new int[1];
auto arr1 = arr.assumeUnique;
static assert(is(typeof(arr1) == immutable(int)[]));
writeln(arr); // null
writeln(arr1); // [0]

```
 
 
Examples:


```
int[string] arr = ["a":1];
auto arr1 = arr.assumeUnique;
static assert(is(typeof(arr1) == immutable(int[string])));
writeln(arr); // null
writeln(arr1.keys); // ["a"]

```
 
  nothrow T **assumeWontThrow**(T)(lazy T expr, string msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Wraps a possibly-throwing expression in a `nothrow` wrapper so that it can be called by a `nothrow` function. 


This wrapper function documents commitment on the part of the caller that the appropriate steps have been taken to avoid whatever conditions may trigger an exception during the evaluation of `expr`. If it turns out that the expression *does* throw at runtime, the wrapper will throw an `AssertError`.   
  
 (Note that `Throwable` objects such as `AssertError` that do not subclass `Exception` may be thrown even from `nothrow` functions, since they are considered to be serious runtime problems that cannot be recovered from.) 

 
Parameters:


|  |  |
| --- | --- |
| T `expr` | The expression asserted not to throw. |
| string `msg` | The message to include in the `AssertError` if the assumption turns out to be false. |
| string `file` | The source file name of the caller. |
| size\_t `line` | The line number of the caller. |


 
Returns:
The value of `expr`, if any.
 
Examples:


```
import std.math : sqrt;

// This function may throw.
int squareRoot(int x)
{
    if (x < 0)
        throw new Exception("Tried to take root of negative number");
    return cast(int) sqrt(cast(double) x);
}

// This function never throws.
int computeLength(int x, int y) nothrow
{
    // Since x*x + y*y is always positive, we can safely assume squareRoot
    // won't throw, and use it to implement this nothrow function. If it
    // does throw (e.g., if x*x + y*y overflows a 32-bit value), then the
    // program will terminate.
    return assumeWontThrow(squareRoot(x*x + y*y));
}

writeln(computeLength(3, 4)); // 5

```
 
  pure nothrow @nogc @trusted bool **doesPointTo**(S, T, Tdummy = void)(auto ref const S source, ref const T target)  
 Constraints: if (\_\_traits(isRef, source) || isDynamicArray!S || isPointer!S || is(S == class));   
  
pure nothrow @trusted bool **doesPointTo**(S, T)(auto ref const shared S source, ref const shared T target);   
  
pure nothrow @trusted bool **mayPointTo**(S, T, Tdummy = void)(auto ref const S source, ref const T target)  
 Constraints: if (\_\_traits(isRef, source) || isDynamicArray!S || isPointer!S || is(S == class));   
  
pure nothrow @trusted bool **mayPointTo**(S, T)(auto ref const shared S source, ref const shared T target);  
Checks whether a given source object contains pointers or references to a given target object. 



Parameters:


|  |  |
| --- | --- |
| S `source` | The source object |
| T `target` | The target object |


 
Bugs:
The function is explicitly annotated `@nogc` because inference could fail, see [issue 17084](https://issues.dlang.org/show_bug.cgi?id=17084). 
 
Returns:

`true` if `source`'s representation embeds a pointer that points to `target`'s representation or somewhere inside it. If `source` is or contains a dynamic array, then, then these functions will check if there is overlap between the dynamic array and `target`'s representation. If `source` is a class, then it will be handled as a pointer. If `target` is a pointer, a dynamic array or a class, then these functions will only check if `source` points to `target`, *not* what `target` references. If `source` is or contains a union or `void[n]`, then there may be either false positives or false negatives: `doesPointTo` will return `true` if it is absolutely certain `source` points to `target`. It may produce false negatives, but never false positives. This function should be prefered when trying to validate input data. `mayPointTo` will return `false` if it is absolutely certain `source` does not point to `target`. It may produce false positives, but never false negatives. This function should be prefered for defensively choosing a code path. 
 
Note
 Evaluating `doesPointTo(x, x)` checks whether `x` has internal pointers. This should only be done as an assertive test, as the language is free to assume objects don't have internal pointers (TDPL 7.1.3.5).
 
Examples:
Pointers 
```
int  i = 0;
int* p = null;
assert(!p.doesPointTo(i));
p = &i;
assert( p.doesPointTo(i));

```
 
 
Examples:
Structs and Unions 
```
struct S
{
    int v;
    int* p;
}
int i;
auto s = S(0, &i);

// structs and unions "own" their members
// pointsTo will answer true if one of the members pointsTo.
assert(!s.doesPointTo(s.v)); //s.v is just v member of s, so not pointed.
assert( s.p.doesPointTo(i)); //i is pointed by s.p.
assert( s  .doesPointTo(i)); //which means i is pointed by s itself.

// Unions will behave exactly the same. Points to will check each "member"
// individually, even if they share the same memory

```
 
 
Examples:
Arrays (dynamic and static) 
```
int i;
 // trick the compiler when initializing slice
 // https://issues.dlang.org/show_bug.cgi?id=18637
int* p = &i;
int[]  slice = [0, 1, 2, 3, 4];
int[5] arr   = [0, 1, 2, 3, 4];
int*[]  slicep = [p];
int*[1] arrp   = [&i];

// A slice points to all of its members:
assert( slice.doesPointTo(slice[3]));
assert(!slice[0 .. 2].doesPointTo(slice[3])); // Object 3 is outside of the
                                              // slice [0 .. 2]

// Note that a slice will not take into account what its members point to.
assert( slicep[0].doesPointTo(i));
assert(!slicep   .doesPointTo(i));

// static arrays are objects that own their members, just like structs:
assert(!arr.doesPointTo(arr[0])); // arr[0] is just a member of arr, so not
                                  // pointed.
assert( arrp[0].doesPointTo(i));  // i is pointed by arrp[0].
assert( arrp   .doesPointTo(i));  // which means i is pointed by arrp
                                  // itself.

// Notice the difference between static and dynamic arrays:
assert(!arr  .doesPointTo(arr[0]));
assert( arr[].doesPointTo(arr[0]));
assert( arrp  .doesPointTo(i));
assert(!arrp[].doesPointTo(i));

```
 
 
Examples:
Classes 
```
class C
{
    this(int* p){this.p = p;}
    int* p;
}
int i;
C a = new C(&i);
C b = a;

// Classes are a bit particular, as they are treated like simple pointers
// to a class payload.
assert( a.p.doesPointTo(i)); // a.p points to i.
assert(!a  .doesPointTo(i)); // Yet a itself does not point i.

//To check the class payload itself, iterate on its members:
()
{
    import std.traits : Fields;

    foreach (index, _; Fields!C)
        if (doesPointTo(a.tupleof[index], i))
            return;
    assert(0);
}();

// To check if a class points a specific payload, a direct memmory check
// can be done:
auto aLoc = cast(ubyte[__traits(classInstanceSize, C)]*) a;
assert(b.doesPointTo(*aLoc)); // b points to where a is pointing

```
 
  class **ErrnoException**: object.Exception;  
Thrown if errors that set `errno` occur.



Examples:


```
import core.stdc.errno : EAGAIN;
auto ex = new ErrnoException("oh no", EAGAIN);
writeln(ex.errno); // EAGAIN

```
 
 
Examples:
errno is used by default if no explicit error code is provided 
```
import core.stdc.errno : errno, EAGAIN;

auto old = errno;
scope(exit) errno = old;

// fake that errno got set by the callee
errno = EAGAIN;
auto ex = new ErrnoException("oh no");
writeln(ex.errno); // EAGAIN

```
 
 
final pure nothrow @nogc @property @safe uint **errno**();  
Operating system error code.

  @safe this(string msg, string file = null, size\_t line = 0);  
Constructor which takes an error message. The current global [`core.stdc.errno.errno`](core_stdc_errno#errno) value is used as error code.

  @safe this(string msg, int errno, string file = null, size\_t line = 0);  
Constructor which takes an error message and error code.

    CommonType!(T1, T2) **ifThrown**(E : Throwable = Exception, T1, T2)(lazy scope T1 expression, lazy scope T2 errorHandler);   
  
CommonType!(T1, T2) **ifThrown**(E : Throwable, T1, T2)(lazy scope T1 expression, scope T2 delegate(E) errorHandler);   
  
CommonType!(T1, T2) **ifThrown**(T1, T2)(lazy scope T1 expression, scope T2 delegate(Exception) errorHandler);  
ML-style functional exception handling. Runs the supplied expression and returns its result. If the expression throws a `Throwable`, runs the supplied error handler instead and return its result. The error handler's type must be the same as the expression's type. 



Parameters:


|  |  |
| --- | --- |
| E | The type of `Throwable`s to catch. Defaults to `Exception` |
| T1 | The type of the expression. |
| T2 | The return type of the error handler. |
| T1 `expression` | The expression to run and return its result. |
| T2 `errorHandler` | The handler to run if the expression throwed. |


 
Returns:
expression, if it does not throw. Otherwise, returns the result of errorHandler.
 
Examples:
Revert to a default value upon an error: 
```
import std.conv : to;
writeln("x".to!int.ifThrown(0)); // 0

```
 
 
Examples:
Chain multiple calls to ifThrown, each capturing errors from the entire preceding expression. 
```
import std.conv : ConvException, to;
string s = "true";
assert(s.to!int.ifThrown(cast(int) s.to!double)
               .ifThrown(cast(int) s.to!bool) == 1);

s = "2.0";
assert(s.to!int.ifThrown(cast(int) s.to!double)
               .ifThrown(cast(int) s.to!bool) == 2);

// Respond differently to different types of errors
alias orFallback = (lazy a)  => a.ifThrown!ConvException("not a number")
                                 .ifThrown!Exception("number too small");

writeln(orFallback(enforce("x".to!int < 1).to!string)); // "not a number"
writeln(orFallback(enforce("2".to!int < 1).to!string)); // "number too small"

```
 
 
Examples:
The expression and the errorHandler must have a common type they can both be implicitly casted to, and that type will be the type of the compound expression. 
```
// null and new Object have a common type(Object).
static assert(is(typeof(null.ifThrown(new Object())) == Object));
static assert(is(typeof((new Object()).ifThrown(null)) == Object));

// 1 and new Object do not have a common type.
static assert(!__traits(compiles, 1.ifThrown(new Object())));
static assert(!__traits(compiles, (new Object()).ifThrown(1)));

```
 
 
Examples:
Use a lambda to get the thrown object. 
```
import std.format : format;
// "std.format.FormatException"
writeln("%s".format.ifThrown!Exception(e => e.classinfo.name));

```
 
  enum **RangePrimitive**: int;  
This `enum` is used to select the primitives of the range to handle by the [`handle`](#handle) range wrapper. The values of the `enum` can be `OR`'d to select multiple primitives to be handled. 


`RangePrimitive.access` is a shortcut for the access primitives; `front`, `back` and `opIndex`.   
  
 `RangePrimitive.pop` is a shortcut for the mutating primitives; `popFront` and `popBack`.

 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map, splitter;
import std.conv : to, ConvException;

auto s = "12,1337z32,54,2,7,9,1z,6,8";

// The next line composition will throw when iterated
// as some elements of the input do not convert to integer
auto r = s.splitter(',').map!(a => to!int(a));

// Substitute 0 for cases of ConvException
auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8]));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : retro;
import std.utf : UTFException;

auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit

auto handled = str.handle!(UTFException, RangePrimitive.access,
        (e, r) => ' '); // Replace invalid code points with spaces

assert(handled.equal("hello world")); // `front` is handled,
assert(handled.retro.equal("dlrow olleh")); // as well as `back`

```
 
 

**front**  
  
**back**  
  
**popFront**  
  
**popBack**  
  
**empty**  
  
**save**  
  
**length**  
  
**opDollar**  
  
**opIndex**  
  
**opSlice**  
  
**access**  
  
**pop**
   auto **handle**(E : Throwable, RangePrimitive primitivesToHandle, alias handler, Range)(Range input)  
 Constraints: if (isInputRange!Range); 
 
Handle exceptions thrown from range primitives. 


Use the [`RangePrimitive`](#RangePrimitive) enum to specify which primitives to handle. Multiple range primitives can be handled at once by using the `OR` operator or the pseudo-primitives `RangePrimitive.access` and `RangePrimitive.pop`. All handled primitives must have return types or values compatible with the user-supplied handler. 

 
Parameters:


|  |  |
| --- | --- |
| E | The type of `Throwable` to handle. |
| primitivesToHandle | Set of range primitives to handle. |
| handler | The callable that is called when a handled primitive throws a `Throwable` of type `E`. The handler must accept arguments of the form `E, ref IRange` and its return value is used as the primitive's return value whenever `E` is thrown. For `opIndex`, the handler can optionally recieve a third argument; the index that caused the exception. |
| Range `input` | The range to handle. |


 
Returns:
A wrapper `struct` that preserves the range interface of `input`. 
 
Note
 Infinite ranges with slicing support must return an instance of [`std.range.Take`](std_range#Take) when sliced with a specific lower and upper bound (see [`std.range.primitives.hasSlicing`](std_range_primitives#hasSlicing)); `handle` deals with this by `take`ing 0 from the return value of the handler function and returning that when an exception is caught.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map, splitter;
import std.conv : to, ConvException;

auto s = "12,1337z32,54,2,7,9,1z,6,8";

// The next line composition will throw when iterated
// as some elements of the input do not convert to integer
auto r = s.splitter(',').map!(a => to!int(a));

// Substitute 0 for cases of ConvException
auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8]));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : retro;
import std.utf : UTFException;

auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit

auto handled = str.handle!(UTFException, RangePrimitive.access,
        (e, r) => ' '); // Replace invalid code points with spaces

assert(handled.equal("hello world")); // `front` is handled,
assert(handled.retro.equal("dlrow olleh")); // as well as `back`

```
 
  template **basicExceptionCtors**() 
Convenience mixin for trivially sub-classing exceptions 


Even trivially sub-classing an exception involves writing boilerplate code for the constructor to: 1) correctly pass in the source file and line number the exception was thrown from; 2) be usable with [`enforce`](#enforce) which expects exception constructors to take arguments in a fixed order. This mixin provides that boilerplate code.   
  
 Note however that you need to mark the **mixin** line with at least a minimal (i.e. just **///**) DDoc comment if you want the mixed-in constructors to be documented in the newly created Exception subclass.   
  
 Current limitation: Due to [bug #11500](https://issues.dlang.org/show_bug.cgi?id=11500), currently the constructors specified in this mixin cannot be overloaded with any other custom constructors. Thus this mixin can currently only be used when no such custom constructors need to be explicitly specified.

 
Examples:


```
class MeaCulpa: Exception
{
    ///
    mixin basicExceptionCtors;
}

try
    throw new MeaCulpa("test");
catch (MeaCulpa e)
{
    writeln(e.msg); // "test"
    writeln(e.file); // __FILE__
    writeln(e.line); // __LINE__ - 5
}

```
 
 
pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |
| Throwable `next` | The previous exception in the chain of exceptions, if any. |


  pure nothrow @nogc @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| Throwable `next` | The previous exception in the chain of exceptions. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |


    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_exception.html>

std.experimental.allocator
==========================

 High-level interface for allocators. Implements bundled allocation/creation and destruction/deallocation of data including `struct`s and `class`es, and also array primitives related to allocation. This module is the entry point for both making use of allocators and for their documentation. 


 

| Category | Functions |
| --- | --- |
| Make | [`make`](#make) [`makeArray`](#makeArray) [`makeMultidimensionalArray`](#makeMultidimensionalArray) |
| Dispose | [`dispose`](#dispose) [`disposeMultidimensionalArray`](#disposeMultidimensionalArray) |
| Modify | [`expandArray`](#expandArray) [`shrinkArray`](#shrinkArray) |
| Global | [`processAllocator`](#processAllocator) [`theAllocator`](#theAllocator) |
| Class interface | [`allocatorObject`](#allocatorObject) [`CAllocatorImpl`](#CAllocatorImpl) [`IAllocator`](#IAllocator) |

 

 
Synopsis


```
// Allocate an int, initialize it with 42
int* p = theAllocator.make!int(42);
assert(*p == 42);
// Destroy and deallocate it
theAllocator.dispose(p);

// Allocate using the global process allocator
p = processAllocator.make!int(100);
assert(*p == 100);
// Destroy and deallocate
processAllocator.dispose(p);

// Create an array of 50 doubles initialized to -1.0
double[] arr = theAllocator.makeArray!double(50, -1.0);
// Append two zeros to it
theAllocator.expandArray(arr, 2, 0.0);
// On second thought, take that back
theAllocator.shrinkArray(arr, 2);
// Destroy and deallocate
theAllocator.dispose(arr);

```
 Layered Structure
-----------------

 D's allocators have a layered structure in both implementation and documentation: 1. A high-level, dynamically-typed layer (described further down in this module). It consists of an interface called [`IAllocator`](#IAllocator), which concrete allocators need to implement. The interface primitives themselves are oblivious to the type of the objects being allocated; they only deal in `void[]`, by necessity of the interface being dynamic (as opposed to type-parameterized). Each thread has a current allocator it uses by default, which is a thread-local variable [`theAllocator`](#theAllocator) of type [`IAllocator`](#IAllocator). The process has a global allocator called [`processAllocator`](#processAllocator), also of type [`IAllocator`](#IAllocator). When a new thread is created, [`processAllocator`](#processAllocator) is copied into [`theAllocator`](#theAllocator). An application can change the objects to which these references point. By default, at application startup, [`processAllocator`](#processAllocator) refers to an object that uses D's garbage collected heap. This layer also include high-level functions such as [`make`](#make) and [`dispose`](#dispose) that comfortably allocate/create and respectively destroy/deallocate objects. This layer is all needed for most casual uses of allocation primitives.
2. A mid-level, statically-typed layer for assembling several allocators into one. It uses properties of the type of the objects being created to route allocation requests to possibly specialized allocators. This layer is relatively thin and implemented and documented in the [`std.experimental.allocator.typed`](std_experimental_allocator_typed) module. It allows an interested user to e.g. use different allocators for arrays versus fixed-sized objects, to the end of better overall performance.
3. A low-level collection of highly generic *heap building blocks* —  Lego-like pieces that can be used to assemble application-specific allocators. The real allocation smarts are occurring at this level. This layer is of interest to advanced applications that want to configure their own allocators. A good illustration of typical uses of these building blocks is module [`std.experimental.allocator.showcase`](std_experimental_allocator_showcase) which defines a collection of frequently- used preassembled allocator objects. The implementation and documentation entry point is [`std.experimental.allocator.building_blocks`](std_experimental_allocator_building_blocks). By design, the primitives of the static interface have the same signatures as the [`IAllocator`](#IAllocator) primitives but are for the most part optional and driven by static introspection. The parameterized class [`CAllocatorImpl`](#CAllocatorImpl) offers an immediate and useful means to package a static low-level allocator into an implementation of [`IAllocator`](#IAllocator).
4. Core allocator objects that interface with D's garbage collected heap ([`std.experimental.allocator.gc_allocator`](std_experimental_allocator_gc_allocator)), the C `malloc` family ([`std.experimental.allocator.mallocator`](std_experimental_allocator_mallocator)), and the OS ([`std.experimental.allocator.mmap_allocator`](std_experimental_allocator_mmap_allocator)). Most custom allocators would ultimately obtain memory from one of these core allocators.

 Idiomatic Use of `std.experimental.allocator`
---------------------------------------------

 As of this time, `std.experimental.allocator` is not integrated with D's built-in operators that allocate memory, such as `new`, array literals, or array concatenation operators. That means `std.experimental.allocator` is opt-in — applications need to make explicit use of it. For casual creation and disposal of dynamically-allocated objects, use [`make`](#make), [`dispose`](#dispose), and the array-specific functions [`makeArray`](#makeArray), [`expandArray`](#expandArray), and [`shrinkArray`](#shrinkArray). These use by default D's garbage collected heap, but open the application to better configuration options. These primitives work either with `theAllocator` but also with any allocator obtained by combining heap building blocks. For example: 
```
void fun(size_t n)
{
    // Use the current allocator
    int[] a1 = theAllocator.makeArray!int(n);
    scope(exit) theAllocator.dispose(a1);
    ...
}

```
 To experiment with alternative allocators, set [`theAllocator`](#theAllocator) for the current thread. For example, consider an application that allocates many 8-byte objects. These are not well supported by the default allocator, so a [free list allocator](std_experimental_allocator_building_blocks_free_list) would be recommended. To install one in `main`, the application would use: 
```
void main()
{
    import std.experimental.allocator.building_blocks.free_list
        : FreeList;
    theAllocator = allocatorObject(FreeList!8());
    ...
}

```
 ### Saving the `IAllocator` Reference For Later Use

 As with any global resource, setting `theAllocator` and `processAllocator` should not be done often and casually. In particular, allocating memory with one allocator and deallocating with another causes undefined behavior. Typically, these variables are set during application initialization phase and last through the application. To avoid this, long-lived objects that need to perform allocations, reallocations, and deallocations relatively often may want to store a reference to the allocator object they use throughout their lifetime. Then, instead of using `theAllocator` for internal allocation-related tasks, they'd use the internally held reference. For example, consider a user-defined hash table: 
```
struct HashTable
{
    private IAllocator allocator;
    this(size_t buckets, IAllocator allocator = theAllocator) {
        this.allocator = allocator;
        ...
    }
    // Getter and setter
    IAllocator allocator() { return allocator; }
    void allocator(IAllocator a) { assert(empty); allocator = a; }
}

```
 Following initialization, the `HashTable` object would consistently use its `allocator` object for acquiring memory. Furthermore, setting `HashTable.allocator` to point to a different allocator should be legal but only if the object is empty; otherwise, the object wouldn't be able to deallocate its existing state. ### Using Allocators without `IAllocator`

 Allocators assembled from the heap building blocks don't need to go through `IAllocator` to be usable. They have the same primitives as `IAllocator` and they work with [`make`](#make), [`makeArray`](#makeArray), [`dispose`](#dispose) etc. So it suffice to create allocator objects wherever fit and use them appropriately: 
```
void fun(size_t n)
{
    // Use a stack-installed allocator for up to 64KB
    StackFront!65536 myAllocator;
    int[] a2 = myAllocator.makeArray!int(n);
    scope(exit) myAllocator.dispose(a2);
    ...
}

```
 In this case, `myAllocator` does not obey the `IAllocator` interface, but implements its primitives so it can work with `makeArray` by means of duck typing. One important thing to note about this setup is that statically-typed assembled allocators are almost always faster than allocators that go through `IAllocator`. An important rule of thumb is: "assemble allocator first, adapt to `IAllocator` after". A good allocator implements intricate logic by means of template assembly, and gets wrapped with `IAllocator` (usually by means of [`allocatorObject`](#allocatorObject)) only once, at client level. 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com) 
 
Source
 [std/experimental/allocator](https://github.com/dlang/phobos/blob/master/std/experimental/allocator)

 
interface **IAllocator**;  
Dynamic allocator interface. Code that defines allocators ultimately implements this interface. This should be used wherever a uniform type is required for encapsulating various allocator implementations. 


Composition of allocators is not recommended at this level due to inflexibility of dynamic interfaces and inefficiencies caused by cascaded multiple calls. Instead, compose allocators using the static interface defined in [`std.experimental.allocator.building_blocks`](std_experimental_allocator_building_blocks), then adapt the composed allocator to `IAllocator` (possibly by using [`CAllocatorImpl`](#CAllocatorImpl) below).   
  
 Methods returning `Ternary` return `Ternary.yes` upon success, `Ternary.no` upon failure, and `Ternary.unknown` if the primitive is not implemented by the allocator instance.

 
abstract nothrow @property uint **alignment**();  
Returns the alignment offered.

  abstract nothrow size\_t **goodAllocSize**(size\_t s);  
Returns the good allocation size that guarantees zero internal fragmentation.

  abstract nothrow void[] **allocate**(size\_t, TypeInfo ti = null);  
Allocates `n` bytes of memory.

  abstract nothrow void[] **alignedAllocate**(size\_t n, uint a);  
Allocates `n` bytes of memory with specified alignment `a`. Implementations that do not support this primitive should always return `null`.

  abstract nothrow void[] **allocateAll**();  
Allocates and returns all memory available to this allocator. Implementations that do not support this primitive should always return `null`.

  abstract nothrow bool **expand**(ref void[], size\_t);  
Expands a memory block in place and returns `true` if successful. Implementations that don't support this primitive should always return `false`.

  abstract nothrow bool **reallocate**(ref void[], size\_t);  
Reallocates a memory block.

  abstract nothrow bool **alignedReallocate**(ref void[] b, size\_t size, uint alignment);  
Reallocates a memory block with specified alignment.

  abstract nothrow Ternary **owns**(void[] b);  
Returns `Ternary.yes` if the allocator owns `b`, `Ternary.no` if the allocator doesn't own `b`, and `Ternary.unknown` if ownership cannot be determined. Implementations that don't support this primitive should always return `Ternary.unknown`.

  abstract nothrow Ternary **resolveInternalPointer**(const void\* p, ref void[] result);  
Resolves an internal pointer to the full block allocated. Implementations that don't support this primitive should always return `Ternary.unknown`.

  abstract nothrow bool **deallocate**(void[] b);  
Deallocates a memory block. Implementations that don't support this primitive should always return `false`. A simple way to check that an allocator supports deallocation is to call `deallocate(null)`.

  abstract nothrow bool **deallocateAll**();  
Deallocates all memory. Implementations that don't support this primitive should always return `false`.

  abstract nothrow Ternary **empty**();  
Returns `Ternary.yes` if no memory is currently allocated from this allocator, `Ternary.no` if some allocations are currently active, or `Ternary.unknown` if not supported.

  abstract pure nothrow @nogc @safe void **incRef**();  
Increases the reference count of the concrete class that implements this interface. 


For stateless allocators, this does nothing.

  abstract pure nothrow @nogc @safe bool **decRef**();  
Decreases the reference count of the concrete class that implements this interface. When the reference count is `0`, the object self-destructs. 



Returns:

`true` if the reference count is greater than `0` and `false` when it hits `0`. For stateless allocators, it always returns `true`.
    struct **RCIAllocator**;  
A reference counted struct that wraps the dynamic allocator interface. This should be used wherever a uniform type is required for encapsulating various allocator implementations. 


Code that defines allocators ultimately implements the [`IAllocator`](#IAllocator) interface, possibly by using [`CAllocatorImpl`](#CAllocatorImpl) below, and then build a `RCIAllocator` out of this.   
  
 Composition of allocators is not recommended at this level due to inflexibility of dynamic interfaces and inefficiencies caused by cascaded multiple calls. Instead, compose allocators using the static interface defined in [`std.experimental.allocator.building_blocks`](std_experimental_allocator_building_blocks), then adapt the composed allocator to `RCIAllocator` (possibly by using [`allocatorObject`](#allocatorObject) below).

  interface **ISharedAllocator**;  
Dynamic shared allocator interface. Code that defines allocators shareable across threads ultimately implements this interface. This should be used wherever a uniform type is required for encapsulating various allocator implementations. 


Composition of allocators is not recommended at this level due to inflexibility of dynamic interfaces and inefficiencies caused by cascaded multiple calls. Instead, compose allocators using the static interface defined in [`std.experimental.allocator.building_blocks`](std_experimental_allocator_building_blocks), then adapt the composed allocator to `ISharedAllocator` (possibly by using [`CSharedAllocatorImpl`](#CSharedAllocatorImpl) below).   
  
 Methods returning `Ternary` return `Ternary.yes` upon success, `Ternary.no` upon failure, and `Ternary.unknown` if the primitive is not implemented by the allocator instance.

 
abstract shared nothrow @property uint **alignment**();  
Returns the alignment offered.

  abstract shared nothrow size\_t **goodAllocSize**(size\_t s);  
Returns the good allocation size that guarantees zero internal fragmentation.

  abstract shared nothrow void[] **allocate**(size\_t, TypeInfo ti = null);  
Allocates `n` bytes of memory.

  abstract shared nothrow void[] **alignedAllocate**(size\_t n, uint a);  
Allocates `n` bytes of memory with specified alignment `a`. Implementations that do not support this primitive should always return `null`.

  abstract shared nothrow void[] **allocateAll**();  
Allocates and returns all memory available to this allocator. Implementations that do not support this primitive should always return `null`.

  abstract shared nothrow bool **expand**(ref void[], size\_t);  
Expands a memory block in place and returns `true` if successful. Implementations that don't support this primitive should always return `false`.

  abstract shared nothrow bool **reallocate**(ref void[], size\_t);  
Reallocates a memory block.

  abstract shared nothrow bool **alignedReallocate**(ref void[] b, size\_t size, uint alignment);  
Reallocates a memory block with specified alignment.

  abstract shared nothrow Ternary **owns**(void[] b);  
Returns `Ternary.yes` if the allocator owns `b`, `Ternary.no` if the allocator doesn't own `b`, and `Ternary.unknown` if ownership cannot be determined. Implementations that don't support this primitive should always return `Ternary.unknown`.

  abstract shared nothrow Ternary **resolveInternalPointer**(const void\* p, ref void[] result);  
Resolves an internal pointer to the full block allocated. Implementations that don't support this primitive should always return `Ternary.unknown`.

  abstract shared nothrow bool **deallocate**(void[] b);  
Deallocates a memory block. Implementations that don't support this primitive should always return `false`. A simple way to check that an allocator supports deallocation is to call `deallocate(null)`.

  abstract shared nothrow bool **deallocateAll**();  
Deallocates all memory. Implementations that don't support this primitive should always return `false`.

  abstract shared nothrow Ternary **empty**();  
Returns `Ternary.yes` if no memory is currently allocated from this allocator, `Ternary.no` if some allocations are currently active, or `Ternary.unknown` if not supported.

  abstract shared pure nothrow @nogc @safe void **incRef**();  
Increases the reference count of the concrete class that implements this interface. 


For stateless allocators, this does nothing.

  abstract shared pure nothrow @nogc @safe bool **decRef**();  
Decreases the reference count of the concrete class that implements this interface. When the reference count is `0`, the object self-destructs. 


For stateless allocators, this does nothing. 

 
Returns:

`true` if the reference count is greater than `0` and `false` when it hits `0`. For stateless allocators, it always returns `true`.
    struct **RCISharedAllocator**;  
A reference counted struct that wraps the dynamic shared allocator interface. This should be used wherever a uniform type is required for encapsulating various allocator implementations. 


Code that defines allocators shareable across threads ultimately implements the [`ISharedAllocator`](#ISharedAllocator) interface, possibly by using [`CSharedAllocatorImpl`](#CSharedAllocatorImpl) below, and then build a `RCISharedAllocator` out of this.   
  
 Composition of allocators is not recommended at this level due to inflexibility of dynamic interfaces and inefficiencies caused by cascaded multiple calls. Instead, compose allocators using the static interface defined in [`std.experimental.allocator.building_blocks`](std_experimental_allocator_building_blocks), then adapt the composed allocator to `RCISharedAllocator` (possibly by using [`sharedAllocatorObject`](#sharedAllocatorObject) below).

  nothrow @nogc @property ref @safe RCIAllocator **theAllocator**();   
  
nothrow @nogc @property @system void **theAllocator**(RCIAllocator a);  
Gets/sets the allocator for the current thread. This is the default allocator that should be used for allocating thread-local memory. For allocating memory to be shared across threads, use `processAllocator` (below). By default, `theAllocator` ultimately fetches memory from `processAllocator`, which in turn uses the garbage collected heap.



Examples:


```
// Install a new allocator that is faster for 128-byte allocations.
import std.experimental.allocator.building_blocks.free_list : FreeList;
import std.experimental.allocator.gc_allocator : GCAllocator;
auto oldAllocator = theAllocator;
scope(exit) theAllocator = oldAllocator;
theAllocator = allocatorObject(FreeList!(GCAllocator, 128)());
// Use the now changed allocator to allocate an array
const ubyte[] arr = theAllocator.makeArray!ubyte(128);
assert(arr.ptr);
//...

```
 
  nothrow @nogc @property ref @trusted RCISharedAllocator **processAllocator**();   
  
nothrow @nogc @property @system void **processAllocator**(ref RCISharedAllocator a);  
Gets/sets the allocator for the current process. This allocator must be used for allocating memory shared across threads. Objects created using this allocator can be cast to `shared`.

  auto **make**(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args);  
Dynamically allocates (using `alloc`) and then creates in the memory allocated an object of type `T`, using `args` (if any) for its initialization. Initialization occurs in the memory allocated and is otherwise semantically the same as `T(args)`. (Note that using `alloc.make!(T[])` creates a pointer to an (empty) array of `T`s, not an array. To use an allocator to allocate and initialize an array, use `alloc.makeArray!T` described below.) 



Parameters:


|  |  |
| --- | --- |
| T | Type of the object being created. |
| Allocator `alloc` | The allocator used for getting the needed memory. It may be an object implementing the static interface for allocators, or an `IAllocator` reference. |
| A `args` | Optional arguments used for initializing the created object. If not present, the object is default constructed. |


 
Returns:
If `T` is a class type, returns a reference to the created `T` object. Otherwise, returns a `T*` pointing to the created object. In all cases, returns `null` if allocation failed. 
 
Throws:
If `T`'s constructor throws, deallocates the allocated memory and propagates the exception.
 
Examples:


```
// Dynamically allocate one integer
const int* p1 = theAllocator.make!int;
// It's implicitly initialized with its .init value
writeln(*p1); // 0
// Dynamically allocate one double, initialize to 42.5
const double* p2 = theAllocator.make!double(42.5);
writeln(*p2); // 42.5

// Dynamically allocate a struct
static struct Point
{
    int x, y, z;
}
// Use the generated constructor taking field values in order
const Point* p = theAllocator.make!Point(1, 2);
assert(p.x == 1 && p.y == 2 && p.z == 0);

// Dynamically allocate a class object
static class Customer
{
    uint id = uint.max;
    this() {}
    this(uint id) { this.id = id; }
    // ...
}
Customer cust = theAllocator.make!Customer;
assert(cust.id == uint.max); // default initialized
cust = theAllocator.make!Customer(42);
writeln(cust.id); // 42

// explicit passing of outer pointer
static class Outer
{
    int x = 3;
    class Inner
    {
        auto getX() { return x; }
    }
}
auto outer = theAllocator.make!Outer();
auto inner = theAllocator.make!(Outer.Inner)(outer);
writeln(outer.x); // inner.getX

```
 
  T[] **makeArray**(T, Allocator)(auto ref Allocator alloc, size\_t length);   
  
T[] **makeArray**(T, Allocator)(auto ref Allocator alloc, size\_t length, T init);   
  
Unqual!(ElementEncodingType!R)[] **makeArray**(Allocator, R)(auto ref Allocator alloc, R range)  
 Constraints: if (isInputRange!R && !isInfinite!R);   
  
T[] **makeArray**(T, Allocator, R)(auto ref Allocator alloc, R range)  
 Constraints: if (isInputRange!R && !isInfinite!R); 
 
Create an array of `T` with `length` elements using `alloc`. The array is either default-initialized, filled with copies of `init`, or initialized with values fetched from `range`. 



Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| Allocator `alloc` | the allocator used for getting memory |
| size\_t `length` | length of the newly created array |
| T `init` | element used for filling the array |
| R `range` | range used for initializing the array elements |


 
Returns:
The newly-created array, or `null` if either `length` was `0` or allocation failed. 
 
Throws:
The first two overloads throw only if `alloc`'s primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
 
Examples:


```
import std.algorithm.comparison : equal;
static void test(T)()
{
    T[] a = theAllocator.makeArray!T(2);
    assert(a.equal([0, 0]));
    a = theAllocator.makeArray!T(3, 42);
    assert(a.equal([42, 42, 42]));
    import std.range : only;
    a = theAllocator.makeArray!T(only(42, 43, 44));
    assert(a.equal([42, 43, 44]));
}
test!int();
test!(shared int)();
test!(const int)();
test!(immutable int)();

```
 
  bool **expandArray**(T, Allocator)(auto ref Allocator alloc, ref T[] array, size\_t delta);   
  
bool **expandArray**(T, Allocator)(auto ref Allocator alloc, ref T[] array, size\_t delta, auto ref T init);   
  
bool **expandArray**(T, Allocator, R)(auto ref Allocator alloc, ref T[] array, R range)  
 Constraints: if (isInputRange!R); 
 
Grows `array` by appending `delta` more elements. The needed memory is allocated using `alloc`. The extra elements added are either default- initialized, filled with copies of `init`, or initialized with values fetched from `range`. 



Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| Allocator `alloc` | the allocator used for getting memory |
| T[] `array` | a reference to the array being grown |
| size\_t `delta` | number of elements to add (upon success the new length of `array` is `array.length + delta`) |
| T `init` | element used for filling the array |
| R `range` | range used for initializing the array elements |


 
Returns:

`true` upon success, `false` if memory could not be allocated. In the latter case `array` is left unaffected. 
 
Throws:
The first two overloads throw only if `alloc`'s primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
 
Examples:


```
auto arr = theAllocator.makeArray!int([1, 2, 3]);
assert(theAllocator.expandArray(arr, 2));
writeln(arr); // [1, 2, 3, 0, 0]
import std.range : only;
assert(theAllocator.expandArray(arr, only(4, 5)));
writeln(arr); // [1, 2, 3, 0, 0, 4, 5]

```
 
  bool **shrinkArray**(T, Allocator)(auto ref Allocator alloc, ref T[] array, size\_t delta);  
Shrinks an array by `delta` elements. 


If `array.length < delta`, does nothing and returns `false`. Otherwise, destroys the last `array.length - delta` elements in the array and then reallocates the array's buffer. If reallocation fails, fills the array with default-initialized data. 

 
Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| Allocator `alloc` | the allocator used for getting memory |
| T[] `array` | a reference to the array being shrunk |
| size\_t `delta` | number of elements to remove (upon success the new length of `array` is `array.length - delta`) |


 
Returns:

`true` upon success, `false` if memory could not be reallocated. In the latter case, the slice `array[$ - delta .. $]` is left with default-initialized elements. 
 
Throws:
The first two overloads throw only if `alloc`'s primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
 
Examples:


```
int[] a = theAllocator.makeArray!int(100, 42);
writeln(a.length); // 100
assert(theAllocator.shrinkArray(a, 98));
writeln(a.length); // 2
writeln(a); // [42, 42]

```
 
  void **dispose**(A, T)(auto ref A alloc, auto ref T\* p);   
  
void **dispose**(A, T)(auto ref A alloc, auto ref T p)  
 Constraints: if (is(T == class) || is(T == interface));   
  
void **dispose**(A, T)(auto ref A alloc, auto ref T[] array);  
Destroys and then deallocates (using `alloc`) the object pointed to by a pointer, the class object referred to by a `class` or `interface` reference, or an entire array. It is assumed the respective entities had been allocated with the same allocator. 

  auto **makeMultidimensionalArray**(T, Allocator, size\_t N)(auto ref Allocator alloc, size\_t[N] lengths...);  
Allocates a multidimensional array of elements of type T. 



Parameters:


|  |  |
| --- | --- |
| N | number of dimensions |
| T | element type of an element of the multidimensional arrat |
| Allocator `alloc` | the allocator used for getting memory |
| size\_t[N] `lengths` | static array containing the size of each dimension |


 
Returns:
An N-dimensional array with individual elements of type T.
 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;

auto mArray = Mallocator.instance.makeMultidimensionalArray!int(2, 3, 6);

// deallocate when exiting scope
scope(exit)
{
    Mallocator.instance.disposeMultidimensionalArray(mArray);
}

writeln(mArray.length); // 2
foreach (lvl2Array; mArray)
{
    writeln(lvl2Array.length); // 3
    foreach (lvl3Array; lvl2Array)
        writeln(lvl3Array.length); // 6
}

```
 
  void **disposeMultidimensionalArray**(T, Allocator)(auto ref Allocator alloc, auto ref T[] array);  
Destroys and then deallocates a multidimensional array, assuming it was created with makeMultidimensionalArray and the same allocator was used. 



Parameters:


|  |  |
| --- | --- |
| T | element type of an element of the multidimensional array |
| Allocator `alloc` | the allocator used for getting memory |
| T[] `array` | the multidimensional array that is to be deallocated |


 
Examples:


```
struct TestAllocator
{
    import std.experimental.allocator.common : platformAlignment;
    import std.experimental.allocator.mallocator : Mallocator;

    alias allocator = Mallocator.instance;

    private static struct ByteRange
    {
        void* ptr;
        size_t length;
    }

    private ByteRange[] _allocations;

    enum uint alignment = platformAlignment;

    void[] allocate(size_t numBytes)
    {
         auto ret = allocator.allocate(numBytes);
         _allocations ~= ByteRange(ret.ptr, ret.length);
         return ret;
    }

    bool deallocate(void[] bytes)
    {
        import std.algorithm.mutation : remove;
        import std.algorithm.searching : canFind;

        bool pred(ByteRange other)
        { return other.ptr == bytes.ptr && other.length == bytes.length; }

        assert(_allocations.canFind!pred);

         _allocations = _allocations.remove!pred;
         return allocator.deallocate(bytes);
    }

    ~this()
    {
        assert(!_allocations.length);
    }
}

TestAllocator allocator;

auto mArray = allocator.makeMultidimensionalArray!int(2, 3, 5, 6, 7, 2);

allocator.disposeMultidimensionalArray(mArray);

```
 
  RCIAllocator **allocatorObject**(A)(auto ref A a)  
 Constraints: if (!isPointer!A);   
  
RCIAllocator **allocatorObject**(A)(A\* pa);  
Returns a dynamically-typed `CAllocator` built around a given statically- typed allocator `a` of type `A`. Passing a pointer to the allocator creates a dynamic allocator around the allocator pointed to by the pointer, without attempting to copy or move it. Passing the allocator by value or reference behaves as follows. 


* If `A` has no state, the resulting object is allocated in static shared storage.
* If `A` has state, the result will [`std.algorithm.mutation.move`](std_algorithm_mutation#move) the supplied allocator `A a` within. The result itself is allocated in its own statically-typed allocator.


 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;

RCIAllocator a = allocatorObject(Mallocator.instance);
auto b = a.allocate(100);
writeln(b.length); // 100
assert(a.deallocate(b));

// The in-situ region must be used by pointer
import std.experimental.allocator.building_blocks.region : InSituRegion;
auto r = InSituRegion!1024();
a = allocatorObject(&r);
b = a.allocate(200);
writeln(b.length); // 200
// In-situ regions can deallocate the last allocation
assert(a.deallocate(b));

```
 
  nothrow RCISharedAllocator **sharedAllocatorObject**(A)(auto ref A a)  
 Constraints: if (!isPointer!A);   
  
RCISharedAllocator **sharedAllocatorObject**(A)(A\* pa);  
Returns a dynamically-typed `CSharedAllocator` built around a given statically- typed allocator `a` of type `A`. Passing a pointer to the allocator creates a dynamic allocator around the allocator pointed to by the pointer, without attempting to copy or move it. Passing the allocator by value or reference behaves as follows. 


* If `A` has no state, the resulting object is allocated in static shared storage.
* If `A` has state and is copyable, the result will [`std.algorithm.mutation.move`](std_algorithm_mutation#move) the supplied allocator `A a` within. The result itself is allocated in its own statically-typed allocator.
* If `A` has state and is not copyable, the result will move the passed-in argument into the result. The result itself is allocated in its own statically-typed allocator.


  class **CAllocatorImpl**(Allocator, Flag!"indirect" indirect = No.indirect): IAllocator;  
Implementation of `IAllocator` using `Allocator`. This adapts a statically-built allocator type to `IAllocator` that is directly usable by non-templated code. 


Usually `CAllocatorImpl` is used indirectly by calling [`theAllocator`](#theAllocator).

 
pure @nogc ref @safe Allocator **impl**();  
The implementation is available as a public member.

  pure @nogc @safe this(Allocator\* pa);  
The implementation is available as a public member.

  @property uint **alignment**();  
Returns `impl.alignment`.

  size\_t **goodAllocSize**(size\_t s);  
Returns `impl.goodAllocSize(s)`.

  void[] **allocate**(size\_t s, TypeInfo ti = null);  
Returns `impl.allocate(s)`.

  void[] **alignedAllocate**(size\_t s, uint a);  
If `impl.alignedAllocate` exists, calls it and returns the result. Otherwise, always returns `null`.

  Ternary **owns**(void[] b);  
If `Allocator` implements `owns`, forwards to it. Otherwise, returns `Ternary.unknown`.

  bool **expand**(ref void[] b, size\_t s);  
Returns `impl.expand(b, s)` if defined, `false` otherwise.

  bool **reallocate**(ref void[] b, size\_t s);  
Returns `impl.reallocate(b, s)`.

  bool **alignedReallocate**(ref void[] b, size\_t s, uint a);  
Forwards to `impl.alignedReallocate` if defined, `false` otherwise.

  bool **deallocate**(void[] b);  
If `impl.deallocate` is not defined, returns `false`. Otherwise it forwards the call.

  bool **deallocateAll**();  
Calls `impl.deallocateAll()` and returns the result if defined, otherwise returns `false`.

  Ternary **empty**();  
Forwards to `impl.empty()` if defined, otherwise returns `Ternary.unknown`.

  void[] **allocateAll**();  
Returns `impl.allocateAll()` if present, `null` otherwise.

    class **CSharedAllocatorImpl**(Allocator, Flag!"indirect" indirect = No.indirect): ISharedAllocator;  
Implementation of `ISharedAllocator` using `Allocator`. This adapts a statically-built, shareable across threads, allocator type to `ISharedAllocator` that is directly usable by non-templated code. 


Usually `CSharedAllocatorImpl` is used indirectly by calling [`processAllocator`](#processAllocator).

 
shared pure @nogc ref @safe Allocator **impl**();  
The implementation is available as a public member.

  shared pure @nogc @safe this(Allocator\* pa);  
The implementation is available as a public member.

  shared @property uint **alignment**();  
Returns `impl.alignment`.

  shared size\_t **goodAllocSize**(size\_t s);  
Returns `impl.goodAllocSize(s)`.

  shared void[] **allocate**(size\_t s, TypeInfo ti = null);  
Returns `impl.allocate(s)`.

  shared void[] **alignedAllocate**(size\_t s, uint a);  
If `impl.alignedAllocate` exists, calls it and returns the result. Otherwise, always returns `null`.

  shared Ternary **owns**(void[] b);  
If `Allocator` implements `owns`, forwards to it. Otherwise, returns `Ternary.unknown`.

  shared bool **expand**(ref void[] b, size\_t s);  
Returns `impl.expand(b, s)` if defined, `false` otherwise.

  shared bool **reallocate**(ref void[] b, size\_t s);  
Returns `impl.reallocate(b, s)`.

  shared bool **alignedReallocate**(ref void[] b, size\_t s, uint a);  
Forwards to `impl.alignedReallocate` if defined, `false` otherwise.

  shared bool **deallocate**(void[] b);  
If `impl.deallocate` is not defined, returns `false`. Otherwise it forwards the call.

  shared bool **deallocateAll**();  
Calls `impl.deallocateAll()` and returns the result if defined, otherwise returns `false`.

  shared Ternary **empty**();  
Forwards to `impl.empty()` if defined, otherwise returns `Ternary.unknown`.

  shared void[] **allocateAll**();  
Returns `impl.allocateAll()` if present, `null` otherwise.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator.html>

std.experimental.allocator.building\_blocks.bitmapped\_block
============================================================

 
Source
 [std/experimental/allocator/building\_blocks/bitmapped\_block.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/bitmapped_block.d)

 
struct **BitmappedBlock**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator, Flag!"multiblock" f = Yes.multiblock);  
`BitmappedBlock` implements a simple heap consisting of one contiguous area of memory organized in blocks, each of size `theBlockSize`. A block is a unit of allocation. A bitmap serves as bookkeeping data, more precisely one bit per block indicating whether that block is currently allocated or not. 


Passing `NullAllocator` as `ParentAllocator` (the default) means user code manages allocation of the memory block from the outside; in that case `BitmappedBlock` must be constructed with a `ubyte[]` preallocated block and has no responsibility regarding the lifetime of its support underlying storage. If another allocator type is passed, `BitmappedBlock` defines a destructor that uses the parent allocator to release the memory block. That makes the combination of `AllocatorList`, `BitmappedBlock`, and a back-end allocator such as `MmapAllocator` a simple and scalable solution for memory allocation.   
  
 There are advantages to storing bookkeeping data separated from the payload (as opposed to e.g. using `AffixAllocator` to store metadata together with each allocation). The layout is more compact (overhead is one bit per block), searching for a free block during allocation enjoys better cache locality, and deallocation does not touch memory around the payload being deallocated (which is often cold).   
  
 Allocation requests are handled on a first-fit basis. Although linear in complexity, allocation is in practice fast because of the compact bookkeeping representation, use of simple and fast bitwise routines, and caching of the first available block position. A known issue with this general approach is fragmentation, partially mitigated by coalescing. Since `BitmappedBlock` does not need to maintain the allocated size, freeing memory implicitly coalesces free blocks together. Also, tuning `blockSize` has a considerable impact on both internal and external fragmentation.   
  
 If the last template parameter is set to `No.multiblock`, the allocator will only serve allocations which require at most `theBlockSize`. The `BitmappedBlock` has a specialized implementation for single-block allocations which allows for greater performance, at the cost of not being able to allocate more than one block at a time.   
  
 The size of each block can be selected either during compilation or at run time. Statically-known block sizes are frequent in practice and yield slightly better performance. To choose a block size statically, pass it as the `blockSize` parameter as in `BitmappedBlock!(4096)`. To choose a block size parameter, use `BitmappedBlock!(chooseAtRuntime)` and pass the block size to the constructor. 

 
Parameters:


|  |  |
| --- | --- |
| theBlockSize | the length of a block, which must be a multiple of `theAlignment` |
| theAlignment | alignment of each block |
| ParentAllocator | allocator from which the `BitmappedBlock` will draw memory. If set to `NullAllocator`, the storage must be passed via the constructor |
| f | `Yes.multiblock` to support allocations spanning across multiple blocks and `No.multiblock` to support single block allocations. Although limited by single block allocations, `No.multiblock` will generally provide higher performance. |


 
Examples:


```
// Create a block allocator on top of a 10KB stack region.
import std.experimental.allocator.building_blocks.region : InSituRegion;
import std.traits : hasMember;
InSituRegion!(10_240, 64) r;
auto a = BitmappedBlock!(64, 64)(cast(ubyte[])(r.allocateAll()));
static assert(hasMember!(InSituRegion!(10_240, 64), "allocateAll"));
const b = a.allocate(100);
writeln(b.length); // 100

```
 
 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;
import std.typecons : Flag, Yes;

enum blockSize = 64;
enum numBlocks = 10;

// The 'BitmappedBlock' is implicitly instantiated with Yes.multiblock
auto a = BitmappedBlock!(blockSize, 8, Mallocator, Yes.multiblock)(numBlocks * blockSize);

// Instantiated with Yes.multiblock, can allocate more than one block at a time
void[] buf = a.allocate(2 * blockSize);
writeln(buf.length); // 2 * blockSize
assert(a.deallocate(buf));

// Can also allocate less than one block
buf = a.allocate(blockSize / 2);
writeln(buf.length); // blockSize / 2

// Expands inside the same block
assert(a.expand(buf, blockSize / 2));
writeln(buf.length); // blockSize

// If Yes.multiblock, can expand past the size of a single block
assert(a.expand(buf, 3 * blockSize));
writeln(buf.length); // 4 * blockSize
assert(a.deallocate(buf));

```
 
 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;
import std.typecons : Flag, No;

enum blockSize = 64;
auto a = BitmappedBlock!(blockSize, 8, Mallocator, No.multiblock)(1024 * blockSize);

// Since instantiated with No.multiblock, can only allocate at most the block size
void[] buf = a.allocate(blockSize + 1);
assert(buf is null);

buf = a.allocate(blockSize);
writeln(buf.length); // blockSize
assert(a.deallocate(buf));

// This is also fine, because it's less than the block size
buf = a.allocate(blockSize / 2);
writeln(buf.length); // blockSize / 2

// Can expand the buffer until its length is at most 64
assert(a.expand(buf, blockSize / 2));
writeln(buf.length); // blockSize

// Cannot expand anymore
assert(!a.expand(buf, 1));
assert(a.deallocate(buf));

```
 
 
this(ubyte[] data);   
  
this(ubyte[] data, uint blockSize);   
  
this(size\_t capacity);   
  
this(ParentAllocator parent, size\_t capacity);   
  
this(size\_t capacity, uint blockSize);   
  
this(ParentAllocator parent, size\_t capacity, uint blockSize);  
Constructs a block allocator given a hunk of memory, or a desired capacity in bytes. * If `ParentAllocator` is [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), only the constructor taking `data` is defined and the user is responsible for freeing `data` if desired.
* Otherwise, both constructors are defined. The `data`-based constructor assumes memory has been allocated with the parent allocator. The `capacity`-based constructor uses `ParentAllocator` to allocate an appropriate contiguous hunk of memory. Regardless of the constructor used, the destructor releases the memory by using `ParentAllocator.deallocate`.


  alias **blockSize** = theBlockSize;  
If `blockSize == chooseAtRuntime`, `BitmappedBlock` offers a read/write property `blockSize`. It must be set before any use of the allocator. Otherwise (i.e. `theBlockSize` is a legit constant), `blockSize` is an alias for `theBlockSize`. Whether constant or variable, must also be a multiple of `alignment`. This constraint is `assert`ed statically and dynamically.

  alias **alignment** = theAlignment;  
The alignment offered is user-configurable statically through parameter `theAlignment`, defaulted to `platformAlignment`.

  ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Returns the actual bytes allocated when `n` bytes are requested, i.e. `n.roundUpToMultipleOf(blockSize)`.

  const pure nothrow @nogc @trusted Ternary **owns**(const void[] b);  
Returns `Ternary.yes` if `b` belongs to the `BitmappedBlock` object, `Ternary.no` otherwise. Never returns `Ternary.unkown`. (This method is somewhat tolerant in that accepts an interior slice.)

  pure nothrow @nogc @trusted bool **expand**(ref void[] b, immutable size\_t delta);  
Expands in place a buffer previously allocated by `BitmappedBlock`. If instantiated with `No.multiblock`, the expansion fails if the new length exceeds `theBlockSize`.

  nothrow @nogc bool **deallocate**(void[] b);  
Deallocates a block previously allocated with this allocator.

  pure nothrow @nogc @trusted void[] **allocate**(const size\_t s);  
Allocates `s` bytes of memory and returns it, or `null` if memory could not be allocated. 


The following information might be of help with choosing the appropriate block size. Actual allocation occurs in sizes multiple of the block size. Allocating one block is the fastest because only one 0 bit needs to be found in the metadata. Allocating 2 through 64 blocks is the next cheapest because it affects a maximum of two `ulong` in the metadata. Allocations greater than 64 blocks require a multiword search through the metadata.   
  
 If instantiated with `No.multiblock`, it performs a search for the first zero bit in the bitmap and sets it.

  @trusted void[] **allocateFresh**(const size\_t s);  
Allocates s bytes of memory and returns it, or `null` if memory could not be allocated. `allocateFresh` behaves just like allocate, the only difference being that this always returns unused(fresh) memory. Although there may still be available space in the `BitmappedBlock`, `allocateFresh` could still return null, because all the available blocks have been previously deallocated.

  void[] **allocateAll**();  
If the `BitmappedBlock` object is empty (has no active allocation), allocates all memory within and returns a slice to it. Otherwise, returns `null` (i.e. no attempt is made to allocate the largest available block).

  pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if no memory is currently allocated with this allocator, otherwise `Ternary.no`. This method never returns `Ternary.unknown`.

  pure nothrow @nogc bool **deallocateAll**();  
Forcibly deallocates all memory allocated by this allocator, making it available for further allocations. Does not return memory to `ParentAllocator`.

  @system bool **alignedReallocate**(ref void[] b, size\_t newSize, uint a);  
Reallocates a block previously allocated with `alignedAllocate`. Contractions do not occur in place.

  @system bool **reallocate**(ref void[] b, size\_t newSize);  
Reallocates a previously-allocated block. Contractions occur in place.

  void[] **alignedAllocate**(size\_t n, uint a);  
Allocates a block with specified alignment `a`. The alignment must be a power of 2. If `a <= alignment`, function forwards to `allocate`. Otherwise, it attempts to overallocate and then adjust the result for proper alignment. In the worst case the slack memory is around two blocks.

    struct **SharedBitmappedBlock**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator, Flag!"multiblock" f = Yes.multiblock);  
The threadsafe version of the [`BitmappedBlock`](#BitmappedBlock). The semantics of the `SharedBitmappedBlock` are identical to the regular [`BitmappedBlock`](#BitmappedBlock). 



Parameters:


|  |  |
| --- | --- |
| theBlockSize | the length of a block, which must be a multiple of `theAlignment` |
| theAlignment | alignment of each block |
| ParentAllocator | allocator from which the `BitmappedBlock` will draw memory. If set to `NullAllocator`, the storage must be passed via the constructor |
| f | `Yes.multiblock` to support allocations spanning across multiple blocks and `No.multiblock` to support single block allocations. Although limited by single block allocations, `No.multiblock` will generally provide higher performance. |


 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;
import std.experimental.allocator.common : platformAlignment;
import std.typecons : Flag, Yes, No;

// Create 'numThreads' threads, each allocating in parallel a chunk of memory
static void testAlloc(Allocator)(ref Allocator a, size_t allocSize)
{
    import core.thread : ThreadGroup;
    import std.algorithm.sorting : sort;
    import core.internal.spinlock : SpinLock;

    SpinLock lock = SpinLock(SpinLock.Contention.brief);
    enum numThreads = 10;
    void[][numThreads] buf;
    size_t count = 0;

    // Each threads allocates 'allocSize'
    void fun()
    {
        void[] b = a.allocate(allocSize);
        writeln(b.length); // allocSize

        lock.lock();
        scope(exit) lock.unlock();

        buf[count] = b;
        count++;
    }

    auto tg = new ThreadGroup;
    foreach (i; 0 .. numThreads)
    {
        tg.create(&fun);
    }
    tg.joinAll();

    // Sorting the allocations made by each thread, we expect the buffers to be
    // adjacent inside the SharedBitmappedBlock
    sort!((a, b) => a.ptr < b.ptr)(buf[0 .. numThreads]);
    foreach (i; 0 .. numThreads - 1)
    {
        assert(buf[i].ptr + a.goodAllocSize(buf[i].length) <= buf[i + 1].ptr);
    }

    // Deallocate everything
    foreach (i; 0 .. numThreads)
    {
        assert(a.deallocate(buf[i]));
    }
}

enum blockSize = 64;
auto alloc1 = SharedBitmappedBlock!(blockSize, platformAlignment, Mallocator, Yes.multiblock)(1024 * 1024);
auto alloc2 = SharedBitmappedBlock!(blockSize, platformAlignment, Mallocator, No.multiblock)(1024 * 1024);
testAlloc(alloc1, 2 * blockSize);
testAlloc(alloc2, blockSize);

```
 
 
this(ubyte[] data);   
  
this(ubyte[] data, uint blockSize);   
  
this(size\_t capacity);   
  
this(ParentAllocator parent, size\_t capacity);   
  
this(size\_t capacity, uint blockSize);   
  
this(ParentAllocator parent, size\_t capacity, uint blockSize);  
Constructs a block allocator given a hunk of memory, or a desired capacity in bytes. * If `ParentAllocator` is [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), only the constructor taking `data` is defined and the user is responsible for freeing `data` if desired.
* Otherwise, both constructors are defined. The `data`-based constructor assumes memory has been allocated with the parent allocator. The `capacity`-based constructor uses `ParentAllocator` to allocate an appropriate contiguous hunk of memory. Regardless of the constructor used, the destructor releases the memory by using `ParentAllocator.deallocate`.


  alias **blockSize** = theBlockSize;  
If `blockSize == chooseAtRuntime`, `SharedBitmappedBlock` offers a read/write property `blockSize`. It must be set before any use of the allocator. Otherwise (i.e. `theBlockSize` is a legit constant), `blockSize` is an alias for `theBlockSize`. Whether constant or variable, must also be a multiple of `alignment`. This constraint is `assert`ed statically and dynamically.

  alias **alignment** = theAlignment;  
The alignment offered is user-configurable statically through parameter `theAlignment`, defaulted to `platformAlignment`.

  ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Returns the actual bytes allocated when `n` bytes are requested, i.e. `n.roundUpToMultipleOf(blockSize)`.

  const pure nothrow @nogc @trusted Ternary **owns**(const void[] b);  
Returns `Ternary.yes` if `b` belongs to the `SharedBitmappedBlock` object, `Ternary.no` otherwise. Never returns `Ternary.unkown`. (This method is somewhat tolerant in that accepts an interior slice.)

  bool **expand**(ref void[] b, immutable size\_t delta);  
Expands in place a buffer previously allocated by `SharedBitmappedBlock`. Expansion fails if the new length exceeds the block size.

  nothrow @nogc bool **deallocate**(void[] b);  
Deallocates the given buffer `b`, by atomically setting the corresponding bit to `0`. `b` must be valid, and cannot contain multiple adjacent `blocks`.

  nothrow @nogc @trusted void[] **allocate**(const size\_t s);  
Allocates `s` bytes of memory and returns it, or `null` if memory could not be allocated. 


The `SharedBitmappedBlock` cannot allocate more than the given block size. Allocations are satisfied by searching the first unset bit in the bitmap, and atomically setting it. In rare memory pressure scenarios, the allocation could fail.

  @trusted void[] **allocateFresh**(const size\_t s);  
Allocates s bytes of memory and returns it, or `null` if memory could not be allocated. `allocateFresh` behaves just like allocate, the only difference being that this always returns unused(fresh) memory. Although there may still be available space in the `SharedBitmappedBlock`, `allocateFresh` could still return null, because all the available blocks have been previously deallocated.

  void[] **allocateAll**();  
If the `SharedBitmappedBlock` object is empty (has no active allocation), allocates all memory within and returns a slice to it. Otherwise, returns `null` (i.e. no attempt is made to allocate the largest available block).

  nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if no memory is currently allocated with this allocator, otherwise `Ternary.no`. This method never returns `Ternary.unknown`.

  nothrow @nogc bool **deallocateAll**();  
Forcibly deallocates all memory allocated by this allocator, making it available for further allocations. Does not return memory to `ParentAllocator`.

  @system bool **alignedReallocate**(ref void[] b, size\_t newSize, uint a);  
Reallocates a block previously allocated with `alignedAllocate`. Contractions do not occur in place.

  @system bool **reallocate**(ref void[] b, size\_t newSize);  
Reallocates a previously-allocated block. Contractions occur in place.

  void[] **alignedAllocate**(size\_t n, uint a);  
Allocates a block with specified alignment `a`. The alignment must be a power of 2. If `a <= alignment`, function forwards to `allocate`. Otherwise, it attempts to overallocate and then adjust the result for proper alignment. In the worst case the slack memory is around two blocks.

    struct **BitmappedBlockWithInternalPointers**(size\_t theBlockSize, uint theAlignment = platformAlignment, ParentAllocator = NullAllocator);  
A `BitmappedBlock` with additional structure for supporting `resolveInternalPointer`. To that end, `BitmappedBlockWithInternalPointers` adds a bitmap (one bit per block) that marks object starts. The bitmap itself has variable size and is allocated together with regular allocations. 


The time complexity of `resolveInternalPointer` is Ο(`k`), where `k` is the size of the object within which the internal pointer is looked up.

 
this(ubyte[] data);   
  
this(size\_t capacity);   
  
this(ParentAllocator parent, size\_t capacity);  
Constructors accepting desired capacity or a preallocated buffer, similar in semantics to those of `BitmappedBlock`.

  alias **alignment** = theAlignment;   
  
pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);   
  
void[] **allocate**(size\_t bytes);   
  
void[] **allocateAll**();   
  
bool **expand**(ref void[] b, size\_t bytes);   
  
bool **deallocate**(void[] b);   
  
nothrow @nogc @safe Ternary **resolveInternalPointer**(const void\* p, ref void[] result);   
  
Ternary **empty**();  
Allocator primitives.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_bitmapped_block.html>

std.experimental.allocator.building\_blocks.fallback\_allocator
===============================================================

 
Source
 [std/experimental/allocator/building\_blocks/fallback\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/fallback_allocator.d)

 
struct **FallbackAllocator**(Primary, Fallback);  
`FallbackAllocator` is the allocator equivalent of an "or" operator in algebra. An allocation request is first attempted with the `Primary` allocator. If that returns `null`, the request is forwarded to the `Fallback` allocator. All other requests are dispatched appropriately to one of the two allocators. 


In order to work, `FallbackAllocator` requires that `Primary` defines the `owns` method. This is needed in order to decide which allocator was responsible for a given allocation.   
  
 `FallbackAllocator` is useful for fast, special-purpose allocators backed up by general-purpose allocators. The example below features a stack region backed up by the `GCAllocator`.

 
Primary **primary**;  
The primary allocator.

  Fallback **fallback**;  
The fallback allocator.

  static FallbackAllocator **instance**;  
If both `Primary` and `Fallback` are stateless, `FallbackAllocator` defines a static instance called `instance`.

  enum uint **alignment**;  
The alignment offered is the minimum of the two allocators' alignment.

  void[] **allocate**(size\_t s);  
Allocates memory trying the primary allocator first. If it returns  `null`, the fallback allocator is tried.

  void[] **alignedAllocate**(size\_t s, uint a);  
`FallbackAllocator` offers `alignedAllocate` iff at least one of the allocators also offers it. It attempts to allocate using either or both.

  bool **expand**(ref void[] b, size\_t delta);  
`expand` is defined if and only if at least one of the allocators defines `expand`. It works as follows. If `primary.owns(b)`, then the request is forwarded to `primary.expand` if it is defined, or fails (returning `false`) otherwise. If `primary` does not own `b`, then the request is forwarded to `fallback.expand` if it is defined, or fails (returning `false`) otherwise. 

  bool **reallocate**(ref void[] b, size\_t newSize);  
`reallocate` works as follows. If `primary.owns(b)`, then  `primary.reallocate(b, newSize)` is attempted. If it fails, an attempt is made to move the allocation from `primary` to `fallback`. 


If `primary` does not own `b`, then `fallback.reallocate(b, newSize)` is attempted. If that fails, an attempt is made to move the allocation from `fallback` to `primary`.

  Ternary **owns**(void[] b);  
`owns` is defined if and only if both allocators define `owns`. Returns `primary.owns(b) | fallback.owns(b)`.

  Ternary **resolveInternalPointer**(const void\* p, ref void[] result);  
`resolveInternalPointer` is defined if and only if both allocators define it.

  bool **deallocate**(void[] b);  
`deallocate` is defined if and only if at least one of the allocators define `deallocate`. It works as follows. If `primary.owns(b)`, then the request is forwarded to `primary.deallocate` if it is defined, or is a no-op otherwise. If `primary` does not own `b`, then the request is forwarded to `fallback.deallocate` if it is defined, or is a no-op otherwise.

  Ternary **empty**();  
`empty` is defined if both allocators also define it. 



Returns:
`primary.empty & fallback.empty`
    FallbackAllocator!(Primary, Fallback) **fallbackAllocator**(Primary, Fallback)(auto ref Primary p, auto ref Fallback f);  
Convenience function that uses type deduction to return the appropriate `FallbackAllocator` instance. To initialize with allocators that don't have state, use their `it` static member.



Examples:


```
import std.experimental.allocator.building_blocks.region : Region;
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.typecons : Ternary;
auto a = fallbackAllocator(Region!GCAllocator(1024), GCAllocator.instance);
auto b1 = a.allocate(1020);
writeln(b1.length); // 1020
writeln(a.primary.owns(b1)); // Ternary.yes
auto b2 = a.allocate(10);
writeln(b2.length); // 10
writeln(a.primary.owns(b2)); // Ternary.no

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_fallback_allocator.html>

std.datetime.interval
=====================

  

| Category | Functions |
| --- | --- |
| Main types | [`Interval`](#Interval) [`Direction`](#Direction) |
| Special intervals | [`everyDayOfWeek`](#everyDayOfWeek) [`everyMonth`](#everyMonth) [`everyDuration`](#everyDuration) |
| Special intervals | [`NegInfInterval`](#NegInfInterval) [`PosInfInterval`](#PosInfInterval) |
| Underlying ranges | [`IntervalRange`](#IntervalRange) [`NegInfIntervalRange`](#NegInfIntervalRange) [`PosInfIntervalRange`](#PosInfIntervalRange) |
| Flags | [`PopFirst`](#PopFirst) |

 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/datetime/interval.d](https://github.com/dlang/phobos/blob/master/std/datetime/interval.d)

 
enum **Direction**: int;  
Indicates a direction in time. One example of its use is [`Interval`](#Interval)'s [`expand`](#expand) function which uses it to indicate whether the interval should be expanded backwards (into the past), forwards (into the future), or both.

 
**bwd** 
Backward.

  **fwd** 
Forward.

  **both** 
Both backward and forward.

    alias **PopFirst** = std.typecons.Flag!"popFirst".Flag;  
Used to indicate whether `popFront` should be called immediately upon creating a range. The idea is that for some functions used to generate a range for an interval, `front` is not necessarily a time point which would ever be generated by the range (e.g. if the range were every Sunday within an interval, but the interval started on a Monday), so there needs to be a way to deal with that. To get the first time point in the range to match what the function generates, then use `PopFirst.yes` to indicate that the range should have `popFront` called on it before the range is returned so that `front` is a time point which the function would generate. To let the first time point not match the generator function, use `PopFront.no`. 


For instance, if the function used to generate a range of time points generated successive Easters (i.e. you're iterating over all of the Easters within the interval), the initial date probably isn't an Easter. Using `PopFirst.yes` would tell the function which returned the range that `popFront` was to be called so that front would then be an Easter - the next one generated by the function (which when iterating forward would be the Easter following the original `front`, while when iterating backward, it would be the Easter prior to the original `front`). If `PopFirst.no` were used, then `front` would remain the original time point and it would not necessarily be a time point which would be generated by the range-generating function (which in many cases is exactly what is desired - e.g. if iterating over every day starting at the beginning of the interval).   
  
 If set to `PopFirst.no`, then popFront is not called before returning the range.   
  
 Otherwise, if set to `PopFirst.yes`, then popFront is called before returning the range.

  struct **Interval**(TP);  
Represents an interval of time. 


An `Interval` has a starting point and an end point. The interval of time is therefore the time starting at the starting point up to, but not including, the end point. e.g.   
  
 

|  |
| --- |
| [January 5th, 2010 - March 10th, 2010) |
| [05:00:30 - 12:00:00) |
| [1982-01-04T08:59:00 - 2010-07-04T12:00:00) |

   
  
 A range can be obtained from an `Interval`, allowing iteration over that interval, with the exact time points which are iterated over depending on the function which generates the range.

 
pure this(U)(scope const TP begin, scope const U end)  
 Constraints: if (is(immutable(TP) == immutable(U))); 
 

Parameters:


|  |  |
| --- | --- |
| TP `begin` | The time point which begins the interval. |
| U `end` | The time point which ends (but is not included in) the interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if end is before begin. 
 
Example


```
Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));

```
  pure this(D)(scope const TP begin, scope const D duration)  
 Constraints: if (\_\_traits(compiles, begin + duration)); 
 

Parameters:


|  |  |
| --- | --- |
| TP `begin` | The time point which begins the interval. |
| D `duration` | The duration from the starting point to the end point. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the resulting `end` is before `begin`. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), dur!"days"(3)) ==
       Interval!Date(Date(1996, 1, 2), Date(1996, 1, 5)));

```
  pure nothrow ref Interval **opAssign**(ref const Interval rhs);  

Parameters:


|  |  |
| --- | --- |
| Interval `rhs` | The [`Interval`](#Interval) to assign to this one. |


  pure nothrow ref Interval **opAssign**(Interval rhs);  

Parameters:


|  |  |
| --- | --- |
| Interval `rhs` | The [`Interval`](#Interval) to assign to this one. |


  const pure nothrow @property TP **begin**();  
The starting point of the interval. It is included in the interval. 



Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).begin ==
       Date(1996, 1, 2));

```
  pure @property void **begin**(TP timePoint);  
The starting point of the interval. It is included in the interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to set `begin` to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the resulting interval would be invalid.
  const pure nothrow @property TP **end**();  
The end point of the interval. It is excluded from the interval. 



Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).end ==
       Date(2012, 3, 1));

```
  pure @property void **end**(TP timePoint);  
The end point of the interval. It is excluded from the interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to set end to. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the resulting interval would be invalid.
  const pure nothrow @property auto **length**();  
Returns the duration between `begin` and `end`. 



Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).length ==
       dur!"days"(5903));

```
  const pure nothrow @property bool **empty**();  
Whether the interval's length is 0, that is, whether `begin == end`. 



Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(1996, 1, 2)).empty);
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).empty);

```
  const pure bool **contains**(scope const TP timePoint);  
Whether the given time point is within this interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Date(1994, 12, 24)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Date(2000, 1, 5)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Date(2012, 3, 1)));

```
  const pure bool **contains**(scope const Interval interval);  
Whether the given interval is completely within this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));

```
  const pure bool **contains**(scope const PosInfInterval!TP interval);  
Whether the given interval is completely within this interval. 


Always returns false (unless this interval is empty), because an interval going to positive infinity can never be contained in a finite interval. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            PosInfInterval!Date(Date(1999, 5, 4))));

```
  const pure bool **contains**(scope const NegInfInterval!TP interval);  
Whether the given interval is completely within this interval. 


Always returns false (unless this interval is empty), because an interval beginning at negative infinity can never be contained in a finite interval. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
            NegInfInterval!Date(Date(1996, 5, 4))));

```
  const pure bool **isBefore**(scope const TP timePoint);  
Whether this interval is before the given time point. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is before it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Date(1994, 12, 24)));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Date(2000, 1, 5)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Date(2012, 3, 1)));

```
  const pure bool **isBefore**(scope const Interval interval);  
Whether this interval is before the given interval and does not intersect with it. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to check for against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(2012, 3, 1), Date(2013, 5, 1))));

```
  const pure bool **isBefore**(scope const PosInfInterval!TP interval);  
Whether this interval is before the given interval and does not intersect with it. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            PosInfInterval!Date(Date(2013, 3, 7))));

```
  const pure bool **isBefore**(scope const NegInfInterval!TP interval);  
Whether this interval is before the given interval and does not intersect with it. 


Always returns false (unless this interval is empty) because a finite interval can never be before an interval beginning at negative infinity. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
            NegInfInterval!Date(Date(1996, 5, 4))));

```
  const pure bool **isAfter**(scope const TP timePoint);  
Whether this interval is after the given time point. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is after it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Date(1994, 12, 24)));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Date(2000, 1, 5)));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Date(2012, 3, 1)));

```
  const pure bool **isAfter**(scope const Interval interval);  
Whether this interval is after the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to check against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));

```
  const pure bool **isAfter**(scope const PosInfInterval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 


Always returns false (unless this interval is empty) because a finite interval can never be after an interval going to positive infinity. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            PosInfInterval!Date(Date(1999, 5, 4))));

```
  const pure bool **isAfter**(scope const NegInfInterval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
            NegInfInterval!Date(Date(1996, 1, 2))));

```
  const pure bool **intersects**(scope const Interval interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to check for intersection with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));

```
  const pure bool **intersects**(scope const PosInfInterval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for intersection with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure bool **intersects**(scope const NegInfInterval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for intersection with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            NegInfInterval!Date(Date(1996, 1, 2))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
            NegInfInterval!Date(Date(2000, 1, 2))));

```
  const Interval **intersection**(scope const Interval interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect or if either interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
       Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));

```
  const Interval **intersection**(scope const PosInfInterval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect or if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            PosInfInterval!Date(Date(1999, 1, 12))) ==
       Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));

```
  const Interval **intersection**(scope const NegInfInterval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect or if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            NegInfInterval!Date(Date(1999, 7, 6))) ==
       Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));

```
  const pure bool **isAdjacent**(scope const Interval interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to check whether its adjecent to this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(1990, 7, 6), Date(1996, 1, 2))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(2012, 3, 1), Date(2013, 9, 17))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(1989, 3, 1), Date(2012, 3, 1))));

```
  const pure bool **isAdjacent**(scope const PosInfInterval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure bool **isAdjacent**(scope const NegInfInterval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            NegInfInterval!Date(Date(1996, 1, 2))));

assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
            NegInfInterval!Date(Date(2000, 1, 2))));

```
  const Interval **merge**(scope const Interval interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to merge with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect and are not adjacent or if either interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));

```
  const PosInfInterval!TP **merge**(scope const PosInfInterval!TP interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to merge with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect and are not adjacent or if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            PosInfInterval!Date(Date(2012, 3, 1))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  const NegInfInterval!TP **merge**(scope const NegInfInterval!TP interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to merge with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect and are not adjacent or if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            NegInfInterval!Date(Date(1996, 1, 2))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       NegInfInterval!Date(Date(2013, 1 , 12)));

```
  const pure Interval **span**(scope const Interval interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| Interval `interval` | The interval to create a span together with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if either interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            Interval!Date(Date(1990, 7, 6), Date(1991, 1, 8))) ==
       Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));

```
  const pure PosInfInterval!TP **span**(scope const PosInfInterval!TP interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to create a span together with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            PosInfInterval!Date(Date(2050, 1, 1))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  const pure NegInfInterval!TP **span**(scope const NegInfInterval!TP interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to create a span together with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Example


```
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            NegInfInterval!Date(Date(1602, 5, 21))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       NegInfInterval!Date(Date(2013, 1 , 12)));

```
  pure void **shift**(D)(D duration)  
 Constraints: if (\_\_traits(compiles, begin + duration)); 
 
Shifts the interval forward or backwards in time by the given duration (a positive duration shifts the interval forward; a negative duration shifts it backward). Effectively, it does `begin += duration` and `end += duration`. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to shift the interval by. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));

interval1.shift(dur!"days"(50));
assert(interval1 == Interval!Date(Date(1996, 2, 21), Date(2012, 5, 25)));

interval2.shift(dur!"days"(-50));
assert(interval2 == Interval!Date(Date(1995, 11, 13), Date(2012, 2, 15)));

```
  void **shift**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (isIntegral!T); 
 
Shifts the interval forward or backwards in time by the given number of years and/or months (a positive number of years and months shifts the interval forward; a negative number shifts it backward). It adds the years the given years and months to both begin and end. It effectively calls `add!"years"()` and then `add!"months"()` on begin and end with the given number of years and months. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to shift the interval by. |
| T `months` | The number of months to shift the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `begin` and `end`, causing their month to increment. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));

interval1.shift(2);
assert(interval1 == Interval!Date(Date(1998, 1, 2), Date(2014, 3, 1)));

interval2.shift(-2);
assert(interval2 == Interval!Date(Date(1994, 1, 2), Date(2010, 3, 1)));

```
  pure void **expand**(D)(D duration, Direction dir = Direction.both)  
 Constraints: if (\_\_traits(compiles, begin + duration)); 
 
Expands the interval forwards and/or backwards in time. Effectively, it does `begin -= duration` and/or `end += duration`. Whether it expands forwards and/or backwards in time is determined by dir. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to expand the interval by. |
| Direction `dir` | The direction in time to expand the interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));

interval1.expand(2);
assert(interval1 == Interval!Date(Date(1994, 1, 2), Date(2014, 3, 1)));

interval2.expand(-2);
assert(interval2 == Interval!Date(Date(1998, 1, 2), Date(2010, 3, 1)));

```
  void **expand**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes, Direction dir = Direction.both)  
 Constraints: if (isIntegral!T); 
 
Expands the interval forwards and/or backwards in time. Effectively, it subtracts the given number of months/years from `begin` and adds them to `end`. Whether it expands forwards and/or backwards in time is determined by dir. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to expand the interval by. |
| T `months` | The number of months to expand the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `begin` and `end`, causing their month to increment. |
| Direction `dir` | The direction in time to expand the interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));

interval1.expand(2);
assert(interval1 == Interval!Date(Date(1994, 1, 2), Date(2014, 3, 1)));

interval2.expand(-2);
assert(interval2 == Interval!Date(Date(1998, 1, 2), Date(2010, 3, 1)));

```
  const IntervalRange!(TP, Direction.fwd) **fwdRange**(TP delegate(scope const TP) func, PopFirst popFirst = PopFirst.no);  
Returns a range which iterates forward over the interval, starting at `begin`, using func to generate each successive time point. 


The range's `front` is the interval's `begin`. func is used to generate the next `front` when `popFront` is called. If popFirst is `PopFirst.yes`, then `popFront` is called before the range is returned (so that `front` is a time point which func would generate).   
  
 If func ever generates a time point less than or equal to the current `front` of the range, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. The range will be empty and iteration complete when func generates a time point equal to or beyond the `end` of the interval.   
  
 There are helper functions in this module which generate common delegates to pass to `fwdRange`. Their documentation starts with "Range-generating function," making them easily searchable. 

 
Parameters:


|  |  |
| --- | --- |
| TP delegate(scope const TP) `func` | The function used to generate the time points of the range over the interval. |
| PopFirst `popFirst` | Whether `popFront` should be called on the range before returning it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Warning
 func must be logically pure. Ideally, func would be a function pointer to a pure function, but forcing func to be pure is far too restrictive to be useful, and in order to have the ease of use of having functions which generate functions to pass to `fwdRange`, func must be a delegate. 
 If func retains state which changes as it is called, then some algorithms will not work correctly, because the range's `save` will have failed to have really saved the range's state. To avoid such bugs, don't pass a delegate which is not logically pure to `fwdRange`. If func is given the same time point with two different calls, it must return the same result both times. Of course, none of the functions in this module have this problem, so it's only relevant if when creating a custom delegate. 
Example


```
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = delegate (scope const Date date) // For iterating over even-numbered days.
            {
                if ((date.day & 1) == 0)
                    return date + dur!"days"(2);

                return date + dur!"days"(1);
            };
auto range = interval.fwdRange(func);

// An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
assert(range.front == Date(2010, 9, 1));

range.popFront();
assert(range.front == Date(2010, 9, 2));

range.popFront();
assert(range.front == Date(2010, 9, 4));

range.popFront();
assert(range.front == Date(2010, 9, 6));

range.popFront();
assert(range.front == Date(2010, 9, 8));

range.popFront();
assert(range.empty);

```
  const IntervalRange!(TP, Direction.bwd) **bwdRange**(TP delegate(scope const TP) func, PopFirst popFirst = PopFirst.no);  
Returns a range which iterates backwards over the interval, starting at `end`, using func to generate each successive time point. 


The range's `front` is the interval's `end`. func is used to generate the next `front` when `popFront` is called. If popFirst is `PopFirst.yes`, then `popFront` is called before the range is returned (so that `front` is a time point which func would generate).   
  
 If func ever generates a time point greater than or equal to the current `front` of the range, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. The range will be empty and iteration complete when func generates a time point equal to or less than the `begin` of the interval.   
  
 There are helper functions in this module which generate common delegates to pass to `bwdRange`. Their documentation starts with "Range-generating function," making them easily searchable. 

 
Parameters:


|  |  |
| --- | --- |
| TP delegate(scope const TP) `func` | The function used to generate the time points of the range over the interval. |
| PopFirst `popFirst` | Whether `popFront` should be called on the range before returning it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Warning
 func must be logically pure. Ideally, func would be a function pointer to a pure function, but forcing func to be pure is far too restrictive to be useful, and in order to have the ease of use of having functions which generate functions to pass to `fwdRange`, func must be a delegate. 
 If func retains state which changes as it is called, then some algorithms will not work correctly, because the range's `save` will have failed to have really saved the range's state. To avoid such bugs, don't pass a delegate which is not logically pure to `fwdRange`. If func is given the same time point with two different calls, it must return the same result both times. Of course, none of the functions in this module have this problem, so it's only relevant for custom delegates. 
Example


```
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = delegate (scope const Date date) // For iterating over even-numbered days.
            {
                if ((date.day & 1) == 0)
                    return date - dur!"days"(2);

                return date - dur!"days"(1);
            };
auto range = interval.bwdRange(func);

// An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).
assert(range.front == Date(2010, 9, 9));

range.popFront();
assert(range.front == Date(2010, 9, 8));

range.popFront();
assert(range.front == Date(2010, 9, 6));

range.popFront();
assert(range.front == Date(2010, 9, 4));

range.popFront();
assert(range.front == Date(2010, 9, 2));

range.popFront();
assert(range.empty);

```
  const nothrow @safe string **toString**();   
  
const void **toString**(Writer)(ref Writer w)  
 Constraints: if (isOutputRange!(Writer, char)); 
 
Converts this interval to a string. 



Parameters:


|  |  |
| --- | --- |
| Writer `w` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
    struct **PosInfInterval**(TP);  
Represents an interval of time which has positive infinity as its end point. 


Any ranges which iterate over a `PosInfInterval` are infinite. So, the main purpose of using `PosInfInterval` is to create an infinite range which starts at a fixed point in time and goes to positive infinity.

 
pure nothrow this(scope const TP begin);  

Parameters:


|  |  |
| --- | --- |
| TP `begin` | The time point which begins the interval. |


 
Example


```
auto interval = PosInfInterval!Date(Date(1996, 1, 2));

```
  pure nothrow ref PosInfInterval **opAssign**(ref const PosInfInterval rhs);  

Parameters:


|  |  |
| --- | --- |
| PosInfInterval `rhs` | The `PosInfInterval` to assign to this one. |


  pure nothrow ref PosInfInterval **opAssign**(PosInfInterval rhs);  

Parameters:


|  |  |
| --- | --- |
| PosInfInterval `rhs` | The `PosInfInterval` to assign to this one. |


  const pure nothrow @property TP **begin**();  
The starting point of the interval. It is included in the interval. 



Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).begin == Date(1996, 1, 2));

```
  pure nothrow @property void **begin**(TP timePoint);  
The starting point of the interval. It is included in the interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to set `begin` to. |


  enum bool **empty**;  
Whether the interval's length is 0. Always returns false. 



Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).empty);

```
  const pure nothrow bool **contains**(TP timePoint);  
Whether the given time point is within this interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check for inclusion in this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(1994, 12, 24)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(2000, 1, 5)));

```
  const pure bool **contains**(scope const Interval!TP interval);  
Whether the given interval is completely within this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
            Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));

```
  const pure nothrow bool **contains**(scope const PosInfInterval interval);  
Whether the given interval is completely within this interval. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to check for inclusion in this interval. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
            PosInfInterval!Date(Date(1995, 7, 2))));

```
  const pure nothrow bool **contains**(scope const NegInfInterval!TP interval);  
Whether the given interval is completely within this interval. 


Always returns false because an interval going to positive infinity can never contain an interval beginning at negative infinity. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for inclusion in this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
            NegInfInterval!Date(Date(1996, 5, 4))));

```
  const pure nothrow bool **isBefore**(scope const TP timePoint);  
Whether this interval is before the given time point. 


Always returns false because an interval going to positive infinity can never be before any time point. 

 
Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is before it. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(2000, 1, 5)));

```
  const pure bool **isBefore**(scope const Interval!TP interval);  
Whether this interval is before the given interval and does not intersect it. 


Always returns false (unless the given interval is empty) because an interval going to positive infinity can never be before any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

```
  const pure nothrow bool **isBefore**(scope const PosInfInterval interval);  
Whether this interval is before the given interval and does not intersect it. 


Always returns false because an interval going to positive infinity can never be before any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to check for against this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
            PosInfInterval!Date(Date(1992, 5, 4))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
            PosInfInterval!Date(Date(2013, 3, 7))));

```
  const pure nothrow bool **isBefore**(scope const NegInfInterval!TP interval);  
Whether this interval is before the given interval and does not intersect it. 


Always returns false because an interval going to positive infinity can never be before any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for against this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
            NegInfInterval!Date(Date(1996, 5, 4))));

```
  const pure nothrow bool **isAfter**(scope const TP timePoint);  
Whether this interval is after the given time point. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is after it. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(2000, 1, 5)));

```
  const pure bool **isAfter**(scope const Interval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));

```
  const pure nothrow bool **isAfter**(scope const PosInfInterval interval);  
Whether this interval is after the given interval and does not intersect it. 


Always returns false because an interval going to positive infinity can never be after another interval going to positive infinity. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to check against this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            PosInfInterval!Date(Date(1990, 1, 7))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            PosInfInterval!Date(Date(1999, 5, 4))));

```
  const pure nothrow bool **isAfter**(scope const NegInfInterval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check against this interval. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            NegInfInterval!Date(Date(1996, 1, 2))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
            NegInfInterval!Date(Date(2000, 7, 1))));

```
  const pure bool **intersects**(scope const Interval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for intersection with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));

```
  const pure nothrow bool **intersects**(scope const PosInfInterval interval);  
Whether the given interval overlaps this interval. 


Always returns true because two intervals going to positive infinity always overlap. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to check for intersection with this interval. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            PosInfInterval!Date(Date(1990, 1, 7))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            PosInfInterval!Date(Date(1999, 5, 4))));

```
  const pure nothrow bool **intersects**(scope const NegInfInterval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for intersection with this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            NegInfInterval!Date(Date(1996, 1, 2))));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
            NegInfInterval!Date(Date(2000, 7, 1))));

```
  const Interval!TP **intersection**(scope const Interval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect or if the given interval is empty. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
       Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));

```
  const pure nothrow PosInfInterval **intersection**(scope const PosInfInterval interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to intersect with this interval. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            PosInfInterval!Date(Date(1999, 1, 12))) ==
       PosInfInterval!Date(Date(1999, 1 , 12)));

```
  const Interval!TP **intersection**(scope const NegInfInterval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            NegInfInterval!Date(Date(1999, 7, 6))) ==
       Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       Interval!Date(Date(1996, 1 , 2), Date(2013, 1, 12)));

```
  const pure bool **isAdjacent**(scope const Interval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
            Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));

assert(!PosInfInterval!Date(Date(1999, 1, 12)).isAdjacent(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

```
  const pure nothrow bool **isAdjacent**(scope const PosInfInterval interval);  
Whether the given interval is adjacent to this interval. 


Always returns false because two intervals going to positive infinity can never be adjacent to one another. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to check whether its adjecent to this interval. |


 
Example


```
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
            PosInfInterval!Date(Date(1990, 1, 7))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
            PosInfInterval!Date(Date(1996, 1, 2))));

```
  const pure nothrow bool **isAdjacent**(scope const NegInfInterval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
            NegInfInterval!Date(Date(1996, 1, 2))));

assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
            NegInfInterval!Date(Date(2000, 7, 1))));

```
  const PosInfInterval **merge**(scope const Interval!TP interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to merge with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect and are not adjacent or if the given interval is empty. 
 
Note
 There is no overload for `merge` which takes a `NegInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  const pure nothrow PosInfInterval **merge**(scope const PosInfInterval interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to merge with this interval. |


 
Note
 There is no overload for `merge` which takes a `NegInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
            PosInfInterval!Date(Date(1999, 1, 12))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  const pure PosInfInterval **span**(scope const Interval!TP interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to create a span together with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Note
 There is no overload for `span` which takes a `NegInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
            Interval!Date(Date(500, 8, 9), Date(1602, 1, 31))) ==
       PosInfInterval!Date(Date(500, 8, 9)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  const pure nothrow PosInfInterval **span**(scope const PosInfInterval interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval `interval` | The interval to create a span together with this interval. |


 
Note
 There is no overload for `span` which takes a `NegInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       PosInfInterval!Date(Date(1990, 7 , 6)));

assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
            PosInfInterval!Date(Date(1999, 1, 12))) ==
       PosInfInterval!Date(Date(1996, 1 , 2)));

```
  pure nothrow void **shift**(D)(D duration)  
 Constraints: if (\_\_traits(compiles, begin + duration)); 
 
Shifts the `begin` of this interval forward or backwards in time by the given duration (a positive duration shifts the interval forward; a negative duration shifts it backward). Effectively, it does `begin += duration`. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to shift the interval by. |


 
Example


```
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));

interval1.shift(dur!"days"(50));
assert(interval1 == PosInfInterval!Date(Date(1996, 2, 21)));

interval2.shift(dur!"days"(-50));
assert(interval2 == PosInfInterval!Date(Date(1995, 11, 13)));

```
  void **shift**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (isIntegral!T); 
 
Shifts the `begin` of this interval forward or backwards in time by the given number of years and/or months (a positive number of years and months shifts the interval forward; a negative number shifts it backward). It adds the years the given years and months to `begin`. It effectively calls `add!"years"()` and then `add!"months"()` on `begin` with the given number of years and months. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to shift the interval by. |
| T `months` | The number of months to shift the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `begin`, causing its month to increment. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));

interval1.shift(dur!"days"(50));
assert(interval1 == PosInfInterval!Date(Date(1996, 2, 21)));

interval2.shift(dur!"days"(-50));
assert(interval2 == PosInfInterval!Date(Date(1995, 11, 13)));

```
  pure nothrow void **expand**(D)(D duration)  
 Constraints: if (\_\_traits(compiles, begin + duration)); 
 
Expands the interval backwards in time. Effectively, it does `begin -= duration`. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to expand the interval by. |


 
Example


```
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));

interval1.expand(dur!"days"(2));
assert(interval1 == PosInfInterval!Date(Date(1995, 12, 31)));

interval2.expand(dur!"days"(-2));
assert(interval2 == PosInfInterval!Date(Date(1996, 1, 4)));

```
  void **expand**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (isIntegral!T); 
 
Expands the interval forwards and/or backwards in time. Effectively, it subtracts the given number of months/years from `begin`. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to expand the interval by. |
| T `months` | The number of months to expand the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `begin`, causing its month to increment. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));

interval1.expand(2);
assert(interval1 == PosInfInterval!Date(Date(1994, 1, 2)));

interval2.expand(-2);
assert(interval2 == PosInfInterval!Date(Date(1998, 1, 2)));

```
  const PosInfIntervalRange!TP **fwdRange**(TP delegate(scope const TP) func, PopFirst popFirst = PopFirst.no);  
Returns a range which iterates forward over the interval, starting at `begin`, using func to generate each successive time point. 


The range's `front` is the interval's `begin`. func is used to generate the next `front` when `popFront` is called. If popFirst is `PopFirst.yes`, then `popFront` is called before the range is returned (so that `front` is a time point which func would generate).   
  
 If func ever generates a time point less than or equal to the current `front` of the range, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown.   
  
 There are helper functions in this module which generate common delegates to pass to `fwdRange`. Their documentation starts with "Range-generating function," to make them easily searchable. 

 
Parameters:


|  |  |
| --- | --- |
| TP delegate(scope const TP) `func` | The function used to generate the time points of the range over the interval. |
| PopFirst `popFirst` | Whether `popFront` should be called on the range before returning it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Warning
 func must be logically pure. Ideally, func would be a function pointer to a pure function, but forcing func to be pure is far too restrictive to be useful, and in order to have the ease of use of having functions which generate functions to pass to `fwdRange`, func must be a delegate. 
 If func retains state which changes as it is called, then some algorithms will not work correctly, because the range's `save` will have failed to have really saved the range's state. To avoid such bugs, don't pass a delegate which is not logically pure to `fwdRange`. If func is given the same time point with two different calls, it must return the same result both times. Of course, none of the functions in this module have this problem, so it's only relevant for custom delegates. 
Example


```
auto interval = PosInfInterval!Date(Date(2010, 9, 1));
auto func = delegate (scope const Date date) //For iterating over even-numbered days.
            {
                if ((date.day & 1) == 0)
                    return date + dur!"days"(2);

                return date + dur!"days"(1);
            };
auto range = interval.fwdRange(func);

//An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
assert(range.front == Date(2010, 9, 1));

range.popFront();
assert(range.front == Date(2010, 9, 2));

range.popFront();
assert(range.front == Date(2010, 9, 4));

range.popFront();
assert(range.front == Date(2010, 9, 6));

range.popFront();
assert(range.front == Date(2010, 9, 8));

range.popFront();
assert(!range.empty);

```
  const nothrow string **toString**();  
Converts this interval to a string.

    struct **NegInfInterval**(TP);  
Represents an interval of time which has negative infinity as its starting point. 


Any ranges which iterate over a `NegInfInterval` are infinite. So, the main purpose of using `NegInfInterval` is to create an infinite range which starts at negative infinity and goes to a fixed end point. Iterate over it in reverse.

 
pure nothrow this(scope const TP end);  

Parameters:


|  |  |
| --- | --- |
| TP `end` | The time point which ends the interval. |


 
Example


```
auto interval = PosInfInterval!Date(Date(1996, 1, 2));

```
  pure nothrow ref NegInfInterval **opAssign**(ref const NegInfInterval rhs);  

Parameters:


|  |  |
| --- | --- |
| NegInfInterval `rhs` | The `NegInfInterval` to assign to this one. |


  pure nothrow ref NegInfInterval **opAssign**(NegInfInterval rhs);  

Parameters:


|  |  |
| --- | --- |
| NegInfInterval `rhs` | The `NegInfInterval` to assign to this one. |


  const pure nothrow @property TP **end**();  
The end point of the interval. It is excluded from the interval. 



Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).end == Date(2012, 3, 1));

```
  pure nothrow @property void **end**(TP timePoint);  
The end point of the interval. It is excluded from the interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to set end to. |


  enum bool **empty**;  
Whether the interval's length is 0. Always returns false. 



Example


```
assert(!NegInfInterval!Date(Date(1996, 1, 2)).empty);

```
  const pure nothrow bool **contains**(TP timePoint);  
Whether the given time point is within this interval. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check for inclusion in this interval. |


 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(1994, 12, 24)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2012, 3, 1)));

```
  const pure bool **contains**(scope const Interval!TP interval);  
Whether the given interval is completely within this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for inclusion in this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
            Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));

```
  const pure nothrow bool **contains**(scope const PosInfInterval!TP interval);  
Whether the given interval is completely within this interval. 


Always returns false because an interval beginning at negative infinity can never contain an interval going to positive infinity. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for inclusion in this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
            PosInfInterval!Date(Date(1999, 5, 4))));

```
  const pure nothrow bool **contains**(scope const NegInfInterval interval);  
Whether the given interval is completely within this interval. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to check for inclusion in this interval. |


 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
            NegInfInterval!Date(Date(1996, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
            NegInfInterval!Date(Date(2013, 7, 9))));

```
  const pure nothrow bool **isBefore**(scope const TP timePoint);  
Whether this interval is before the given time point. 



Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is before it. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2000, 1, 5)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2012, 3, 1)));

```
  const pure bool **isBefore**(scope const Interval!TP interval);  
Whether this interval is before the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty 
 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));

```
  const pure nothrow bool **isBefore**(scope const PosInfInterval!TP interval);  
Whether this interval is before the given interval and does not intersect it. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for against this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure nothrow bool **isBefore**(scope const NegInfInterval interval);  
Whether this interval is before the given interval and does not intersect it. 


Always returns false because an interval beginning at negative infinity can never be before another interval beginning at negative infinity. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to check for against this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            NegInfInterval!Date(Date(1996, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
            NegInfInterval!Date(Date(2013, 7, 9))));

```
  const pure nothrow bool **isAfter**(scope const TP timePoint);  
Whether this interval is after the given time point. 


Always returns false because an interval beginning at negative infinity can never be after any time point. 

 
Parameters:


|  |  |
| --- | --- |
| TP `timePoint` | The time point to check whether this interval is after it. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2012, 3, 1)));

```
  const pure bool **isAfter**(scope const Interval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 


Always returns false (unless the given interval is empty) because an interval beginning at negative infinity can never be after any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check against this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));

```
  const pure nothrow bool **isAfter**(scope const PosInfInterval!TP interval);  
Whether this interval is after the given interval and does not intersect it. 


Always returns false because an interval beginning at negative infinity can never be after any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check against this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure nothrow bool **isAfter**(scope const NegInfInterval interval);  
Whether this interval is after the given interval and does not intersect it. 


Always returns false because an interval beginning at negative infinity can never be after any other interval. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to check against this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            NegInfInterval!Date(Date(1996, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
            NegInfInterval!Date(Date(2013, 7, 9))));

```
  const pure bool **intersects**(scope const Interval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check for intersection with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));

```
  const pure nothrow bool **intersects**(scope const PosInfInterval!TP interval);  
Whether the given interval overlaps this interval. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check for intersection with this interval. |


 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure nothrow bool **intersects**(scope const NegInfInterval!TP interval);  
Whether the given interval overlaps this interval. 


Always returns true because two intervals beginning at negative infinity always overlap. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval!TP `interval` | The interval to check for intersection with this interval. |


 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            NegInfInterval!Date(Date(1996, 5, 4))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
            NegInfInterval!Date(Date(2013, 7, 9))));

```
  const Interval!TP **intersection**(scope const Interval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect or if the given interval is empty. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       Interval!Date(Date(1990, 7 , 6), Date(2000, 8, 2)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
       Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));

```
  const Interval!TP **intersection**(scope const PosInfInterval!TP interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to intersect with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            PosInfInterval!Date(Date(1990, 7, 6))) ==
       Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            PosInfInterval!Date(Date(1999, 1, 12))) ==
       Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));

```
  const nothrow NegInfInterval **intersection**(scope const NegInfInterval interval);  
Returns the intersection of two intervals 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to intersect with this interval. |


 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            NegInfInterval!Date(Date(1999, 7, 6))) ==
       NegInfInterval!Date(Date(1999, 7 , 6)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

```
  const pure bool **isAdjacent**(scope const Interval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(1999, 1, 12), Date(2012, 3, 1))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(2012, 3, 1), Date(2019, 2, 2))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));

```
  const pure nothrow bool **isAdjacent**(scope const PosInfInterval!TP interval);  
Whether the given interval is adjacent to this interval. 



Parameters:


|  |  |
| --- | --- |
| PosInfInterval!TP `interval` | The interval to check whether its adjecent to this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            PosInfInterval!Date(Date(1999, 5, 4))));

assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            PosInfInterval!Date(Date(2012, 3, 1))));

```
  const pure nothrow bool **isAdjacent**(scope const NegInfInterval interval);  
Whether the given interval is adjacent to this interval. 


Always returns false because two intervals beginning at negative infinity can never be adjacent to one another. 

 
Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to check whether its adjecent to this interval. |


 
Example


```
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            NegInfInterval!Date(Date(1996, 5, 4))));

assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
            NegInfInterval!Date(Date(2012, 3, 1))));

```
  const NegInfInterval **merge**(scope const Interval!TP interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to merge with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the two intervals do not intersect and are not adjacent or if the given interval is empty. 
 
Note
 There is no overload for `merge` which takes a `PosInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
            Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
       NegInfInterval!Date(Date(2015, 9 , 2)));

```
  const pure nothrow NegInfInterval **merge**(scope const NegInfInterval interval);  
Returns the union of two intervals 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to merge with this interval. |


 
Note
 There is no overload for `merge` which takes a `PosInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
            NegInfInterval!Date(Date(1999, 7, 6))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       NegInfInterval!Date(Date(2013, 1 , 12)));

```
  const pure NegInfInterval **span**(scope const Interval!TP interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| Interval!TP `interval` | The interval to create a span together with this interval. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the given interval is empty. 
 
Note
 There is no overload for `span` which takes a `PosInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
            Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
            Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
       NegInfInterval!Date(Date(2015, 9 , 2)));

assert(NegInfInterval!Date(Date(1600, 1, 7)).span(
            Interval!Date(Date(2012, 3, 11), Date(2017, 7, 1))) ==
       NegInfInterval!Date(Date(2017, 7 , 1)));

```
  const pure nothrow NegInfInterval **span**(scope const NegInfInterval interval);  
Returns an interval that covers from the earliest time point of two intervals up to (but not including) the latest time point of two intervals. 



Parameters:


|  |  |
| --- | --- |
| NegInfInterval `interval` | The interval to create a span together with this interval. |


 
Note
 There is no overload for `span` which takes a `PosInfInterval`, because an interval going from negative infinity to positive infinity is not possible. 
 
Example


```
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
            NegInfInterval!Date(Date(1999, 7, 6))) ==
       NegInfInterval!Date(Date(2012, 3 , 1)));

assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
            NegInfInterval!Date(Date(2013, 1, 12))) ==
       NegInfInterval!Date(Date(2013, 1 , 12)));

```
  pure nothrow void **shift**(D)(D duration)  
 Constraints: if (\_\_traits(compiles, end + duration)); 
 
Shifts the `end` of this interval forward or backwards in time by the given duration (a positive duration shifts the interval forward; a negative duration shifts it backward). Effectively, it does `end += duration`. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to shift the interval by. |


 
Example


```
auto interval1 = NegInfInterval!Date(Date(2012, 4, 5));
auto interval2 = NegInfInterval!Date(Date(2012, 4, 5));

interval1.shift(dur!"days"(50));
assert(interval1 == NegInfInterval!Date(Date(2012, 5, 25)));

interval2.shift(dur!"days"(-50));
assert(interval2 == NegInfInterval!Date( Date(2012, 2, 15)));

```
  void **shift**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (isIntegral!T); 
 
Shifts the `end` of this interval forward or backwards in time by the given number of years and/or months (a positive number of years and months shifts the interval forward; a negative number shifts it backward). It adds the years the given years and months to end. It effectively calls `add!"years"()` and then `add!"months"()` on end with the given number of years and months. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to shift the interval by. |
| T `months` | The number of months to shift the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `end`, causing its month to increment. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if empty is true or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));

interval1.shift(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));

interval2.shift(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));

```
  pure nothrow void **expand**(D)(D duration)  
 Constraints: if (\_\_traits(compiles, end + duration)); 
 
Expands the interval forwards in time. Effectively, it does `end += duration`. 



Parameters:


|  |  |
| --- | --- |
| D `duration` | The duration to expand the interval by. |


 
Example


```
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));

interval1.expand(dur!"days"(2));
assert(interval1 == NegInfInterval!Date(Date(2012, 3, 3)));

interval2.expand(dur!"days"(-2));
assert(interval2 == NegInfInterval!Date(Date(2012, 2, 28)));

```
  void **expand**(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)  
 Constraints: if (isIntegral!T); 
 
Expands the interval forwards and/or backwards in time. Effectively, it adds the given number of months/years to end. 



Parameters:


|  |  |
| --- | --- |
| T `years` | The number of years to expand the interval by. |
| T `months` | The number of months to expand the interval by. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `end`, causing their month to increment. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if empty is true or if the resulting interval would be invalid. 
 
Example


```
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));

interval1.expand(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));

interval2.expand(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));

```
  const NegInfIntervalRange!TP **bwdRange**(TP delegate(scope const TP) func, PopFirst popFirst = PopFirst.no);  
Returns a range which iterates backwards over the interval, starting at `end`, using func to generate each successive time point. 


The range's `front` is the interval's `end`. func is used to generate the next `front` when `popFront` is called. If popFirst is `PopFirst.yes`, then `popFront` is called before the range is returned (so that `front` is a time point which func would generate).   
  
 If func ever generates a time point greater than or equal to the current `front` of the range, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown.   
  
 There are helper functions in this module which generate common delegates to pass to `bwdRange`. Their documentation starts with "Range-generating function," to make them easily searchable. 

 
Parameters:


|  |  |
| --- | --- |
| TP delegate(scope const TP) `func` | The function used to generate the time points of the range over the interval. |
| PopFirst `popFirst` | Whether `popFront` should be called on the range before returning it. |


 
Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if this interval is empty. 
 
Warning
 func must be logically pure. Ideally, func would be a function pointer to a pure function, but forcing func to be pure is far too restrictive to be useful, and in order to have the ease of use of having functions which generate functions to pass to `fwdRange`, func must be a delegate. 
 If func retains state which changes as it is called, then some algorithms will not work correctly, because the range's `save` will have failed to have really saved the range's state. To avoid such bugs, don't pass a delegate which is not logically pure to `fwdRange`. If func is given the same time point with two different calls, it must return the same result both times. Of course, none of the functions in this module have this problem, so it's only relevant for custom delegates. 
Example


```
auto interval = NegInfInterval!Date(Date(2010, 9, 9));
auto func = delegate (scope const Date date) //For iterating over even-numbered days.
            {
                if ((date.day & 1) == 0)
                    return date - dur!"days"(2);

                return date - dur!"days"(1);
            };
auto range = interval.bwdRange(func);

assert(range.front == Date(2010, 9, 9)); //An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).

range.popFront();
assert(range.front == Date(2010, 9, 8));

range.popFront();
assert(range.front == Date(2010, 9, 6));

range.popFront();
assert(range.front == Date(2010, 9, 4));

range.popFront();
assert(range.front == Date(2010, 9, 2));

range.popFront();
assert(!range.empty);

```
  const nothrow string **toString**();  
Converts this interval to a string.

    nothrow TP delegate(scope const TP) **everyDayOfWeek**(TP, Direction dir = Direction.fwd)(DayOfWeek dayOfWeek)  
 Constraints: if (isTimePoint!TP && (dir == Direction.fwd || dir == Direction.bwd) && \_\_traits(hasMember, TP, "dayOfWeek") && !\_\_traits(isStaticFunction, TP.dayOfWeek) && is(typeof(TP.dayOfWeek) == DayOfWeek)); 
 
Range-generating function. 


Returns a delegate which returns the next time point with the given `DayOfWeek` in a range.   
  
 Using this delegate allows iteration over successive time points which are all the same day of the week. e.g. passing `DayOfWeek.mon` to `everyDayOfWeek` would result in a delegate which could be used to iterate over all of the Mondays in a range. 

 
Parameters:


|  |  |
| --- | --- |
| dir | The direction to iterate in. If passing the return value to `fwdRange`, use `Direction.fwd`. If passing it to `bwdRange`, use `Direction.bwd`. |
| DayOfWeek `dayOfWeek` | The week that each time point in the range will be. |


 
Examples:


```
import std.datetime.date : Date, DayOfWeek;

auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDayOfWeek!Date(DayOfWeek.mon);
auto range = interval.fwdRange(func);

// A Thursday. Using PopFirst.yes would have made this Date(2010, 9, 6).
writeln(range.front); // Date(2010, 9, 2)

range.popFront();
writeln(range.front); // Date(2010, 9, 6)

range.popFront();
writeln(range.front); // Date(2010, 9, 13)

range.popFront();
writeln(range.front); // Date(2010, 9, 20)

range.popFront();
assert(range.empty);

```
 
  TP delegate(scope const TP) **everyMonth**(TP, Direction dir = Direction.fwd)(int month)  
 Constraints: if (isTimePoint!TP && (dir == Direction.fwd || dir == Direction.bwd) && \_\_traits(hasMember, TP, "month") && !\_\_traits(isStaticFunction, TP.month) && is(typeof(TP.month) == Month)); 
 
Range-generating function. 


Returns a delegate which returns the next time point with the given month which would be reached by adding months to the given time point.   
  
 So, using this delegate allows iteration over successive time points which are in the same month but different years. For example, iterate over each successive December 25th in an interval by starting with a date which had the 25th as its day and passed `Month.dec` to `everyMonth` to create the delegate.   
  
 Since it wouldn't really make sense to be iterating over a specific month and end up with some of the time points in the succeeding month or two years after the previous time point, `AllowDayOverflow.no` is always used when calculating the next time point. 

 
Parameters:


|  |  |
| --- | --- |
| dir | The direction to iterate in. If passing the return value to `fwdRange`, use `Direction.fwd`. If passing it to `bwdRange`, use `Direction.bwd`. |
| int `month` | The month that each time point in the range will be in (January is 1). |


 
Examples:


```
import std.datetime.date : Date, Month;

auto interval = Interval!Date(Date(2000, 1, 30), Date(2004, 8, 5));
auto func = everyMonth!Date(Month.feb);
auto range = interval.fwdRange(func);

// Using PopFirst.yes would have made this Date(2010, 2, 29).
writeln(range.front); // Date(2000, 1, 30)

range.popFront();
writeln(range.front); // Date(2000, 2, 29)

range.popFront();
writeln(range.front); // Date(2001, 2, 28)

range.popFront();
writeln(range.front); // Date(2002, 2, 28)

range.popFront();
writeln(range.front); // Date(2003, 2, 28)

range.popFront();
writeln(range.front); // Date(2004, 2, 28)

range.popFront();
assert(range.empty);

```
 
  nothrow TP delegate(scope const TP) **everyDuration**(TP, Direction dir = Direction.fwd, D)(D duration)  
 Constraints: if (isTimePoint!TP && \_\_traits(compiles, TP.init + duration) && (dir == Direction.fwd || dir == Direction.bwd)); 
 
Range-generating function. 


Returns a delegate which returns the next time point which is the given duration later.   
  
 Using this delegate allows iteration over successive time points which are apart by the given duration e.g. passing `dur!"days"(3)` to `everyDuration` would result in a delegate which could be used to iterate over a range of days which are each 3 days apart. 

 
Parameters:


|  |  |
| --- | --- |
| dir | The direction to iterate in. If passing the return value to `fwdRange`, use `Direction.fwd`. If passing it to `bwdRange`, use `Direction.bwd`. |
| D `duration` | The duration which separates each successive time point in the range. |


 
Examples:


```
import core.time : dur;
import std.datetime.date : Date;

auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDuration!Date(dur!"days"(8));
auto range = interval.fwdRange(func);

// Using PopFirst.yes would have made this Date(2010, 9, 10).
writeln(range.front); // Date(2010, 9, 2)

range.popFront();
writeln(range.front); // Date(2010, 9, 10)

range.popFront();
writeln(range.front); // Date(2010, 9, 18)

range.popFront();
writeln(range.front); // Date(2010, 9, 26)

range.popFront();
assert(range.empty);

```
 
  nothrow TP delegate(scope const TP) **everyDuration**(TP, Direction dir = Direction.fwd, D)(int years, int months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes, D duration = dur!"days"(0))  
 Constraints: if (isTimePoint!TP && \_\_traits(compiles, TP.init + duration) && \_\_traits(compiles, TP.init.add!"years"(years)) && \_\_traits(compiles, TP.init.add!"months"(months)) && (dir == Direction.fwd || dir == Direction.bwd)); 
 
Range-generating function. 


Returns a delegate which returns the next time point which is the given number of years, month, and duration later.   
  
 The difference between this version of `everyDuration` and the version which just takes a [`core.time.Duration`](core_time#Duration) is that this one also takes the number of years and months (along with an `AllowDayOverflow` to indicate whether adding years and months should allow the days to overflow).   
  
 Note that if iterating forward, `add!"years"()` is called on the given time point, then `add!"months"()`, and finally the duration is added to it. However, if iterating backwards, the duration is added first, then `add!"months"()` is called, and finally `add!"years"()` is called. That way, going backwards generates close to the same time points that iterating forward does, but since adding years and months is not entirely reversible (due to possible day overflow, regardless of whether `AllowDayOverflow.yes` or `AllowDayOverflow.no` is used), it can't be guaranteed that iterating backwards will give the same time points as iterating forward would have (even assuming that the end of the range is a time point which would be returned by the delegate when iterating forward from `begin`). 

 
Parameters:


|  |  |
| --- | --- |
| dir | The direction to iterate in. If passing the return value to `fwdRange`, use `Direction.fwd`. If passing it to `bwdRange`, use `Direction.bwd`. |
| int `years` | The number of years to add to the time point passed to the delegate. |
| int `months` | The number of months to add to the time point passed to the delegate. |
| AllowDayOverflow `allowOverflow` | Whether the days should be allowed to overflow on `begin` and `end`, causing their month to increment. |
| D `duration` | The duration to add to the time point passed to the delegate. |


 
Examples:


```
import core.time : dur;
import std.datetime.date : AllowDayOverflow, Date;

auto interval = Interval!Date(Date(2010, 9, 2), Date(2025, 9, 27));
auto func = everyDuration!Date(4, 1, AllowDayOverflow.yes, dur!"days"(2));
auto range = interval.fwdRange(func);

// Using PopFirst.yes would have made this Date(2014, 10, 12).
writeln(range.front); // Date(2010, 9, 2)

range.popFront();
writeln(range.front); // Date(2014, 10, 4)

range.popFront();
writeln(range.front); // Date(2018, 11, 6)

range.popFront();
writeln(range.front); // Date(2022, 12, 8)

range.popFront();
assert(range.empty);

```
 
  struct **IntervalRange**(TP, Direction dir) if (isTimePoint!TP && (dir != Direction.both));  
A range over an [`Interval`](#Interval). 


`IntervalRange` is only ever constructed by [`Interval`](#Interval). However, when it is constructed, it is given a function, `func`, which is used to generate the time points which are iterated over. `func` takes a time point and returns a time point of the same type. For instance, to iterate over all of the days in the interval `Interval!Date`, pass a function to [`Interval`](#Interval)'s `fwdRange` where that function took a [`std.datetime.date.Date`](std_datetime_date#Date) and returned a [`std.datetime.date.Date`](std_datetime_date#Date) which was one day later. That function would then be used by `IntervalRange`'s `popFront` to iterate over the [`std.datetime.date.Date`](std_datetime_date#Date)s in the interval.   
  
 If `dir == Direction.fwd`, then a range iterates forward in time, whereas if `dir == Direction.bwd`, then it iterates backwards in time. So, if `dir == Direction.fwd` then `front == interval.begin`, whereas if `dir == Direction.bwd` then `front == interval.end`. `func` must generate a time point going in the proper direction of iteration, or a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. So, to iterate forward in time, the time point that `func` generates must be later in time than the one passed to it. If it's either identical or earlier in time, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. To iterate backwards, then the generated time point must be before the time point which was passed in.   
  
 If the generated time point is ever passed the edge of the range in the proper direction, then the edge of that range will be used instead. So, if iterating forward, and the generated time point is past the interval's `end`, then `front` becomes `end`. If iterating backwards, and the generated time point is before `begin`, then `front` becomes `begin`. In either case, the range would then be empty.   
  
 Also note that while normally the `begin` of an interval is included in it and its `end` is excluded from it, if `dir == Direction.bwd`, then `begin` is treated as excluded and `end` is treated as included. This allows for the same behavior in both directions. This works because none of [`Interval`](#Interval)'s functions which care about whether `begin` or `end` is included or excluded are ever called by `IntervalRange`. `interval` returns a normal interval, regardless of whether `dir == Direction.fwd` or if `dir == Direction.bwd`, so any [`Interval`](#Interval) functions which are called on it which care about whether `begin` or `end` are included or excluded will treat `begin` as included and `end` as excluded.

 
pure nothrow ref IntervalRange **opAssign**(ref IntervalRange rhs);   
  
pure nothrow ref IntervalRange **opAssign**(IntervalRange rhs);  

Parameters:


|  |  |
| --- | --- |
| IntervalRange `rhs` | The `IntervalRange` to assign to this one. |


  const pure nothrow @property bool **empty**();  
Whether this `IntervalRange` is empty.

  const pure @property TP **front**();  
The first time point in the range. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the range is empty.
  void **popFront**();  
Pops `front` from the range, using `func` to generate the next time point in the range. If the generated time point is beyond the edge of the range, then `front` is set to that edge, and the range is then empty. So, if iterating forwards, and the generated time point is greater than the interval's `end`, then `front` is set to `end`. If iterating backwards, and the generated time point is less than the interval's `begin`, then `front` is set to `begin`. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the range is empty or if the generated time point is in the wrong direction (i.e. if iterating forward and the generated time point is before `front`, or if iterating backwards and the generated time point is after `front`).
  pure nothrow @property IntervalRange **save**();  
Returns a copy of `this`.

  const pure nothrow @property Interval!TP **interval**();  
The interval that this `IntervalRange` currently covers.

  pure nothrow @property TP delegate(scope const TP) **func**();  
The function used to generate the next time point in the range.

  const pure nothrow @property Direction **direction**();  
The `Direction` that this range iterates in.

    struct **PosInfIntervalRange**(TP) if (isTimePoint!TP);  
A range over a `PosInfInterval`. It is an infinite range. 


`PosInfIntervalRange` is only ever constructed by `PosInfInterval`. However, when it is constructed, it is given a function, `func`, which is used to generate the time points which are iterated over. `func` takes a time point and returns a time point of the same type. For instance, to iterate over all of the days in the interval `PosInfInterval!Date`, pass a function to `PosInfInterval`'s `fwdRange` where that function took a [`std.datetime.date.Date`](std_datetime_date#Date) and returned a [`std.datetime.date.Date`](std_datetime_date#Date) which was one day later. That function would then be used by `PosInfIntervalRange`'s `popFront` to iterate over the [`std.datetime.date.Date`](std_datetime_date#Date)s in the interval - though obviously, since the range is infinite, use a function such as `std.range.take` with it rather than iterating over *all* of the dates.   
  
 As the interval goes to positive infinity, the range is always iterated over forwards, never backwards. `func` must generate a time point going in the proper direction of iteration, or a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. So, the time points that `func` generates must be later in time than the one passed to it. If it's either identical or earlier in time, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown.

 
pure nothrow ref PosInfIntervalRange **opAssign**(ref PosInfIntervalRange rhs);   
  
pure nothrow ref PosInfIntervalRange **opAssign**(PosInfIntervalRange rhs);  

Parameters:


|  |  |
| --- | --- |
| PosInfIntervalRange `rhs` | The `PosInfIntervalRange` to assign to this one. |


  enum bool **empty**;  
This is an infinite range, so it is never empty.

  const pure nothrow @property TP **front**();  
The first time point in the range.

  void **popFront**();  
Pops `front` from the range, using `func` to generate the next time point in the range. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the generated time point is less than `front`.
  pure nothrow @property PosInfIntervalRange **save**();  
Returns a copy of `this`.

  const pure nothrow @property PosInfInterval!TP **interval**();  
The interval that this range currently covers.

  pure nothrow @property TP delegate(scope const TP) **func**();  
The function used to generate the next time point in the range.

    struct **NegInfIntervalRange**(TP) if (isTimePoint!TP);  
A range over a `NegInfInterval`. It is an infinite range. 


`NegInfIntervalRange` is only ever constructed by `NegInfInterval`. However, when it is constructed, it is given a function, `func`, which is used to generate the time points which are iterated over. `func` takes a time point and returns a time point of the same type. For instance, to iterate over all of the days in the interval `NegInfInterval!Date`, pass a function to `NegInfInterval`'s `bwdRange` where that function took a [`std.datetime.date.Date`](std_datetime_date#Date) and returned a [`std.datetime.date.Date`](std_datetime_date#Date) which was one day earlier. That function would then be used by `NegInfIntervalRange`'s `popFront` to iterate over the [`std.datetime.date.Date`](std_datetime_date#Date)s in the interval - though obviously, since the range is infinite, use a function such as `std.range.take` with it rather than iterating over *all* of the dates.   
  
 As the interval goes to negative infinity, the range is always iterated over backwards, never forwards. `func` must generate a time point going in the proper direction of iteration, or a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown. So, the time points that `func` generates must be earlier in time than the one passed to it. If it's either identical or later in time, then a [`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) will be thrown.   
  
 Also note that while normally the `end` of an interval is excluded from it, `NegInfIntervalRange` treats it as if it were included. This allows for the same behavior as with `PosInfIntervalRange`. This works because none of `NegInfInterval`'s functions which care about whether `end` is included or excluded are ever called by `NegInfIntervalRange`. `interval` returns a normal interval, so any `NegInfInterval` functions which are called on it which care about whether `end` is included or excluded will treat `end` as excluded.

 
pure nothrow ref NegInfIntervalRange **opAssign**(ref NegInfIntervalRange rhs);   
  
pure nothrow ref NegInfIntervalRange **opAssign**(NegInfIntervalRange rhs);  

Parameters:


|  |  |
| --- | --- |
| NegInfIntervalRange `rhs` | The `NegInfIntervalRange` to assign to this one. |


  enum bool **empty**;  
This is an infinite range, so it is never empty.

  const pure nothrow @property TP **front**();  
The first time point in the range.

  void **popFront**();  
Pops `front` from the range, using `func` to generate the next time point in the range. 



Throws:

[`std.datetime.date.DateTimeException`](std_datetime_date#DateTimeException) if the generated time point is greater than `front`.
  pure nothrow @property NegInfIntervalRange **save**();  
Returns a copy of `this`.

  const pure nothrow @property NegInfInterval!TP **interval**();  
The interval that this range currently covers.

  pure nothrow @property TP delegate(scope const TP) **func**();  
The function used to generate the next time point in the range.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_datetime_interval.html>

std.experimental.allocator.building\_blocks.free\_list
======================================================

 
Source
 [std/experimental/allocator/building\_blocks/free\_list.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/free_list.d)

 
struct **FreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize, Flag!"adaptive" adaptive = No.adaptive);  
[Free list allocator](http://en.wikipedia.org/wiki/Free_list), stackable on top of another allocator. Allocation requests between `min` and `max` bytes are rounded up to `max` and served from a singly-linked list of buffers deallocated in the past. All other allocations are directed to `ParentAllocator`. Due to the simplicity of free list management, allocations from the free list are fast. If `adaptive` is set to `Yes.adaptive`, the free list gradually reduces its size if allocations tend to use the parent allocator much more than the lists' available nodes. 


One instantiation is of particular interest: `FreeList!(0, unbounded)` puts every deallocation in the freelist, and subsequently serves any allocation from the freelist (if not empty). There is no checking of size matching, which would be incorrect for a freestanding allocator but is both correct and fast when an owning allocator on top of the free list allocator (such as `Segregator`) is already in charge of handling size checking.   
  
 The following methods are defined if `ParentAllocator` defines them, and forward to it: `expand`, `owns`, `reallocate`.

 
const @property size\_t **min**();  
Returns the smallest allocation size eligible for allocation from the freelist. (If `minSize != chooseAtRuntime`, this is simply an alias for `minSize`.)

  @property void **min**(size\_t low);  
If `FreeList` has been instantiated with `minSize == chooseAtRuntime`, then the `min` property is writable. Setting it must precede any allocation. 



Parameters:


|  |  |
| --- | --- |
| size\_t `low` | new value for `min` |


 
Precondition
 `low <= max`, or `maxSize == chooseAtRuntime` and `max` has not yet been initialized. Also, no allocation has been yet done with this allocator. 
 
Postcondition
 `min == low`

  const @property size\_t **max**();  
Returns the largest allocation size eligible for allocation from the freelist. (If `maxSize != chooseAtRuntime`, this is simply an alias for `maxSize`.) All allocation requests for sizes greater than or equal to `min` and less than or equal to `max` are rounded to  `max` and forwarded to the parent allocator. When the block fitting the same constraint gets deallocated, it is put in the freelist with the allocated size assumed to be `max`.

  @property void **max**(size\_t high);  
If `FreeList` has been instantiated with `maxSize == chooseAtRuntime`, then the `max` property is writable. Setting it must precede any allocation. 



Parameters:


|  |  |
| --- | --- |
| size\_t `high` | new value for `max` |


 
Precondition
 `high >= min`, or `minSize == chooseAtRuntime` and `min` has not yet been initialized. Also `high >= (void*).sizeof`. Also, no allocation has been yet done with this allocator. 
 
Postcondition
 `max == high`

  ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  alias **alignment** = ParentAllocator.**alignment**;  
Alignment offered.

  size\_t **goodAllocSize**(size\_t bytes);  
If `maxSize == unbounded`, returns `parent.goodAllocSize(bytes)`. Otherwise, returns `max` for sizes in the interval `[min, max]`, and `parent.goodAllocSize(bytes)` otherwise. 



Precondition
 If set at runtime, `min` and/or `max` must be initialized appropriately. 
 
Postcondition
 `result >= bytes`

  void[] **allocate**(size\_t n);  
Allocates memory either off of the free list or from the parent allocator. If `n` is within `[min, max]` or if the free list is unchecked (`minSize == 0 && maxSize == size_t.max`), then the free list is consulted first. If not empty (hit), the block at the front of the free list is removed from the list and returned. Otherwise (miss), a new block of `max` bytes is allocated, truncated to `n` bytes, and returned. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |


 
Returns:
The allocated block, or `null`. 
 
Precondition
 If set at runtime, `min` and/or `max` must be initialized appropriately. 
 
Postcondition
 `result.length == bytes || result is null`

  bool **deallocate**(void[] block);  
If `block.length` is within `[min, max]` or if the free list is unchecked (`minSize == 0 && maxSize == size_t.max`), then inserts the block at the front of the free list. For all others, forwards to  `parent.deallocate` if `Parent.deallocate` is defined. 



Parameters:


|  |  |
| --- | --- |
| void[] `block` | Block to deallocate. |


 
Precondition
 If set at runtime, `min` and/or `max` must be initialized appropriately. The block must have been allocated with this freelist, and no dynamic changing of `min` or `max` is allowed to occur between allocation and deallocation.
  bool **deallocateAll**();  
Defined only if `ParentAllocator` defines `deallocateAll`. If so, forwards to it and resets the freelist.

  void **minimize**();  
Nonstandard function that minimizes the memory usage of the freelist by freeing each element in turn. Defined only if `ParentAllocator` defines `deallocate`. `FreeList!(0, unbounded)` does not have this function.

    struct **ContiguousFreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize);  
Free list built on top of exactly one contiguous block of memory. The block is assumed to have been allocated with `ParentAllocator`, and is released in `ContiguousFreeList`'s destructor (unless `ParentAllocator` is `NullAllocator`). 


`ContiguousFreeList` has most advantages of `FreeList` but fewer disadvantages. It has better cache locality because items are closer to one another. It imposes less fragmentation on its parent allocator.   
  
 The disadvantages of `ContiguousFreeList` over `FreeList` are its pay upfront model (as opposed to `FreeList`'s pay-as-you-go approach), and a hard limit on the number of nodes in the list. Thus, a large number of long- lived objects may occupy the entire block, making it unavailable for serving allocations from the free list. However, an absolute cap on the free list size may be beneficial.   
  
 The options `minSize == unbounded` and `maxSize == unbounded` are not available for `ContiguousFreeList`.

 
Examples:


```
import std.experimental.allocator.building_blocks.allocator_list
    : AllocatorList;
import std.experimental.allocator.gc_allocator : GCAllocator;

import std.experimental.allocator.common : unbounded;

alias ScalableFreeList = AllocatorList!((n) =>
    ContiguousFreeList!(GCAllocator, 0, unbounded)(4096)
);

```
 
 
SParent **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  enum uint **alignment**;  
Alignment offered.

  this(ubyte[] buffer);   
  
this(ParentAllocator parent, ubyte[] buffer);   
  
this(size\_t bytes);   
  
this(ParentAllocator parent, size\_t bytes);   
  
this(size\_t bytes, size\_t max);   
  
this(ParentAllocator parent, size\_t bytes, size\_t max);   
  
this(size\_t bytes, size\_t min, size\_t max);   
  
this(ParentAllocator parent, size\_t bytes, size\_t min, size\_t max);  
Constructors setting up the memory structured as a free list. 



Parameters:


|  |  |
| --- | --- |
| ubyte[] `buffer` | Buffer to structure as a free list. If `ParentAllocator` is not `NullAllocator`, the buffer is assumed to be allocated by `parent` and will be freed in the destructor. |
| ParentAllocator `parent` | Parent allocator. For construction from stateless allocators, use their `instance` static member. |
| size\_t `bytes` | Bytes (not items) to be allocated for the free list. Memory will be allocated during construction and deallocated in the destructor. |
| size\_t `max` | Maximum size eligible for freelisting. Construction with this parameter is defined only if `maxSize == chooseAtRuntime` or `maxSize == unbounded`. |
| size\_t `min` | Minimum size eligible for freelisting. Construction with this parameter is defined only if `minSize == chooseAtRuntime`. If this condition is met and no `min` parameter is present, `min` is initialized with `max`. |


  size\_t **goodAllocSize**(size\_t n);  
If `n` is eligible for freelisting, returns `max`. Otherwise, returns `parent.goodAllocSize(n)`. 



Precondition
 If set at runtime, `min` and/or `max` must be initialized appropriately. 
 
Postcondition
 `result >= bytes`

  void[] **allocate**(size\_t n);  
Allocate `n` bytes of memory. If `n` is eligible for freelist and the freelist is not empty, pops the memory off the free list. In all other cases, uses the parent allocator.

  Ternary **owns**(void[] b);  
Defined if `ParentAllocator` defines it. Checks whether the block belongs to this allocator.

  bool **deallocate**(void[] b);  
Deallocates `b`. If it's of eligible size, it's put on the free list. Otherwise, it's returned to `parent`. 



Precondition
 `b` has been allocated with this allocator, or is  `null`.
  bool **deallocateAll**();  
Deallocates everything from the parent.

  Ternary **empty**();  
Returns `Ternary.yes` if no memory is currently allocated with this allocator, `Ternary.no` otherwise. This method never returns `Ternary.unknown`.

    struct **SharedFreeList**(ParentAllocator, size\_t minSize, size\_t maxSize = minSize, size\_t approxMaxNodes = unbounded);  
FreeList shared across threads. Allocation and deallocation are lock-free. The parameters have the same semantics as for `FreeList`. 


`expand` is defined to forward to `ParentAllocator.expand` (it must be also `shared`).

 
Examples:


```
import std.experimental.allocator.common : chooseAtRuntime;
import std.experimental.allocator.mallocator : Mallocator;

shared SharedFreeList!(Mallocator, chooseAtRuntime, chooseAtRuntime) a;
a.setBounds(64, 128);
writeln(a.max); // 128
writeln(a.min); // 64

```
 
 
Examples:


```
import std.experimental.allocator.common : chooseAtRuntime;
import std.experimental.allocator.mallocator : Mallocator;

shared SharedFreeList!(Mallocator, 50, 50, chooseAtRuntime) a;
// Set the maxSize first so setting the minSize doesn't throw
a.approxMaxLength = 128;
writeln(a.approxMaxLength); // 128
a.approxMaxLength = 1024;
writeln(a.approxMaxLength); // 1024
a.approxMaxLength = 1;
writeln(a.approxMaxLength); // 1

```
 
 
@property size\_t **min**();   
  
@property void **min**(size\_t newMinSize);   
  
@property size\_t **max**();   
  
@property void **max**(size\_t newMaxSize);   
  
void **setBounds**(size\_t newMin, size\_t newMax);  
Properties for getting (and possibly setting) the bounds. Setting bounds is allowed only once , and before any allocation takes place. Otherwise, the primitives have the same semantics as those of `FreeList`.

  shared const @property size\_t **approxMaxLength**();   
  
shared @property void **approxMaxLength**(size\_t x);  
Properties for getting (and possibly setting) the approximate maximum length of a shared freelist.

  shared ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  enum uint **alignment**;   
  
shared size\_t **goodAllocSize**(size\_t bytes);   
  
shared const Ternary **owns**(const void[] b);   
  
shared bool **reallocate**(ref void[] b, size\_t s);   
  
shared void[] **allocate**(size\_t bytes);   
  
shared bool **deallocate**(void[] b);   
  
shared bool **deallocateAll**();  
Standard primitives.

  shared void **minimize**();  
Nonstandard function that minimizes the memory usage of the freelist by freeing each element in turn. Defined only if `ParentAllocator` defines `deallocate`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_free_list.html>

std.experimental.allocator.building\_blocks.free\_tree
======================================================

 
Source
 [std/experimental/allocator/building\_blocks/free\_tree.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/free_tree.d)

 
struct **FreeTree**(ParentAllocator);  
The Free Tree allocator, stackable on top of any other allocator, bears similarity with the free list allocator. Instead of a singly-linked list of previously freed blocks, it maintains a binary search tree. This allows the Free Tree allocator to manage blocks of arbitrary lengths and search them efficiently. 


Common uses of `FreeTree` include:   
  
 * Adding `deallocate` capability to an allocator that lacks it (such as simple regions).
* Getting the benefits of multiple adaptable freelists that do not need to be tuned for one specific size but insted automatically adapts itself to frequently used sizes.

   
  
 The free tree has special handling of duplicates (a singly-linked list per node) in anticipation of large number of duplicates. Allocation time from the free tree is expected to be Ο(`log n`) where `n` is the number of distinct sizes (not total nodes) kept in the free tree.   
  
 Allocation requests first search the tree for a buffer of suitable size deallocated in the past. If a match is found, the node is removed from the tree and the memory is returned. Otherwise, the allocation is directed to `ParentAllocator`. If at this point `ParentAllocator` also fails to allocate, `FreeTree` frees everything and then tries the parent allocator again.   
  
 Upon deallocation, the deallocated block is inserted in the internally maintained free tree (not returned to the parent). The free tree is not kept balanced. Instead, it has a last-in-first-out flavor because newly inserted blocks are rotated to the root of the tree. That way allocations are cache friendly and also frequently used sizes are more likely to be found quickly, whereas seldom used sizes migrate to the leaves of the tree.   
  
 `FreeTree` rounds up small allocations to at least `4 * size_t.sizeof`, which on 64-bit system is one cache line size. If very small objects need to be efficiently allocated, the `FreeTree` should be fronted with an appropriate small object allocator.   
  
 The following methods are defined if `ParentAllocator` defines them, and forward to it: `allocateAll`, `expand`, `owns`, `reallocate`.

 
enum uint **alignment**;  
The `FreeTree` is word aligned.

  size\_t **goodAllocSize**(size\_t s);  
Returns `parent.goodAllocSize(max(Node.sizeof, s))`.

  void[] **allocate**(size\_t n);  
Allocates `n` bytes of memory. First consults the free tree, and returns from it if a suitably sized block is found. Otherwise, the parent allocator is tried. If allocation from the parent succeeds, the allocated block is returned. Otherwise, the free tree tries an alternate strategy: If  `ParentAllocator` defines `deallocate`, `FreeTree` releases all of its contents and tries again. 



TODO
 Splitting and coalescing should be implemented if `ParentAllocator` does not defined `deallocate`.
  bool **deallocate**(void[] b);  
Places `b` into the free tree.

  void **clear**();  
Defined if `ParentAllocator.deallocate` exists, and returns to it all memory held in the free tree.

  bool **deallocateAll**();  
Defined if `ParentAllocator.deallocateAll` exists, and forwards to it. Also nullifies the free tree (it's assumed the parent frees all memory stil managed by the free tree). 

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_free_tree.html>

std.experimental.allocator.building\_blocks.null\_allocator
===========================================================

 
Source
 [std/experimental/allocator/building\_blocks/null\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/null_allocator.d)

 
struct **NullAllocator**;  
`NullAllocator` is an emphatically empty implementation of the allocator interface. Although it has no direct use, it is useful as a "terminator" in composite allocators.

 
enum uint **alignment**;  
`NullAllocator` advertises a relatively large alignment equal to 64 KB. This is because `NullAllocator` never actually needs to honor this alignment and because composite allocators using `NullAllocator` shouldn't be unnecessarily constrained.

  shared pure nothrow @nogc @safe void[] **allocate**(size\_t);  
Always returns `null`.

  shared pure nothrow @nogc @safe void[] **alignedAllocate**(size\_t, uint);  
Always returns `null`.

  shared pure nothrow @nogc @safe void[] **allocateAll**();  
Always returns `null`.

  shared pure nothrow @nogc @safe bool **expand**(ref void[] b, size\_t s);   
  
shared pure nothrow @nogc @safe bool **reallocate**(ref void[] b, size\_t);   
  
shared pure nothrow @nogc @safe bool **alignedReallocate**(ref void[] b, size\_t, uint);  
These methods return `false`. 



Precondition
 `b is null`. This is because there is no other possible legitimate input.
  shared const pure nothrow @nogc @safe Ternary **owns**(const void[]);  
Returns `Ternary.no`.

  shared const pure nothrow @nogc @safe Ternary **resolveInternalPointer**(const void\*, ref void[]);  
Returns `Ternary.no`.

  shared pure nothrow @nogc @safe bool **deallocate**(void[] b);  
No-op. 



Precondition
 `b is null`

  shared pure nothrow @nogc @safe bool **deallocateAll**();  
No-op.

  shared const pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes`.

  static shared NullAllocator **instance**;  
Returns the `shared` global instance of the `NullAllocator`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_null_allocator.html>

std.experimental.allocator.building\_blocks.kernighan\_ritchie
==============================================================

 
Source
 [std/experimental/allocator/building\_blocks/kernighan\_ritchie.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/kernighan_ritchie.d)

 
struct **KRRegion**(ParentAllocator = NullAllocator);  
`KRRegion` draws inspiration from the [region allocation strategy](std_experimental_allocator_building_blocks_region) and also the [famed allocator](http://stackoverflow.com/questions/13159564/explain-this-implementation-of-malloc-from-the-kr-book) described by Brian Kernighan and Dennis Ritchie in section 8.7 of the book ["The C Programming Language"](http://amazon.com/exec/obidos/ASIN/0131103628/classicempire), Second Edition, Prentice Hall, 1988. 


#### 
`KRRegion` = `Region` + Kernighan-Ritchie Allocator

   
  
 Initially, `KRRegion` starts in "region" mode: allocations are served from the memory chunk in a region fashion. Thus, as long as there is enough memory left, `KRRegion.allocate` has the performance profile of a region allocator. Deallocation inserts (in Ο(`1`) time) the deallocated blocks in an unstructured freelist, which is not read in region mode.   
  
 Once the region cannot serve an `allocate` request, `KRRegion` switches to "free list" mode. It sorts the list of previously deallocated blocks by address and serves allocation requests off that free list. The allocation and deallocation follow the pattern described by Kernighan and Ritchie.   
  
 The recommended use of `KRRegion` is as a *region with deallocation*. If the `KRRegion` is dimensioned appropriately, it could often not enter free list mode during its lifetime. Thus it is as fast as a simple region, whilst offering deallocation at a small cost. When the region memory is exhausted, the previously deallocated memory is still usable, at a performance cost. If the region is not excessively large and fragmented, the linear allocation and deallocation cost may still be compensated for by the good locality characteristics.   
  
 If the chunk of memory managed is large, it may be desirable to switch management to free list from the beginning. That way, memory may be used in a more compact manner than region mode. To force free list mode, call `switchToFreeList` shortly after construction or when deemed appropriate.   
  
 The smallest size that can be allocated is two words (16 bytes on 64-bit systems, 8 bytes on 32-bit systems). This is because the free list management needs two words (one for the length, the other for the next pointer in the singly-linked list).   
  
 The `ParentAllocator` type parameter is the type of the allocator used to allocate the memory chunk underlying the `KRRegion` object. Choosing the default (`NullAllocator`) means the user is responsible for passing a buffer at construction (and for deallocating it if necessary). Otherwise, `KRRegion` automatically deallocates the buffer during destruction. For that reason, if `ParentAllocator` is not `NullAllocator`, then `KRRegion` is not copyable.   
  
 #### Implementation Details

   
  
 In free list mode, `KRRegion` embeds a free blocks list onto the chunk of memory. The free list is circular, coalesced, and sorted by address at all times. Allocations and deallocations take time proportional to the number of previously deallocated blocks. (In practice the cost may be lower, e.g. if memory is deallocated in reverse order of allocation, all operations take constant time.) Memory utilization is good (small control structure and no per-allocation overhead). The disadvantages of freelist mode include proneness to fragmentation, a minimum allocation size of two words, and linear worst-case allocation and deallocation times.   
  
 Similarities of `KRRegion` (in free list mode) with the Kernighan-Ritchie allocator:   
  
 * Free blocks have variable size and are linked in a singly-linked list.
* The freelist is maintained in increasing address order, which makes coalescing easy.
* The strategy for finding the next available block is first fit.
* The free list is circular, with the last node pointing back to the first.
* Coalescing is carried during deallocation.

   
  
 Differences from the Kernighan-Ritchie allocator:   
  
 * Once the chunk is exhausted, the Kernighan-Ritchie allocator allocates another chunk using operating system primitives. For better composability, `KRRegion` just gets full (returns `null` on new allocation requests). The decision to allocate more blocks is deferred to a higher-level entity. For an example, see the example below using `AllocatorList` in conjunction with `KRRegion`.
* Allocated blocks do not hold a size prefix. This is because in D the size information is available in client code at deallocation time.


 
Examples:

`KRRegion` is preferable to `Region` as a front for a general-purpose allocator if `deallocate` is needed, yet the actual deallocation traffic is relatively low. The example below shows a `KRRegion` using stack storage fronting the GC allocator. 
```
import std.experimental.allocator.building_blocks.fallback_allocator
    : fallbackAllocator;
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.typecons : Ternary;
// KRRegion fronting a general-purpose allocator
ubyte[1024 * 128] buf;
auto alloc = fallbackAllocator(KRRegion!()(buf), GCAllocator.instance);
auto b = alloc.allocate(100);
writeln(b.length); // 100
writeln((() pure nothrow @safe @nogc => alloc.primary.owns(b))()); // Ternary.yes

```
 
 
Examples:
The code below defines a scalable allocator consisting of 1 MB (or larger) blocks fetched from the garbage-collected heap. Each block is organized as a KR-style heap. More blocks are allocated and freed on a need basis. This is the closest example to the allocator introduced in the K&R book. It should perform slightly better because instead of searching through one large free list, it searches through several shorter lists in LRU order. Also, it actually returns memory to the operating system when possible. 
```
import std.algorithm.comparison : max;
import std.experimental.allocator.building_blocks.allocator_list
    : AllocatorList;
import std.experimental.allocator.mmap_allocator : MmapAllocator;
AllocatorList!(n => KRRegion!MmapAllocator(max(n * 16, 1024 * 1024))) alloc;

```
 
 
ParentAllocator **parent**;  
If `ParentAllocator` holds state, `parent` is a public member of type `KRRegion`. Otherwise, `parent` is an `alias` for `ParentAllocator.instance`.

  this(ubyte[] b);   
  
this(size\_t n);   
  
this(ParentAllocator parent, size\_t n);  
Create a `KRRegion`. If `ParentAllocator` is not `NullAllocator`, `KRRegion`'s destructor will call `parent.deallocate`. 



Parameters:


|  |  |
| --- | --- |
| ubyte[] `b` | Block of memory to serve as support for the allocator. Memory must be larger than two words and word-aligned. |
| size\_t `n` | Capacity desired. This constructor is defined only if  `ParentAllocator` is not `NullAllocator`. |


  void **switchToFreeList**();  
Forces free list mode. If already in free list mode, does nothing. Otherwise, sorts the free list accumulated so far and switches strategy for future allocations to KR style.

  enum auto **alignment**;  
Word-level alignment.

  void[] **allocate**(size\_t n);  
Allocates `n` bytes. Allocation searches the list of available blocks until a free block with `n` or more bytes is found (first fit strategy). The block is split (if larger) and returned. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |


 
Returns:
A word-aligned buffer of `n` bytes, or `null`.
  nothrow @nogc bool **deallocate**(void[] b);  
Deallocates `b`, which is assumed to have been previously allocated with this allocator. Deallocation performs a linear search in the free list to preserve its sorting order. It follows that blocks with higher addresses in allocators with many free blocks are slower to deallocate. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | block to be deallocated |


  void[] **allocateAll**();  
Allocates all memory available to this allocator. If the allocator is empty, returns the entire available block of memory. Otherwise, it still performs a best-effort allocation: if there is no fragmentation (e.g. `allocate` has been used but not `deallocate`), allocates and returns the only available block of memory. 


The operation takes time proportional to the number of adjacent free blocks at the front of the free list. These blocks get coalesced, whether `allocateAll` succeeds or fails due to fragmentation.

 
Examples:


```
import std.experimental.allocator.gc_allocator : GCAllocator;
auto alloc = KRRegion!GCAllocator(1024 * 64);
const b1 = alloc.allocate(2048);
writeln(b1.length); // 2048
const b2 = alloc.allocateAll;
writeln(b2.length); // 1024 * 62

```
 
  pure nothrow @nogc bool **deallocateAll**();  
Deallocates all memory currently allocated, making the allocator ready for other allocations. This is a Ο(`1`) operation.

  pure nothrow @nogc @trusted Ternary **owns**(void[] b);  
Checks whether the allocator is responsible for the allocation of `b`. It does a simple Ο(`1`) range check. `b` should be a buffer either allocated with `this` or obtained through other means.

  static pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Adjusts `n` to a size suitable for allocation (two words or larger, word-aligned).

  pure nothrow @nogc @safe Ternary **empty**();  

Returns:

`Ternary.yes` if the allocator is empty, `Ternary.no` otherwise. Never returns `Ternary.unknown`.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_kernighan_ritchie.html>

std.experimental.allocator.building\_blocks.quantizer
=====================================================

 
Source
 [std/experimental/allocator/building\_blocks/quantizer.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/quantizer.d)

 
struct **Quantizer**(ParentAllocator, alias roundingFunction);  
This allocator sits on top of `ParentAllocator` and quantizes allocation sizes, usually from arbitrary positive numbers to a small set of round numbers (e.g. powers of two, page sizes etc). This technique is commonly used to: 


* Preallocate more memory than requested such that later on, when reallocation is needed (e.g. to grow an array), expansion can be done quickly in place. Reallocation to smaller sizes is also fast (in-place) when the new size requested is within the same quantum as the existing size. Code that's reallocation-heavy can therefore benefit from fronting a generic allocator with a `Quantizer`. These advantages are present even if `ParentAllocator` does not support reallocation at all.
* Improve behavior of allocators sensitive to allocation sizes, such as `FreeList` and `FreeTree`. Rounding allocation requests up makes for smaller free lists/trees at the cost of slack memory (internal fragmentation).

   
  
 The following methods are forwarded to the parent allocator if present: `allocateAll`, `owns`, `deallocateAll`, `empty`. 

 
Preconditions
 `roundingFunction` must satisfy three constraints. These are not enforced (save for the use of `assert`) for the sake of efficiency. 

1. `roundingFunction(n) >= n` for all `n` of type `size_t`;
2. `roundingFunction` must be monotonically increasing, i.e. `roundingFunction(n1) <= roundingFunction(n2)` for all `n1 < n2`;
3. `roundingFunction` must be `nothrow`, `@safe`, `@nogc` and `pure`, i.e. always return the same value for a given `n`.

 
Examples:


```
import std.experimental.allocator.building_blocks.free_tree : FreeTree;
import std.experimental.allocator.gc_allocator : GCAllocator;

size_t roundUpToMultipleOf(size_t s, uint base)
{
    auto rem = s % base;
    return rem ? s + base - rem : s;
}

// Quantize small allocations to a multiple of cache line, large ones to a
// multiple of page size
alias MyAlloc = Quantizer!(
    FreeTree!GCAllocator,
    n => roundUpToMultipleOf(n, n <= 16_384 ? 64 : 4096));
MyAlloc alloc;
const buf = alloc.allocate(256);
assert(buf.ptr);

```
 
 
ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  size\_t **goodAllocSize**(size\_t n);  
Returns `roundingFunction(n)`.

  enum auto **alignment**;  
Alignment is identical to that of the parent.

  void[] **allocate**(size\_t n);  
Gets a larger buffer `buf` by calling `parent.allocate(goodAllocSize(n))`. If `buf` is `null`, returns `null`. Otherwise, returns `buf[0 .. n]`.

  void[] **alignedAllocate**(size\_t n, uint a);  
Defined only if `parent.alignedAllocate` exists and works similarly to `allocate` by forwarding to `parent.alignedAllocate(goodAllocSize(n), a)`.

  bool **expand**(ref void[] b, size\_t delta);  
First checks whether there's enough slack memory preallocated for `b` by evaluating `b.length + delta <= goodAllocSize(b.length)`. If that's the case, expands `b` in place. Otherwise, attempts to use `parent.expand` appropriately if present.

  bool **reallocate**(ref void[] b, size\_t s);  
Expands or shrinks allocated block to an allocated size of  `goodAllocSize(s)`. Expansion occurs in place under the conditions required by `expand`. Shrinking occurs in place if `goodAllocSize(b.length) == goodAllocSize(s)`.

  bool **alignedReallocate**(ref void[] b, size\_t s, uint a);  
Defined only if `ParentAllocator.alignedAllocate` exists. Expansion occurs in place under the conditions required by `expand`. Shrinking occurs in place if `goodAllocSize(b.length) == goodAllocSize(s)`.

  bool **deallocate**(void[] b);  
Defined if `ParentAllocator.deallocate` exists and forwards to `parent.deallocate(b.ptr[0 .. goodAllocSize(b.length)])`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_quantizer.html>

std.experimental.allocator.building\_blocks.scoped\_allocator
=============================================================

 
Source
 [std/experimental/allocator/building\_blocks/scoped\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/scoped_allocator.d)

 
struct **ScopedAllocator**(ParentAllocator);  
`ScopedAllocator` delegates all allocation requests to `ParentAllocator`. When destroyed, the `ScopedAllocator` object automatically calls `deallocate` for all memory allocated through its lifetime. (The `deallocateAll` function is also implemented with the same semantics.) 


`deallocate` is also supported, which is where most implementation effort and overhead of `ScopedAllocator` go. If `deallocate` is not needed, a simpler design combining `AllocatorList` with `Region` is recommended.

 
Examples:


```
import std.experimental.allocator.mallocator : Mallocator;
import std.typecons : Ternary;
ScopedAllocator!Mallocator alloc;
writeln(alloc.empty); // Ternary.yes
const b = alloc.allocate(10);
writeln(b.length); // 10
writeln(alloc.empty); // Ternary.no

```
 
 
Allocator **parent**;  
If `ParentAllocator` is stateful, `parent` is a property giving access to an `AffixAllocator!ParentAllocator`. Otherwise, `parent` is an alias for `AffixAllocator!ParentAllocator.instance`.

  enum auto **alignment**;  
Alignment offered

  size\_t **goodAllocSize**(size\_t n);  
Forwards to `parent.goodAllocSize` (which accounts for the management overhead).

  void[] **allocate**(size\_t n);  
Allocates memory. For management it actually allocates extra memory from the parent.

  bool **expand**(ref void[] b, size\_t delta);  
Forwards to `parent.expand(b, delta)`.

  bool **reallocate**(ref void[] b, size\_t s);  
Reallocates `b` to new size `s`.

  Ternary **owns**(void[] b);  
Forwards to `parent.owns(b)`.

  bool **deallocate**(void[] b);  
Deallocates `b`.

  bool **deallocateAll**();  
Deallocates all memory allocated.

  const pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if this allocator is not responsible for any memory, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.)

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_scoped_allocator.html>

std.experimental.allocator.building\_blocks.segregator
======================================================

 
Source
 [std/experimental/allocator/building\_blocks/segregator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/segregator.d)

 
struct **Segregator**(size\_t threshold, SmallAllocator, LargeAllocator);  
Dispatches allocations (and deallocations) between two allocators (`SmallAllocator` and `LargeAllocator`) depending on the size allocated, as follows. All allocations smaller than or equal to `threshold` will be dispatched to `SmallAllocator`. The others will go to `LargeAllocator`. 


If both allocators are `shared`, the `Segregator` will also offer `shared` methods.

 
Examples:


```
import std.experimental.allocator.building_blocks.free_list : FreeList;
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.experimental.allocator.mallocator : Mallocator;
alias A =
    Segregator!(
        1024 * 4,
        Segregator!(
            128, FreeList!(Mallocator, 0, 128),
            GCAllocator),
        Segregator!(
            1024 * 1024, Mallocator,
            GCAllocator)
        );
A a;
auto b = a.allocate(200);
writeln(b.length); // 200
a.deallocate(b);

```
 
 
enum uint **alignment**;  
The alignment offered is the minimum of the two allocators' alignment.

  static size\_t **goodAllocSize**(size\_t s);  
This method is defined only if at least one of the allocators defines it. The good allocation size is obtained from `SmallAllocator` if  `s <= threshold`, or `LargeAllocator` otherwise. (If one of the allocators does not define `goodAllocSize`, the default implementation in this module applies.)

  void[] **allocate**(size\_t);  
The memory is obtained from `SmallAllocator` if `s <= threshold`, or `LargeAllocator` otherwise.

  void[] **alignedAllocate**(size\_t, uint);  
This method is defined if both allocators define it, and forwards to `SmallAllocator` or `LargeAllocator` appropriately.

  bool **expand**(ref void[] b, size\_t delta);  
This method is defined only if at least one of the allocators defines it. If `SmallAllocator` defines `expand` and `b.length + delta <= threshold`, the call is forwarded to `SmallAllocator`. If  `LargeAllocator` defines `expand` and `b.length > threshold`, the call is forwarded to `LargeAllocator`. Otherwise, the call returns `false`.

  bool **reallocate**(ref void[] b, size\_t s);  
This method is defined only if at least one of the allocators defines it. If `SmallAllocator` defines `reallocate` and `b.length <= threshold && s <= threshold`, the call is forwarded to  `SmallAllocator`. If `LargeAllocator` defines `expand` and  `b.length > threshold && s > threshold`, the call is forwarded to  `LargeAllocator`. Otherwise, the call returns `false`.

  bool **alignedReallocate**(ref void[] b, size\_t s, uint a);  
This method is defined only if at least one of the allocators defines it, and work similarly to `reallocate`.

  Ternary **owns**(void[] b);  
This method is defined only if both allocators define it. The call is forwarded to `SmallAllocator` if `b.length <= threshold`, or  `LargeAllocator` otherwise.

  bool **deallocate**(void[] b);  
This function is defined only if both allocators define it, and forwards appropriately depending on `b.length`.

  bool **deallocateAll**();  
This function is defined only if both allocators define it, and calls `deallocateAll` for them in turn.

  Ternary **empty**();  
This function is defined only if both allocators define it, and returns the conjunction of `empty` calls for the two.

  ref auto **allocatorForSize**(size\_t s)();  
Composite allocators involving nested instantiations of `Segregator` make it difficult to access individual sub-allocators stored within.  `allocatorForSize` simplifies the task by supplying the allocator nested inside a `Segregator` that is responsible for a specific size `s`. 



Example


```
alias A = Segregator!(300,
    Segregator!(200, A1, A2),
    A3);
A a;
static assert(typeof(a.allocatorForSize!10) == A1);
static assert(typeof(a.allocatorForSize!250) == A2);
static assert(typeof(a.allocatorForSize!301) == A3);

```
    template **Segregator**(Args...) if (Args.length > 3) 
A `Segregator` with more than three arguments expands to a composition of elemental `Segregator`s, as illustrated by the following example: 



```
alias A =
    Segregator!(
        n1, A1,
        n2, A2,
        n3, A3,
        A4
    );

```
   
  
 With this definition, allocation requests for `n1` bytes or less are directed to `A1`; requests between `n1 + 1` and `n2` bytes (inclusive) are directed to `A2`; requests between `n2 + 1` and `n3` bytes (inclusive) are directed to `A3`; and requests for more than `n3` bytes are directed to `A4`. If some particular range should not be handled, `NullAllocator` may be used appropriately.

 
Examples:


```
import std.experimental.allocator.building_blocks.free_list : FreeList;
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.experimental.allocator.mallocator : Mallocator;
alias A =
    Segregator!(
        128, FreeList!(Mallocator, 0, 128),
        1024 * 4, GCAllocator,
        1024 * 1024, Mallocator,
        GCAllocator
    );
A a;
auto b = a.allocate(201);
writeln(b.length); // 201
a.deallocate(b);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_segregator.html>

std.experimental.allocator.common
=================================

 Utility and ancillary artifacts of `std.experimental.allocator`. This module shouldn't be used directly; its functionality will be migrated into more appropriate parts of `std`. 



Authors:

[Andrei Alexandrescu](http://erdani.com), Timon Gehr (`Ternary`) 
 
Source
 [std/experimental/allocator/common.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/common.d)

 
template **stateSize**(T) 
Returns the size in bytes of the state that needs to be allocated to hold an object of type `T`. `stateSize!T` is zero for `struct`s that are not nested and have no nonstatic member variables.

  enum auto **hasStaticallyKnownAlignment**(Allocator);  
Returns `true` if the `Allocator` has the alignment known at compile time; otherwise it returns `false`.

  enum ulong **chooseAtRuntime**;  
`chooseAtRuntime` is a compile-time constant of type `size_t` that several parameterized structures in this module recognize to mean deferral to runtime of the exact value. For example, `BitmappedBlock!(Allocator, 4096)` (described in detail below) defines a block allocator with block size of 4096 bytes, whereas `BitmappedBlock!(Allocator, chooseAtRuntime)` defines a block allocator that has a field storing the block size, initialized by the user.

  enum ulong **unbounded**;  
`unbounded` is a compile-time constant of type `size_t` that several parameterized structures in this module recognize to mean "infinite" bounds for the parameter. For example, `Freelist` (described in detail below) accepts a `maxNodes` parameter limiting the number of freelist items. If `unbounded` is passed for `maxNodes`, then there is no limit and no checking for the number of nodes.

  enum uint **platformAlignment**;  
The alignment that is guaranteed to accommodate any D object allocation on the current platform.

  size\_t **goodAllocSize**(A)(auto ref A a, size\_t n);  
The default good size allocation is deduced as `n` rounded up to the allocator's alignment.

  bool **reallocate**(Allocator)(ref Allocator a, ref void[] b, size\_t s);  
The default `reallocate` function first attempts to use `expand`. If `Allocator.expand` is not defined or returns `false`, `reallocate` allocates a new block of memory of appropriate size and copies data from the old block to the new block. Finally, if `Allocator` defines `deallocate`, `reallocate` uses it to free the old memory block. 


`reallocate` does not attempt to use `Allocator.reallocate` even if defined. This is deliberate so allocators may use it internally within their own implementation of `reallocate`.

  bool **alignedReallocate**(Allocator)(ref Allocator alloc, ref void[] b, size\_t s, uint a)  
 Constraints: if (hasMember!(Allocator, "alignedAllocate")); 
 
The default `alignedReallocate` function first attempts to use `expand`. If `Allocator.expand` is not defined or returns `false`, `alignedReallocate` allocates a new block of memory of appropriate size and copies data from the old block to the new block. Finally, if `Allocator` defines `deallocate`, `alignedReallocate` uses it to free the old memory block. 


`alignedReallocate` does not attempt to use `Allocator.reallocate` even if defined. This is deliberate so allocators may use it internally within their own implementation of `reallocate`.

  string **forwardToMember**(string member, string[] funs...);  
Forwards each of the methods in `funs` (if defined) to `member`.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_common.html>

std.experimental.allocator.building\_blocks.region
==================================================

 
Source
 [std/experimental/allocator/building\_blocks/region.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/region.d)

 
struct **Region**(ParentAllocator = NullAllocator, uint minAlign = platformAlignment, Flag!"growDownwards" growDownwards = No.growDownwards);  
A `Region` allocator allocates memory straight from one contiguous chunk. There is no deallocation, and once the region is full, allocation requests return `null`. Therefore, `Region`s are often used (a) in conjunction with more sophisticated allocators; or (b) for batch-style very fast allocations that deallocate everything at once. 


The region only stores three pointers, corresponding to the current position in the store and the limits. One allocation entails rounding up the allocation size for alignment purposes, bumping the current pointer, and comparing it against the limit.   
  
 If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), `Region` deallocates the chunk of memory during destruction.   
  
 The `minAlign` parameter establishes alignment. If `minAlign > 1`, the sizes of all allocation requests are rounded up to a multiple of `minAlign`. Applications aiming at maximum speed may want to choose `minAlign = 1` and control alignment externally.

 
Examples:


```
import std.algorithm.comparison : max;
import std.experimental.allocator.building_blocks.allocator_list
    : AllocatorList;
import std.experimental.allocator.mallocator : Mallocator;
import std.typecons : Ternary;
// Create a scalable list of regions. Each gets at least 1MB at a time by
// using malloc.
auto batchAllocator = AllocatorList!(
    (size_t n) => Region!Mallocator(max(n, 1024 * 1024))
)();
writeln(batchAllocator.empty); // Ternary.yes
auto b = batchAllocator.allocate(101);
writeln(b.length); // 101
writeln(batchAllocator.empty); // Ternary.no
// This will cause a second allocation
b = batchAllocator.allocate(2 * 1024 * 1024);
writeln(b.length); // 2 * 1024 * 1024
// Destructor will free the memory

```
 
 
ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  pure nothrow @nogc this(ubyte[] store);   
  
this(size\_t n);   
  
this(ParentAllocator parent, size\_t n);  
Constructs a region backed by a user-provided store. Assumes the memory was allocated with `ParentAllocator` (if different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)). 



Parameters:


|  |  |
| --- | --- |
| ubyte[] `store` | User-provided store backing up the region. If  `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), memory is assumed to have been allocated with `ParentAllocator`. |
| size\_t `n` | Bytes to allocate using `ParentAllocator`. This constructor is only defined If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator). If `parent.allocate(n)` returns `null`, the region will be initialized as empty (correctly initialized but unable to allocate). |


  const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Rounds the given size to a multiple of the `alignment`

  alias **alignment** = minAlign;  
Alignment offered.

  pure nothrow @nogc @trusted void[] **allocate**(size\_t n);  
Allocates `n` bytes of memory. The shortest path involves an alignment adjustment (if `alignment > 1`), an increment, and a comparison. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |


 
Returns:
A properly-aligned buffer of size `n` or `null` if request could not be satisfied.
  pure nothrow @nogc @trusted void[] **alignedAllocate**(size\_t n, uint a);  
Allocates `n` bytes of memory aligned at alignment `a`. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |
| uint `a` | alignment for the allocated block |


 
Returns:
Either a suitable block of `n` bytes aligned at `a`, or `null`.
  pure nothrow @nogc @trusted void[] **allocateAll**();  
Allocates and returns all memory available to this region.

  pure nothrow @nogc @safe bool **expand**(ref void[] b, size\_t delta);  
Expands an allocated block in place. Expansion will succeed only if the block is the last allocated. Defined only if `growDownwards` is `No.growDownwards`.

  pure nothrow @nogc bool **deallocate**(void[] b);  
Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). |


  pure nothrow @nogc bool **deallocateAll**();  
Deallocates all memory allocated by this region, which can be subsequently reused for new allocations.

  const pure nothrow @nogc @trusted Ternary **owns**(const void[] b);  
Queries whether `b` has been allocated with this region. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | Arbitrary block of memory (`null` is allowed; `owns(null)` returns `false`). |


 
Returns:

`true` if `b` has been allocated with this region, `false` otherwise.
  const pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if no memory has been allocated in this region, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.)

  const pure nothrow @nogc @safe size\_t **available**();  
Nonstandard property that returns bytes available for allocation.

    struct **InSituRegion**(size\_t size, size\_t minAlign = platformAlignment);  
`InSituRegion` is a convenient region that carries its storage within itself (in the form of a statically-sized array). 


The first template argument is the size of the region and the second is the needed alignment. Depending on the alignment requested and platform details, the actual available storage may be smaller than the compile-time parameter. To make sure that at least `n` bytes are available in the region, use `InSituRegion!(n + a - 1, a)`.   
  
 Given that the most frequent use of `InSituRegion` is as a stack allocator, it allocates starting at the end on systems where stack grows downwards, such that hot memory is used first.

 
Examples:


```
// 128KB region, allocated to x86's cache line
InSituRegion!(128 * 1024, 16) r1;
auto a1 = r1.allocate(101);
writeln(a1.length); // 101

// 128KB region, with fallback to the garbage collector.
import std.experimental.allocator.building_blocks.fallback_allocator
    : FallbackAllocator;
import std.experimental.allocator.building_blocks.free_list
    : FreeList;
import std.experimental.allocator.building_blocks.bitmapped_block
    : BitmappedBlock;
import std.experimental.allocator.gc_allocator : GCAllocator;
FallbackAllocator!(InSituRegion!(128 * 1024), GCAllocator) r2;
const a2 = r2.allocate(102);
writeln(a2.length); // 102

// Reap with GC fallback.
InSituRegion!(128 * 1024, 8) tmp3;
FallbackAllocator!(BitmappedBlock!(64, 8), GCAllocator) r3;
r3.primary = BitmappedBlock!(64, 8)(cast(ubyte[]) (tmp3.allocateAll()));
const a3 = r3.allocate(103);
writeln(a3.length); // 103

// Reap/GC with a freelist for small objects up to 16 bytes.
InSituRegion!(128 * 1024, 64) tmp4;
FreeList!(FallbackAllocator!(BitmappedBlock!(64, 64), GCAllocator), 0, 16) r4;
r4.parent.primary = BitmappedBlock!(64, 64)(cast(ubyte[]) (tmp4.allocateAll()));
const a4 = r4.allocate(104);
writeln(a4.length); // 104

```
 
 
alias **alignment** = minAlign;  
An alias for `minAlign`, which must be a valid alignment (nonzero power of 2). The start of the region and all allocation requests will be rounded up to a multiple of the alignment. 



```
InSituRegion!(4096) a1;
assert(a1.alignment == platformAlignment);
InSituRegion!(4096, 64) a2;
assert(a2.alignment == 64);

```
 

  void[] **allocate**(size\_t n);  
Allocates `bytes` and returns them, or `null` if the region cannot accommodate the request. For efficiency reasons, if `bytes == 0` the function returns an empty non-null slice.

  void[] **alignedAllocate**(size\_t n, uint a);  
As above, but the memory allocated is aligned at `a` bytes.

  bool **deallocate**(void[] b);  
Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. This semantics is tricky and therefore `deallocate` is defined only if `Region` is instantiated with `Yes.defineDeallocate` as the third template argument. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). |


  pure nothrow @nogc @safe Ternary **owns**(const void[] b);  
Returns `Ternary.yes` if `b` is the result of a previous allocation, `Ternary.no` otherwise.

  bool **expand**(ref void[] b, size\_t delta);  
Expands an allocated block in place. Expansion will succeed only if the block is the last allocated.

  bool **deallocateAll**();  
Deallocates all memory allocated with this allocator.

  void[] **allocateAll**();  
Allocates all memory available with this allocator.

  size\_t **available**();  
Nonstandard function that returns the bytes available for allocation.

    struct **SbrkRegion**(uint minAlign = platformAlignment);  
Allocator backed by `[sbrk](https://en.wikipedia.org/wiki/Sbrk)` for Posix systems. Due to the fact that `sbrk` is not thread-safe [by design](http://lifecs.likai.org/2010/02/sbrk-is-not-thread-safe.html), `SbrkRegion` uses a mutex internally. This implies that uncontrolled calls to `brk` and `sbrk` may affect the workings of `SbrkRegion` adversely. 

 
static shared SbrkRegion **instance**;  
Instance shared by all callers.

  enum uint **alignment**;  
Standard allocator primitives.

  shared const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);   
  
shared nothrow @nogc @trusted void[] **allocate**(size\_t bytes);   
  
shared nothrow @nogc @trusted void[] **alignedAllocate**(size\_t bytes, uint a);  
Rounds the given size to a multiple of thew `alignment`

  shared nothrow @nogc @trusted bool **expand**(ref void[] b, size\_t delta);   
  
shared pure nothrow @nogc @trusted Ternary **owns**(const void[] b);  
The `expand` method may only succeed if the argument is the last block allocated. In that case, `expand` attempts to push the break pointer to the right. 

  shared nothrow @nogc bool **deallocate**(void[] b);  
The `deallocate` method only works (and returns `true`) on systems that support reducing the break address (i.e. accept calls to `sbrk` with negative offsets). OSX does not accept such. In addition the argument must be the last block allocated. 

  shared nothrow @nogc bool **deallocateAll**();  
The `deallocateAll` method only works (and returns `true`) on systems that support reducing the break address (i.e. accept calls to `sbrk` with negative offsets). OSX does not accept such.

  shared pure nothrow @nogc @safe Ternary **empty**();  
Standard allocator API.

    struct **SharedRegion**(ParentAllocator = NullAllocator, uint minAlign = platformAlignment, Flag!"growDownwards" growDownwards = No.growDownwards);  
The threadsafe version of the `Region` allocator. Allocations and deallocations are lock-free based using [`core.atomic.cas`](core_atomic#cas).

 
ParentAllocator **parent**;  
The parent allocator. Depending on whether `ParentAllocator` holds state or not, this is a member variable or an alias for `ParentAllocator.instance`.

  pure nothrow @nogc this(ubyte[] store);   
  
this(size\_t n);  
Constructs a region backed by a user-provided store. Assumes the memory was allocated with `ParentAllocator` (if different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator)). 



Parameters:


|  |  |
| --- | --- |
| ubyte[] `store` | User-provided store backing up the region. If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator), memory is assumed to have been allocated with `ParentAllocator`. |
| size\_t `n` | Bytes to allocate using `ParentAllocator`. This constructor is only defined If `ParentAllocator` is different from [`NullAllocator`](std_experimental_allocator_building_blocks_null_allocator#NullAllocator). If `parent.allocate(n)` returns `null`, the region will be initialized as empty (correctly initialized but unable to allocate). |


  const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Rounds the given size to a multiple of the `alignment`

  alias **alignment** = minAlign;  
Alignment offered.

  pure nothrow @nogc @trusted void[] **allocate**(size\_t n);  
Allocates `n` bytes of memory. The allocation is served by atomically incrementing a pointer which keeps track of the current used space. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |


 
Returns:
A properly-aligned buffer of size `n`, or `null` if request could not be satisfied.
  pure nothrow @nogc bool **deallocate**(void[] b);  
Deallocates `b`. This works only if `b` was obtained as the last call to `allocate`; otherwise (i.e. another allocation has occurred since) it does nothing. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | Block previously obtained by a call to `allocate` against this allocator (`null` is allowed). |


  pure nothrow @nogc bool **deallocateAll**();  
Deallocates all memory allocated by this region, which can be subsequently reused for new allocations.

  pure nothrow @nogc @trusted void[] **alignedAllocate**(size\_t n, uint a);  
Allocates `n` bytes of memory aligned at alignment `a`. 



Parameters:


|  |  |
| --- | --- |
| size\_t `n` | number of bytes to allocate |
| uint `a` | alignment for the allocated block |


 
Returns:
Either a suitable block of `n` bytes aligned at `a`, or `null`.
  const pure nothrow @nogc @trusted Ternary **owns**(const void[] b);  
Queries whether `b` has been allocated with this region. 



Parameters:


|  |  |
| --- | --- |
| void[] `b` | Arbitrary block of memory (`null` is allowed; `owns(null)` returns `false`). |


 
Returns:

`true` if `b` has been allocated with this region, `false` otherwise.
  const pure nothrow @nogc @safe Ternary **empty**();  
Returns `Ternary.yes` if no memory has been allocated in this region, `Ternary.no` otherwise. (Never returns `Ternary.unknown`.)

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_region.html>

std.experimental.allocator.building\_blocks.stats\_collector
============================================================

 Allocator that collects useful statistics about allocations, both global and per calling point. The statistics collected can be configured statically by choosing combinations of `Options` appropriately. 



Source
 [std/experimental/allocator/building\_blocks/stats\_collector.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/building_blocks/stats_collector.d)

 
Examples:


```
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.experimental.allocator.building_blocks.free_list : FreeList;
alias Allocator = StatsCollector!(GCAllocator, Options.bytesUsed);

```
 
 
enum **Options**: ulong;  
Options for `StatsCollector` defined below. Each enables during compilation one specific counter, statistic, or other piece of information.

 
**numOwns** 
Counts the number of calls to `owns`.

  **numAllocate** 
Counts the number of calls to `allocate`. All calls are counted, including requests for zero bytes or failed requests.

  **numAllocateOK** 
Counts the number of calls to `allocate` that succeeded, i.e. they returned a block as large as requested. (N.B. requests for zero bytes count as successful.)

  **numExpand** 
Counts the number of calls to `expand`, regardless of arguments or result.

  **numExpandOK** 
Counts the number of calls to `expand` that resulted in a successful expansion.

  **numReallocate** 
Counts the number of calls to `reallocate`, regardless of arguments or result.

  **numReallocateOK** 
Counts the number of calls to `reallocate` that succeeded. (Reallocations to zero bytes count as successful.)

  **numReallocateInPlace** 
Counts the number of calls to `reallocate` that resulted in an in-place reallocation (no memory moved). If this number is close to the total number of reallocations, that indicates the allocator finds room at the current block's end in a large fraction of the cases, but also that internal fragmentation may be high (the size of the unit of allocation is large compared to the typical allocation size of the application).

  **numDeallocate** 
Counts the number of calls to `deallocate`.

  **numDeallocateAll** 
Counts the number of calls to `deallocateAll`.

  **numAlignedAllocate** 
Counts the number of calls to `alignedAllocate`. All calls are counted, including requests for zero bytes or failed requests.

  **numAlignedAllocateOk** 
Counts the number of calls to `alignedAllocate` that succeeded, i.e. they returned a block as large as requested. (N.B. requests for zero bytes count as successful.)

  **numAll** 
Chooses all `numXxx` flags.

  **bytesUsed** 
Tracks bytes currently allocated by this allocator. This number goes up and down as memory is allocated and deallocated, and is zero if the allocator currently has no active allocation.

  **bytesAllocated** 
Tracks total cumulative bytes allocated by means of `allocate`, `expand`, and `reallocate` (when resulting in an expansion). This number always grows and indicates allocation traffic. To compute bytes deallocated cumulatively, subtract `bytesUsed` from `bytesAllocated`.

  **bytesExpanded** 
Tracks the sum of all `delta` values in calls of the form `expand(b, delta)` that succeed (return `true`).

  **bytesContracted** 
Tracks the sum of all `b.length - s` with `b.length > s` in calls of the form `realloc(b, s)` that succeed (return `true`). In per-call statistics, also unambiguously counts the bytes deallocated with `deallocate`.

  **bytesMoved** 
Tracks the sum of all bytes moved as a result of calls to `realloc` that were unable to reallocate in place. A large number (relative to  `bytesAllocated`) indicates that the application should use larger preallocations.

  **bytesNotMoved** 
Tracks the sum of all bytes NOT moved as result of calls to `realloc` that managed to reallocate in place. A large number (relative to  `bytesAllocated`) indicates that the application is expansion-intensive and is saving a good amount of moves. However, if this number is relatively small and `bytesSlack` is high, it means the application is overallocating for little benefit.

  **bytesSlack** 
Measures the sum of extra bytes allocated beyond the bytes requested, i.e. the [internal fragmentation](http://goo.gl/YoKffF). This is the current effective number of slack bytes, and it goes up and down with time.

  **bytesHighTide** 
Measures the maximum bytes allocated over the time. This is useful for dimensioning allocators.

  **bytesAll** 
Chooses all `byteXxx` flags.

  **all** 
Combines all flags above.

    struct **StatsCollector**(Allocator, ulong flags = Options.all, ulong perCallFlags = 0);  
Allocator that collects extra data about allocations. Since each piece of information adds size and time overhead, statistics can be individually enabled or disabled through compile-time `flags`. 


All stats of the form `numXxx` record counts of events occurring, such as calls to functions and specific results. The stats of the form `bytesXxx` collect cumulative sizes.   
  
 In addition, the data `callerSize`, `callerModule`, `callerFile`, `callerLine`, and `callerTime` is associated with each specific allocation. This data prefixes each allocation.

 
Examples:


```
import std.experimental.allocator.building_blocks.free_list : FreeList;
import std.experimental.allocator.gc_allocator : GCAllocator;
alias Allocator = StatsCollector!(GCAllocator, Options.all, Options.all);

Allocator alloc;
auto b = alloc.allocate(10);
alloc.reallocate(b, 20);
alloc.deallocate(b);

import std.file : deleteme, remove;
import std.range : walkLength;
import std.stdio : File;

auto f = deleteme ~ "-dlang.std.experimental.allocator.stats_collector.txt";
scope(exit) remove(f);
Allocator.reportPerCallStatistics(File(f, "w"));
alloc.reportStatistics(File(f, "a"));
writeln(File(f).byLine.walkLength); // 24

```
 
 
Allocator **parent**;  
The parent allocator is publicly accessible either as a direct member if it holds state, or as an alias to `Allocator.instance` otherwise. One may use it for making calls that won't count toward statistics collection.

  alias **alignment** = Allocator.**alignment**;  
Alignment offered is equal to `Allocator.alignment`.

  Ternary **owns**(void[] b);  
Increments `numOwns` (per instance and and per call) and forwards to  `parent.owns(b)`.

  void[] **allocate**(size\_t n);  
Forwards to `parent.allocate`. Affects per instance: `numAllocate`, `bytesUsed`, `bytesAllocated`, `bytesSlack`, `numAllocateOK`, and `bytesHighTide`. Affects per call: `numAllocate`,  `numAllocateOK`, and `bytesAllocated`.

  void[] **alignedAllocate**(size\_t n, uint a);  
Forwards to `parent.alignedAllocate`. Affects per instance: `numAlignedAllocate`, `bytesUsed`, `bytesAllocated`, `bytesSlack`, `numAlignedAllocateOk`, and `bytesHighTide`. Affects per call: `numAlignedAllocate`, `numAlignedAllocateOk`, and `bytesAllocated`.

  bool **expand**(ref void[] b, size\_t delta);  
Defined whether or not `Allocator.expand` is defined. Affects per instance: `numExpand`, `numExpandOK`, `bytesExpanded`, `bytesSlack`, `bytesAllocated`, and `bytesUsed`. Affects per call: `numExpand`, `numExpandOK`, `bytesExpanded`, and `bytesAllocated`.

  bool **reallocate**(ref void[] b, size\_t s);  
Defined whether or not `Allocator.reallocate` is defined. Affects per instance: `numReallocate`, `numReallocateOK`,  `numReallocateInPlace`, `bytesNotMoved`, `bytesAllocated`,  `bytesSlack`, `bytesExpanded`, and `bytesContracted`. Affects per call: `numReallocate`, `numReallocateOK`, `numReallocateInPlace`, `bytesNotMoved`, `bytesExpanded`, `bytesContracted`, and `bytesMoved`.

  bool **deallocate**(void[] b);  
Defined whether or not `Allocator.deallocate` is defined. Affects per instance: `numDeallocate`, `bytesUsed`, and `bytesSlack`. Affects per call: `numDeallocate` and `bytesContracted`.

  bool **deallocateAll**();  
Defined only if `Allocator.deallocateAll` is defined. Affects per instance and per call `numDeallocateAll`.

  pure nothrow @nogc @safe Ternary **empty**();  
Defined only if `Options.bytesUsed` is defined. Returns `bytesUsed == 0`.

  void **reportStatistics**(R)(auto ref R output);  
Reports per instance statistics to `output` (e.g. `stdout`). The format is simple: one kind and value per line, separated by a colon, e.g. `bytesAllocated:7395404`

  struct **PerCallStatistics**;  
Defined if `perCallFlags` is nonzero.

 
string **file**;   
  
uint **line**;  
The file and line of the call.

  Options[] **opts**;  
The options corresponding to the statistics collected.

  ulong[] **values**;  
The values of the statistics. Has the same length as `opts`.

  const string **toString**();  
Format to a string such as: `mymodule.d(655): [numAllocate:21, numAllocateOK:21, bytesAllocated:324202]`.

    static auto **byFileLine**();  
Defined if `perCallFlags` is nonzero. Iterates all monitored file/line instances. The order of iteration is not meaningful (items are inserted at the front of a list upon the first call), so preprocessing the statistics after collection might be appropriate.

  void **reportPerCallStatistics**(R)(auto ref R output);  
Defined if `perCallFlags` is nonzero. Outputs (e.g. to a `File`) a simple report of the collected per-call statistics.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_building_blocks_stats_collector.html>

std.experimental.allocator.gc\_allocator
========================================

 D's built-in garbage-collected allocator. 



Source
 [std/experimental/allocator/gc\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/gc_allocator.d)

 
struct **GCAllocator**;  
D's built-in garbage-collected allocator.



Examples:


```
auto buffer = GCAllocator.instance.allocate(1024 * 1024 * 4);
// deallocate upon scope's end (alternatively: leave it to collection)
scope(exit) GCAllocator.instance.deallocate(buffer);
//...

```
 
 
enum uint **alignment**;  
The alignment is a static constant equal to `platformAlignment`, which ensures proper alignment for any D data type.

  shared const pure nothrow @trusted void[] **allocate**(size\_t bytes);   
  
shared const pure nothrow @trusted bool **expand**(ref void[] b, size\_t delta);   
  
shared const pure nothrow @system bool **reallocate**(ref void[] b, size\_t newSize);   
  
shared const pure nothrow @nogc @trusted Ternary **resolveInternalPointer**(const void\* p, ref void[] result);   
  
shared const pure nothrow @nogc @system bool **deallocate**(void[] b);   
  
shared const pure nothrow @nogc @safe size\_t **goodAllocSize**(size\_t n);  
Standard allocator methods per the semantics defined above. The  `deallocate` and `reallocate` methods are `@system` because they may move memory around, leaving dangling pointers in user code.

  static shared const GCAllocator **instance**;  
Returns the global instance of this allocator type. The garbage collected allocator is thread-safe, therefore all of its methods and `instance` itself are `shared`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_gc_allocator.html>

std.experimental.allocator.mallocator
=====================================

 The C heap allocator. 



Source
 [std/experimental/allocator/mallocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/mallocator.d)

 
struct **Mallocator**;  
The C heap allocator.



Examples:


```
auto buffer = Mallocator.instance.allocate(1024 * 1024 * 4);
scope(exit) Mallocator.instance.deallocate(buffer);
//...

```
 
 
enum uint **alignment**;  
The alignment is a static constant equal to `platformAlignment`, which ensures proper alignment for any D data type.

  shared pure nothrow @nogc @trusted void[] **allocate**(size\_t bytes);   
  
shared pure nothrow @nogc @system bool **deallocate**(void[] b);   
  
shared pure nothrow @nogc @system bool **reallocate**(ref void[] b, size\_t s);  
Standard allocator methods per the semantics defined above. The `deallocate` and `reallocate` methods are `@system` because they may move memory around, leaving dangling pointers in user code. Somewhat paradoxically, `malloc` is `@safe` but that's only useful to safe programs that can afford to leak memory allocated.

  static shared Mallocator **instance**;  
Returns the global instance of this allocator type. The C heap allocator is thread-safe, therefore all of its methods and `it` itself are `shared`.

    struct **AlignedMallocator**;  
Aligned allocator using OS-specific primitives, under a uniform API.



Examples:


```
auto buffer = AlignedMallocator.instance.alignedAllocate(1024 * 1024 * 4,
    128);
scope(exit) AlignedMallocator.instance.deallocate(buffer);
//...

```
 
 
enum uint **alignment**;  
The default alignment is `platformAlignment`.

  shared nothrow @nogc @trusted void[] **allocate**(size\_t bytes);  
Forwards to `alignedAllocate(bytes, platformAlignment)`.

  shared nothrow @nogc @trusted void[] **alignedAllocate**(size\_t bytes, uint a);  
Uses  [`posix_memalign`](http://man7.org/linux/man-pages/man3/posix_memalign.3.html) on Posix and  [`__aligned_malloc`](http://msdn.microsoft.com/en-us/library/8z34s9c6(v=vs.80).aspx) on Windows.

  shared nothrow @nogc @system bool **deallocate**(void[] b);  
Calls `free(b.ptr)` on Posix and  [`__aligned_free(b.ptr)`](http://msdn.microsoft.com/en-US/library/17b5h8td(v=vs.80).aspx) on Windows.

  shared nothrow @nogc @system bool **reallocate**(ref void[] b, size\_t newSize);   
  
shared nothrow @nogc @system bool **alignedReallocate**(ref void[] b, size\_t s, uint a);  
Forwards to `alignedReallocate(b, newSize, platformAlignment)`. Should be used with blocks obtained with `allocate` otherwise the custom alignment passed with `alignedAllocate` can be lost.

  static shared AlignedMallocator **instance**;  
Returns the global instance of this allocator type. The C heap allocator is thread-safe, therefore all of its methods and `instance` itself are `shared`.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_mallocator.html>

std.experimental.allocator.mmap\_allocator
==========================================

 
Source
 [std/experimental/allocator/mmap\_allocator.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/mmap_allocator.d)

 
struct **MmapAllocator**;  
Allocator (currently defined only for Posix and Windows) using `[mmap](https://en.wikipedia.org/wiki/Mmap)` and `[munmap](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=munmap)` directly (or their Windows equivalents). There is no additional structure: each call to `allocate(s)` issues a call to `mmap(null, s, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`, and each call to `deallocate(b)` issues `munmap(b.ptr, b.length)`. So `MmapAllocator` is usually intended for allocating large chunks to be managed by fine-granular allocators.

 
static shared const MmapAllocator **instance**;  
The one shared instance.

  enum size\_t **alignment**;  
Alignment is page-size and hardcoded to 4096 (even though on certain systems it could be larger).

  shared const pure nothrow @nogc @safe void[] **allocate**(size\_t bytes);   
  
shared const pure nothrow @nogc bool **deallocate**(void[] b);  
Allocator API.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_mmap_allocator.html>

std.experimental.allocator.showcase
===================================

 Collection of typical and useful prebuilt allocators using the given components. User code would typically import this module and use its facilities, or import individual heap building blocks and assemble them. 



Source
 [std/experimental/allocator/showcase.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/showcase.d)

 
template **StackFront**(size\_t stackSize, Allocator = GCAllocator) 
Allocator that uses stack allocation for up to `stackSize` bytes and then falls back to `Allocator`. Defined as: 



```
alias StackFront(size_t stackSize, Allocator) =
    FallbackAllocator!(
        InSituRegion!(stackSize, Allocator.alignment,
            hasMember!(Allocator, "deallocate")
                ? Yes.defineDeallocate
                : No.defineDeallocate),
        Allocator);

```
   
  
 Choosing `stackSize` is as always a compromise. Too small a size exhausts the stack storage after a few allocations, after which there are no gains over the backup allocator. Too large a size increases the stack consumed by the thread and may end up worse off because it explores cold portions of the stack.

 
Examples:


```
StackFront!4096 a;
auto b = a.allocate(4000);
writeln(b.length); // 4000
auto c = a.allocate(4000);
writeln(c.length); // 4000
a.deallocate(b);
a.deallocate(c);

```
 
  auto **mmapRegionList**(size\_t bytesPerRegion);  
Creates a scalable `AllocatorList` of `Regions`, each having at least `bytesPerRegion` bytes. Allocation is very fast. This allocator does not offer `deallocate` but does free all regions in its destructor. It is recommended for short-lived batch applications that count on never running out of memory.



Examples:


```
auto alloc = mmapRegionList(1024 * 1024);
const b = alloc.allocate(100);
writeln(b.length); // 100

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_showcase.html>

std.experimental.allocator.typed
================================

 This module defines `TypedAllocator`, a statically-typed allocator that aggregates multiple untyped allocators and uses them depending on the static properties of the types allocated. For example, distinct allocators may be used for thread-local vs. thread-shared data, or for fixed-size data (`struct`, `class` objects) vs. resizable data (arrays). 



Source
 [std/experimental/allocator/typed.d](https://github.com/dlang/phobos/blob/master/std/experimental/allocator/typed.d) 
 
enum **AllocFlag**: uint;  
Allocation-related flags dictated by type characteristics. `TypedAllocator` deduces these flags from the type being allocated and uses the appropriate allocator accordingly.

 
**fixedSize** 
Fixed-size allocation (unlikely to get reallocated later). Examples: `int`, `double`, any `struct` or `class` type. By default it is assumed that the allocation is variable-size, i.e. susceptible to later reallocation (for example all array types). This flag is advisory, i.e. in-place resizing may be attempted for `fixedSize` allocations and may succeed. The flag is just a hint to the compiler it may use allocation strategies that work well with objects of fixed size.

  **hasNoIndirections** 
The type being allocated embeds no pointers. Examples: `int`, `int[]`,  `Tuple!(int, float)`. The implicit conservative assumption is that the type has members with indirections so it needs to be scanned if garbage collected. Example of types with pointers: `int*[]`, `Tuple!(int, string)`.

  
**immutableShared**  
  
**threadLocal**
 
By default it is conservatively assumed that allocated memory may be `cast` to `shared`, passed across threads, and deallocated in a different thread than the one that allocated it. If that's not the case, there are two options. First, `immutableShared` means the memory is allocated for `immutable` data and will be deallocated in the same thread it was allocated in. Second, `threadLocal` means the memory is not to be shared across threads at all. The two flags cannot be simultaneously present.

    struct **TypedAllocator**(PrimaryAllocator, Policies...);  
`TypedAllocator` acts like a chassis on which several specialized allocators can be assembled. To let the system make a choice about a particular kind of allocation, use `Default` for the respective parameters. 


There is a hierarchy of allocation kinds. When an allocator is implemented for a given combination of flags, it is used. Otherwise, the next down the list is chosen.   
  
 

  
  
| `AllocFlag` combination | Description |
  
  
| `AllocFlag.threadLocal | AllocFlag.hasNoIndirections | AllocFlag.fixedSize` | This is the most specific allocation policy: the memory being allocated is thread local, has no indirections at all, and will not be reallocated. Examples of types fitting this description: `int`, `double`, `Tuple!(int, long)`, but not `Tuple!(int, string)`, which contains an indirection. |
  
  
| `AllocFlag.threadLocal | AllocFlag.hasNoIndirections` | As above, but may be reallocated later. Examples of types fitting this description are `int[]`, `double[]`, `Tuple!(int, long)[]`, but not `Tuple!(int, string)[]`, which contains an indirection. |
  
  
| `AllocFlag.threadLocal` | As above, but may embed indirections. Examples of types fitting this description are `int*[]`, `Object[]`, `Tuple!(int, string)[]`. |
  
  
| `AllocFlag.immutableShared | AllocFlag.hasNoIndirections | AllocFlag.fixedSize` | The type being allocated is `immutable` and has no pointers. The thread that allocated it must also deallocate it. Example: `immutable(int)`. |
  
  
| `AllocFlag.immutableShared | AllocFlag.hasNoIndirections` | As above, but the type may be appended to in the future. Example: `string`. |
  
  
| `AllocFlag.immutableShared` | As above, but the type may embed references. Example: `immutable(Object)[]`. |
  
  
| `AllocFlag.hasNoIndirections | AllocFlag.fixedSize` | The type being allocated may be shared across threads, embeds no indirections, and has fixed size. |
  
  
| `AllocFlag.hasNoIndirections` | The type being allocated may be shared across threads, may embed indirections, and has variable size. |
  
  
| `AllocFlag.fixedSize` | The type being allocated may be shared across threads, may embed indirections, and has fixed size. |
  
  
| `0` | The most conservative/general allocation: memory may be shared, deallocated in a different thread, may or may not be resized, and may embed references. |

 

 
Parameters:


|  |  |
| --- | --- |
| PrimaryAllocator | The default allocator. |
| Policies | Zero or more pairs consisting of an `AllocFlag` and an allocator type. |


 
Examples:


```
import std.experimental.allocator.gc_allocator : GCAllocator;
import std.experimental.allocator.mallocator : Mallocator;
import std.experimental.allocator.mmap_allocator : MmapAllocator;
alias MyAllocator = TypedAllocator!(GCAllocator,
    AllocFlag.fixedSize | AllocFlag.threadLocal, Mallocator,
    AllocFlag.fixedSize | AllocFlag.threadLocal
            | AllocFlag.hasNoIndirections,
        MmapAllocator,
);

MyAllocator a;
auto b = &a.allocatorFor!0();
static assert(is(typeof(*b) == shared const(GCAllocator)));
enum f1 = AllocFlag.fixedSize | AllocFlag.threadLocal;
auto c = &a.allocatorFor!f1();
static assert(is(typeof(*c) == Mallocator));
enum f2 = AllocFlag.fixedSize | AllocFlag.threadLocal;
static assert(is(typeof(a.allocatorFor!f2()) == Mallocator));
// Partial match
enum f3 = AllocFlag.threadLocal;
static assert(is(typeof(a.allocatorFor!f3()) == Mallocator));

int* p = a.make!int;
scope(exit) a.dispose(p);
int[] arr = a.makeArray!int(42);
scope(exit) a.dispose(arr);
assert(a.expandArray(arr, 3));
assert(a.shrinkArray(arr, 4));

```
 
 
ref auto **allocatorFor**(uint flags)();   
  
ref auto **allocatorFor**(T)();  
Given `flags` as a combination of `AllocFlag` values, or a type `T`, returns the allocator that's a closest fit in capabilities.

  uint **type2flags**(T)();  
Given a type `T`, returns its allocation-related flags as a combination of `AllocFlag` values.

  auto **make**(T, A...)(auto ref A args);  
Dynamically allocates (using the appropriate allocator chosen with `allocatorFor!T`) and then creates in the memory allocated an object of type `T`, using `args` (if any) for its initialization. Initialization occurs in the memory allocated and is otherwise semantically the same as `T(args)`. (Note that using `make!(T[])` creates a pointer to an (empty) array of `T`s, not an array. To allocate and initialize an array, use `makeArray!T` described below.) 



Parameters:


|  |  |
| --- | --- |
| T | Type of the object being created. |
| A `args` | Optional arguments used for initializing the created object. If not present, the object is default constructed. |


 
Returns:
If `T` is a class type, returns a reference to the created `T` object. Otherwise, returns a `T*` pointing to the created object. In all cases, returns `null` if allocation failed. 
 
Throws:
If `T`'s constructor throws, deallocates the allocated memory and propagates the exception.
  T[] **makeArray**(T)(size\_t length);   
  
T[] **makeArray**(T)(size\_t length, auto ref T init);   
  
T[] **makeArray**(T, R)(R range)  
 Constraints: if (isInputRange!R); 
 
Create an array of `T` with `length` elements. The array is either default-initialized, filled with copies of `init`, or initialized with values fetched from `range`. 



Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| size\_t `length` | length of the newly created array |
| T `init` | element used for filling the array |
| R `range` | range used for initializing the array elements |


 
Returns:
The newly-created array, or `null` if either `length` was `0` or allocation failed. 
 
Throws:
The first two overloads throw only if the used allocator's primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
  bool **expandArray**(T)(ref T[] array, size\_t delta);   
  
bool **expandArray**(T)(T[] array, size\_t delta, auto ref T init);   
  
bool **expandArray**(T, R)(ref T[] array, R range)  
 Constraints: if (isInputRange!R); 
 
Grows `array` by appending `delta` more elements. The needed memory is allocated using the same allocator that was used for the array type. The extra elements added are either default-initialized, filled with copies of `init`, or initialized with values fetched from `range`. 



Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| T[] `array` | a reference to the array being grown |
| size\_t `delta` | number of elements to add (upon success the new length of `array` is `array.length + delta`) |
| T `init` | element used for filling the array |
| R `range` | range used for initializing the array elements |


 
Returns:

`true` upon success, `false` if memory could not be allocated. In the latter case `array` is left unaffected. 
 
Throws:
The first two overloads throw only if the used allocator's primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
  bool **shrinkArray**(T)(ref T[] arr, size\_t delta);  
Shrinks an array by `delta` elements using `allocatorFor!(T[])`. 


If `arr.length < delta`, does nothing and returns `false`. Otherwise, destroys the last `arr.length - delta` elements in the array and then reallocates the array's buffer. If reallocation fails, fills the array with default-initialized data. 

 
Parameters:


|  |  |
| --- | --- |
| T | element type of the array being created |
| T[] `arr` | a reference to the array being shrunk |
| size\_t `delta` | number of elements to remove (upon success the new length of `arr` is `arr.length - delta`) |


 
Returns:

`true` upon success, `false` if memory could not be reallocated. In the latter case `arr[$ - delta .. $]` is left with default-initialized elements. 
 
Throws:
The first two overloads throw only if the used allocator's primitives do. The overloads that involve copy initialization deallocate memory and propagate the exception if the copy operation throws.
  void **dispose**(T)(T\* p);   
  
void **dispose**(T)(T p)  
 Constraints: if (is(T == class) || is(T == interface));   
  
void **dispose**(T)(T[] array);  
Destroys and then deallocates (using `allocatorFor!T`) the object pointed to by a pointer, the class object referred to by a `class` or `interface` reference, or an entire array. It is assumed the respective entities had been allocated with the same allocator.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_allocator_typed.html>

std.experimental.logger
=======================

 Implements logging facilities. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
 [Robert burner Schadek](http://www.svs.informatik.uni-oldenburg.de/60865.html) ### Basic Logging

 Message logging is a common approach to expose runtime information of a program. Logging should be easy, but also flexible and powerful, therefore `D` provides a standard interface for logging. The easiest way to create a log message is to write: 
```
import std.experimental.logger;

void main() {
    log("Hello World");
}

```
 This will print a message to the `stderr` device. The message will contain the filename, the line number, the name of the surrounding function, the time and the message. More complex log call can go along the lines like: 
```
log("Logging to the sharedLog with its default LogLevel");
logf(LogLevel.info, 5 < 6, "%s to the sharedLog with its LogLevel.info", "Logging");
info("Logging to the sharedLog with its info LogLevel");
warning(5 < 6, "Logging to the sharedLog with its LogLevel.warning if 5 is less than 6");
error("Logging to the sharedLog with its error LogLevel");
errorf("Logging %s the sharedLog %s its error LogLevel", "to", "with");
critical("Logging to the"," sharedLog with its error LogLevel");
fatal("Logging to the sharedLog with its fatal LogLevel");

auto fLogger = new FileLogger("NameOfTheLogFile");
fLogger.log("Logging to the fileLogger with its default LogLevel");
fLogger.info("Logging to the fileLogger with its default LogLevel");
fLogger.warning(5 < 6, "Logging to the fileLogger with its LogLevel.warning if 5 is less than 6");
fLogger.warningf(5 < 6, "Logging to the fileLogger with its LogLevel.warning if %s is %s than 6", 5, "less");
fLogger.critical("Logging to the fileLogger with its info LogLevel");
fLogger.log(LogLevel.trace, 5 < 6, "Logging to the fileLogger"," with its default LogLevel if 5 is less than 6");
fLogger.fatal("Logging to the fileLogger with its warning LogLevel");

```
 Additionally, this example shows how a new `FileLogger` is created. Individual `Logger` and the global log functions share commonly named functions to log data. The names of the functions are as follows: * `log`
* `trace`
* `info`
* `warning`
* `critical`
* `fatal`

 The default `Logger` will by default log to `stderr` and has a default `LogLevel` of `LogLevel.all`. The default Logger can be accessed by using the property called `sharedLog`. This property is a reference to the current default `Logger`. This reference can be used to assign a new default `Logger`. 
```
sharedLog = new FileLogger("New_Default_Log_File.log");

```
 Additional `Logger` can be created by creating a new instance of the required `Logger`. ### Logging Fundamentals

 #### LogLevel

 The `LogLevel` of a log call can be defined in two ways. The first is by calling `log` and passing the `LogLevel` explicitly as the first argument. The second way of setting the `LogLevel` of a log call, is by calling either `trace`, `info`, `warning`, `critical`, or `fatal`. The log call will then have the respective `LogLevel`. If no `LogLevel` is defined the log call will use the current `LogLevel` of the used `Logger`. If data is logged with `LogLevel` `fatal` by default an `Error` will be thrown. This behaviour can be modified by using the member `fatalHandler` to assign a custom delegate to handle log call with `LogLevel` `fatal`. #### Conditional Logging

 Conditional logging can be achieved be passing a `bool` as first argument to a log function. If conditional logging is used the condition must be `true` in order to have the log message logged. In order to combine an explicit `LogLevel` passing with conditional logging, the `LogLevel` has to be passed as first argument followed by the `bool`. #### Filtering Log Messages

 Messages are logged if the `LogLevel` of the log message is greater than or equal to the `LogLevel` of the used `Logger` and additionally if the `LogLevel` of the log message is greater than or equal to the global `LogLevel`. If a condition is passed into the log call, this condition must be true. The global `LogLevel` is accessible by using `globalLogLevel`. To assign a `LogLevel` of a `Logger` use the `logLevel` property of the logger. #### Printf Style Logging

 If `printf`-style logging is needed add a **f** to the logging call, such as `myLogger.infof("Hello %s", "world");` or `fatalf("errno %d", 1337)`. The additional **f** appended to the function name enables `printf`-style logging for all combinations of explicit `LogLevel` and conditional logging functions and methods. #### Thread Local Redirection

 Calls to the free standing log functions are not directly forwarded to the global `Logger` `sharedLog`. Actually, a thread local `Logger` of type `StdForwardLogger` processes the log call and then, by default, forwards the created `Logger.LogEntry` to the `sharedLog` `Logger`. The thread local `Logger` is accessible by the `stdThreadLocalLog` property. This property allows to assign user defined `Logger`. The default `LogLevel` of the `stdThreadLocalLog` `Logger` is `LogLevel.all` and it will therefore forward all messages to the `sharedLog` `Logger`. The `LogLevel` of the `stdThreadLocalLog` can be used to filter log calls before they reach the `sharedLog` `Logger`. ### User Defined Logger

 To customize the `Logger` behavior, create a new `class` that inherits from the abstract `Logger` `class`, and implements the `writeLogMsg` method. 
```
class MyCustomLogger : Logger
{
    this(LogLevel lv) @safe
    {
        super(lv);
    }

    override void writeLogMsg(ref LogEntry payload)
    {
        // log message in my custom way
    }
}

auto logger = new MyCustomLogger(LogLevel.info);
logger.log("Awesome log message with LogLevel.info");

```
 To gain more precise control over the logging process, additionally to overriding the `writeLogMsg` method the methods `beginLogMsg`, `logMsgPart` and `finishLogMsg` can be overridden. ### Compile Time Disabling of `Logger`

 In order to disable logging at compile time, pass `StdLoggerDisableLogging` as a version argument to the `D` compiler when compiling your program code. This will disable all logging functionality. Specific `LogLevel` can be disabled at compile time as well. In order to disable logging with the `trace` `LogLevel` pass `StdLoggerDisableTrace` as a version. The following table shows which version statement disables which `LogLevel`. 

|  |  |
| --- | --- |
| `LogLevel.trace` | StdLoggerDisableTrace |
| `LogLevel.info` | StdLoggerDisableInfo |
| `LogLevel.warning` | StdLoggerDisableWarning |
| `LogLevel.error` | StdLoggerDisableError |
| `LogLevel.critical` | StdLoggerDisableCritical |
| `LogLevel.fatal` | StdLoggerDisableFatal |

 Such a version statement will only disable logging in the associated compile unit. ### Provided Logger

 By default four `Logger` implementations are given. The `FileLogger` logs data to files. It can also be used to log to `stdout` and `stderr` as these devices are files as well. A `Logger` that logs to `stdout` can therefore be created by `new FileLogger(stdout)`. The `MultiLogger` is basically an associative array of `string`s to `Logger`. It propagates log calls to its stored `Logger`. The `ArrayLogger` contains an array of `Logger` and also propagates log calls to its stored `Logger`. The `NullLogger` does not do anything. It will never log a message and will never throw on a log call with `LogLevel` `error`. 
 
Source
 [std/experimental/logger/package.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/package.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_logger.html>

std.experimental.logger.filelogger
==================================

 
Source
 [std/experimental/logger/filelogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/filelogger.d)

 
alias **CreateFolder** = std.typecons.Flag!"**CreateFolder**".Flag;  
An option to create [`FileLogger`](#FileLogger) directory if it is non-existent.

  class **FileLogger**: std.experimental.logger.core.Logger;  
This `Logger` implementation writes log messages to the associated file. The name of the file has to be passed on construction time. If the file is already present new log messages will be append at its end.

 
@safe this(const string fn, const LogLevel lv = LogLevel.all);  
A constructor for the `FileLogger` Logger. 



Parameters:


|  |  |
| --- | --- |
| string `fn` | The filename of the output file of the `FileLogger`. If that file can not be opened for writting an exception will be thrown. |
| LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the |


 
Example


```
auto l1 = new FileLogger("logFile");
auto l2 = new FileLogger("logFile", LogLevel.fatal);
auto l3 = new FileLogger("logFile", LogLevel.fatal, CreateFolder.yes);

```
  @safe this(const string fn, const LogLevel lv, CreateFolder createFileNameFolder);  
A constructor for the `FileLogger` Logger that takes a reference to a `File`. 


The `File` passed must be open for all the log call to the `FileLogger`. If the `File` gets closed, using the `FileLogger` for logging will result in undefined behaviour. 

 
Parameters:


|  |  |
| --- | --- |
| string `fn` | The file used for logging. |
| LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the `LogLevel` for `FileLogger` is `LogLevel.all`. |
| CreateFolder `createFileNameFolder` | if yes and fn contains a folder name, this folder will be created. |


 
Example


```
auto file = File("logFile.log", "w");
auto l1 = new FileLogger(file);
auto l2 = new FileLogger(file, LogLevel.fatal);

```
  @safe this(File file, const LogLevel lv = LogLevel.all);  
A constructor for the `FileLogger` Logger that takes a reference to a `File`. 


The `File` passed must be open for all the log call to the `FileLogger`. If the `File` gets closed, using the `FileLogger` for logging will result in undefined behaviour. 

 
Parameters:


|  |  |
| --- | --- |
| File `file` | The file used for logging. |
| LogLevel `lv` | The `LogLevel` for the `FileLogger`. By default the `LogLevel` for `FileLogger` is `LogLevel.all`. |


 
Example


```
auto file = File("logFile.log", "w");
auto l1 = new FileLogger(file);
auto l2 = new FileLogger(file, LogLevel.fatal);

```
  @property @safe File **file**();  
If the `FileLogger` is managing the `File` it logs to, this method will return a reference to this File.

  string **getFilename**();  
If the `FileLogger` was constructed with a filename, this method returns this filename. Otherwise an empty `string` is returned.

  protected File **file\_**;  
The `File` log messages are written to.

  protected string **filename**;  
The filename of the `File` log messages are written to.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_logger_filelogger.html>

std.experimental.logger.nulllogger
==================================

 
Source
 [std/experimental/logger/nulllogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/nulllogger.d)

 
class **NullLogger**: std.experimental.logger.core.Logger;  
The `NullLogger` will not process any log messages. 


In case of a log message with `LogLevel.fatal` nothing will happen.

 
Examples:


```
import std.experimental.logger.core : LogLevel;
auto nl1 = new NullLogger(LogLevel.all);
nl1.info("You will never read this.");
nl1.fatal("You will never read this, either and it will not throw");

```
 
 
@safe this(const LogLevel lv = LogLevel.all);  
The default constructor for the `NullLogger`. 


Independent of the parameter this Logger will never log a message. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `lv` | The `LogLevel` for the `NullLogger`. By default the `LogLevel` for `NullLogger` is `LogLevel.all`. |


    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_logger_nulllogger.html>

std.experimental.logger.multilogger
===================================

 
Source
 [std/experimental/logger/multilogger.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/multilogger.d)

 
struct **MultiLoggerEntry**;  
This Element is stored inside the `MultiLogger` and associates a `Logger` to a `string`.

 
string **name**;  
The name if the `Logger`

  Logger **logger**;  
The stored `Logger`

    class **MultiLogger**: std.experimental.logger.core.Logger;  
MultiLogger logs to multiple `Logger`. The `Logger`s are stored in an `Logger[]` in their order of insertion. 


Every data logged to this `MultiLogger` will be distributed to all the `Logger`s inserted into it. This `MultiLogger` implementation can hold multiple `Logger`s with the same name. If the method `removeLogger` is used to remove a `Logger` only the first occurrence with that name will be removed.

 
@safe this(const LogLevel lv = LogLevel.all);  
A constructor for the `MultiLogger` Logger. 



Parameters:


|  |  |
| --- | --- |
| LogLevel `lv` | The `LogLevel` for the `MultiLogger`. By default the `LogLevel` for `MultiLogger` is `LogLevel.all`. |


 
Example


```
auto l1 = new MultiLogger(LogLevel.trace);

```
  protected MultiLoggerEntry[] **logger**;  
This member holds all `Logger`s stored in the `MultiLogger`. 


When inheriting from `MultiLogger` this member can be used to gain access to the stored `Logger`.

  @safe void **insertLogger**(string name, Logger newLogger);  
This method inserts a new Logger into the `MultiLogger`. 



Parameters:


|  |  |
| --- | --- |
| string `name` | The name of the `Logger` to insert. |
| Logger `newLogger` | The `Logger` to insert. |


  @safe Logger **removeLogger**(in char[] toRemove);  
This method removes a Logger from the `MultiLogger`. 



Parameters:


|  |  |
| --- | --- |
| char[] `toRemove` | The name of the `Logger` to remove. If the `Logger` is not found `null` will be returned. Only the first occurrence of a `Logger` with the given name will be removed. |


 
Returns:
The removed `Logger`.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_logger_multilogger.html>

std.experimental.typecons
=========================

 This module implements experimental additions/modifications to [`std.typecons`](std_typecons). 


Use this module to test out new functionality for [`std.typecons.wrap`](std_typecons#wrap) which allows for a struct to be wrapped against an interface; the implementation in [`std.typecons`](std_typecons) only allows for classes to use the wrap functionality. 

 
Source
 [std/experimental/typecons.d](https://github.com/dlang/phobos/blob/master/std/experimental/typecons.d) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org), [Bartosz Milewski](http://bartoszmilewski.wordpress.com), Don Clugston, Shin Fujishiro, Kenji Hara
 
template **wrap**(Targets...) if (Targets.length >= 1 && allSatisfy!(isInterface, Targets))  
auto **wrap**(Source)(inout Source src)  
 Constraints: if (implementsInterface!(Source, Targets)); 
 
Wrap src in an anonymous class implementing Targets. 


wrap creates an internal wrapper class which implements the interfaces in `Targets` using the methods of `src`, then returns a GC-allocated instance of it.   
  
 Source can be either a `class` or a `struct`, but it must *structurally conform* with all the Targets interfaces; i.e. it must provide concrete methods with compatible signatures of those in Targets.   
  
 If Source is a `struct` then wrapping/unwrapping will create a copy; it is not possible to affect the original `struct` through the wrapper.   
  
 The returned object additionally supports [`unwrap`](#unwrap). 

 
Note
 If Targets has only one entry and Source is a class which explicitly implements it, wrap simply returns src upcasted to `Targets[0]`. 
 
Bugs:
wrap does not support interfaces which take their own type as either a parameter type or return type in any of its methods. 
 
See Also:

[`unwrap`](#unwrap) for examples
    inout(Target) **unwrap**(Target, Source)(inout Source src);  
Extract object previously wrapped by [`wrap`](#wrap). 



Parameters:


|  |  |
| --- | --- |
| Target | type of wrapped object |
| Source `src` | wrapper object returned by [`wrap`](#wrap) |


 
Returns:
the wrapped object, or null if src is not a wrapper created by [`wrap`](#wrap) and Target is a class 
 
Throws:

[`std.conv.ConvException`](std_conv#ConvException) when attempting to extract a struct which is not the wrapped type 
 
See Also:
[`wrap`](#wrap)
 
Examples:


```
interface Quack
{
    int quack();
    @property int height();
}
interface Flyer
{
    @property int height();
}
class Duck : Quack
{
    int quack() { return 1; }
    @property int height() { return 10; }
}
class Human
{
    int quack() { return 2; }
    @property int height() { return 20; }
}
struct HumanStructure
{
    int quack() { return 3; }
    @property int height() { return 30; }
}

Duck d1 = new Duck();
Human h1 = new Human();
HumanStructure hs1;

interface Refreshable
{
    int refresh();
}
// does not have structural conformance
static assert(!__traits(compiles, d1.wrap!Refreshable));
static assert(!__traits(compiles, h1.wrap!Refreshable));
static assert(!__traits(compiles, hs1.wrap!Refreshable));

// strict upcast
Quack qd = d1.wrap!Quack;
assert(qd is d1);
assert(qd.quack() == 1);    // calls Duck.quack
// strict downcast
Duck d2 = qd.unwrap!Duck;
assert(d2 is d1);

// structural upcast
Quack qh = h1.wrap!Quack;
Quack qhs = hs1.wrap!Quack;
assert(qh.quack() == 2);    // calls Human.quack
assert(qhs.quack() == 3);    // calls HumanStructure.quack
// structural downcast
Human h2 = qh.unwrap!Human;
HumanStructure hs2 = qhs.unwrap!HumanStructure;
assert(h2 is h1);
assert(hs2 is hs1);

// structural upcast (two steps)
Quack qx = h1.wrap!Quack;   // Human -> Quack
Quack qxs = hs1.wrap!Quack;   // HumanStructure -> Quack
Flyer fx = qx.wrap!Flyer;   // Quack -> Flyer
Flyer fxs = qxs.wrap!Flyer;   // Quack -> Flyer
assert(fx.height == 20);    // calls Human.height
assert(fxs.height == 30);    // calls HumanStructure.height
// strucural downcast (two steps)
Quack qy = fx.unwrap!Quack; // Flyer -> Quack
Quack qys = fxs.unwrap!Quack; // Flyer -> Quack
Human hy = qy.unwrap!Human; // Quack -> Human
HumanStructure hys = qys.unwrap!HumanStructure; // Quack -> HumanStructure
assert(hy is h1);
assert(hys is hs1);
// strucural downcast (one step)
Human hz = fx.unwrap!Human; // Flyer -> Human
HumanStructure hzs = fxs.unwrap!HumanStructure; // Flyer -> HumanStructure
assert(hz is h1);
assert(hzs is hs1);

```
 
 
Examples:


```
import std.traits : functionAttributes, FunctionAttribute;
interface A { int run(); }
interface B { int stop(); @property int status(); }
class X
{
    int run() { return 1; }
    int stop() { return 2; }
    @property int status() { return 3; }
}

auto x = new X();
auto ab = x.wrap!(A, B);
A a = ab;
B b = ab;
writeln(a.run()); // 1
writeln(b.stop()); // 2
writeln(b.status); // 3
static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);

```
 
  template **Final**(T)  
  
Final!T **makeFinal**(T)(T t);  
Type constructor for final (aka head-const) variables. 


Final variables cannot be directly mutated or rebound, but references reached through the variable are typed with their original mutability. It is equivalent to `final` variables in D1 and Java, as well as `readonly` variables in C#.   
  
 When `T` is a `const` or `immutable` type, `Final` aliases to `T`.

 
Examples:

`Final` can be used to create class references which cannot be rebound: 
```
static class A
{
    int i;

    this(int i) pure nothrow @nogc @safe
    {
        this.i = i;
    }
}

auto a = makeFinal(new A(42));
writeln(a.i); // 42

//a = new A(24); // Reassignment is illegal,
a.i = 24; // But fields are still mutable.

writeln(a.i); // 24

```
 
 
Examples:

`Final` can also be used to create read-only data fields without using transitive immutability: 
```
static class A
{
    int i;

    this(int i) pure nothrow @nogc @safe
    {
        this.i = i;
    }
}

static class B
{
    Final!A a;

    this(A a) pure nothrow @nogc @safe
    {
        this.a = a; // Construction, thus allowed.
    }
}

auto b = new B(new A(42));
writeln(b.a.i); // 42

// b.a = new A(24); // Reassignment is illegal,
b.a.i = 24; // but `a` is still mutable.

writeln(b.a.i); // 24

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_typecons.html>

std.experimental.logger.core
============================

 
Source
 [std/experimental/logger/core.d](https://github.com/dlang/phobos/blob/master/std/experimental/logger/core.d)

 
template **isLoggingActiveAt**(LogLevel ll) 
This template evaluates if the passed `LogLevel` is active. The previously described version statements are used to decide if the `LogLevel` is active. The version statements only influence the compile unit they are used with, therefore this function can only disable logging this specific compile unit.

  enum bool **isLoggingActive**;  
This compile-time flag is `true` if logging is not statically disabled.

  @safe bool **isLoggingEnabled**()(LogLevel ll, LogLevel loggerLL, LogLevel globalLL, lazy bool condition = true);  
This functions is used at runtime to determine if a `LogLevel` is active. The same previously defined version statements are used to disable certain levels. Again the version statements are associated with a compile unit and can therefore not disable logging in other compile units. pure bool isLoggingEnabled()(LogLevel ll) @safe nothrow @nogc

  template **moduleLogLevel**(string moduleName) if (!moduleName.length)  
  
template **moduleLogLevel**(string moduleName) if (moduleName.length) 
This template returns the `LogLevel` named "logLevel" of type `LogLevel` defined in a user defined module where the filename has the suffix "loggerconfig.d". This `LogLevel` sets the minimal `LogLevel` of the module. 


A minimal `LogLevel` can be defined on a per module basis. In order to define a module `LogLevel` a file with a modulename "MODULENAME\_loggerconfig" must be found. If no such module exists and the module is a nested module, it is checked if there exists a "PARENT\_MODULE\_loggerconfig" module with such a symbol. If this module exists and it contains a `LogLevel` called logLevel this `LogLevel` will be used. This parent lookup is continued until there is no parent module. Then the moduleLogLevel is `LogLevel.all`.

 
Examples:


```
static assert(moduleLogLevel!"" == LogLevel.all);

```
 
 
Examples:


```
static assert(moduleLogLevel!"not.amodule.path" == LogLevel.all);

```
 
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy A args)  
 Constraints: if (args.length != 1);   
  
void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy bool condition, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_);  
This function logs data. 


In order for the data to be processed, the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel`; additionally the condition passed must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The `LogLevel` used by this log call. |
| bool `condition` | The condition must be `true` for the data to be logged. |
| A `args` | The data that should be logged. |


 
Example


```
log(LogLevel.warning, true, "Hello World", 3.1415);

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy A args)  
 Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool));   
  
void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_);  
This function logs data. 


In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The `LogLevel` used by this log call. |
| A `args` | The data that should be logged. |


 
Example


```
log(LogLevel.warning, "Hello World", 3.1415);

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args)  
 Constraints: if (args.length != 1);   
  
void **log**(T, string moduleName = \_\_MODULE\_\_)(lazy bool condition, lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_);  
This function logs data. 


In order for the data to be processed the `LogLevel` of the `sharedLog` must be greater or equal to the `defaultLogLevel` add the condition passed must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| A `args` | The data that should be logged. |


 
Example


```
log(true, "Hello World", 3.1415);

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args)  
 Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) && !is(Unqual!(A[0]) == LogLevel) || args.length == 0); 
 
This function logs data. 


In order for the data to be processed the `LogLevel` of the `sharedLog` must be greater or equal to the `defaultLogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| A `args` | The data that should be logged. |


 
Example


```
log("Hello World", 3.1415);

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy string msg, lazy A args);  
This function logs data in a `printf`-style manner. 


In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel` additionally the condition passed must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The `LogLevel` used by this log call. |
| bool `condition` | The condition must be `true` for the data to be logged. |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
logf(LogLevel.warning, true, "Hello World %f", 3.1415);

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy string msg, lazy A args);  
This function logs data in a `printf`-style manner. 


In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `sharedLog` and the `defaultLogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The `LogLevel` used by this log call. |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
logf(LogLevel.warning, "Hello World %f", 3.1415);

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);  
This function logs data in a `printf`-style manner. 


In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `defaultLogLevel` additionally the condition passed must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
logf(true, "Hello World %f", 3.1415);

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);  
This function logs data in a `printf`-style manner. 


In order for the data to be processed the `LogLevel` of the log call must be greater or equal to the `defaultLogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
logf("Hello World %f", 3.1415);

```
  template **defaultLogFunction**(LogLevel ll) 
This template provides the global log functions with the `LogLevel` is encoded in the function name. 


The aliases following this template create the public names of these log functions.

  alias **trace** = defaultLogFunction!LogLevel.**trace**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
alias **info** = defaultLogFunction!LogLevel.**info**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
alias **warning** = defaultLogFunction!LogLevel.**warning**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
alias **error** = defaultLogFunction!LogLevel.**error**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
alias **critical** = defaultLogFunction!LogLevel.**critical**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
alias **fatal** = defaultLogFunction!LogLevel.**fatal**.defaultLogFunction(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length > 0 && !is(Unqual!(A[0]) : bool) || args.length == 0);  
This function logs data to the `stdThreadLocalLog`, optionally depending on a condition. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `stdThreadLocalLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. If a condition is given, it must evaluate to `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool condition | The condition must be `true` for the data to be logged. |
| A args | The data that should be logged. |


 
Example


```
trace(1337, "is number");
info(1337, "is number");
error(1337, "is number");
critical(1337, "is number");
fatal(1337, "is number");
trace(true, 1337, "is number");
info(false, 1337, "is number");
error(true, 1337, "is number");
critical(false, 1337, "is number");
fatal(true, 1337, "is number");

```
  template **defaultLogFunctionf**(LogLevel ll) 
This template provides the global `printf`-style log functions with the `LogLevel` is encoded in the function name. 


The aliases following this template create the public names of the log functions.

  alias **tracef** = defaultLogFunctionf!LogLevel.trace.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);   
  
alias **infof** = defaultLogFunctionf!LogLevel.info.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);   
  
alias **warningf** = defaultLogFunctionf!LogLevel.warning.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);   
  
alias **errorf** = defaultLogFunctionf!LogLevel.error.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);   
  
alias **criticalf** = defaultLogFunctionf!LogLevel.critical.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);   
  
alias **fatalf** = defaultLogFunctionf!LogLevel.fatal.defaultLogFunctionf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);  
This function logs data to the `sharedLog` in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `sharedLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. 

 
Parameters:


|  |  |
| --- | --- |
| string msg | The `printf`-style string. |
| A args | The data that should be logged. |


 
Example


```
tracef("is number %d", 1);
infof("is number %d", 2);
errorf("is number %d", 3);
criticalf("is number %d", 4);
fatalf("is number %d", 5);

```
 The second version of the function logs data to the `sharedLog` in a `printf`-style manner. In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the `sharedLog` and must be greater or equal than the global `LogLevel`. Additionally the `LogLevel` must be greater or equal than the `LogLevel` of the `stdSharedLogger`. 
Parameters:


|  |  |
| --- | --- |
| bool condition | The condition must be `true` for the data to be logged. |
| string msg | The `printf`-style string. |
| A args | The data that should be logged. |


 
Example


```
tracef(false, "is number %d", 1);
infof(false, "is number %d", 2);
errorf(true, "is number %d", 3);
criticalf(true, "is number %d", 4);
fatalf(someFunct(), "is number %d", 5);

```
  enum **LogLevel**: ubyte;  
There are eight usable logging level. These level are *all*, *trace*, *info*, *warning*, *error*, *critical*, *fatal*, and *off*. If a log function with `LogLevel.fatal` is called the shutdown handler of that logger is called.

 
**all** 
Lowest possible assignable `LogLevel`.

  **trace** 
`LogLevel` for tracing the execution of the program.

  **info** 
This level is used to display information about the program.

  **warning** 
warnings about the program should be displayed with this level.

  **error** 
Information about errors should be logged with this level.

  **critical** 
Messages that inform about critical errors should be logged with this level.

  **fatal** 
Log messages that describe fatal errors should use this level.

  **off** 
Highest possible `LogLevel`.

    abstract class **Logger**;  
This class is the base of every logger. In order to create a new kind of logger a deriving class needs to implement the `writeLogMsg` method. By default this is not thread-safe. 


It is also possible to `override` the three methods `beginLogMsg`, `logMsgPart` and `finishLogMsg` together, this option gives more flexibility.

 
struct **LogEntry**;  
LogEntry is a aggregation combining all information associated with a log message. This aggregation will be passed to the method writeLogMsg.

 
string **file**;  
the filename the log function was called from

  int **line**;  
the line number the log function was called from

  string **funcName**;  
the name of the function the log function was called from

  string **prettyFuncName**;  
the pretty formatted name of the function the log function was called from

  string **moduleName**;  
the name of the module the log message is coming from

  LogLevel **logLevel**;  
the `LogLevel` associated with the log message

  Tid **threadId**;  
thread id of the log message

  SysTime **timestamp**;  
the time the message was logged

  string **msg**;  
the message of the log message

  Logger **logger**;  
A refernce to the `Logger` used to create this `LogEntry`

    @safe this(LogLevel lv);  
Every subclass of `Logger` has to call this constructor from their constructor. It sets the `LogLevel`, and creates a fatal handler. The fatal handler will throw an `Error` if a log call is made with level `LogLevel.fatal`. 



Parameters:


|  |  |
| --- | --- |
| LogLevel `lv` | `LogLevel` to use for this `Logger` instance. |


  protected abstract @safe void **writeLogMsg**(ref LogEntry payload);  
A custom logger must implement this method in order to work in a `MultiLogger` and `ArrayLogger`. 



Parameters:


|  |  |
| --- | --- |
| LogEntry `payload` | All information associated with call to log function. |


 
See Also:
beginLogMsg, logMsgPart, finishLogMsg
  protected @safe void **logMsgPart**(scope const(char)[] msg);  
Logs a part of the log message.

  protected @safe void **finishLogMsg**();  
Signals that the message has been written and no more calls to `logMsgPart` follow.

  final const pure @nogc @property @safe LogLevel **logLevel**();   
  
final @nogc @property @safe void **logLevel**(const LogLevel lv);  
The `LogLevel` determines if the log call are processed or dropped by the `Logger`. In order for the log call to be processed the `LogLevel` of the log call must be greater or equal to the `LogLevel` of the `logger`. 


These two methods set and get the `LogLevel` of the used `Logger`. 

 
Example


```
auto f = new FileLogger(stdout);
f.logLevel = LogLevel.info;
assert(f.logLevel == LogLevel.info);

```
  final @nogc @property @safe void delegate() **fatalHandler**();   
  
final @nogc @property @safe void **fatalHandler**(void delegate() @safe fh);  
This `delegate` is called in case a log message with `LogLevel.fatal` gets logged. 


By default an `Error` will be thrown.

  @trusted void **forwardMsg**(ref LogEntry payload);  
This method allows forwarding log entries from one logger to another. 


`forwardMsg` will ensure proper synchronization and then call `writeLogMsg`. This is an API for implementing your own loggers and should not be called by normal user code. A notable difference from other logging functions is that the `globalLogLevel` wont be evaluated again since it is assumed that the caller already checked that.

  template **memLogFunctions**(LogLevel ll)  
  
alias **trace** = .Logger.memLogFunctions!LogLevel.**trace**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **tracef** = .Logger.memLogFunctions!LogLevel.trace.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);   
  
alias **info** = .Logger.memLogFunctions!LogLevel.**info**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **infof** = .Logger.memLogFunctions!LogLevel.info.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);   
  
alias **warning** = .Logger.memLogFunctions!LogLevel.**warning**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **warningf** = .Logger.memLogFunctions!LogLevel.warning.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);   
  
alias **error** = .Logger.memLogFunctions!LogLevel.**error**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **errorf** = .Logger.memLogFunctions!LogLevel.error.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);   
  
alias **critical** = .Logger.memLogFunctions!LogLevel.**critical**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **criticalf** = .Logger.memLogFunctions!LogLevel.critical.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);   
  
alias **fatal** = .Logger.memLogFunctions!LogLevel.**fatal**.logImpl(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args) if (args.length == 0 || args.length > 0 && !is(A[0] : bool));   
  
alias **fatalf** = .Logger.memLogFunctions!LogLevel.fatal.logImplf(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);  
This template provides the log functions for the `Logger` `class` with the `LogLevel` encoded in the function name. 


For further information see the the two functions defined inside of this template.   
  
 The aliases following this template create the public names of these log functions.

 
void **logImpl**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args)  
 Constraints: if (args.length == 0 || args.length > 0 && !is(A[0] : bool)); 
 
This function logs data to the used `Logger`. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.trace(1337, "is number");
s.info(1337, "is number");
s.error(1337, "is number");
s.critical(1337, "is number");
s.fatal(1337, "is number");

```
  void **logImpl**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args);  
This function logs data to the used `Logger` depending on a condition. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` additionally the condition passed must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.trace(true, 1337, "is number");
s.info(false, 1337, "is number");
s.error(true, 1337, "is number");
s.critical(false, 1337, "is number");
s.fatal(true, 1337, "is number");

```
  void **logImplf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);  
This function logs data to the used `Logger` in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` additionally the passed condition must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stderr);
s.tracef(true, "is number %d", 1);
s.infof(true, "is number %d", 2);
s.errorf(false, "is number %d", 3);
s.criticalf(someFunc(), "is number %d", 4);
s.fatalf(true, "is number %d", 5);

```
  void **logImplf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);  
This function logs data to the used `Logger` in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| string `msg` | The `printf`-style string. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stderr);
s.tracef("is number %d", 1);
s.infof("is number %d", 2);
s.errorf("is number %d", 3);
s.criticalf("is number %d", 4);
s.fatalf("is number %d", 5);

```
    void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy A args)  
 Constraints: if (args.length != 1);   
  
void **log**(T, string moduleName = \_\_MODULE\_\_)(const LogLevel ll, lazy bool condition, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_);  
This method logs data with the `LogLevel` of the used `Logger`. 


This method takes a `bool` as first argument. In order for the data to be processed the `bool` must be `true` and the `LogLevel` of the Logger must be greater or equal to the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| A `args` | The data that should be logged. |
| bool `condition` | The condition must be `true` for the data to be logged. |
| A `args` | The data that is to be logged. |


 
Returns:
The logger used by the logging function as reference. 
 
Example


```
auto l = new StdioLogger();
l.log(1337);

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy A args)  
 Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) || args.length == 0);   
  
void **log**(T)(const LogLevel ll, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_);  
This function logs data to the used `Logger` with a specific `LogLevel`. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The specific `LogLevel` used for logging the log message. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.log(LogLevel.trace, 1337, "is number");
s.log(LogLevel.info, 1337, "is number");
s.log(LogLevel.warning, 1337, "is number");
s.log(LogLevel.error, 1337, "is number");
s.log(LogLevel.fatal, 1337, "is number");

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy A args)  
 Constraints: if (args.length != 1);   
  
void **log**(T)(lazy bool condition, lazy T args, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_);  
This function logs data to the used `Logger` depending on a explicitly passed condition with the `LogLevel` of the used `Logger`. 


In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel` and the condition must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.log(true, 1337, "is number");
s.log(true, 1337, "is number");
s.log(true, 1337, "is number");
s.log(false, 1337, "is number");
s.log(false, 1337, "is number");

```
  void **log**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy A args)  
 Constraints: if (args.length > 1 && !is(Unqual!(A[0]) : bool) && !is(immutable(A[0]) == immutable(LogLevel)) || args.length == 0);   
  
void **log**(T)(lazy T arg, int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_);  
This function logs data to the used `Logger` with the `LogLevel` of the used `Logger`. 


In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.log(1337, "is number");
s.log(info, 1337, "is number");
s.log(1337, "is number");
s.log(1337, "is number");
s.log(1337, "is number");

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy bool condition, lazy string msg, lazy A args);  
This function logs data to the used `Logger` with a specific `LogLevel` and depending on a condition in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel` and the condition must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The specific `LogLevel` used for logging the log message. |
| bool `condition` | The condition must be `true` for the data to be logged. |
| string `msg` | The format string used for this log call. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.logf(LogLevel.trace, true ,"%d %s", 1337, "is number");
s.logf(LogLevel.info, true ,"%d %s", 1337, "is number");
s.logf(LogLevel.warning, true ,"%d %s", 1337, "is number");
s.logf(LogLevel.error, false ,"%d %s", 1337, "is number");
s.logf(LogLevel.fatal, true ,"%d %s", 1337, "is number");

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(const LogLevel ll, lazy string msg, lazy A args);  
This function logs data to the used `Logger` with a specific `LogLevel` in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` must be greater or equal than the `LogLevel` of the used `Logger` and must be greater or equal than the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| LogLevel `ll` | The specific `LogLevel` used for logging the log message. |
| string `msg` | The format string used for this log call. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.logf(LogLevel.trace, "%d %s", 1337, "is number");
s.logf(LogLevel.info, "%d %s", 1337, "is number");
s.logf(LogLevel.warning, "%d %s", 1337, "is number");
s.logf(LogLevel.error, "%d %s", 1337, "is number");
s.logf(LogLevel.fatal, "%d %s", 1337, "is number");

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy bool condition, lazy string msg, lazy A args);  
This function logs data to the used `Logger` depending on a condition with the `LogLevel` of the used `Logger` in a `printf`-style manner. 


In order for the resulting log message to be logged the `LogLevel` of the used `Logger` must be greater or equal than the global `LogLevel` and the condition must be `true`. 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | The condition must be `true` for the data to be logged. |
| string `msg` | The format string used for this log call. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.logf(true ,"%d %s", 1337, "is number");
s.logf(true ,"%d %s", 1337, "is number");
s.logf(true ,"%d %s", 1337, "is number");
s.logf(false ,"%d %s", 1337, "is number");
s.logf(true ,"%d %s", 1337, "is number");

```
  void **logf**(int line = \_\_LINE\_\_, string file = \_\_FILE\_\_, string funcName = \_\_FUNCTION\_\_, string prettyFuncName = \_\_PRETTY\_FUNCTION\_\_, string moduleName = \_\_MODULE\_\_, A...)(lazy string msg, lazy A args);  
This method logs data to the used `Logger` with the `LogLevel` of the this `Logger` in a `printf`-style manner. 


In order for the data to be processed the `LogLevel` of the `Logger` must be greater or equal to the global `LogLevel`. 

 
Parameters:


|  |  |
| --- | --- |
| string `msg` | The format string used for this log call. |
| A `args` | The data that should be logged. |


 
Example


```
auto s = new FileLogger(stdout);
s.logf("%d %s", 1337, "is number");
s.logf("%d %s", 1337, "is number");
s.logf("%d %s", 1337, "is number");
s.logf("%d %s", 1337, "is number");
s.logf("%d %s", 1337, "is number");

```
    @property @safe Logger **sharedLog**();   
  
@property @trusted void **sharedLog**(Logger logger);  
This property sets and gets the default `Logger`. 



Example


```
sharedLog = new FileLogger(yourFile);

```
 The example sets a new `FileLogger` as new `sharedLog`. If at some point you want to use the original default logger again, you can use `sharedLog = null;`. This will put back the original. 
Note
 While getting and setting `sharedLog` is thread-safe, it has to be considered that the returned reference is only a current snapshot and in the following code, you must make sure no other thread reassigns to it between reading and writing `sharedLog`. 
 `sharedLog` is only thread-safe if the the used `Logger` is thread-safe. The default `Logger` is thread-safe. 
```
if (sharedLog !is myLogger)
    sharedLog = new myLogger;

```
  @nogc @property @safe LogLevel **globalLogLevel**();   
  
@property @safe void **globalLogLevel**(LogLevel ll);  
This methods get and set the global `LogLevel`. 


Every log message with a `LogLevel` lower as the global `LogLevel` will be discarded before it reaches `writeLogMessage` method of any `Logger`.

  class **StdForwardLogger**: std.experimental.logger.core.Logger;  
The `StdForwardLogger` will always forward anything to the sharedLog. 


The `StdForwardLogger` will not throw if data is logged with `LogLevel.fatal`.

 
Examples:


```
auto nl1 = new StdForwardLogger(LogLevel.all);

```
 
 
@safe this(const LogLevel lv = LogLevel.all);  
The default constructor for the `StdForwardLogger`. 



Parameters:


|  |  |
| --- | --- |
| LogLevel `lv` | The `LogLevel` for the `MultiLogger`. By default the  `LogLevel` is `all`. |


    @property @safe Logger **stdThreadLocalLog**();   
  
@property @safe void **stdThreadLocalLog**(Logger logger);  
This function returns a thread unique `Logger`, that by default propergates all data logged to it to the `sharedLog`. 


These properties can be used to set and get this `Logger`. Every modification to this `Logger` will only be visible in the thread the modification has been done from.   
  
 This `Logger` is called by the free standing log functions. This allows to create thread local redirections and still use the free standing log functions.

 
Examples:
Ditto 
```
import std.experimental.logger.filelogger : FileLogger;
import std.file : deleteme, remove;
Logger l = stdThreadLocalLog;
stdThreadLocalLog = new FileLogger(deleteme ~ "-someFile.log");
scope(exit) remove(deleteme ~ "-someFile.log");

auto tempLog = stdThreadLocalLog;
stdThreadLocalLog = l;
destroy(tempLog);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_logger_core.html>

std.getopt
==========

 Processing of command line options. 


The getopt module implements a `getopt` function, which adheres to the POSIX syntax for command line options. GNU extensions are supported in the form of long options introduced by a double dash ("--"). Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) 
 
Credits
 This module and its documentation are inspired by Perl's [Getopt::Long](https://perldoc.perl.org/Getopt/Long.html) module. The syntax of D's `getopt` is simpler than its Perl counterpart because  `getopt` infers the expected parameter types from the static types of the passed-in pointers. 
 
Source
 [std/getopt.d](https://github.com/dlang/phobos/blob/master/std/getopt.d)

 
class **GetOptException**: object.Exception;  
Thrown on one of the following conditions: * An unrecognized command-line argument is passed, and `std.getopt.config.passThrough` was not present.
* A command-line option was not found, and `std.getopt.config.required` was present.


  GetoptResult **getopt**(T...)(ref string[] args, T opts);  
Parse and remove command line options from a string array. 



Synopsis


```
import std.getopt;

string data = "file.dat";
int length = 24;
bool verbose;
enum Color { no, yes };
Color color;

void main(string[] args)
{
  auto helpInformation = getopt(
    args,
    "length",  &length,    // numeric
    "file",    &data,      // string
    "verbose", &verbose,   // flag
    "color", "Information about this color", &color);    // enum
  ...

  if (helpInformation.helpWanted)
  {
    defaultGetoptPrinter("Some information about the program.",
      helpInformation.options);
  }
}

```
 The `getopt` function takes a reference to the command line (as received by `main`) as its first argument, and an unbounded number of pairs of strings and pointers. Each string is an option meant to "fill" the value referenced by the pointer to its right (the "bound" pointer). The option string in the call to `getopt` should not start with a dash. In all cases, the command-line options that were parsed and used by `getopt` are removed from `args`. Whatever in the arguments did not look like an option is left in `args` for further processing by the program. Values that were unaffected by the options are not touched, so a common idiom is to initialize options to their defaults and then invoke `getopt`. If a command-line argument is recognized as an option with a parameter and the parameter cannot be parsed properly (e.g., a number is expected but not present), a `ConvException` exception is thrown. If `std.getopt.config.passThrough` was not passed to `getopt` and an unrecognized command-line argument is found, a `GetOptException` is thrown. Depending on the type of the pointer being bound, `getopt` recognizes the following kinds of options: 1. *Boolean options*. A lone argument sets the option to `true`. Additionally **true** or **false** can be set within the option separated with an "=" sign: 
```
  bool verbose = false, debugging = true;
  getopt(args, "verbose", &verbose, "debug", &debugging);

```
 To set `verbose` to `true`, invoke the program with either `--verbose` or `--verbose=true`. To set `debugging` to `false`, invoke the program with `--debugging=false`.
2. *Numeric options.* If an option is bound to a numeric type, a number is expected as the next option, or right within the option separated with an "=" sign: 
```
  uint timeout;
  getopt(args, "timeout", &timeout);

```
 To set `timeout` to `5`, invoke the program with either `--timeout=5` or `--timeout 5`.
3. *Incremental options.* If an option name has a "+" suffix and is bound to a numeric type, then the option's value tracks the number of times the option occurred on the command line: 
```
  uint paranoid;
  getopt(args, "paranoid+", &paranoid);

```
 Invoking the program with "--paranoid --paranoid --paranoid" will set  `paranoid` to 3. Note that an incremental option never expects a parameter, e.g., in the command line "--paranoid 42 --paranoid", the "42" does not set `paranoid` to 42; instead, `paranoid` is set to 2 and "42" is not considered as part of the normal program arguments.
4. *Enum options.* If an option is bound to an enum, an enum symbol as a string is expected as the next option, or right within the option separated with an "=" sign: 
```
  enum Color { no, yes };
  Color color; // default initialized to Color.no
  getopt(args, "color", &color);

```
 To set `color` to `Color.yes`, invoke the program with either `--color=yes` or `--color yes`.
5. *String options.* If an option is bound to a string, a string is expected as the next option, or right within the option separated with an "=" sign: 
```
string outputFile;
getopt(args, "output", &outputFile);

```
 Invoking the program with "--output=myfile.txt" or "--output myfile.txt" will set `outputFile` to "myfile.txt". If you want to pass a string containing spaces, you need to use the quoting that is appropriate to your shell, e.g. --output='my file.txt'.
6. *Array options.* If an option is bound to an array, a new element is appended to the array each time the option occurs: 
```
string[] outputFiles;
getopt(args, "output", &outputFiles);

```
 Invoking the program with "--output=myfile.txt --output=yourfile.txt" or "--output myfile.txt --output yourfile.txt" will set `outputFiles` to `[ "myfile.txt", "yourfile.txt" ]`. Alternatively you can set [`arraySep`](#arraySep) to allow multiple elements in one parameter. 
```
string[] outputFiles;
arraySep = ",";  // defaults to "", meaning one element per parameter
getopt(args, "output", &outputFiles);

```
 With the above code you can invoke the program with "--output=myfile.txt,yourfile.txt", or "--output myfile.txt,yourfile.txt".
7. *Hash options.* If an option is bound to an associative array, a string of the form "name=value" is expected as the next option, or right within the option separated with an "=" sign: 
```
double[string] tuningParms;
getopt(args, "tune", &tuningParms);

```
 Invoking the program with e.g. "--tune=alpha=0.5 --tune beta=0.6" will set `tuningParms` to [ "alpha" : 0.5, "beta" : 0.6 ]. Alternatively you can set [`arraySep`](#arraySep) as the element separator: 
```
double[string] tuningParms;
arraySep = ",";  // defaults to "", meaning one element per parameter
getopt(args, "tune", &tuningParms);

```
 With the above code you can invoke the program with "--tune=alpha=0.5,beta=0.6", or "--tune alpha=0.5,beta=0.6". In general, the keys and values can be of any parsable types.
8. *Callback options.* An option can be bound to a function or delegate with the signature `void function()`, `void function(string option)`, `void function(string option, string value)`, or their delegate equivalents.
	* If the callback doesn't take any arguments, the callback is invoked whenever the option is seen.
	* If the callback takes one string argument, the option string (without the leading dash(es)) is passed to the callback. After that, the option string is considered handled and removed from the options array. 
	```
	void main(string[] args)
	{
	  uint verbosityLevel = 1;
	  void myHandler(string option)
	  {
	    if (option == "quiet")
	    {
	      verbosityLevel = 0;
	    }
	    else
	    {
	      assert(option == "verbose");
	      verbosityLevel = 2;
	    }
	  }
	  getopt(args, "verbose", &myHandler, "quiet", &myHandler);
	}
	
	```
	* If the callback takes two string arguments, the option string is handled as an option with one argument, and parsed accordingly. The option and its value are passed to the callback. After that, whatever was passed to the callback is considered handled and removed from the list. 
	```
	int main(string[] args)
	{
	  uint verbosityLevel = 1;
	  bool handlerFailed = false;
	  void myHandler(string option, string value)
	  {
	    switch (value)
	    {
	      case "quiet": verbosityLevel = 0; break;
	      case "verbose": verbosityLevel = 2; break;
	      case "shouting": verbosityLevel = verbosityLevel.max; break;
	      default :
	        stderr.writeln("Unknown verbosity level ", value);
	        handlerFailed = true;
	        break;
	    }
	  }
	  getopt(args, "verbosity", &myHandler);
	  return handlerFailed ? 1 : 0;
	}
	
	```

 
Options with multiple names
 Sometimes option synonyms are desirable, e.g. "--verbose", "--loquacious", and "--garrulous" should have the same effect. Such alternate option names can be included in the option specification, using "|" as a separator: 
 
```
bool verbose;
getopt(args, "verbose|loquacious|garrulous", &verbose);

```
 
Case
 By default options are case-insensitive. You can change that behavior by passing `getopt` the `caseSensitive` directive like this: 
 
```
bool foo, bar;
getopt(args,
    std.getopt.config.caseSensitive,
    "foo", &foo,
    "bar", &bar);

```
 In the example above, "--foo" and "--bar" are recognized, but "--Foo", "--Bar", "--FOo", "--bAr", etc. are rejected. The directive is active until the end of `getopt`, or until the converse directive `caseInsensitive` is encountered: 
```
bool foo, bar;
getopt(args,
    std.getopt.config.caseSensitive,
    "foo", &foo,
    std.getopt.config.caseInsensitive,
    "bar", &bar);

```
 The option "--Foo" is rejected due to `std.getopt.config.caseSensitive`, but not "--Bar", "--bAr" etc. because the directive `std.getopt.config.caseInsensitive` turned sensitivity off before option "bar" was parsed. 
Short versus long options
 Traditionally, programs accepted single-letter options preceded by only one dash (e.g. `-t`). `getopt` accepts such parameters seamlessly. When used with a double-dash (e.g. `--t`), a single-letter option behaves the same as a multi-letter option. When used with a single dash, a single-letter option is accepted. 
 To set `timeout` to `5`, use either of the following: `--timeout=5`, `--timeout 5`, `--t=5`, `--t 5`, `-t5`, or `-t 5`. Forms such as `-timeout=5` will be not accepted. For more details about short options, refer also to the next section. 
Bundling
 Single-letter options can be bundled together, i.e. "-abc" is the same as `"-a -b -c"`. By default, this option is turned off. You can turn it on with the `std.getopt.config.bundling` directive: 
 
```
bool foo, bar;
getopt(args,
    std.getopt.config.bundling,
    "foo|f", &foo,
    "bar|b", &bar);

```
 In case you want to only enable bundling for some of the parameters, bundling can be turned off with `std.getopt.config.noBundling`. 
Required
 An option can be marked as required. If that option is not present in the arguments an exception will be thrown. 
 
```
bool foo, bar;
getopt(args,
    std.getopt.config.required,
    "foo|f", &foo,
    "bar|b", &bar);

```
 Only the option directly following `std.getopt.config.required` is required. 
Passing unrecognized options through
 If an application needs to do its own processing of whichever arguments `getopt` did not understand, it can pass the `std.getopt.config.passThrough` directive to `getopt`: 
 
```
bool foo, bar;
getopt(args,
    std.getopt.config.passThrough,
    "foo", &foo,
    "bar", &bar);

```
 An unrecognized option such as "--baz" will be found untouched in `args` after `getopt` returns. 
Help Information Generation
 If an option string is followed by another string, this string serves as a description for this option. The `getopt` function returns a struct of type `GetoptResult`. This return value contains information about all passed options as well a `bool GetoptResult.helpWanted` flag indicating whether information about these options was requested. The `getopt` function always adds an option for `--help|-h` to set the flag if the option is seen on the command line. 
 
Options Terminator
 A lone double-dash terminates `getopt` gathering. It is used to separate program options from other parameters (e.g., options to be passed to another program). Invoking the example above with `"--foo -- --bar"` parses foo but leaves "--bar" in `args`. The double-dash itself is removed from the argument array unless the `std.getopt.config.keepEndOfOptions` directive is given.
 
Examples:


```
auto args = ["prog", "--foo", "-b"];

bool foo;
bool bar;
auto rslt = getopt(args, "foo|f", "Some information about foo.", &foo, "bar|b",
    "Some help message about bar.", &bar);

if (rslt.helpWanted)
{
    defaultGetoptPrinter("Some information about the program.",
        rslt.options);
}

```
 
  enum **config**: int;  
Configuration options for `getopt`. 


You can pass them to `getopt` in any position, except in between an option string and its bound pointer.

 
**caseSensitive** 
Turn case sensitivity on

  **caseInsensitive** 
Turn case sensitivity off (default)

  **bundling** 
Turn bundling on

  **noBundling** 
Turn bundling off (default)

  **passThrough** 
Pass unrecognized arguments through

  **noPassThrough** 
Signal unrecognized arguments as errors (default)

  **stopOnFirstNonOption** 
Stop at first argument that does not look like an option

  **keepEndOfOptions** 
Do not erase the endOfOptions separator from args

  **required** 
Make the next option a required option

    struct **GetoptResult**;  
The result of the `getopt` function. 


`helpWanted` is set if the option `--help` or `-h` was passed to the option parser.

 
bool **helpWanted**;  
Flag indicating if help was requested

  Option[] **options**;  
All possible options

    struct **Option**;  
Information about an option.

 
string **optShort**;  
The short symbol for this option

  string **optLong**;  
The long symbol for this option

  string **help**;  
The description of this option

  bool **required**;  
If a option is required, not passing it will result in an error

    dchar **optionChar**;  
The option character (default '-'). 


Defaults to '-' but it can be assigned to prior to calling `getopt`.

  string **endOfOptions**;  
The string that conventionally marks the end of all options (default '--'). 


Defaults to "--" but can be assigned to prior to calling `getopt`. Assigning an empty string to `endOfOptions` effectively disables it.

  dchar **assignChar**;  
The assignment character used in options with parameters (default '='). 


Defaults to '=' but can be assigned to prior to calling `getopt`.

  string **arraySep**;  
When set to "", parameters to array and associative array receivers are treated as an individual argument. That is, only one argument is appended or inserted per appearance of the option switch. If `arraySep` is set to something else, then each parameter is first split by the separator, and the individual pieces are treated as arguments to the same option. 


Defaults to "" but can be assigned to prior to calling `getopt`.

  void **defaultGetoptPrinter**(string text, Option[] opt);  
This function prints the passed `Option`s and text in an aligned manner on `stdout`. 


The passed text will be printed first, followed by a newline, then the short and long version of every option will be printed. The short and long version will be aligned to the longest option of every `Option` passed. If the option is required, then "Required:" will be printed after the long version of the `Option`. If a help message is present it will be printed next. The format is illustrated by this code:   
  
 
```
foreach (it; opt)
{
    writefln("%*s %*s%s%s", lengthOfLongestShortOption, it.optShort,
        lengthOfLongestLongOption, it.optLong,
        it.required ? " Required: " : " ", it.help);
}

```
 

 
Parameters:


|  |  |
| --- | --- |
| string `text` | The text to printed at the beginning of the help output. |
| Option[] `opt` | The `Option` extracted from the `getopt` parameter. |


  void **defaultGetoptFormatter**(Output)(Output output, string text, Option[] opt, string style = "%\*s %\*s%\*s%s\x0a");  
This function writes the passed text and `Option` into an output range in the manner described in the documentation of function `defaultGetoptPrinter`, unless the style option is used. 



Parameters:


|  |  |
| --- | --- |
| Output `output` | The output range used to write the help information. |
| string `text` | The text to print at the beginning of the help output. |
| Option[] `opt` | The `Option` extracted from the `getopt` parameter. |
| string `style` | The manner in which to display the output of each `Option.` |


  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_getopt.html>

std.mathspecial
===============

 Mathematical Special Functions 


The technical term 'Special Functions' includes several families of transcendental functions, which have important applications in particular branches of mathematics and physics.   
  
 The gamma and related functions, and the error function are crucial for mathematical statistics. The Bessel and related functions arise in problems involving wave propagation (especially in optics). Other major categories of special functions include the elliptic integrals (related to the arc length of an ellipse), and the hypergeometric functions. 

 
Status
 Many more functions will be added to this module. The naming convention for the distribution functions (gammaIncomplete, etc) is not yet finalized and will probably change. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Stephen L. Moshier (original C code). Conversion to D by Don Clugston 
 
Source
 [std/mathspecial.d](https://github.com/dlang/phobos/blob/master/std/mathspecial.d)

 
pure nothrow @nogc @safe real **gamma**(real x);  
The Gamma function, Γ(x) 


Γ(x) is a generalisation of the factorial function to real and complex numbers. Like x!, Γ(x+1) = x \* Γ(x).   
  
 Mathematically, if z.re > 0 then Γ(z) = *∫0∞* tz-1e-t dt   
  
 

Special Values|  x |  Γ(x)  |
| NAN | NAN |
|  ±0.0 | ±∞ |
| integer > 0 |  (x-1)!  |
| integer < 0 | NAN |
| +∞ |  +∞  |
| -∞ | NAN |



  pure nothrow @nogc @safe real **logGamma**(real x);  
Natural logarithm of the gamma function, Γ(x) 


Returns the base e (2.718...) logarithm of the absolute value of the gamma function of the argument.   
  
 For reals, logGamma is equivalent to log(fabs(gamma(x))).   
  
 

Special Values|  x |  logGamma(x)  |
| NAN | NAN |
| integer <= 0 |  +∞  |
| ±∞ |  +∞  |



  pure nothrow @nogc @safe real **sgnGamma**(real x);  
The sign of Γ(x). 


Returns -1 if Γ(x) < 0, +1 if Γ(x) > 0, NAN if sign is indeterminate.   
  
 Note that this function can be used in conjunction with logGamma(x) to evaluate gamma for very large values of x.

  pure nothrow @nogc @safe real **beta**(real x, real y);  
Beta function 


The beta function is defined as   
  
 beta(x, y) = (Γ(x) \* Γ(y)) / Γ(x + y)

  pure nothrow @nogc @safe real **digamma**(real x);  
Digamma function 


The digamma function is the logarithmic derivative of the gamma function.   
  
 digamma(x) = d/dx logGamma(x) 

 
See Also:

[`logmdigamma`](#logmdigamma), [`logmdigammaInverse`](#logmdigammaInverse).
  pure nothrow @nogc @safe real **logmdigamma**(real x);  
Log Minus Digamma function 


logmdigamma(x) = log(x) - digamma(x) 

 
See Also:

[`digamma`](#digamma), [`logmdigammaInverse`](#logmdigammaInverse).
  pure nothrow @nogc @safe real **logmdigammaInverse**(real x);  
Inverse of the Log Minus Digamma function 


Given y, the function finds x such log(x) - digamma(x) = y. 

 
See Also:

[`logmdigamma`](#logmdigamma), [`digamma`](#digamma).
  pure nothrow @nogc @safe real **betaIncomplete**(real a, real b, real x);  
Incomplete beta integral 


Returns incomplete beta integral of the arguments, evaluated from zero to x. The regularized incomplete beta function is defined as   
  
 betaIncomplete(a, b, x) = Γ(a + b) / ( Γ(a) Γ(b) ) \* *∫0x* ta-1(1-t)b-1 dt   
  
 and is the same as the the cumulative distribution function.   
  
 The domain of definition is 0 <= x <= 1. In this implementation a and b are restricted to positive values. The integral from x to 1 may be obtained by the symmetry relation   
  
 betaIncompleteCompl(a, b, x ) = betaIncomplete( b, a, 1-x )   
  
 The integral is evaluated by a continued fraction expansion or, when b \* x is small, by a power series.

  pure nothrow @nogc @safe real **betaIncompleteInverse**(real a, real b, real y);  
Inverse of incomplete beta integral 


Given y, the function finds x such that   
  
 betaIncomplete(a, b, x) == y   
  
 Newton iterations or interval halving is used.

  pure nothrow @nogc @safe real **gammaIncomplete**(real a, real x);   
  
pure nothrow @nogc @safe real **gammaIncompleteCompl**(real a, real x);  
Incomplete gamma integral and its complement 


These functions are defined by   
  
 gammaIncomplete = ( *∫0x* e-t ta-1 dt )/ Γ(a)   
  
 gammaIncompleteCompl(a,x) = 1 - gammaIncomplete(a,x) = (*∫x∞* e-t ta-1 dt )/ Γ(a)   
  
 In this implementation both arguments must be positive. The integral is evaluated by either a power series or continued fraction expansion, depending on the relative values of a and x.

  pure nothrow @nogc @safe real **gammaIncompleteComplInverse**(real a, real p);  
Inverse of complemented incomplete gamma integral 


Given a and p, the function finds x such that   
  
 gammaIncompleteCompl( a, x ) = p.

  pure nothrow @nogc @safe real **erf**(real x);  
Error function 


The integral is   
  
 erf(x) = 2/ √(π) *∫0x* exp( - t2) dt   
  
 The magnitude of x is limited to about 106.56 for IEEE 80-bit arithmetic; 1 or -1 is returned outside this range.

  pure nothrow @nogc @safe real **erfc**(real x);  
Complementary error function 


erfc(x) = 1 - erf(x) = 2/ √(π) *∫x∞* exp( - t2) dt   
  
 This function has high relative accuracy for values of x far from zero. (For values near zero, use erf(x)).

  pure nothrow @nogc @safe real **normalDistribution**(real x);  
Standard normal distribution function. 


The normal (or Gaussian, or bell-shaped) distribution is defined as:   
  
 normalDist(x) = 1/√(2π) *∫-∞x* exp( - t2/2) dt = 0.5 + 0.5 \* erf(x/sqrt(2)) = 0.5 \* erfc(- x/sqrt(2))   
  
 To maintain accuracy at values of x near 1.0, use normalDistribution(x) = 1.0 - normalDistribution(-x). 

 
References
 <http://www.netlib.org/cephes/ldoubdoc.html>, G. Marsaglia, "Evaluating the Normal Distribution", Journal of Statistical Software **11**, (July 2004).
  pure nothrow @nogc @safe real **normalDistributionInverse**(real p);  
Inverse of Standard normal distribution function 


Returns the argument, x, for which the area under the Normal probability density function (integrated from minus infinity to x) is equal to p. 

 
Note
 This function is only implemented to 80 bit precision.
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_mathspecial.html>

std.mmfile
==========

 Read and write memory mapped files. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Matthew Wilson 
 
Source
 [std/mmfile.d](https://github.com/dlang/phobos/blob/master/std/mmfile.d) 
 
class **MmFile**;  
MmFile objects control the memory mapped file resource.

 
enum **Mode**: int;  
The mode the memory mapped file is opened with.

 
**read** 
Read existing file

  **readWriteNew** 
Delete existing file, write new file

  **readWrite** 
Read/Write existing file, create if not existing

  **readCopyOnWrite** 
Read/Write existing file, copy on write

    this(string filename);  
Open memory mapped file filename for reading. File is closed when the object instance is deleted. 



Throws:
std.file.FileException
  this(string filename, Mode mode, ulong size, void\* address, size\_t window = 0);  
Open memory mapped file filename in mode. File is closed when the object instance is deleted. 



Parameters:


|  |  |
| --- | --- |
| string `filename` | name of the file. If null, an anonymous file mapping is created. |
| Mode `mode` | access mode defined above. |
| ulong `size` | the size of the file. If 0, it is taken to be the size of the existing file. |
| void\* `address` | the preferred address to map the file to, although the system is not required to honor it. If null, the system selects the most convenient address. |
| size\_t `window` | preferred block size of the amount of data to map at one time with 0 meaning map the entire file. The window size must be a multiple of the memory allocation page size. |


 
Throws:
std.file.FileException
  const @property ulong **length**();  
Gives size in bytes of the memory mapped file.

  alias **opDollar** = length;  
Forwards `length`.

  Mode **mode**();  
Read-only property returning the file mode.

  void[] **opSlice**();  
Returns entire file contents as an array.

  void[] **opSlice**(ulong i1, ulong i2);  
Returns slice of file contents as an array.

  ubyte **opIndex**(ulong i);  
Returns byte at index i in file.

  ubyte **opIndexAssign**(ubyte value, ulong i);  
Sets and returns byte at index i in file to value.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_mmfile.html>

std.functional
==============

 Functions that manipulate other functions. 


This module provides functions for compile time function composition. These functions are helpful when constructing predicates for the algorithms in [`std.algorithm`](std_algorithm) or [`std.range`](std_range).   
  
 

| Function Name | Description |
| --- | --- |
| [`adjoin`](#adjoin) | Joins a couple of functions into one that executes the original functions independently and returns a tuple with all the results.  |
| [`compose`](#compose), [`pipe`](#pipe) | Join a couple of functions into one that executes the original functions one after the other, using one function's result for the next function's argument.  |
| [`forward`](#forward) | Forwards function arguments while saving ref-ness.  |
| [`lessThan`](#lessThan), [`greaterThan`](#greaterThan), [`equalTo`](#equalTo) | Ready-made predicate functions to compare two values.  |
| [`memoize`](#memoize) | Creates a function that caches its result for fast re-evaluation.  |
| [`not`](#not) | Creates a function that negates another.  |
| [`partial`](#partial) | Creates a function that binds the first argument of a given function to a given value.  |
| [`curry`](#curry) | Converts a multi-argument function into a series of single-argument functions. f(x, y) == curry(f)(x)(y)  |
| [`reverseArgs`](#reverseArgs) | Predicate that reverses the order of its arguments.  |
| [`toDelegate`](#toDelegate) | Converts a callable to a delegate.  |
| [`unaryFun`](#unaryFun), [`binaryFun`](#binaryFun) | Create a unary or binary function from a string. Most often used when defining algorithms on ranges.  |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) 
 
Source
 [std/functional.d](https://github.com/dlang/phobos/blob/master/std/functional.d)

 
template **unaryFun**(alias fun, string parmName = "a") 
Transforms a `string` representing an expression into a unary function. The `string` must either use symbol name `a` as the parameter or provide the symbol via the `parmName` argument. 



Parameters:


|  |  |
| --- | --- |
| fun | a `string` or a callable |
| parmName | the name of the parameter if `fun` is a string. Defaults to `"a"`. |


 
Returns:
If `fun` is a `string`, a new single parameter function If `fun` is not a `string`, an alias to `fun`.
 
Examples:


```
// Strings are compiled into functions:
alias isEven = unaryFun!("(a & 1) == 0");
assert(isEven(2) && !isEven(1));

```
 
  template **binaryFun**(alias fun, string parm1Name = "a", string parm2Name = "b") 
Transforms a `string` representing an expression into a binary function. The `string` must either use symbol names `a` and `b` as the parameters or provide the symbols via the `parm1Name` and `parm2Name` arguments. 



Parameters:


|  |  |
| --- | --- |
| fun | a `string` or a callable |
| parm1Name | the name of the first parameter if `fun` is a string. Defaults to `"a"`. |
| parm2Name | the name of the second parameter if `fun` is a string. Defaults to `"b"`. |


 
Returns:
If `fun` is not a string, `binaryFun` aliases itself away to `fun`.
 
Examples:


```
alias less = binaryFun!("a < b");
assert(less(1, 2) && !less(2, 1));
alias greater = binaryFun!("a > b");
assert(!greater("1", "2") && greater("2", "1"));

```
 
  alias **lessThan** = safeOp!"<".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);  
Predicate that returns a < b. Correctly compares signed and unsigned integers, ie. -1 < 2U.



Examples:


```
assert(lessThan(2, 3));
assert(lessThan(2U, 3U));
assert(lessThan(2, 3.0));
assert(lessThan(-2, 3U));
assert(lessThan(2, 3U));
assert(!lessThan(3U, -2));
assert(!lessThan(3U, 2));
assert(!lessThan(0, 0));
assert(!lessThan(0U, 0));
assert(!lessThan(0, 0U));

```
 
  alias **greaterThan** = safeOp!">".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);  
Predicate that returns a > b. Correctly compares signed and unsigned integers, ie. 2U > -1.



Examples:


```
assert(!greaterThan(2, 3));
assert(!greaterThan(2U, 3U));
assert(!greaterThan(2, 3.0));
assert(!greaterThan(-2, 3U));
assert(!greaterThan(2, 3U));
assert(greaterThan(3U, -2));
assert(greaterThan(3U, 2));
assert(!greaterThan(0, 0));
assert(!greaterThan(0U, 0));
assert(!greaterThan(0, 0U));

```
 
  alias **equalTo** = safeOp!"==".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);  
Predicate that returns a == b. Correctly compares signed and unsigned integers, ie. !(-1 == ~0U).



Examples:


```
assert(equalTo(0U, 0));
assert(equalTo(0, 0U));
assert(!equalTo(-1, ~0U));

```
 
  template **reverseArgs**(alias pred) 
N-ary predicate that reverses the order of arguments, e.g., given `pred(a, b, c)`, returns `pred(c, b, a)`. 



Parameters:


|  |  |
| --- | --- |
| pred | A callable |


 
Returns:
A function which calls `pred` after reversing the given parameters
 
Examples:


```
alias gt = reverseArgs!(binaryFun!("a < b"));
assert(gt(2, 1) && !gt(1, 1));

```
 
 
Examples:


```
int x = 42;
bool xyz(int a, int b) { return a * x < b / x; }
auto foo = &xyz;
foo(4, 5);
alias zyx = reverseArgs!(foo);
writeln(zyx(5, 4)); // foo(4, 5)

```
 
 
Examples:


```
alias gt = reverseArgs!(binaryFun!("a < b"));
assert(gt(2, 1) && !gt(1, 1));
int x = 42;
bool xyz(int a, int b) { return a * x < b / x; }
auto foo = &xyz;
foo(4, 5);
alias zyx = reverseArgs!(foo);
writeln(zyx(5, 4)); // foo(4, 5)

```
 
 
Examples:


```
int abc(int a, int b, int c) { return a * b + c; }
alias cba = reverseArgs!abc;
writeln(abc(91, 17, 32)); // cba(32, 17, 91)

```
 
 
Examples:


```
int a(int a) { return a * 2; }
alias _a = reverseArgs!a;
writeln(a(2)); // _a(2)

```
 
 
Examples:


```
int b() { return 4; }
alias _b = reverseArgs!b;
writeln(b()); // _b()

```
 
  template **not**(alias pred) 
Negates predicate `pred`. 



Parameters:


|  |  |
| --- | --- |
| pred | A string or a callable |


 
Returns:
A function which calls `pred` and returns the logical negation of its return value.
 
Examples:


```
import std.algorithm.searching : find;
import std.functional;
import std.uni : isWhite;
string a = "   Hello, world!";
writeln(find!(not!isWhite)(a)); // "Hello, world!"

```
 
  template **partial**(alias fun, alias arg) 
[Partially applies](http://en.wikipedia.org/wiki/Partial_application) fun by tying its first argument to arg. 



Parameters:


|  |  |
| --- | --- |
| fun | A callable |
| arg | The first argument to apply to `fun` |


 
Returns:
A new function which calls `fun` with `arg` plus the passed parameters.
 
Examples:


```
int fun(int a, int b) { return a + b; }
alias fun5 = partial!(fun, 5);
writeln(fun5(6)); // 11
// Note that in most cases you'd use an alias instead of a value
// assignment. Using an alias allows you to partially evaluate template
// functions without committing to a particular type of the function.

```
 
  auto **curry**(alias F)()  
 Constraints: if (isCallable!F && Parameters!F.length);   
  
auto **curry**(T)(T t)  
 Constraints: if (isCallable!T && Parameters!T.length); 
 
Takes a function of (potentially) many arguments, and returns a function taking one argument and returns a callable taking the rest. f(x, y) == curry(f)(x)(y) 



Parameters:


|  |  |
| --- | --- |
| F | a function taking at least one argument |
| T `t` | a callable object whose opCall takes at least 1 object |


 
Returns:
A single parameter callable object
 
Examples:


```
int f(int x, int y, int z)
{
    return x + y + z;
}
auto cf = curry!f;
auto cf1 = cf(1);
auto cf2 = cf(2);

writeln(cf1(2)(3)); // f(1, 2, 3)
writeln(cf2(2)(3)); // f(2, 2, 3)

```
 
 
Examples:


```
//works with callable structs too
struct S
{
    int w;
    int opCall(int x, int y, int z)
    {
        return w + x + y + z;
    }
}

S s;
s.w = 5;

auto cs = curry(s);
auto cs1 = cs(1);
auto cs2 = cs(2);

writeln(cs1(2)(3)); // s(1, 2, 3)
writeln(cs1(2)(3)); // (1 + 2 + 3 + 5)
writeln(cs2(2)(3)); // s(2, 2, 3)

```
 
  template **adjoin**(F...) if (F.length == 1)  
  
template **adjoin**(F...) if (F.length > 1) 
Takes multiple functions and adjoins them together. 



Parameters:


|  |  |
| --- | --- |
| F | the call-able(s) to adjoin |


 
Returns:
A new function which returns a [`std.typecons.Tuple`](std_typecons#Tuple). Each of the elements of the tuple will be the return values of `F`. 
 
Note
 In the special case where only a single function is provided (`F.length == 1`), adjoin simply aliases to the single passed function (`F[0]`).
 
Examples:


```
import std.functional, std.typecons : Tuple;
static bool f1(int a) { return a != 0; }
static int f2(int a) { return a / 2; }
auto x = adjoin!(f1, f2)(5);
assert(is(typeof(x) == Tuple!(bool, int)));
assert(x[0] == true && x[1] == 2);

```
 
  template **compose**(fun...) if (fun.length > 0) 
Composes passed-in functions `fun[0], fun[1], ...`. 



Parameters:


|  |  |
| --- | --- |
| fun | the call-able(s) or `string`(s) to compose into one function |


 
Returns:
A new function `f(x)` that in turn returns `fun[0](fun[1](...(x)))...`. 
 
See Also:
[`pipe`](#pipe)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.array : split;
import std.conv : to;

// First split a string in whitespace-separated tokens and then
// convert each token into an integer
assert(compose!(map!(to!(int)), split)("1 2 3").equal([1, 2, 3]));

```
 
  template **pipe**(fun...) 
Pipes functions in sequence. Offers the same functionality as  `compose`, but with functions specified in reverse order. This may lead to more readable code in some situation because the order of execution is the same as lexical order. 



Parameters:


|  |  |
| --- | --- |
| fun | the call-able(s) or `string`(s) to compose into one function |


 
Returns:
A new function `f(x)` that in turn returns `fun[$-1](...fun[1](fun[0](x)))...`. 
 
Example


```
// Read an entire text file, split the resulting string in
// whitespace-separated tokens, and then convert each token into an
// integer
int[] a = pipe!(readText, split, map!(to!(int)))("file.txt");

```
 
See Also:
[`compose`](#compose)
 
Examples:


```
import std.conv : to;
string foo(int a) { return to!(string)(a); }
int bar(string a) { return to!(int)(a) + 1; }
double baz(int a) { return a + 0.5; }
writeln(compose!(baz, bar, foo)(1)); // 2.5
writeln(pipe!(foo, bar, baz)(1)); // 2.5

writeln(compose!(baz, `to!(int)(a) + 1`, foo)(1)); // 2.5
writeln(compose!(baz, bar)("1"[])); // 2.5

writeln(compose!(baz, bar)("1")); // 2.5

writeln(compose!(`a + 0.5`, `to!(int)(a) + 1`, foo)(1)); // 2.5

```
 
  ReturnType!fun **memoize**(alias fun)(Parameters!fun args);   
  
ReturnType!fun **memoize**(alias fun, uint maxSize)(Parameters!fun args);  
[Memoizes](https://en.wikipedia.org/wiki/Memoization) a function so as to avoid repeated computation. The memoization structure is a hash table keyed by a tuple of the function's arguments. There is a speed gain if the function is repeatedly called with the same arguments and is more expensive than a hash table lookup. For more information on memoization, refer to [this book chapter](http://docs.google.com/viewer?url=http%3A%2F%2Fhop.perl.plover.com%2Fbook%2Fpdf%2F03CachingAndMemoization.pdf). 



Example


```
double transmogrify(int a, string b)
{
   ... expensive computation ...
}
alias fastTransmogrify = memoize!transmogrify;
unittest
{
    auto slow = transmogrify(2, "hello");
    auto fast = fastTransmogrify(2, "hello");
    assert(slow == fast);
}

```
 
Parameters:


|  |  |
| --- | --- |
| fun | the call-able to memozie |
| maxSize | The maximum size of the GC buffer to hold the return values |


 
Returns:
A new function which calls `fun` and caches its return values. 
 
Note
 Technically the memoized function should be pure because `memoize` assumes it will always return the same result for a given tuple of arguments. However, `memoize` does not enforce that because sometimes it is useful to memoize an impure function, too.
 
Examples:
To memoize a recursive function, simply insert the memoized call in lieu of the plain recursive call. For example, to transform the exponential-time Fibonacci implementation into a linear-time computation: 
```
ulong fib(ulong n) @safe nothrow
{
    return n < 2 ? n : memoize!fib(n - 2) + memoize!fib(n - 1);
}
writeln(fib(10)); // 55

```
 
 
Examples:
To improve the speed of the factorial function, 
```
ulong fact(ulong n) @safe
{
    return n < 2 ? 1 : n * memoize!fact(n - 1);
}
writeln(fact(10)); // 3628800

```
 
 
Examples:
This memoizes all values of `fact` up to the largest argument. To only cache the final result, move `memoize` outside the function as shown below. 
```
ulong factImpl(ulong n) @safe
{
    return n < 2 ? 1 : n * factImpl(n - 1);
}
alias fact = memoize!factImpl;
writeln(fact(10)); // 3628800

```
 
 
Examples:
When the `maxSize` parameter is specified, memoize will used a fixed size hash table to limit the number of cached entries. 
```
ulong fact(ulong n)
{
    // Memoize no more than 8 values
    return n < 2 ? 1 : n * memoize!(fact, 8)(n - 1);
}
writeln(fact(8)); // 40320
// using more entries than maxSize will overwrite existing entries
writeln(fact(10)); // 3628800

```
 
  auto **toDelegate**(F)(auto ref F fp)  
 Constraints: if (isCallable!F); 
 
Convert a callable to a delegate with the same parameter list and return type, avoiding heap allocations and use of auxiliary storage. 



Parameters:


|  |  |
| --- | --- |
| F `fp` | a function pointer or an aggregate type with `opCall` defined. |


 
Returns:
A delegate with the context pointer pointing to nothing. 
 
Example


```
void doStuff() {
    writeln("Hello, world.");
}

void runDelegate(void delegate() myDelegate) {
    myDelegate();
}

auto delegateToPass = toDelegate(&doStuff);
runDelegate(delegateToPass);  // Calls doStuff, prints "Hello, world."

```
 
Bugs:
* Does not work with `@safe` functions.
* Ignores C-style / D-style variadic arguments.

 
Examples:


```
static int inc(ref uint num) {
    num++;
    return 8675309;
}

uint myNum = 0;
auto incMyNumDel = toDelegate(&inc);
auto returnVal = incMyNumDel(myNum);
writeln(myNum); // 1

```
 
  template **forward**(args...) 
Forwards function arguments while keeping `out`, `ref`, and `lazy` on the parameters. 



Parameters:


|  |  |
| --- | --- |
| args | a parameter list or an [`std.meta.AliasSeq`](std_meta#AliasSeq). |


 
Returns:
An `AliasSeq` of `args` with `out`, `ref`, and `lazy` saved.
 
Examples:


```
class C
{
    static int foo(int n) { return 1; }
    static int foo(ref int n) { return 2; }
}

// with forward
int bar()(auto ref int x) { return C.foo(forward!x); }

// without forward
int baz()(auto ref int x) { return C.foo(x); }

int i;
writeln(bar(1)); // 1
writeln(bar(i)); // 2

writeln(baz(1)); // 2
writeln(baz(i)); // 2

```
 
 
Examples:


```
void foo(int n, ref string s) { s = null; foreach (i; 0 .. n) s ~= "Hello"; }

// forwards all arguments which are bound to parameter tuple
void bar(Args...)(auto ref Args args) { return foo(forward!args); }

// forwards all arguments with swapping order
void baz(Args...)(auto ref Args args) { return foo(forward!args[$/2..$], forward!args[0..$/2]); }

string s;
bar(1, s);
writeln(s); // "Hello"
baz(s, 2);
writeln(s); // "HelloHello"

```
 
 
Examples:


```
struct X {
    int i;
    this(this)
    {
        ++i;
    }
}

struct Y
{
    private X x_;
    this()(auto ref X x)
    {
        x_ = forward!x;
    }
}

struct Z
{
    private const X x_;
    this()(auto ref X x)
    {
        x_ = forward!x;
    }
    this()(auto const ref X x)
    {
        x_ = forward!x;
    }
}

X x;
const X cx;
auto constX = (){ const X x; return x; };
static assert(__traits(compiles, { Y y = x; }));
static assert(__traits(compiles, { Y y = X(); }));
static assert(!__traits(compiles, { Y y = cx; }));
static assert(!__traits(compiles, { Y y = constX(); }));
static assert(__traits(compiles, { Z z = x; }));
static assert(__traits(compiles, { Z z = X(); }));
static assert(__traits(compiles, { Z z = cx; }));
static assert(__traits(compiles, { Z z = constX(); }));


Y y1 = x;
// ref lvalue, copy
writeln(y1.x_.i); // 1
Y y2 = X();
// rvalue, move
writeln(y2.x_.i); // 0

Z z1 = x;
// ref lvalue, copy
writeln(z1.x_.i); // 1
Z z2 = X();
// rvalue, move
writeln(z2.x_.i); // 0
Z z3 = cx;
// ref const lvalue, copy
writeln(z3.x_.i); // 1
Z z4 = constX();
// const rvalue, copy
writeln(z4.x_.i); // 1

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_functional.html>

std.json
========

 JavaScript Object Notation 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Jeremie Pelletier, David Herberth 
 
References
 <http://json.org/>, <http://seriot.ch/parsing_json.html> 
 
Source
 [std/json.d](https://github.com/dlang/phobos/blob/master/std/json.d)

 
Examples:


```
import std.conv : to;

// parse a file or string of json into a usable structure
string s = `{ "language": "D", "rating": 3.5, "code": "42" }`;
JSONValue j = parseJSON(s);
// j and j["language"] return JSONValue,
// j["language"].str returns a string
writeln(j["language"].str); // "D"
writeln(j["rating"].floating); // 3.5

// check a type
long x;
if (const(JSONValue)* code = "code" in j)
{
    if (code.type() == JSONType.integer)
        x = code.integer;
    else
        x = to!int(code.str);
}

// create a json struct
JSONValue jj = [ "language": "D" ];
// rating doesnt exist yet, so use .object to assign
jj.object["rating"] = JSONValue(3.5);
// create an array to assign to list
jj.object["list"] = JSONValue( ["a", "b", "c"] );
// list already exists, so .object optional
jj["list"].array ~= JSONValue("D");

string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`;
writeln(jj.toString); // jjStr

```
 
 
enum **JSONFloatLiteral**: string;  
String literals used to represent special float values within JSON strings.

 
**nan** 
string representation of floating-point NaN

  **inf** 
string representation of floating-point Infinity

  **negativeInf** 
string representation of floating-point negative Infinity

    enum **JSONOptions**: int;  
Flags that control how json is encoded and parsed.

 
**none** 
standard parsing

  **specialFloatLiterals** 
encode NaN and Inf float values as strings

  **escapeNonAsciiChars** 
encode non ascii characters with an unicode escape sequence

  **doNotEscapeSlashes** 
do not escape slashes ('/')

  **strictParsing** 
Strictly follow RFC-8259 grammar when parsing

    enum **JSONType**: byte;  
JSON type enumeration

 

**null\_**  
  
**string**  
  
**integer**  
  
**uinteger**  
  
**float\_**  
  
**array**  
  
**object**  
  
**true\_**  
  
**false\_**
 
Indicates the type of a `JSONValue`.

    struct **JSONValue**;  
JSON value node

 
const pure nothrow @nogc @property @safe JSONType **type**();  
Returns the JSONType of the value stored in this structure.



Examples:


```
string s = "{ \"language\": \"D\" }";
JSONValue j = parseJSON(s);
writeln(j.type); // JSONType.object
writeln(j["language"].type); // JSONType.string

```
 
  const pure @property @trusted string **str**();   
  
pure nothrow @nogc @property @safe string **str**(string v);  
Value getter/setter for `JSONType.string`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.string`.
 
Examples:


```
JSONValue j = [ "language": "D" ];

// get value
writeln(j["language"].str); // "D"

// change existing key to new string
j["language"].str = "Perl";
writeln(j["language"].str); // "Perl"

```
 
  const pure @property @safe long **integer**();   
  
pure nothrow @nogc @property @safe long **integer**(long v);  
Value getter/setter for `JSONType.integer`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.integer`.
  const pure @property @safe ulong **uinteger**();   
  
pure nothrow @nogc @property @safe ulong **uinteger**(ulong v);  
Value getter/setter for `JSONType.uinteger`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.uinteger`.
  const pure @property @safe double **floating**();   
  
pure nothrow @nogc @property @safe double **floating**(double v);  
Value getter/setter for `JSONType.float_`. Note that despite the name, this is a **64**-bit `double`, not a 32-bit `float`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.float_`.
  const pure @property @safe bool **boolean**();   
  
pure nothrow @nogc @property @safe bool **boolean**(bool v);  
Value getter/setter for boolean stored in JSON. 



Throws:

`JSONException` for read access if `this.type` is not `JSONType.true_` or `JSONType.false_`.
 
Examples:


```
JSONValue j = true;
writeln(j.boolean); // true

j.boolean = false;
writeln(j.boolean); // false

j.integer = 12;
import std.exception : assertThrown;
assertThrown!JSONException(j.boolean);

```
 
  inout pure @property ref @system inout(JSONValue[string]) **object**();   
  
pure nothrow @nogc @property @safe JSONValue[string] **object**(JSONValue[string] v);  
Value getter/setter for `JSONType.object`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.object`. 
 
Note
 this is @system because of the following pattern: 


```
auto a = &(json.object());
json.uinteger = 0;        // overwrite AA pointer
(*a)["hello"] = "world";  // segmentation fault

```
  inout pure @property @trusted inout(JSONValue[string]) **objectNoRef**();  
Value getter for `JSONType.object`. Unlike `object`, this retrieves the object by value and can be used in @safe code. 


 A caveat is that, if the returned value is null, modifications will not be visible: 
```
JSONValue json;
json.object = null;
json.objectNoRef["hello"] = JSONValue("world");
assert("hello" !in json.object);

```
 

 
Throws:

`JSONException` for read access if `type` is not `JSONType.object`.
  inout pure @property ref @system inout(JSONValue[]) **array**();   
  
pure nothrow @nogc @property @safe JSONValue[] **array**(JSONValue[] v);  
Value getter/setter for `JSONType.array`. 



Throws:

`JSONException` for read access if `type` is not `JSONType.array`. 
 
Note
 this is @system because of the following pattern: 


```
auto a = &(json.array());
json.uinteger = 0;  // overwrite array pointer
(*a)[0] = "world";  // segmentation fault

```
  inout pure @property @trusted inout(JSONValue[]) **arrayNoRef**();  
Value getter for `JSONType.array`. Unlike `array`, this retrieves the array by value and can be used in @safe code. 


A caveat is that, if you append to the returned array, the new values aren't visible in the 

 
JSONValue


```
JSONValue json;
json.array = [JSONValue("hello")];
json.arrayNoRef ~= JSONValue("world");
assert(json.array.length == 1);

```
 
Throws:

`JSONException` for read access if `type` is not `JSONType.array`.
  const pure nothrow @nogc @property @safe bool **isNull**();  
Test whether the type is `JSONType.null_`

  inout const pure @property @safe inout(T) **get**(T)();   
  
inout pure @property @trusted inout(T) **get**(T : JSONValue[string])();  
Generic type value getter A convenience getter that returns this `JSONValue` as the specified D type. 



Note
 only numeric, `bool`, `string`, `JSONValue[string]` and `JSONValue[]` types are accepted 
 
Throws:

`JSONException` if `T` cannot hold the contents of this `JSONValue` `ConvException` in case of integer overflow when converting to `T`

 
Examples:


```
import std.exception;
import std.conv;
string s =
`{
    "a": 123,
    "b": 3.1415,
    "c": "text",
    "d": true,
    "e": [1, 2, 3],
    "f": { "a": 1 },
    "g": -45,
    "h": ` ~ ulong.max.to!string ~ `,
 }`;

struct a { }

immutable json = parseJSON(s);
writeln(json["a"].get!double); // 123.0
writeln(json["a"].get!int); // 123
writeln(json["a"].get!uint); // 123
writeln(json["b"].get!double); // 3.1415
assertThrown!JSONException(json["b"].get!int);
writeln(json["c"].get!string); // "text"
writeln(json["d"].get!bool); // true
assertNotThrown(json["e"].get!(JSONValue[]));
assertNotThrown(json["f"].get!(JSONValue[string]));
static assert(!__traits(compiles, json["a"].get!a));
assertThrown!JSONException(json["e"].get!float);
assertThrown!JSONException(json["d"].get!(JSONValue[string]));
assertThrown!JSONException(json["f"].get!(JSONValue[]));
writeln(json["g"].get!int); // -45
assertThrown!ConvException(json["g"].get!uint);
writeln(json["h"].get!ulong); // ulong.max
assertThrown!ConvException(json["h"].get!uint);
assertNotThrown(json["h"].get!float);

```
 
  this(T)(T arg)  
 Constraints: if (!isStaticArray!T);   
  
this(T)(ref T arg)  
 Constraints: if (isStaticArray!T);   
  
inout this(T : JSONValue)(inout T arg);  
Constructor for `JSONValue`. If `arg` is a `JSONValue` its value and type will be copied to the new `JSONValue`. Note that this is a shallow copy: if type is `JSONType.object` or `JSONType.array` then only the reference to the data will be copied. Otherwise, `arg` must be implicitly convertible to one of the following types: `typeof(null)`, `string`, `ulong`, `long`, `double`, an associative array `V[K]` for any `V` and `K` i.e. a JSON object, any array or `bool`. The type will be set accordingly.



Examples:


```
JSONValue j = JSONValue( "a string" );
j = JSONValue(42);

j = JSONValue( [1, 2, 3] );
writeln(j.type); // JSONType.array

j = JSONValue( ["language": "D"] );
writeln(j.type); // JSONType.object

```
 
  inout pure ref @safe inout(JSONValue) **opIndex**(size\_t i);  
Array syntax for json arrays. 



Throws:

`JSONException` if `type` is not `JSONType.array`.
 
Examples:


```
JSONValue j = JSONValue( [42, 43, 44] );
writeln(j[0].integer); // 42
writeln(j[1].integer); // 43

```
 
  inout pure ref @safe inout(JSONValue) **opIndex**(string k);  
Hash syntax for json objects. 



Throws:

`JSONException` if `type` is not `JSONType.object`.
 
Examples:


```
JSONValue j = JSONValue( ["language": "D"] );
writeln(j["language"].str); // "D"

```
 
  void **opIndexAssign**(T)(auto ref T value, string key);  
Operator sets `value` for element of JSON object by `key`. 


If JSON value is null, then operator initializes it with object and then sets `value` for it. 

 
Throws:

`JSONException` if `type` is not `JSONType.object` or `JSONType.null_`.
 
Examples:


```
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
writeln(j["language"].str); // "Perl"

```
 
  const @safe auto **opBinaryRight**(string op : "in")(string k);  
Support for the `in` operator. 


Tests wether a key can be found in an object. 

 
Returns:
when found, the `const(JSONValue)*` that matches to the key, otherwise `null`. 
 
Throws:

`JSONException` if the right hand side argument `JSONType` is not `object`.
 
Examples:


```
JSONValue j = [ "language": "D", "author": "walter" ];
string a = ("author" in j).str;

```
 
  @system int **opApply**(scope int delegate(size\_t index, ref JSONValue) dg);  
Implements the foreach `opApply` interface for json arrays.

  @system int **opApply**(scope int delegate(string key, ref JSONValue) dg);  
Implements the foreach `opApply` interface for json objects.

  const @safe string **toString**(in JSONOptions options = JSONOptions.none);  
Implicitly calls `toJSON` on this JSONValue. 


*options* can be used to tweak the conversion behavior.

  const void **toString**(Out)(Out sink, in JSONOptions options = JSONOptions.none);  const @safe string **toPrettyString**(in JSONOptions options = JSONOptions.none);  
Implicitly calls `toJSON` on this JSONValue, like `toString`, but also passes *true* as *pretty* argument. 


*options* can be used to tweak the conversion behavior

  const void **toPrettyString**(Out)(Out sink, in JSONOptions options = JSONOptions.none);    JSONValue **parseJSON**(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none)  
 Constraints: if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T)); 
 
Parses a serialized string and returns a tree of JSON values. 



Throws:

[`JSONException`](#JSONException) if string does not follow the JSON grammar or the depth exceeds the max depth, [`ConvException`](#ConvException) if a number in the input cannot be represented by a native D type. 
 
Parameters:


|  |  |
| --- | --- |
| T `json` | json-formatted string to parse |
| int `maxDepth` | maximum depth of nesting allowed, -1 disables depth checking |
| JSONOptions `options` | enable decoding string representations of NaN/Inf as float values |


  JSONValue **parseJSON**(T)(T json, JSONOptions options)  
 Constraints: if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T)); 
 
Parses a serialized string and returns a tree of JSON values. 



Throws:

[`JSONException`](#JSONException) if the depth exceeds the max depth. 
 
Parameters:


|  |  |
| --- | --- |
| T `json` | json-formatted string to parse |
| JSONOptions `options` | enable decoding string representations of NaN/Inf as float values |


  @safe string **toJSON**(ref const JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none);  
Takes a tree of JSON values and returns the serialized string. 


Any Object types will be serialized in a key-sorted order.   
  
 If `pretty` is false no whitespaces are generated. If `pretty` is true serialized string is formatted to be human-readable. Set the [`JSONOptions.specialFloatLiterals`](#JSONOptions.specialFloatLiterals) flag is set in `options` to encode NaN/Infinity as strings.

  void **toJSON**(Out)(auto ref Out json, ref const JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none)  
 Constraints: if (isOutputRange!(Out, char)); 
 class **JSONException**: object.Exception;  
Exception thrown on JSON errors

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_json.html>

std.experimental.checkedint
===========================


This module defines facilities for efficient checking of integral operations against overflow, casting with loss of precision, unexpected change of sign, etc. The checking (and possibly correction) can be done at operation level, for example [`opChecked`](#opChecked)`!"+"(x, y, overflow)` adds two integrals `x` and `y` and sets `overflow` to `true` if an overflow occurred. The flag `overflow` (a `bool` passed by reference) is not touched if the operation succeeded, so the same flag can be reused for a sequence of operations and tested at the end.   
  
 Issuing individual checked operations is flexible and efficient but often tedious. The [`Checked`](#Checked) facility offers encapsulated integral wrappers that do all checking internally and have configurable behavior upon erroneous results. For example, `Checked!int` is a type that behaves like `int` but aborts execution immediately whenever involved in an operation that produces the arithmetically wrong result. The accompanying convenience function [`checked`](#checked) uses type deduction to convert a value `x` of integral type `T` to `Checked!T` by means of `checked(x)`. For example:   
  
 
```
void main()
{
    import std.experimental.checkedint, std.stdio;
    writeln((checked(5) + 7).get); // 12
    writeln((checked(10) * 1000 * 1000 * 1000).get); // Overflow
}

```
   
  
 Similarly, `checked(-1) > uint(0)` aborts execution (even though the built-in comparison `int(-1) > uint(0)` is surprisingly true due to language's conversion rules modeled after C). Thus, `Checked!int` is a virtually drop-in replacement for `int` useable in debug builds, to be replaced by `int` in release mode if efficiency demands it.   
  
 `Checked` has customizable behavior with the help of a second type parameter, `Hook`. Depending on what methods `Hook` defines, core operations on the underlying integral may be verified for overflow or completely redefined. If `Hook` defines no method at all and carries no state, there is no change in behavior, i.e. `Checked!(int, void)` is a wrapper around `int` that adds no customization at all.   
  
 This module provides a few predefined hooks (below) that add useful behavior to `Checked`:   
  
 

|  |  |
| --- | --- |
| [`Abort`](#Abort) |  fails every incorrect operation with a message to [`std.stdio. stderr`](std_stdio#%20%20%20%20%20%20%20%20stderr) followed by a call to `assert(0)`. It is the default second parameter, i.e. `Checked!short` is the same as `Checked!(short, Abort)`.  |
| [`Throw`](#Throw) |  fails every incorrect operation by throwing an exception.  |
| [`Warn`](#Warn) |  prints incorrect operations to [`std.stdio.stderr`](std_stdio#stderr) but otherwise preserves the built-in behavior.  |
| [`ProperCompare`](#ProperCompare) |  fixes the comparison operators `==`, `!=`, `<`, `<=`, `>`, and `>=` to return correct results in all circumstances, at a slight cost in efficiency. For example, `Checked!(uint, ProperCompare)(1) > -1` is `true`, which is not the case for the built-in comparison. Also, comparing numbers for equality with floating-point numbers only passes if the integral can be converted to the floating-point number precisely, so as to preserve transitivity of equality.  |
| [`WithNaN`](#WithNaN) |  reserves a special "Not a Number" (NaN) value akin to the homonym value reserved for floating-point values. Once a `Checked!(X, WithNaN)` gets this special value, it preserves and propagates it until reassigned. [`isNaN`](#isNaN) can be used to query whether the object is not a number.  |
| [`Saturate`](#Saturate) |  implements saturating arithmetic, i.e. `Checked!(int, Saturate)` "stops" at `int.max` for all operations that would cause an `int` to overflow toward infinity, and at `int.min` for all operations that would correspondingly overflow toward negative infinity.  |

   
  
   
  
 These policies may be used alone, e.g. `Checked!(uint, WithNaN)` defines a `uint`-like type that reaches a stable NaN state for all erroneous operations. They may also be "stacked" on top of each other, owing to the property that a checked integral emulates an actual integral, which means another checked integral can be built on top of it. Some combinations of interest include:   
  
 

|  |
| --- |
| `Checked!(Checked!int, ProperCompare)` |
| defines an `int` with fixed comparison operators that will fail with `assert(0)` upon overflow. (Recall that `Abort` is the default policy.) The order in which policies are combined is important because the outermost policy (`ProperCompare` in this case) has the first crack at intercepting an operator. The converse combination `Checked!(Checked!(int, ProperCompare))` is meaningless because `Abort` will intercept comparison and will fail without giving `ProperCompare` a chance to intervene.  |
|  |
| `Checked!(Checked!(int, ProperCompare), WithNaN)` |
| defines an `int`-like type that supports a NaN value. For values that are not NaN, comparison works properly. Again the composition order is important; `Checked!(Checked!(int, WithNaN), ProperCompare)` does not have good semantics because `ProperCompare` intercepts comparisons before the numbers involved are tested for NaN.  |

   
  
 The hook's members are looked up statically in a Design by Introspection manner and are all optional. The table below illustrates the members that a hook type may define and their influence over the behavior of the `Checked` type using it. In the table, `hook` is an alias for `Hook` if the type `Hook` does not introduce any state, or an object of type `Hook` otherwise.   
  
 

| `Hook` member | Semantics in `Checked!(T, Hook)` |
| --- | --- |
| `defaultValue` | If defined, `Hook.defaultValue!T` is used as the default initializer of the payload. |
| `min` | If defined, `Hook.min!T` is used as the minimum value of the payload. |
| `max` | If defined, `Hook.max!T` is used as the maximum value of the payload. |
| `hookOpCast` | If defined, `hook.hookOpCast!U(get)` is forwarded to unconditionally when the payload is to be cast to type `U`. |
| `onBadCast` | If defined and `hookOpCast` is *not* defined, `onBadCast!U(get)` is forwarded to when the payload is to be cast to type `U` and the cast would lose information or force a change of sign. |
| `hookOpEquals` | If defined, `hook.hookOpEquals(get, rhs)` is forwarded to unconditionally when the payload is compared for equality against value `rhs` of integral, floating point, or Boolean type. |
| `hookOpCmp` | If defined, `hook.hookOpCmp(get, rhs)` is forwarded to unconditionally when the payload is compared for ordering against value `rhs` of integral, floating point, or Boolean type. |
| `hookOpUnary` | If defined, `hook.hookOpUnary!op(get)` (where `op` is the operator symbol) is forwarded to for unary operators `-` and `~`. In addition, for unary operators `++` and `--`, `hook.hookOpUnary!op(payload)` is called, where `payload` is a reference to the value wrapped by `Checked` so the hook can change it. |
| `hookOpBinary` | If defined, `hook.hookOpBinary!op(get, rhs)` (where `op` is the operator symbol and `rhs` is the right-hand side operand) is forwarded to unconditionally for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. |
| `hookOpBinaryRight` | If defined, `hook.hookOpBinaryRight!op(lhs, get)` (where `op` is the operator symbol and `lhs` is the left-hand side operand) is forwarded to unconditionally for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. |
| `onOverflow` | If defined, `hook.onOverflow!op(get)` is forwarded to for unary operators that overflow but only if `hookOpUnary` is not defined. Unary `~` does not overflow; unary `-` overflows only when the most negative value of a signed type is negated, and the result of the hook call is returned. When the increment or decrement operators overflow, the payload is assigned the result of `hook.onOverflow!op(get)`. When a binary operator overflows, the result of `hook.onOverflow!op(get, rhs)` is returned, but only if `Hook` does not define `hookOpBinary`. |
| `hookOpOpAssign` | If defined, `hook.hookOpOpAssign!op(payload, rhs)` (where `op` is the operator symbol and `rhs` is the right-hand side operand) is forwarded to unconditionally for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. |
| `onLowerBound` | If defined, `hook.onLowerBound(value, bound)` (where `value` is the value being assigned) is forwarded to when the result of binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` is smaller than the smallest value representable by `T`. |
| `onUpperBound` | If defined, `hook.onUpperBound(value, bound)` (where `value` is the value being assigned) is forwarded to when the result of binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` is larger than the largest value representable by `T`. |
| `hookToHash` | If defined, `hook.hookToHash(payload)` (where `payload` is a reference to the value wrapped by Checked) is forwarded to when `toHash` is called on a Checked type. Custom hashing can be implemented in a `Hook`, otherwise the built-in hashing is used. |

 

 
Source
 [std/experimental/checkedint.d](https://github.com/dlang/phobos/blob/master/std/experimental/checkedint.d)

 
Examples:


```
int[] concatAndAdd(int[] a, int[] b, int offset)
{
    // Aborts on overflow on size computation
    auto r = new int[(checked(a.length) + b.length).get];
    // Aborts on overflow on element computation
    foreach (i; 0 .. a.length)
        r[i] = (a[i] + checked(offset)).get;
    foreach (i; 0 .. b.length)
        r[i + a.length] = (b[i] + checked(offset)).get;
    return r;
}
writeln(concatAndAdd([1, 2, 3], [4, 5], -1)); // [0, 1, 2, 3, 4]

```
 
 
Examples:

`Saturate` stops at an overflow 
```
auto x = (cast(byte) 127).checked!Saturate;
writeln(x); // 127
x++;
writeln(x); // 127

```
 
 
Examples:

`WithNaN` has a special "Not a Number" (NaN) value akin to the homonym value reserved for floating-point values 
```
auto x = 100.checked!WithNaN;
writeln(x); // 100
x /= 0;
assert(x.isNaN);

```
 
 
Examples:

`ProperCompare` fixes the comparison operators ==, !=, <, <=, >, and >= to return correct results 
```
uint x = 1;
auto y = x.checked!ProperCompare;
assert(x < -1); // built-in comparison
assert(y > -1); // ProperCompare

```
 
 
Examples:

`Throw` fails every incorrect operation by throwing an exception 
```
import std.exception : assertThrown;
auto x = -1.checked!Throw;
assertThrown(x / 0);
assertThrown(x + int.min);
assertThrown(x == uint.max);

```
 
 
struct **Checked**(T, Hook = Abort) if (isIntegral!T || is(T == **Checked**!(U, H), U, H));  
Checked integral type wraps an integral `T` and customizes its behavior with the help of a `Hook` type. The type wrapped must be one of the predefined integrals (unqualified), or another instance of `Checked`.

 
alias **Representation** = T;  
The type of the integral subject to checking.

  Hook **hook**;  
`hook` is a member variable if it has state, or an alias for `Hook` otherwise.

  inout auto **get**();  
Returns a copy of the underlying value.



Examples:


```
auto x = checked(ubyte(42));
static assert(is(typeof(x.get()) == ubyte));
writeln(x.get); // 42
const y = checked(ubyte(42));
static assert(is(typeof(y.get()) == const ubyte));
writeln(y.get); // 42

```
 
  enum Checked!(T, Hook) **min**;   
  
enum Checked!(T, Hook) **max**;  
Defines the minimum and maximum. These values are hookable by defining `Hook.min` and/or `Hook.max`.



Examples:
Defines the minimum and maximum. These values are hookable by defining `Hook.min` and/or `Hook.max`. 
```
writeln(Checked!short.min); // -32768
writeln(Checked!(short, WithNaN).min); // -32767
writeln(Checked!(uint, WithNaN).max); // uint.max - 1

```
 
  this(U)(U rhs)  
 Constraints: if (valueConvertible!(U, T) || !isIntegral!T && is(typeof(T(rhs))) || is(U == Checked!(V, W), V, W) && is(typeof(Checked!(T, Hook)(rhs.get)))); 
 
Constructor taking a value properly convertible to the underlying type. `U` may be either an integral that can be converted to `T` without a loss, or another `Checked` instance whose representation may be in turn converted to `T` without a loss.



Examples:


```
auto a = checked(42L);
writeln(a); // 42
auto b = Checked!long(4242); // convert 4242 to long
writeln(b); // 4242

```
 
  ref Checked **opAssign**(U)(U rhs) return  
 Constraints: if (is(typeof(Checked!(T, Hook)(rhs)))); 
 
Assignment operator. Has the same constraints as the constructor.



Examples:


```
Checked!long a;
a = 42L;
writeln(a); // 42
a = 4242;
writeln(a); // 4242

```
 
 
Examples:


```
Checked!long a, b;
a = b = 3;
assert(a == 3 && b == 3);

```
 
  U **opCast**(U, this \_)()  
 Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool)); 
 
Casting operator to integral, `bool`, or floating point type. If `Hook` defines `hookOpCast`, the call immediately returns `hook.hookOpCast!U(get)`. Otherwise, casting to `bool` yields  `get != 0` and casting to another integral that can represent all values of `T` returns `get` promoted to `U`. 


If a cast to a floating-point type is requested and `Hook` defines `onBadCast`, the cast is verified by ensuring `get == cast(T) U(get)`. If that is not `true`, `hook.onBadCast!U(get)` is returned.   
  
 If a cast to an integral type is requested and `Hook` defines `onBadCast`, the cast is verified by ensuring `get` and `cast(U) get` are the same arithmetic number. (Note that `int(-1)` and `uint(1)` are different values arithmetically although they have the same bitwise representation and compare equal by language rules.) If the numbers are not arithmetically equal, `hook.onBadCast!U(get)` is returned.

 
Examples:


```
writeln(cast(uint)checked(42)); // 42
writeln(cast(uint)checked!WithNaN(-42)); // uint.max

```
 
  bool **opEquals**(U, this \_)(U rhs)  
 Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool) || is(U == Checked!(V, W), V, W) && is(typeof(this == rhs.payload))); 
 
Compares `this` against `rhs` for equality. If `Hook` defines `hookOpEquals`, the function forwards to  `hook.hookOpEquals(get, rhs)`. Otherwise, the result of the built-in operation `get == rhs` is returned. 


If `U` is also an instance of `Checked`, both hooks (left- and right-hand side) are introspected for the method `hookOpEquals`. If both define it, priority is given to the left-hand side.

 
Examples:


```
import std.traits : isUnsigned;

static struct MyHook
{
    static bool thereWereErrors;
    static bool hookOpEquals(L, R)(L lhs, R rhs)
    {
        if (lhs != rhs) return false;
        static if (isUnsigned!L && !isUnsigned!R)
        {
            if (lhs > 0 && rhs < 0) thereWereErrors = true;
        }
        else static if (isUnsigned!R && !isUnsigned!L)
            if (lhs < 0 && rhs > 0) thereWereErrors = true;
        // Preserve built-in behavior.
        return true;
    }
}
auto a = checked!MyHook(-42);
writeln(a); // uint(-42)
assert(MyHook.thereWereErrors);
MyHook.thereWereErrors = false;
writeln(checked!MyHook(uint(-42))); // -42
assert(MyHook.thereWereErrors);
static struct MyHook2
{
    static bool hookOpEquals(L, R)(L lhs, R rhs)
    {
        return lhs == rhs;
    }
}
MyHook.thereWereErrors = false;
writeln(checked!MyHook2(uint(-42))); // a
// Hook on left hand side takes precedence, so no errors
assert(!MyHook.thereWereErrors);

```
 
  const nothrow @safe size\_t **toHash**();  
Generates a hash for `this`. If `Hook` defines `hookToHash`, the call immediately returns `hook.hookToHash(payload)`. If `Hook` does not implement `hookToHash`, but it has state, a hash will be generated for the `Hook` using the built-in function and it will be xored with the hash of the `payload`.

  auto **opCmp**(U, this \_)(const U rhs)  
 Constraints: if (isIntegral!U || isFloatingPoint!U || is(U == bool));   
  
auto **opCmp**(U, Hook1, this \_)(Checked!(U, Hook1) rhs);  
Compares `this` against `rhs` for ordering. If `Hook` defines `hookOpCmp`, the function forwards to `hook.hookOpCmp(get, rhs)`. Otherwise, the result of the built-in comparison operation is returned. 


If `U` is also an instance of `Checked`, both hooks (left- and right-hand side) are introspected for the method `hookOpCmp`. If both define it, priority is given to the left-hand side.

 
Examples:


```
import std.traits : isUnsigned;

static struct MyHook
{
    static bool thereWereErrors;
    static int hookOpCmp(L, R)(L lhs, R rhs)
    {
        static if (isUnsigned!L && !isUnsigned!R)
        {
            if (rhs < 0 && rhs >= lhs)
                thereWereErrors = true;
        }
        else static if (isUnsigned!R && !isUnsigned!L)
        {
            if (lhs < 0 && lhs >= rhs)
                thereWereErrors = true;
        }
        // Preserve built-in behavior.
        return lhs < rhs ? -1 : lhs > rhs;
    }
}
auto a = checked!MyHook(-42);
assert(a > uint(42));
assert(MyHook.thereWereErrors);
static struct MyHook2
{
    static int hookOpCmp(L, R)(L lhs, R rhs)
    {
        // Default behavior
        return lhs < rhs ? -1 : lhs > rhs;
    }
}
MyHook.thereWereErrors = false;
assert(Checked!(uint, MyHook2)(uint(-42)) <= a);
//assert(Checked!(uint, MyHook2)(uint(-42)) >= a);
// Hook on left hand side takes precedence, so no errors
assert(!MyHook.thereWereErrors);
assert(a <= Checked!(uint, MyHook2)(uint(-42)));
assert(MyHook.thereWereErrors);

```
 
  auto **opUnary**(string op, this \_)()  
 Constraints: if (op == "+" || op == "-" || op == "~");   
  
ref Checked **opUnary**(string op)() return  
 Constraints: if (op == "++" || op == "--"); 
 
Defines unary operators `+`, `-`, `~`, `++`, and `--`. Unary `+` is not overridable and always has built-in behavior (returns `this`). For the others, if `Hook` defines `hookOpUnary`, `opUnary` forwards to  `Checked!(typeof(hook.hookOpUnary!op(get)), Hook)(hook.hookOpUnary!op(get))`. 


If `Hook` does not define `hookOpUnary` but defines `onOverflow`, `opUnary` forwards to `hook.onOverflow!op(get)` in case an overflow occurs. For `++` and `--`, the payload is assigned from the result of the call to `onOverflow`.   
  
 Note that unary `-` is considered to overflow if `T` is a signed integral of 32 or 64 bits and is equal to the most negative value. This is because that value has no positive negation.

 
Examples:


```
static struct MyHook
{
    static bool thereWereErrors;
    static L hookOpUnary(string x, L)(L lhs)
    {
        if (x == "-" && lhs == -lhs) thereWereErrors = true;
        return -lhs;
    }
}
auto a = checked!MyHook(long.min);
writeln(a); // -a
assert(MyHook.thereWereErrors);
auto b = checked!void(42);
writeln(++b); // 43

```
 
  auto **opBinary**(string op, Rhs)(const Rhs rhs)  
 Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool));   
  
const auto **opBinary**(string op, Rhs)(const Rhs rhs)  
 Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool));   
  
auto **opBinary**(string op, U, Hook1)(Checked!(U, Hook1) rhs);   
  
const auto **opBinary**(string op, U, Hook1)(Checked!(U, Hook1) rhs);  
Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. If `Hook` defines `hookOpBinary`, `opBinary` forwards to  `Checked!(typeof(hook.hookOpBinary!op(get, rhs)), Hook)(hook.hookOpBinary!op(get, rhs))`. 


If `Hook` does not define `hookOpBinary` but defines `onOverflow`, `opBinary` forwards to `hook.onOverflow!op(get, rhs)` in case an overflow occurs.   
  
 If two `Checked` instances are involved in a binary operation and both define `hookOpBinary`, the left-hand side hook has priority. If both define `onOverflow`, a compile-time error occurs.

  auto **opBinaryRight**(string op, Lhs)(const Lhs lhs)  
 Constraints: if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool));   
  
const auto **opBinaryRight**(string op, Lhs)(const Lhs lhs)  
 Constraints: if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool)); 
 
Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for the case when a built-in numeric or Boolean type is on the left-hand side, and a `Checked` instance is on the right-hand side. 

  ref Checked **opOpAssign**(string op, Rhs)(const Rhs rhs) return  
 Constraints: if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool));   
  
ref Checked **opOpAssign**(string op, Rhs)(const Rhs rhs) return  
 Constraints: if (is(Rhs == Checked!(RhsT, RhsHook), RhsT, RhsHook)); 
 
Defines operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. 


If `Hook` defines `hookOpOpAssign`, `opOpAssign` forwards to `hook.hookOpOpAssign!op(payload, rhs)`, where `payload` is a reference to the internally held data so the hook can change it.   
  
 Otherwise, the operator first evaluates `auto result = opBinary!op(payload, rhs).payload`, which is subject to the hooks in `opBinary`. Then, if `result` is less than `Checked!(T, Hook).min` and if `Hook` defines `onLowerBound`, the payload is assigned from  `hook.onLowerBound(result, min)`. If `result` is greater than `Checked!(T, Hook).max` and if `Hook` defines `onUpperBound`, the payload is assigned from `hook.onUpperBound(result, min)`.   
  
 If the right-hand side is also a Checked but with a different hook or underlying type, the hook and underlying type of this Checked takes precedence.   
  
 In all other cases, the built-in behavior is carried out. 

 
Parameters:


|  |  |
| --- | --- |
| op | The operator involved (without the `"="`, e.g. `"+"` for `"+="` etc) |
| Rhs `rhs` | The right-hand side of the operator (left-hand side is `this`) |


 
Returns:
A reference to `this`.
 
Examples:


```
static struct MyHook
{
    static bool thereWereErrors;
    static T onLowerBound(Rhs, T)(Rhs rhs, T bound)
    {
        thereWereErrors = true;
        return bound;
    }
    static T onUpperBound(Rhs, T)(Rhs rhs, T bound)
    {
        thereWereErrors = true;
        return bound;
    }
}
auto x = checked!MyHook(byte.min);
x -= 1;
assert(MyHook.thereWereErrors);
MyHook.thereWereErrors = false;
x = byte.max;
x += 1;
assert(MyHook.thereWereErrors);

```
 
    Checked!(T, Hook) **checked**(Hook = Abort, T)(const T value)  
 Constraints: if (is(typeof(Checked!(T, Hook)(value)))); 
 
Convenience function that turns an integral into the corresponding `Checked` instance by using template argument deduction. The hook type may be specified (by default `Abort`). 



Examples:


```
static assert(is(typeof(checked(42)) == Checked!int));
writeln(checked(42)); // Checked!int(42)
static assert(is(typeof(checked!WithNaN(42)) == Checked!(int, WithNaN)));
writeln(checked!WithNaN(42)); // Checked!(int, WithNaN)(42)

```
 
  struct **Abort**;  
Force all integral errors to fail by printing an error message to `stderr` and then abort the program. `Abort` is the default second argument for `Checked`. 

 
Dst **onBadCast**(Dst, Src)(Src src);  
Called automatically upon a bad cast (one that loses precision or attempts to convert a negative value to an unsigned type). The source type is `Src` and the destination type is `Dst`. 



Parameters:


|  |  |
| --- | --- |
| Src `src` | The source of the cast |


 
Returns:
Nominally the result is the desired value of the cast operation, which will be forwarded as the result of the cast. For `Abort`, the function never returns because it aborts the program.
  T **onLowerBound**(Rhs, T)(Rhs rhs, T bound);   
  
T **onUpperBound**(Rhs, T)(Rhs rhs, T bound);  
Called automatically upon a bounds error. 



Parameters:


|  |  |
| --- | --- |
| Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated |
| T `bound` | The value of the bound being violated |


 
Returns:
Nominally the result is the desired value of the operator, which will be forwarded as result. For `Abort`, the function never returns because it aborts the program.
  bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon a comparison for equality. In case of a erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value), this hook issues `assert(0)` which terminates the application. 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
Upon a correct comparison, returns the result of the comparison. Otherwise, the function terminates the application so it never returns.
  int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), then application is terminated with `assert(0)`. Otherwise, the three-state result is returned (positive if `lhs > rhs`, negative if `lhs < rhs`, `0` otherwise). 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
For correct comparisons, returns a positive integer if `lhs > rhs`, a negative integer if `lhs < rhs`, `0` if the two are equal. Upon a mistaken comparison such as `int(-1) < uint(0)`, the function never returns because it aborts the program.
  typeof(~Lhs()) **onOverflow**(string x, Lhs)(Lhs lhs);   
  
typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon an overflow during a unary or binary operation. 



Parameters:


|  |  |
| --- | --- |
| x | The operator, e.g. `-` |
| Lhs `lhs` | The left-hand side (or sole) argument |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
Nominally the result is the desired value of the operator, which will be forwarded as result. For `Abort`, the function never returns because it aborts the program.
    struct **Throw**;  
Force all integral errors to fail by throwing an exception of type `Throw.CheckFailure`. The message coming with the error is similar to the one printed by `Warn`. 



Examples:


```
void test(T)()
{
    Checked!(int, Throw) x;
    x = 42;
    auto x1 = cast(T) x;
    writeln(x1); // 42
    x = T.max + 1;
    import std.exception : assertThrown, assertNotThrown;
    assertThrown(cast(T) x);
    x = x.max;
    assertThrown(x += 42);
    assertThrown(x += 42L);
    x = x.min;
    assertThrown(-x);
    assertThrown(x -= 42);
    assertThrown(x -= 42L);
    x = -1;
    assertNotThrown(x == -1);
    assertThrown(x == uint(-1));
    assertNotThrown(x <= -1);
    assertThrown(x <= uint(-1));
}
test!short;
test!(const short);
test!(immutable short);

```
 
 
class **CheckFailure**: object.Exception;  
Exception type thrown upon any failure.

  Dst **onBadCast**(Dst, Src)(Src src);  
Called automatically upon a bad cast (one that loses precision or attempts to convert a negative value to an unsigned type). The source type is `Src` and the destination type is `Dst`. 



Parameters:


|  |  |
| --- | --- |
| Src `src` | The source of the cast |


 
Returns:
Nominally the result is the desired value of the cast operation, which will be forwarded as the result of the cast. For `Throw`, the function never returns because it throws an exception.
  T **onLowerBound**(Rhs, T)(Rhs rhs, T bound);   
  
T **onUpperBound**(Rhs, T)(Rhs rhs, T bound);  
Called automatically upon a bounds error. 



Parameters:


|  |  |
| --- | --- |
| Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated |
| T `bound` | The value of the bound being violated |


 
Returns:
Nominally the result is the desired value of the operator, which will be forwarded as result. For `Throw`, the function never returns because it throws.
  bool **hookOpEquals**(L, R)(L lhs, R rhs);  
Called automatically upon a comparison for equality. Throws upon an erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value). 



Parameters:


|  |  |
| --- | --- |
| L `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| R `rhs` | The right-hand side type involved in the operator |


 
Returns:
The result of the comparison. 
 
Throws:

`CheckFailure` if the comparison is mathematically erroneous.
  int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), throws a `Throw.CheckFailure` exception. Otherwise, the three-state result is returned (positive if `lhs > rhs`, negative if `lhs < rhs`, `0` otherwise). 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
For correct comparisons, returns a positive integer if `lhs > rhs`, a negative integer if `lhs < rhs`, `0` if the two are equal. 
 
Throws:
Upon a mistaken comparison such as `int(-1) < uint(0)`, the function never returns because it throws a `Throw.CheckedFailure` exception.
  typeof(~Lhs()) **onOverflow**(string x, Lhs)(Lhs lhs);   
  
typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon an overflow during a unary or binary operation. 



Parameters:


|  |  |
| --- | --- |
| x | The operator, e.g. `-` |
| Lhs `lhs` | The left-hand side (or sole) argument |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
Nominally the result is the desired value of the operator, which will be forwarded as result. For `Throw`, the function never returns because it throws an exception.
    struct **Warn**;  
Hook that prints to `stderr` a trace of all integral errors, without affecting default behavior.



Examples:


```
auto x = checked!Warn(42);
short x1 = cast(short) x;
//x += long(int.max);
auto y = checked!Warn(cast(const int) 42);
short y1 = cast(const byte) y;

```
 
 
Dst **onBadCast**(Dst, Src)(Src src);  
Called automatically upon a bad cast from `src` to type `Dst` (one that loses precision or attempts to convert a negative value to an unsigned type). 



Parameters:


|  |  |
| --- | --- |
| Src `src` | The source of the cast |
| Dst | The target type of the cast |


 
Returns:
`cast(Dst) src`
  Lhs **onLowerBound**(Rhs, T)(Rhs rhs, T bound);   
  
T **onUpperBound**(Rhs, T)(Rhs rhs, T bound);  
Called automatically upon a bad `opOpAssign` call (one that loses precision or attempts to convert a negative value to an unsigned type). 



Parameters:


|  |  |
| --- | --- |
| Rhs `rhs` | The right-hand side value in the assignment, after the operator has been evaluated |
| T `bound` | The bound being violated |


 
Returns:
`cast(Lhs) rhs`
  bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon a comparison for equality. In case of an Erroneous comparison (one that would make a signed negative value appear equal to an unsigned positive value), writes a warning message to `stderr` as a side effect. 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
In all cases the function returns the built-in result of `lhs == rhs`.
 
Examples:


```
auto x = checked!Warn(-42);
// Passes
writeln(x); // -42
// Passes but prints a warning
// assert(x == uint(-42));

```
 
  int **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon a comparison for ordering using one of the operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. it would make a signed negative value appear greater than or equal to an unsigned positive value), then a warning message is printed to `stderr`. 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs `rhs` | The right-hand side type involved in the operator |


 
Returns:
In all cases, returns `lhs < rhs ? -1 : lhs > rhs`. The result is not autocorrected in case of an erroneous comparison.
 
Examples:


```
auto x = checked!Warn(-42);
// Passes
assert(x <= -42);
// Passes but prints a warning
// assert(x <= uint(-42));

```
 
  typeof(~Lhs()) **onOverflow**(string x, Lhs)(ref Lhs lhs);   
  
typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Called automatically upon an overflow during a unary or binary operation. 



Parameters:


|  |  |
| --- | --- |
| x | The operator involved |
| Lhs | The first argument of `Checked`, e.g. `int` if the left-hand side of the operator is `Checked!int` |
| Rhs | The right-hand side type involved in the operator |


 
Returns:

`mixin(x ~ "lhs")` for unary, `mixin("lhs" ~ x ~ "rhs")` for binary
    struct **ProperCompare**;  
Hook that provides arithmetically correct comparisons for equality and ordering. Comparing an object of type `Checked!(X, ProperCompare)` against another integral (for equality or ordering) ensures that no surprising conversions from signed to unsigned integral occur before the comparison. Using `Checked!(X, ProperCompare)` on either side of a comparison for equality against a floating-point number makes sure the integral can be properly converted to the floating point type, thus making sure equality is transitive. 



Examples:


```
alias opEqualsProper = ProperCompare.hookOpEquals;
assert(opEqualsProper(42, 42));
assert(opEqualsProper(42.0, 42.0));
assert(opEqualsProper(42u, 42));
assert(opEqualsProper(42, 42u));
writeln(-1); // 4294967295u
assert(!opEqualsProper(-1, 4294967295u));
assert(!opEqualsProper(const uint(-1), -1));
assert(!opEqualsProper(uint(-1), -1.0));
writeln(3_000_000_000U); // -1_294_967_296
assert(!opEqualsProper(3_000_000_000U, -1_294_967_296));

```
 
 
bool **hookOpEquals**(L, R)(L lhs, R rhs);  
Hook for `==` and `!=` that ensures comparison against integral values has the behavior expected by the usual arithmetic rules. The built-in semantics yield surprising behavior when comparing signed values against unsigned values for equality, for example `uint.max == -1` or `-1_294_967_296 == 3_000_000_000u`. The call `hookOpEquals(x, y)` returns `true` if and only if `x` and `y` represent the same arithmetic number. 


If one of the numbers is an integral and the other is a floating-point number, `hookOpEquals(x, y)` returns `true` if and only if the integral can be converted exactly (without approximation) to the floating-point number. This is in order to preserve transitivity of equality: if  `hookOpEquals(x, y)` and `hookOpEquals(y, z)` then `hookOpEquals(y, z)`, in case `x`, `y`, and `z` are a mix of integral and floating-point numbers. 

 
Parameters:


|  |  |
| --- | --- |
| L `lhs` | The left-hand side of the comparison for equality |
| R `rhs` | The right-hand side of the comparison for equality |


 
Returns:
The result of the comparison, `true` if the values are equal
  auto **hookOpCmp**(L, R)(L lhs, R rhs);  
Hook for `<`, `<=`, `>`, and `>=` that ensures comparison against integral values has the behavior expected by the usual arithmetic rules. The built-in semantics yield surprising behavior when comparing signed values against unsigned values, for example `0u < -1`. The call `hookOpCmp(x, y)` returns `-1` if and only if `x` is smaller than `y` in abstract arithmetic sense. 


If one of the numbers is an integral and the other is a floating-point number, `hookOpEquals(x, y)` returns a floating-point number that is `-1` if `x < y`, `0` if `x == y`, `1` if `x > y`, and `NaN` if the floating-point number is `NaN`. 

 
Parameters:


|  |  |
| --- | --- |
| L `lhs` | The left-hand side of the comparison for ordering |
| R `rhs` | The right-hand side of the comparison for ordering |


 
Returns:
The result of the comparison (negative if `lhs < rhs`, positive if  `lhs > rhs`, `0` if the values are equal)
    struct **WithNaN**;  
Hook that reserves a special value as a "Not a Number" representative. For signed integrals, the reserved value is `T.min`. For signed integrals, the reserved value is `T.max`. 


The default value of a `Checked!(X, WithNaN)` is its NaN value, so care must be taken that all variables are explicitly initialized. Any arithmetic and logic operation involving at least on NaN becomes NaN itself. All of `a == b`, `a < b`, `a > b`, `a <= b`, `a >= b` yield `false` if at least one of `a` and `b` is NaN.

 
Examples:


```
auto x1 = Checked!(int, WithNaN)();
assert(x1.isNaN);
writeln(x1.get); // int.min
assert(x1 != x1);
assert(!(x1 < x1));
assert(!(x1 > x1));
assert(!(x1 == x1));
++x1;
assert(x1.isNaN);
writeln(x1.get); // int.min
--x1;
assert(x1.isNaN);
writeln(x1.get); // int.min
x1 = 42;
assert(!x1.isNaN);
writeln(x1); // x1
assert(x1 <= x1);
assert(x1 >= x1);
static assert(x1.min == int.min + 1);
x1 += long(int.max);

```
 
 
enum T **defaultValue**(T);  
The default value used for values not explicitly initialized. It is the NaN value, i.e. `T.min` for signed integrals and `T.max` for unsigned integrals.

  enum T **max**(T);   
  
enum T **min**(T);  
The maximum value representable is `T.max` for signed integrals,  `T.max - 1` for unsigned integrals. The minimum value representable is  `T.min + 1` for signed integrals, `0` for unsigned integrals.

  Lhs **hookOpCast**(Lhs, Rhs)(Rhs rhs);  
If `rhs` is `WithNaN.defaultValue!Rhs`, returns `WithNaN.defaultValue!Lhs`. Otherwise, returns `cast(Lhs) rhs`. 



Parameters:


|  |  |
| --- | --- |
| Rhs `rhs` | the value being cast (`Rhs` is the first argument to `Checked`) |
| Lhs | the target type of the cast |


 
Returns:
The result of the cast operation.
 
Examples:


```
auto x = checked!WithNaN(422);
writeln((cast(ubyte)x)); // 255
x = checked!WithNaN(-422);
writeln((cast(byte)x)); // -128
writeln(cast(short)x); // -422
assert(cast(bool) x);
x = x.init; // set back to NaN
assert(x != true);
assert(x != false);

```
 
  bool **hookOpEquals**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Returns `false` if `lhs == WithNaN.defaultValue!Lhs`, `lhs == rhs` otherwise. 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The left-hand side of the comparison (`Lhs` is the first argument to `Checked`) |
| Rhs `rhs` | The right-hand side of the comparison |


 
Returns:
`lhs != WithNaN.defaultValue!Lhs && lhs == rhs`
  double **hookOpCmp**(Lhs, Rhs)(Lhs lhs, Rhs rhs);  
If `lhs == WithNaN.defaultValue!Lhs`, returns `double.init`. Otherwise, has the same semantics as the default comparison. 



Parameters:


|  |  |
| --- | --- |
| Lhs `lhs` | The left-hand side of the comparison (`Lhs` is the first argument to `Checked`) |
| Rhs `rhs` | The right-hand side of the comparison |


 
Returns:

`double.init` if `lhs == WitnNaN.defaultValue!Lhs`, `-1.0` if  `lhs < rhs`, `0.0` if `lhs == rhs`, `1.0` if `lhs > rhs`.
 
Examples:


```
Checked!(int, WithNaN) x;
assert(!(x < 0) && !(x > 0) && !(x == 0));
x = 1;
assert(x > 0 && !(x < 0) && !(x == 0));

```
 
  auto **hookOpUnary**(string x, T)(ref T v);  
Defines hooks for unary operators `-`, `~`, `++`, and `--`. 


For `-` and `~`, if `v == WithNaN.defaultValue!T`, returns `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the built-in operator.   
  
 For `++` and `--`, if `v == WithNaN.defaultValue!Lhs` or the operation would result in an overflow, sets `v` to `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the built-in operator. 

 
Parameters:


|  |  |
| --- | --- |
| x | The operator symbol |
| T `v` | The left-hand side of the comparison (`T` is the first argument to `Checked`) |


 
Returns:
* For `x == "-" || x == "~"`: If `v == WithNaN.defaultValue!T`, the function returns `WithNaN.defaultValue!T`. Otherwise it returns the normal result of the operator.
* For `x == "++" || x == "--"`: The function returns `void`.

 
Examples:


```
Checked!(int, WithNaN) x;
++x;
assert(x.isNaN);
x = 1;
assert(!x.isNaN);
x = -x;
++x;
assert(!x.isNaN);

```
 
  auto **hookOpBinary**(string x, L, R)(L lhs, R rhs);  
Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the left-hand side operand. If `lhs == WithNaN.defaultValue!Lhs`, returns `WithNaN.defaultValue!(typeof(lhs + rhs))` without evaluating the operand. Otherwise, evaluates the operand. If evaluation does not overflow, returns the result. Otherwise, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. 



Parameters:


|  |  |
| --- | --- |
| x | The operator symbol |
| L `lhs` | The left-hand side operand (`Lhs` is the first argument to `Checked`) |
| R `rhs` | The right-hand side operand |


 
Returns:
If `lhs != WithNaN.defaultValue!Lhs` and the operator does not overflow, the function returns the same result as the built-in operator. In all other cases, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`.
 
Examples:


```
Checked!(int, WithNaN) x;
assert((x + 1).isNaN);
x = 100;
assert(!(x + 1).isNaN);

```
 
  auto **hookOpBinaryRight**(string x, L, R)(L lhs, R rhs);  
Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the right-hand side operand. If `rhs == WithNaN.defaultValue!Rhs`, returns `WithNaN.defaultValue!(typeof(lhs + rhs))` without evaluating the operand. Otherwise, evaluates the operand. If evaluation does not overflow, returns the result. Otherwise, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`. 



Parameters:


|  |  |
| --- | --- |
| x | The operator symbol |
| L `lhs` | The left-hand side operand |
| R `rhs` | The right-hand side operand (`Rhs` is the first argument to `Checked`) |


 
Returns:
If `rhs != WithNaN.defaultValue!Rhs` and the operator does not overflow, the function returns the same result as the built-in operator. In all other cases, returns `WithNaN.defaultValue!(typeof(lhs + rhs))`.
 
Examples:


```
Checked!(int, WithNaN) x;
assert((1 + x).isNaN);
x = 100;
assert(!(1 + x).isNaN);

```
 
  void **hookOpOpAssign**(string x, L, R)(ref L lhs, R rhs);  
Defines hooks for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` for cases where a `Checked` object is the left-hand side operand. If `lhs == WithNaN.defaultValue!Lhs`, no action is carried. Otherwise, evaluates the operand. If evaluation does not overflow and fits in `Lhs` without loss of information or change of sign, sets `lhs` to the result. Otherwise, sets `lhs` to `WithNaN.defaultValue!Lhs`. 



Parameters:


|  |  |
| --- | --- |
| x | The operator symbol (without the `=`) |
| L `lhs` | The left-hand side operand (`Lhs` is the first argument to `Checked`) |
| R `rhs` | The right-hand side operand |


 
Returns:
`void`
 
Examples:


```
Checked!(int, WithNaN) x;
x += 4;
assert(x.isNaN);
x = 0;
x += 4;
assert(!x.isNaN);
x += int.max;
assert(x.isNaN);

```
 
    bool **isNaN**(T)(const Checked!(T, WithNaN) x);  
Queries whether a `Checked!(T, WithNaN)` object is not a number (NaN). 



Parameters:


|  |  |
| --- | --- |
| Checked!(T, WithNaN) `x` | the `Checked` instance queried |


 
Returns:

`true` if `x` is a NaN, `false` otherwise
 
Examples:


```
auto x1 = Checked!(int, WithNaN)();
assert(x1.isNaN);
x1 = 1;
assert(!x1.isNaN);
x1 = x1.init;
assert(x1.isNaN);

```
 
  struct **Saturate**;  
Hook that implements *saturation*, i.e. any arithmetic operation that would overflow leaves the result at its extreme value (`min` or `max` depending on the direction of the overflow). 


Saturation is not sticky; if a value reaches its saturation value, another operation may take it back to normal range.

 
Examples:


```
auto x = checked!Saturate(int.max);
++x;
writeln(x); // int.max
--x;
writeln(x); // int.max - 1
x = int.min;
writeln(-x); // int.max
x -= 42;
writeln(x); // int.min
writeln(x * -2); // int.max

```
 
 
T **onLowerBound**(Rhs, T)(Rhs rhs, T bound);   
  
T **onUpperBound**(Rhs, T)(Rhs rhs, T bound);  
Implements saturation for operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`. This hook is called if the result of the binary operation does not fit in `Lhs` without loss of information or a change in sign. 



Parameters:


|  |  |
| --- | --- |
| Rhs | The right-hand side type in the assignment, after the operation has been computed |
| T `bound` | The bound being violated |


 
Returns:

`Lhs.max` if `rhs >= 0`, `Lhs.min` otherwise.
 
Examples:


```
auto x = checked!Saturate(short(100));
x += 33000;
writeln(x); // short.max
x -= 70000;
writeln(x); // short.min

```
 
  auto **onOverflow**(string x, Lhs)(Lhs lhs);   
  
typeof(Lhs() + Rhs()) **onOverflow**(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs);  
Implements saturation for operators `+`, `-` (unary and binary), `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. 


For unary `-`, `onOverflow` is called if `lhs == Lhs.min` and `Lhs` is a signed type. The function returns `Lhs.max`.   
  
 For binary operators, the result is as follows: * `Lhs.max` if the result overflows in the positive direction, on division by `0`, or on shifting right by a negative value
* `Lhs.min` if the result overflows in the negative direction
* `0` if `lhs` is being shifted left by a negative value, or shifted right by a large positive value

 

 
Parameters:


|  |  |
| --- | --- |
| x | The operator involved in the `opAssign` operation |
| Lhs | The left-hand side of the operator (`Lhs` is the first argument to `Checked`) |
| Rhs | The right-hand side type in the operator |


 
Returns:
The saturated result of the operator.
 
Examples:


```
writeln(checked!Saturate(int.max) + 1); // int.max
writeln(checked!Saturate(100)^^10); // int.max
writeln(checked!Saturate(-100)^^10); // int.max
writeln(checked!Saturate(100) / 0); // int.max
writeln(checked!Saturate(100) << -1); // 0
writeln(checked!Saturate(100) << 33); // int.max
writeln(checked!Saturate(100) >> -1); // int.max
writeln(checked!Saturate(100) >> 33); // 0

```
 
    typeof(mixin(x == "cmp" ? "0" : "L() " ~ x ~ " R()")) **opChecked**(string x, L, R)(const L lhs, const R rhs, ref bool overflow)  
 Constraints: if (isIntegral!L && isIntegral!R); 
 
Defines binary operations with overflow checking for any two integral types. The result type obeys the language rules (even when they may be counterintuitive), and `overflow` is set if an overflow occurs (including inadvertent change of signedness, e.g. `-1` is converted to `uint`). Conceptually the behavior is: 


1. Perform the operation in infinite precision
2. If the infinite-precision result fits in the result type, return it and do not touch `overflow`
3. Otherwise, set `overflow` to `true` and return an unspecified value

   
  
 The implementation exploits properties of types and operations to minimize additional work. 

 
Parameters:


|  |  |
| --- | --- |
| x | The binary operator involved, e.g. `/` |
| L `lhs` | The left-hand side of the operator |
| R `rhs` | The right-hand side of the operator |
| bool `overflow` | The overflow indicator (assigned `true` in case there's an error) |


 
Returns:
The result of the operation, which is the same as the built-in operator
 
Examples:


```
bool overflow;
assert(opChecked!"+"(const short(1), short(1), overflow) == 2 && !overflow);
assert(opChecked!"+"(1, 1, overflow) == 2 && !overflow);
assert(opChecked!"+"(1, 1u, overflow) == 2 && !overflow);
assert(opChecked!"+"(-1, 1u, overflow) == 0 && !overflow);
assert(opChecked!"+"(1u, -1, overflow) == 0 && !overflow);

```
 
 
Examples:


```
bool overflow;
assert(opChecked!"-"(1, 1, overflow) == 0 && !overflow);
assert(opChecked!"-"(1, 1u, overflow) == 0 && !overflow);
assert(opChecked!"-"(1u, -1, overflow) == 2 && !overflow);
assert(opChecked!"-"(-1, 1u, overflow) == 0 && overflow);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_experimental_checkedint.html>

std.net.isemail
===============

 Validates an email address according to RFCs 5321, 5322 and others. 



Authors:
Dominic Sayers <dominic@sayers.cc>, Jacob Carlborg 
 
License:

[Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt) Dominic Sayers graciously granted permission to use the Boost license via email on Feb 22, 2011. 
 
Version:
3.0.13 - Version 3.0 of the original PHP implementation: <http://www.dominicsayers.com/isemail> 
 
Standards:

* RFC 5321
* RFC 5322

 
 
References

* <http://www.dominicsayers.com/isemail>
* <http://tools.ietf.org/html/rfc5321>
* <http://tools.ietf.org/html/rfc5322>

 
Source
 [std/net/isemail.d](https://github.com/dlang/phobos/blob/master/std/net/isemail.d)

 
EmailStatus **isEmail**(Char)(const(Char)[] email, CheckDns checkDNS = No.checkDns, EmailStatusCode errorLevel = EmailStatusCode.none)  
 Constraints: if (isSomeChar!Char); 
 
Check that an email address conforms to RFCs 5321, 5322 and others. 


Distinguishes between a Mailbox as defined by RFC 5321 and an addr-spec as defined by RFC 5322. Depending on the context, either can be regarded as a valid email address. 

 
Note
 The DNS check is currently not implemented. 
 
Parameters:


|  |  |
| --- | --- |
| const(Char)[] `email` | The email address to check |
| CheckDns `checkDNS` | If `Yes.checkDns` then a DNS check for MX records will be made |
| EmailStatusCode `errorLevel` | Determines the boundary between valid and invalid addresses. Status codes above this number will be returned as-is, status codes below will be returned as EmailStatusCode.valid. Thus the calling program can simply look for EmailStatusCode.valid if it is only interested in whether an address is valid or not. The errorLevel will determine how "picky" isEmail() is about the address. If omitted or passed as EmailStatusCode.none then isEmail() will not perform any finer grained error checking and an address is either considered valid or not. Email status code will either be EmailStatusCode.valid or EmailStatusCode.error. |


 
Returns:
An [`EmailStatus`](#EmailStatus), indicating the status of the email address.
  alias **CheckDns** = std.typecons.Flag!"checkDns".Flag;  
Flag for indicating if the isEmail function should perform a DNS check or not. 


If set to `CheckDns.no`, isEmail does not perform DNS checking.   
  
 Otherwise if set to `CheckDns.yes`, isEmail performs DNS checking.

  struct **EmailStatus**;  
Represents the status of an email address

 
const pure nothrow @nogc @property @safe bool **valid**();  

Returns:
If the email address is valid or not.
  const pure nothrow @nogc @property @safe string **localPart**();  

Returns:
The local part of the email address, that is, the part before the @ sign.
  const pure nothrow @nogc @property @safe string **domainPart**();  

Returns:
The domain part of the email address, that is, the part after the @ sign.
  const pure nothrow @nogc @property @safe EmailStatusCode **statusCode**();  

Returns:
The email status code
  const pure nothrow @nogc @property @safe string **status**();  

Returns:
A describing string of the status code
  const pure @safe string **toString**();  

Returns:
A textual representation of the email status
    pure nothrow @nogc @safe string **statusCodeDescription**(EmailStatusCode statusCode);  

Parameters:


|  |  |
| --- | --- |
| EmailStatusCode `statusCode` | The [`EmailStatusCode`](#EmailStatusCode) to read |


 
Returns:
A detailed string describing the given status code
  enum **EmailStatusCode**: int;  
An email status code, indicating if an email address is valid or not. If it is invalid it also indicates why.

 
**validCategory** 
Address is valid

  **dnsWarning** 
Address is valid but a DNS check was not successful

  **rfc5321** 
Address is valid for SMTP but has unusual elements

  **cFoldingWhitespace** 
Address is valid within the message but cannot be used unmodified for the envelope

  **deprecated\_** 
Address contains deprecated elements but may still be valid in restricted contexts

  **rfc5322** 
The address is only valid according to the broad definition of RFC 5322. It is otherwise invalid

  **any** 
All finer grained error checking is turned on. Address containing errors or warnings is considered invalid. A specific email status code will be returned indicating the error/warning of the address.

  **none** 
Address is either considered valid or not, no finer grained error checking is performed. Returned email status code will be either Error or Valid.

  **warning** 
Address containing warnings is considered valid, that is, any status code below 16 is considered valid.

  **error** 
Address is invalid for any purpose

  **valid** 
Address is valid

  **dnsWarningNoMXRecord** 
Could not find an MX record for this domain but an A-record does exist

  **dnsWarningNoRecord** 
Could not find an MX record or an A-record for this domain

  **rfc5321TopLevelDomain** 
Address is valid but at a Top Level Domain

  **rfc5321TopLevelDomainNumeric** 
Address is valid but the Top Level Domain begins with a number

  **rfc5321QuotedString** 
Address is valid but contains a quoted string

  **rfc5321AddressLiteral** 
Address is valid but at a literal address not a domain

  **rfc5321IpV6Deprecated** 
Address is valid but contains a :: that only elides one zero group

  **comment** 
Address contains comments

  **foldingWhitespace** 
Address contains Folding White Space

  **deprecatedLocalPart** 
The local part is in a deprecated form

  **deprecatedFoldingWhitespace** 
Address contains an obsolete form of Folding White Space

  **deprecatedQuotedText** 
A quoted string contains a deprecated character

  **deprecatedQuotedPair** 
A quoted pair contains a deprecated character

  **deprecatedComment** 
Address contains a comment in a position that is deprecated

  **deprecatedCommentText** 
A comment contains a deprecated character

  **deprecatedCommentFoldingWhitespaceNearAt** 
Address contains a comment or Folding White Space around the @ sign

  **rfc5322Domain** 
Address is RFC 5322 compliant but contains domain characters that are not allowed by DNS

  **rfc5322TooLong** 
Address is too long

  **rfc5322LocalTooLong** 
The local part of the address is too long

  **rfc5322DomainTooLong** 
The domain part is too long

  **rfc5322LabelTooLong** 
The domain part contains an element that is too long

  **rfc5322DomainLiteral** 
The domain literal is not a valid RFC 5321 address literal

  **rfc5322DomainLiteralObsoleteText** 
The domain literal is not a valid RFC 5321 address literal and it contains obsolete characters

  **rfc5322IpV6GroupCount** 
The IPv6 literal address contains the wrong number of groups

  **rfc5322IpV6TooManyDoubleColons** 
The IPv6 literal address contains too many :: sequences

  **rfc5322IpV6BadChar** 
The IPv6 address contains an illegal group of characters

  **rfc5322IpV6MaxGroups** 
The IPv6 address has too many groups

  **rfc5322IpV6ColonStart** 
IPv6 address starts with a single colon

  **rfc5322IpV6ColonEnd** 
IPv6 address ends with a single colon

  **errorExpectingDomainText** 
A domain literal contains a character that is not allowed

  **errorNoLocalPart** 
Address has no local part

  **errorNoDomain** 
Address has no domain part

  **errorConsecutiveDots** 
The address may not contain consecutive dots

  **errorTextAfterCommentFoldingWhitespace** 
Address contains text after a comment or Folding White Space

  **errorTextAfterQuotedString** 
Address contains text after a quoted string

  **errorTextAfterDomainLiteral** 
Extra characters were found after the end of the domain literal

  **errorExpectingQuotedPair** 
The address contains a character that is not allowed in a quoted pair

  **errorExpectingText** 
Address contains a character that is not allowed

  **errorExpectingQuotedText** 
A quoted string contains a character that is not allowed

  **errorExpectingCommentText** 
A comment contains a character that is not allowed

  **errorBackslashEnd** 
The address cannot end with a backslash

  **errorDotStart** 
Neither part of the address may begin with a dot

  **errorDotEnd** 
Neither part of the address may end with a dot

  **errorDomainHyphenStart** 
A domain or subdomain cannot begin with a hyphen

  **errorDomainHyphenEnd** 
A domain or subdomain cannot end with a hyphen

  **errorUnclosedQuotedString** 
Unclosed quoted string

  **errorUnclosedComment** 
Unclosed comment

  **errorUnclosedDomainLiteral** 
Domain literal is missing its closing bracket

  **errorFoldingWhitespaceCrflX2** 
Folding White Space contains consecutive CRLF sequences

  **errorFoldingWhitespaceCrLfEnd** 
Folding White Space ends with a CRLF sequence

  **errorCrNoLf** 
Address contains a carriage return that is not followed by a line feed

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_net_isemail.html>

std.outbuffer
=============

 Serialize data to `ubyte` arrays. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/outbuffer.d](https://github.com/dlang/phobos/blob/master/std/outbuffer.d) 
 
class **OutBuffer**;  
OutBuffer provides a way to build up an array of bytes out of raw data. It is useful for things like preparing an array of bytes to write out to a file. OutBuffer's byte order is the format native to the computer. To control the byte order (endianness), use a class derived from OutBuffer. OutBuffer's internal buffer is allocated with the GC. Pointers stored into the buffer are scanned by the GC, but you have to ensure proper alignment, e.g. by using alignSize((void\*).sizeof).



Examples:


```
import std.string : cmp;

OutBuffer buf = new OutBuffer();

writeln(buf.offset); // 0
buf.write("hello");
buf.write(cast(byte) 0x20);
buf.write("world");
buf.printf(" %d", 62665);
writeln(cmp(buf.toString(), "hello world 62665")); // 0

buf.clear();
writeln(cmp(buf.toString(), "")); // 0
buf.write("New data");
writeln(cmp(buf.toString(), "New data")); // 0

```
 
 
inout pure nothrow scope @safe inout(ubyte)[] **toBytes**();  
Convert to array of bytes.

  pure nothrow @trusted void **reserve**(size\_t nbytes);  
Preallocate nbytes more to the size of the internal buffer. 


This is a speed optimization, a good guess at the maximum size of the resulting buffer will improve performance by eliminating reallocations and copying.

  alias **put** = write;  
put enables OutBuffer to be used as an OutputRange.

  pure nothrow @safe void **write**(scope const(ubyte)[] bytes);   
  
pure nothrow @safe void **write**(byte b);   
  
pure nothrow @safe void **write**(char c);   
  
pure nothrow @safe void **write**(dchar c);   
  
pure nothrow @safe void **write**(short s);   
  
pure nothrow @safe void **write**(int i);   
  
pure nothrow @safe void **write**(long l);  
Append data to the internal buffer.

  pure nothrow @safe void **fill0**(size\_t nbytes);  
Append nbytes of 0 to the internal buffer.

  pure nothrow @safe void **alignSize**(size\_t alignsize);  
0-fill to align on power of 2 boundary.

  pure nothrow @safe void **clear**();  
Clear the data in the buffer

  pure nothrow @safe void **align2**();  
Optimize common special case alignSize(2)

  pure nothrow @safe void **align4**();  
Optimize common special case alignSize(4)

  const pure nothrow @safe string **toString**();  
Convert internal buffer to array of chars.

  nothrow @trusted void **vprintf**(scope string format, va\_list args);  
Append output of C's vprintf() to internal buffer.

  @trusted void **printf**(scope string format, ...);  
Append output of C's printf() to internal buffer.

  void **writef**(Char, A...)(scope const(Char)[] fmt, A args);  
Formats and writes its arguments in text format to the OutBuffer. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `fmt` | format string as described in [`std.format.formattedWrite`](std_format#formattedWrite) |
| A `args` | arguments to be formatted |


 
See Also:

[`std.stdio.writef`](std_stdio#writef); [`std.format.formattedWrite`](std_format#formattedWrite);
 
Examples:


```
OutBuffer b = new OutBuffer();
b.writef("a%sb", 16);
writeln(b.toString()); // "a16b"

```
 
  void **writefln**(Char, A...)(scope const(Char)[] fmt, A args);  
Formats and writes its arguments in text format to the OutBuffer, followed by a newline. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `fmt` | format string as described in [`std.format.formattedWrite`](std_format#formattedWrite) |
| A `args` | arguments to be formatted |


 
See Also:

[`std.stdio.writefln`](std_stdio#writefln); [`std.format.formattedWrite`](std_format#formattedWrite);
 
Examples:


```
OutBuffer b = new OutBuffer();
b.writefln("a%sb", 16);
writeln(b.toString()); // "a16b\n"

```
 
  pure nothrow @safe void **spread**(size\_t index, size\_t nbytes);  
At offset index into buffer, create nbytes of space by shifting upwards all data past index.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_outbuffer.html>

std.format
==========

 This module implements the formatting functionality for strings and I/O. It's comparable to C99's `vsprintf()` and uses a similar format encoding scheme. 


For an introductory look at **std.format**'s capabilities and how to use this module see the dedicated [DWiki article](http://wiki.dlang.org/Defining_custom_print_format_specifiers).   
  
 This module centers around two functions:   
  
 

| Function Name | Description |
| --- | --- |
| [`formattedRead`](#formattedRead) | Reads values according to the format string from an InputRange.  |
| [`formattedWrite`](#formattedWrite) | Formats its arguments according to the format string and puts them to an OutputRange.  |

   
  
 Please see the documentation of function [`formattedWrite`](#formattedWrite) for a description of the format string.   
  
 Two functions have been added for convenience:   
  
 

| Function Name | Description |
| --- | --- |
| [`format`](#format) | Returns a GC-allocated string with the formatting result.  |
| [`sformat`](#sformat) | Puts the formatting result into a preallocated array.  |

   
  
 These two functions are publicly imported by [`std.string`](std_string) to be easily available.   
  
 The functions [`formatValue`](#formatValue) and [`unformatValue`](#unformatValue) are used for the plumbing. 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://walterbright.com),  [Andrei Alexandrescu](http://erdani.com), and Kenji Hara 
 
Source
 [std/format.d](https://github.com/dlang/phobos/blob/master/std/format.d)

 
class **FormatException**: object.Exception;  
Signals a mismatch between a format and its corresponding argument.



Examples:


```
import std.exception : assertThrown;
assertThrown!FormatException(format("%d", "foo"));

```
 
  uint **formattedWrite**(alias fmt, Writer, A...)(auto ref Writer w, A args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
uint **formattedWrite**(Writer, Char, A...)(auto ref Writer w, scope const Char[] fmt, A args);  
Interprets variadic argument list `args`, formats them according to `fmt`, and sends the resulting characters to `w`. The encoding of the output is the same as `Char`. The type `Writer` must satisfy `[std.range.primitives.isOutputRange](std_range_primitives#isOutputRange)!(Writer, Char)`. 


The variadic arguments are normally consumed in order. POSIX-style  [positional parameter syntax](http://opengroup.org/onlinepubs/009695399/functions/printf.html) is also supported. Each argument is formatted into a sequence of chars according to the format specification, and the characters are passed to `w`. As many arguments as specified in the format string are consumed and formatted. If there are fewer arguments than format specifiers, a `FormatException` is thrown. If there are more remaining arguments than needed by the format specification, they are ignored but only if at least one argument was formatted.   
  
 The format string supports the formatting of array and nested array elements via the grouping format specifiers **%(** and **%)**. Each matching pair of **%(** and **%)** corresponds with a single array argument. The enclosed sub-format string is applied to individual array elements. The trailing portion of the sub-format string following the conversion specifier for the array element is interpreted as the array delimiter, and is therefore omitted following the last array 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 array element. (See below for explicit examples.) 

 
Parameters:


|  |  |
| --- | --- |
| Writer `w` | Output is sent to this writer. Typical output writers include [`std.array.Appender!string`](std_array#Appender!string) and [`std.stdio.LockingTextWriter`](std_stdio#LockingTextWriter). |
| Char[] `fmt` | Format string. |
| A `args` | Variadic argument list. |


 
Returns:
Formatted number of arguments. 
 
Throws:
Mismatched arguments and formats result in a  `FormatException` being thrown. 
 
Format String
 *Format strings* consist of characters interspersed with *format specifications*. Characters are simply copied to the output (such as putc) after any necessary conversion to the corresponding UTF-8 sequence. 
 The format string has the following grammar: 
```
FormatString:
    FormatStringItem*
FormatStringItem:
    '%%'
    '%' Position Flags Width Separator Precision FormatChar
    '%(' FormatString '%)'
    '%-(' FormatString '%)'
    OtherCharacterExceptPercent
Position:
    empty
    Integer '$'
Flags:
    empty
    '-' Flags
    '+' Flags
    '#' Flags
    '0' Flags
    ' ' Flags
Width:
    empty
    Integer
    '*'
Separator:
    empty
    ','
    ',' '?'
    ',' '*' '?'
    ',' Integer '?'
    ',' '*'
    ',' Integer
Precision:
    empty
    '.'
    '.' Integer
    '.*'
Integer:
    Digit
    Digit Integer
Digit:
    '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
FormatChar:
    's'|'c'|'b'|'d'|'o'|'x'|'X'|'e'|'E'|'f'|'F'|'g'|'G'|'a'|'A'|'|'

```
 

Flags affect formatting depending on the specifier as follows.| Flag | Types affected | Semantics |
| '-' | numeric, bool, null, char, string, enum, pointer | Left justify the result in the field. It overrides any 0 flag. |
| '+' | numeric | Prefix positive numbers in a signed conversion with a +. It overrides any *space* flag. |
| '#' | integral ('o') | Add to precision as necessary so that the first digit of the octal formatting is a '0', even if both the argument and the  *Precision* are zero. |
| '#' | integral ('x', 'X') | If non-zero, prefix result with 0x (0X). |
| '#' | floating | Always insert the decimal point and print trailing zeros. |
| '0' | numeric | Use leading zeros to pad rather than spaces (except for the floating point values `nan` and `infinity`). Ignore if there's a  *Precision*. |
| ' ' | numeric | Prefix positive numbers in a signed conversion with a space. |

  *Width*  Only used for numeric, bool, null, char, string, enum and pointer types. Specifies the minimum field width. If the width is a **\***, an additional argument of type **int**, preceding the actual argument, is taken as the width. If the width is negative, it is as if the **-** was given as a *Flags* character. *Precision* Gives the precision for numeric conversions. If the precision is a **\***, an additional argument of type **int**, preceding the actual argument, is taken as the precision. If it is negative, it is as if there was no *Precision* specifier. *Separator* Inserts the separator symbols ',' every *X* digits, from right to left, into numeric values to increase readability. The fractional part of floating point values inserts the separator from left to right. Entering an integer after the ',' allows to specify *X*. If a '\*' is placed after the ',' then *X* is specified by an additional parameter to the format function. Adding a '?' after the ',' or *X* specifier allows to specify the separator character as an additional parameter.  *FormatChar*   **'s'** The corresponding argument is formatted in a manner consistent with its type:  **bool** The result is `"true"` or `"false"`. integral types The **%d** format is used. floating point types The **%g** format is used. string types The result is the string converted to UTF-8. A *Precision* specifies the maximum number of characters to use in the result. structs If the struct defines a **toString()** method the result is the string returned from this function. Otherwise the result is StructName(field0, field1, ...) where fieldn is the nth element formatted with the default format. classes derived from **Object**
 The result is the string returned from the class instance's **.toString()** method. A *Precision* specifies the maximum number of characters to use in the result. unions If the union defines a **toString()** method the result is the string returned from this function. Otherwise the result is the name of the union, without its contents. non-string static and dynamic arrays The result is [s0, s1, ...] where sn is the nth element formatted with the default format. associative arrays The result is the equivalent of what the initializer would look like for the contents of the associative array, e.g.: ["red" : 10, "blue" : 20]. 
 **'c'** The corresponding argument must be a character type. **'b','d','o','x','X'** The corresponding argument must be an integral type and is formatted as an integer. If the argument is a signed type and the *FormatChar* is **d** it is converted to a signed string of characters, otherwise it is treated as unsigned. An argument of type **bool** is formatted as '1' or '0'. The base used is binary for **b**, octal for **o**, decimal for **d**, and hexadecimal for **x** or **X**. **x** formats using lower case letters, **X** uppercase. If there are fewer resulting digits than the *Precision*, leading zeros are used as necessary. If the *Precision* is 0 and the number is 0, no digits result. **'e','E'** A floating point number is formatted as one digit before the decimal point, *Precision* digits after, the *FormatChar*, ±, followed by at least a two digit exponent: *d.dddddd*e*±dd*. If there is no *Precision*, six digits are generated after the decimal point. If the *Precision* is 0, no decimal point is generated. **'f','F'** A floating point number is formatted in decimal notation. The *Precision* specifies the number of digits generated after the decimal point. It defaults to six. At least one digit is generated before the decimal point. If the *Precision* is zero, no decimal point is generated. **'g','G'** A floating point number is formatted in either **e** or **f** format for **g**; **E** or **F** format for **G**. The **f** format is used if the exponent for an **e** format is greater than -5 and less than the *Precision*. The *Precision* specifies the number of significant digits, and defaults to six. Trailing zeros are elided after the decimal point, if the fractional part is zero then no decimal point is generated. **'a','A'** A floating point number is formatted in hexadecimal exponential notation 0x*h.hhhhhh*p*±d*. There is one hexadecimal digit before the decimal point, and as many after as specified by the *Precision*. If the *Precision* is zero, no decimal point is generated. If there is no *Precision*, as many hexadecimal digits as necessary to exactly represent the mantissa are generated. The exponent is written in as few digits as possible, but at least one, is in decimal, and represents a power of 2 as in *h.hhhhhh*\*2*±d*. The exponent for zero is zero. The hexadecimal digits, x and p are in upper case if the *FormatChar* is upper case. 
  Floating point NaN's are formatted as **nan** if the *FormatChar* is lower case, or **NAN** if upper. Floating point infinities are formatted as **inf** or **infinity** if the *FormatChar* is lower case, or **INF** or **INFINITY** if upper. The positional and non-positional styles can be mixed in the same format string. (POSIX leaves this behavior undefined.) The internal counter for non-positional parameters tracks the next parameter after the largest positional parameter already used. Example using array and nested array formatting: 
```
import std.stdio;

void main()
{
    writefln("My items are %(%s %).", [1,2,3]);
    writefln("My items are %(%s, %).", [1,2,3]);
}

```
 The output is: 
```
My items are 1 2 3.
My items are 1, 2, 3.

```
 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. 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: 
```
import std.stdio;

void main()
{
    writefln("My items are %(-%s-%|, %).", [1,2,3]);
}

```
 which gives the output: 
```
My items are -1-, -2-, -3-.

```
 These compound format specifiers may be nested in the case of a nested array argument: 
```
import std.stdio;
void main() {
     auto mat = [[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]];

     writefln("%(%(%d %)\n%)", mat);
     writeln();

     writefln("[%(%(%d %)\n %)]", mat);
     writeln();

     writefln("[%([%(%d %)]%|\n %)]", mat);
     writeln();
}

```
 The output is: 
```
1 2 3
4 5 6
7 8 9


[1 2 3
 4 5 6
 7 8 9]


[[1 2 3]
 [4 5 6]
 [7 8 9]]

```
 Inside a compound format specifier, strings and characters are escaped automatically. To avoid this behavior, add **'-'** flag to `"%("`. 
```
import std.stdio;

void main()
{
    writefln("My friends are %s.", ["John", "Nancy"]);
    writefln("My friends are %(%s, %).", ["John", "Nancy"]);
    writefln("My friends are %-(%s, %).", ["John", "Nancy"]);
}

```
 which gives the output: 
```
My friends are ["John", "Nancy"].
My friends are "John", "Nancy".
My friends are John, Nancy.

```
 
Examples:
The format string can be checked at compile-time (see [`format`](#format) for details): 
```
import std.array : appender;

auto writer = appender!string();
writer.formattedWrite!"%s is the ultimate %s."(42, "answer");
writeln(writer.data); // "42 is the ultimate answer."

// Clear the writer
writer = appender!string();
formattedWrite(writer, "Date: %2&dollar;s %1&dollar;s", "October", 5);
writeln(writer.data); // "Date: 5 October"

```
 
 
Examples:


```
writeln(format("%,d", 1000)); // "1,000"
writeln(format("%,f", 1234567.891011)); // "1,234,567.891011"
writeln(format("%,?d", '?', 1000)); // "1?000"
writeln(format("%,1d", 1000)); // "1,0,0,0"
writeln(format("%,*d", 4, -12345)); // "-1,2345"
writeln(format("%,*?d", 4, '_', -12345)); // "-1_2345"
writeln(format("%,6?d", '_', -12345678)); // "-12_345678"
assert(format("%12,3.3f", 1234.5678) == "   1,234.568", "'" ~
        format("%12,3.3f", 1234.5678) ~ "'");

```
 
  uint **formattedRead**(alias fmt, R, S...)(auto ref R r, auto ref S args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
uint **formattedRead**(R, Char, S...)(auto ref R r, const(Char)[] fmt, auto ref S args);  
Reads characters from [input range](std_range_primitives#isInputRange) `r`, converts them according to `fmt`, and writes them to `args`. 



Parameters:


|  |  |
| --- | --- |
| R `r` | The range to read from. |
| const(Char)[] `fmt` | The format of the data to read. |
| S `args` | The drain of the data read. |


 
Returns:
On success, the function returns the number of variables filled. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. 
 
Throws:
A `FormatException` if `S.length == 0` and `fmt` has format specifiers.
 
Examples:
The format string can be checked at compile-time (see [`format`](#format) for details): 
```
string s = "hello!124:34.5";
string a;
int b;
double c;
s.formattedRead!"%s!%s:%s"(a, b, c);
assert(a == "hello" && b == 124 && c == 34.5);

```
 
  struct **FormatSpec**(Char) if (is(Unqual!Char == Char));  
A General handler for `printf` style format specifiers. Used for building more specific formatting functions.



Examples:


```
import std.array;
auto a = appender!(string)();
auto fmt = "Number: %6.4e\nString: %s";
auto f = FormatSpec!char(fmt);

writeln(f.writeUpToNextSpec(a)); // true

writeln(a.data); // "Number: "
writeln(f.trailing); // "\nString: %s"
writeln(f.spec); // 'e'
writeln(f.width); // 6
writeln(f.precision); // 4

writeln(f.writeUpToNextSpec(a)); // true

writeln(a.data); // "Number: \nString: "
writeln(f.trailing); // ""
writeln(f.spec); // 's'

writeln(f.writeUpToNextSpec(a)); // false
writeln(a.data); // "Number: \nString: "

```
 
 
int **width**;  
Minimum width, default `0`.

  int **precision**;  
Precision. Its semantics depends on the argument type. For floating point numbers, precision dictates the number of decimals printed.

  int **separators**;  
Number of digits printed between separators.

  int **separatorCharPos**;  
Set to `DYNAMIC` when the separator character is supplied at runtime.

  dchar **separatorChar**;  
Character to insert between digits.

  enum int **DYNAMIC**;  
Special value for width and precision. `DYNAMIC` width or precision means that they were specified with `'*'` in the format string and are passed at runtime through the varargs.

  enum int **UNSPECIFIED**;  
Special value for precision, meaning the format specifier contained no explicit precision.

  char **spec**;  
The actual format specifier, `'s'` by default.

  ubyte **indexStart**;  
Index of the argument for positional parameters, from `1` to `ubyte.max`. (`0` means not used).

  ubyte **indexEnd**;  
Index of the last argument for positional parameter range, from `1` to `ubyte.max`. (`0` means not used).

  bool **flDash**;  
The format specifier contained a `'-'` (`printf` compatibility).

  bool **flZero**;  
The format specifier contained a `'0'` (`printf` compatibility).

  bool **flSpace**;  
The format specifier contained a `' '` (`printf` compatibility).

  bool **flPlus**;  
The format specifier contained a `'+'` (`printf` compatibility).

  bool **flHash**;  
The format specifier contained a `'#'` (`printf` compatibility).

  bool **flSeparator**;  
The format specifier contained a `','`

  const(Char)[] **nested**;  
In case of a compound format specifier starting with  `"%("` and ending with `"%)"`, `_nested` contains the string contained within the two separators.

  const(Char)[] **sep**;  
In case of a compound format specifier, `_sep` contains the string positioning after `"%|"`. `sep is null` means no separator else `sep.empty` means 0 length separator.

  const(Char)[] **trailing**;  
`_trailing` contains the rest of the format string.

  pure @safe this(in Char[] fmt);  
Construct a new `FormatSpec` using the format string `fmt`, no processing is done until needed.

  scope bool **writeUpToNextSpec**(OutputRange)(ref OutputRange writer);  
Write the format string to an output range until the next format specifier is found and parse that format specifier. 


See [`FormatSpec`](#FormatSpec) for an example, how to use `writeUpToNextSpec`. 

 
Parameters:


|  |  |
| --- | --- |
| OutputRange `writer` | the [output range](std_range_primitives#isOutputRange) |


 
Returns:
True, when a format specifier is found. 
 
Throws:
A [`FormatException`](#FormatException) when the found format specifier could not be parsed.
  const pure @safe string **toString**();   
  
const void **toString**(OutputRange)(ref OutputRange writer)  
 Constraints: if (isOutputRange!(OutputRange, char)); 
 
Gives a string containing all of the member variables on their own line. 



Parameters:


|  |  |
| --- | --- |
| OutputRange `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |


 
Returns:
A `string` when not using an output range; `void` otherwise.
    FormatSpec!Char **singleSpec**(Char)(Char[] fmt);  
Helper function that returns a `FormatSpec` for a single specifier given in `fmt`. 



Parameters:


|  |  |
| --- | --- |
| Char[] `fmt` | A format specifier. |


 
Returns:
A `FormatSpec` with the specifier parsed. 
 
Throws:
A `FormatException` when more than one specifier is given or the specifier is malformed.
 
Examples:


```
import std.exception : assertThrown;
auto spec = singleSpec("%2.3e");

writeln(spec.trailing); // ""
writeln(spec.spec); // 'e'
writeln(spec.width); // 2
writeln(spec.precision); // 3

assertThrown!FormatException(singleSpec(""));
assertThrown!FormatException(singleSpec("2.3e"));
assertThrown!FormatException(singleSpec("%2.3eTest"));

```
 
  void **formatValue**(Writer, T, Char)(auto ref Writer w, auto ref T val, ref scope const FormatSpec!Char f);  
Formats any value into `Char` accepting `OutputRange`, using the given `FormatSpec`. 



Aggregates
 `struct`, `union`, `class`, and `interface` are formatted by calling `toString`. 
 `toString` should have one of the following signatures: 
```
void toString(W)(ref W w, scope const ref FormatSpec fmt)
void toString(W)(ref W w)
string toString();

```
 Where `W` is an [output range](std_range_primitives#isOutputRange) which accepts characters. The template type does not have to be called `W`. The following overloads are also accepted for legacy reasons or for use in virtual functions. It's recommended that any new code forgo these overloads if possible for speed and attribute acceptance reasons. 
```
void toString(scope void delegate(const(char)[]) sink, const ref FormatSpec fmt);
void toString(scope void delegate(const(char)[]) sink, string fmt);
void toString(scope void delegate(const(char)[]) sink);

```
 For the class objects which have input range interface, * If the instance `toString` has overridden `Object.toString`, it is used.
* Otherwise, the objects are formatted as input range.

 For the `struct` and `union` objects which does not have `toString`, * If they have range interface, formatted as input range.
* Otherwise, they are formatted like `Type(field1, filed2, ...)`.

 Otherwise, are formatted just as their type name. 
Parameters:


|  |  |
| --- | --- |
| Writer `w` | The [output range](std_range_primitives#isOutputRange) to write to. |
| T `val` | The value to write. |
| FormatSpec!Char `f` | The [`std.format.FormatSpec`](std_format#FormatSpec) defining how to write the value. |


 
Examples:
The following code compares the use of `formatValue` and `formattedWrite`. 
```
import std.array : appender;

auto writer1 = appender!string();
writer1.formattedWrite("%08b", 42);

auto writer2 = appender!string();
auto f = singleSpec("%08b");
writer2.formatValue(42, f);

assert(writer1.data == writer2.data && writer1.data == "00101010");

```
 
 
Examples:

`bool`s are formatted as `"true"` or `"false"` with `%s` and as `1` or `0` with integral-specific format specs. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
formatValue(w, true, spec);

writeln(w.data); // "true"

```
 
 
Examples:

`null` literal is formatted as `"null"`. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
formatValue(w, null, spec);

writeln(w.data); // "null"

```
 
 
Examples:
Integrals are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf). 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%d");
formatValue(w, 1337, spec);

writeln(w.data); // "1337"

```
 
 
Examples:
Floating-point values are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf) 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%.1f");
formatValue(w, 1337.7, spec);

writeln(w.data); // "1337.7"

```
 
 
Examples:
Individual characters (`char,` wchar`, or` dchar`) are formatted as Unicode characters with `%s` and as integers with integral-specific format specs. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%c");
formatValue(w, 'a', spec);

writeln(w.data); // "a"

```
 
 
Examples:
Strings are formatted like [`core.stdc.stdio.printf`](core_stdc_stdio#printf) 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
formatValue(w, "hello", spec);

writeln(w.data); // "hello"

```
 
 
Examples:
Static-size arrays are formatted as dynamic arrays. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
char[2] two = ['a', 'b'];
formatValue(w, two, spec);

writeln(w.data); // "ab"

```
 
 
Examples:
Dynamic arrays are formatted as input ranges. Specializations: * `void[]` is formatted like `ubyte[]`.
* Const array is converted to input range by removing its qualifier.

 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
auto two = [1, 2];
formatValue(w, two, spec);

writeln(w.data); // "[1, 2]"

```
 
 
Examples:
Associative arrays are formatted by using `':'` and `", "` as separators, and enclosed by `'['` and `']'`. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");
auto aa = ["H":"W"];
formatValue(w, aa, spec);

writeln(w.data); // "[\"H\":\"W\"]"

```
 
 
Examples:

`enum`s are formatted like their base value 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");

enum A { first, second, third }

formatValue(w, A.second, spec);

writeln(w.data); // "second"

```
 
 
Examples:
Formatting a struct by defining a method `toString`, which takes an output range. It's recommended that any `toString` using [output ranges](std_range_primitives#isOutputRange) use [`std.range.primitives.put`](std_range_primitives#put) rather than use the `put` method of the range directly. 
```
import std.array : appender;
import std.range.primitives;

static struct Point
{
    int x, y;

    void toString(W)(ref W writer, scope const ref FormatSpec!char f)
    if (isOutputRange!(W, char))
    {
        // std.range.primitives.put
        put(writer, "(");
        formatValue(writer, x, f);
        put(writer, ",");
        formatValue(writer, y, f);
        put(writer, ")");
    }
}

auto w = appender!string();
auto spec = singleSpec("%s");
auto p = Point(16, 11);

formatValue(w, p, spec);
writeln(w.data); // "(16,11)"

```
 
 
Examples:
Another example of formatting a `struct` with a defined `toString`, this time using the `scope delegate` method. This method is now discouraged for non-virtual functions. If possible, please use the output range method instead. 
```
static struct Point
{
    int x, y;

    void toString(scope void delegate(scope const(char)[]) @safe sink,
                  scope const FormatSpec!char fmt) const
    {
        sink("(");
        sink.formatValue(x, fmt);
        sink(",");
        sink.formatValue(y, fmt);
        sink(")");
    }
}

auto p = Point(16,11);
writeln(format("%03d", p)); // "(016,011)"
writeln(format("%02x", p)); // "(10,0b)"

```
 
 
Examples:
Pointers are formatted as hex integers. 
```
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");

auto q = cast(void*) 0xFFEECCAA;
formatValue(w, q, spec);

writeln(w.data); // "FFEECCAA"

```
 
 
Examples:
SIMD vectors are formatted as arrays. 
```
import core.simd;
import std.array : appender;
auto w = appender!string();
auto spec = singleSpec("%s");

static if (is(float4))
{
    version (X86) {}
    else
    {
        float4 f4;
        f4.array[0] = 1;
        f4.array[1] = 2;
        f4.array[2] = 3;
        f4.array[3] = 4;

        formatValue(w, f4, spec);
        writeln(w.data); // "[1, 2, 3, 4]"
    }
}

```
 
 
Examples:
Delegates are formatted by `ReturnType delegate(Parameters) FunctionAttributes` 
```
import std.conv : to;

int i;

int foo(short k) @nogc
{
    return i + k;
}

@system int delegate(short) @nogc bar() nothrow pure
{
    int* p = new int(1);
    i = *p;
    return &foo;
}

writeln(to!string(&bar)); // "int delegate(short) @nogc delegate() pure nothrow @system"
writeln(() @trusted
{ return bar()(3);
}()); // 4

```
 
  T **unformatValue**(T, Range, Char)(ref Range input, ref scope const FormatSpec!Char spec);  
Reads a value from the given input range according to spec and returns it as type `T`. 



Parameters:


|  |  |
| --- | --- |
| T | the type to return |
| Range `input` | the input range to read from |
| FormatSpec!Char `spec` | the `FormatSpec` to use when reading from `input` |


 
Returns:
A value from `input` of type `T` 
 
Throws:
A `FormatException` if `spec` cannot read a type `T` 
 
See Also:

[`std.conv.parse`](std_conv#parse) and [`std.conv.to`](std_conv#to)

 
Examples:
Booleans 
```
auto str = "false";
auto spec = singleSpec("%s");
writeln(unformatValue!bool(str, spec)); // false

str = "1";
spec = singleSpec("%d");
assert(unformatValue!bool(str, spec));

```
 
 
Examples:
Null values 
```
auto str = "null";
auto spec = singleSpec("%s");
writeln(str.unformatValue!(typeof(null))(spec)); // null

```
 
 
Examples:
Integrals 
```
auto str = "123";
auto spec = singleSpec("%s");
writeln(str.unformatValue!int(spec)); // 123

str = "ABC";
spec = singleSpec("%X");
writeln(str.unformatValue!int(spec)); // 2748

str = "11610";
spec = singleSpec("%o");
writeln(str.unformatValue!int(spec)); // 5000

```
 
 
Examples:
Floating point numbers 
```
import std.math : approxEqual;

auto str = "123.456";
auto spec = singleSpec("%s");
assert(str.unformatValue!double(spec).approxEqual(123.456));

```
 
 
Examples:
Character input ranges 
```
auto str = "aaa";
auto spec = singleSpec("%s");
writeln(str.unformatValue!char(spec)); // 'a'

// Using a numerical format spec reads a Unicode value from a string
str = "65";
spec = singleSpec("%d");
writeln(str.unformatValue!char(spec)); // 'A'

str = "41";
spec = singleSpec("%x");
writeln(str.unformatValue!char(spec)); // 'A'

str = "10003";
spec = singleSpec("%d");
writeln(str.unformatValue!dchar(spec)); // '✓'

```
 
 
Examples:
Arrays and static arrays 
```
string str = "aaa";
auto spec = singleSpec("%s");
writeln(str.unformatValue!(dchar[])(spec)); // "aaa"d

str = "aaa";
spec = singleSpec("%s");
dchar[3] ret = ['a', 'a', 'a'];
writeln(str.unformatValue!(dchar[3])(spec)); // ret

str = "[1, 2, 3, 4]";
spec = singleSpec("%s");
writeln(str.unformatValue!(int[])(spec)); // [1, 2, 3, 4]

str = "[1, 2, 3, 4]";
spec = singleSpec("%s");
int[4] ret2 = [1, 2, 3, 4];
writeln(str.unformatValue!(int[4])(spec)); // ret2

```
 
 
Examples:
Associative arrays 
```
auto str = `["one": 1, "two": 2]`;
auto spec = singleSpec("%s");
writeln(str.unformatValue!(int[string])(spec)); // ["one":1, "two":2]

```
 
  typeof(fmt) **format**(alias fmt, Args...)(Args args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
immutable(Char)[] **format**(Char, Args...)(in Char[] fmt, Args args)  
 Constraints: if (isSomeChar!Char); 
 
Format arguments into a string. 


If the format string is fixed, passing it as a template parameter checks the type correctness of the parameters at compile-time. This also can result in better performance. 

 
Parameters:


|  |  |
| --- | --- |
| Char[] `fmt` | Format string. For detailed specification, see [`formattedWrite`](#formattedWrite). |
| Args `args` | Variadic list of arguments to format into returned string. |


 
Throws:

 if the number of arguments doesn't match the number of format parameters and vice-versa.
 
Examples:
Type checking can be done when fmt is known at compile-time: 
```
auto s = format!"%s is %s"("Pi", 3.14);
writeln(s); // "Pi is 3.14"

static assert(!__traits(compiles, {s = format!"%l"();}));     // missing arg
static assert(!__traits(compiles, {s = format!""(404);}));    // surplus arg
static assert(!__traits(compiles, {s = format!"%d"(4.03);})); // incompatible arg

```
 
  char[] **sformat**(alias fmt, Args...)(char[] buf, Args args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
char[] **sformat**(Char, Args...)(return scope char[] buf, scope const(Char)[] fmt, Args args);  
Format arguments into buffer *buf* which must be large enough to hold the result. 



Returns:
The slice of `buf` containing the formatted string. 
 
Throws:
A `RangeError` if `buf` isn't large enough to hold the formatted string. A [`FormatException`](#FormatException) if the length of `args` is different than the number of format specifiers in `fmt`.
 
Examples:
The format string can be checked at compile-time (see [`format`](#format) for details): 
```
char[10] buf;

writeln(buf[].sformat!"foo%s"('C')); // "fooC"
writeln(sformat(buf[], "%s foo", "bar")); // "bar foo"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_format.html>

std.meta
========

 Templates to manipulate [template parameter sequences](https://dlang.org/spec/template.html#variadic-templates) (also known as *alias sequences*). 


Some operations on alias sequences are built into the language, such as `S[i]`, which accesses the element at index `i` in the sequence. `S[low .. high]` returns a new alias sequence that is a slice of the old one.   
  
 For more information, see [Compile-time Sequences](https://dlang.org/ctarguments.html).   
  
 **Note:** Several templates in this module use or operate on eponymous templates that take a single argument and evaluate to a boolean constant. Such templates are referred to as *template predicates*.   
  
 

| Category | Templates |
| --- | --- |
| Building blocks | [`Alias`](#Alias) [`AliasSeq`](#AliasSeq) [`aliasSeqOf`](#aliasSeqOf) |
| Alias sequence filtering | [`Erase`](#Erase) [`EraseAll`](#EraseAll) [`Filter`](#Filter) [`NoDuplicates`](#NoDuplicates) [`Stride`](#Stride) |
| Alias sequence type hierarchy | [`DerivedToFront`](#DerivedToFront) [`MostDerived`](#MostDerived) |
| Alias sequence transformation | [`Repeat`](#Repeat) [`Replace`](#Replace) [`ReplaceAll`](#ReplaceAll) [`Reverse`](#Reverse) [`staticMap`](#staticMap) [`staticSort`](#staticSort) |
| Alias sequence searching | [`allSatisfy`](#allSatisfy) [`anySatisfy`](#anySatisfy) [`staticIndexOf`](#staticIndexOf) |
| Template predicates | [`templateAnd`](#templateAnd) [`templateNot`](#templateNot) [`templateOr`](#templateOr) [`staticIsSorted`](#staticIsSorted) |
| Template instantiation | [`ApplyLeft`](#ApplyLeft) [`ApplyRight`](#ApplyRight) [`Instantiate`](#Instantiate) |

 

 
References
 Based on ideas in Table 3.1 from  [Modern C++ Design](http://amazon.com/exec/obidos/ASIN/0201704315/ref=ase_classicempire/102-2957199-2585768), Andrei Alexandrescu (Addison-Wesley Professional, 2001) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [David Nadlinger](http://klickverbot.at) 
 
Source
 [std/meta.d](https://github.com/dlang/phobos/blob/master/std/meta.d)

 
template **AliasSeq**(TList...) 
Creates a sequence of zero or more aliases. This is most commonly used as template parameters or arguments. 


In previous versions of Phobos, this was known as `TypeTuple`.

 
Examples:


```
import std.meta;
alias TL = AliasSeq!(int, double);

int foo(TL td)  // same as int foo(int, double);
{
    return td[0] + cast(int) td[1];
}

```
 
 
Examples:


```
alias TL = AliasSeq!(int, double);

alias Types = AliasSeq!(TL, char);
static assert(is(Types == AliasSeq!(int, double, char)));

```
 
 
Examples:


```
// Creates a compile-time sequence of function call expressions
// that each call `func` with the next variadic template argument
template Map(alias func, args...)
{
    auto ref lazyItem() {return func(args[0]);}

    static if (args.length == 1)
    {
        alias Map = lazyItem;
    }
    else
    {
        // recurse
        alias Map = AliasSeq!(lazyItem, Map!(func, args[1 .. $]));
    }
}

static void test(int a, int b)
{
    writeln(a); // 4
    writeln(b); // 16
}

static int a = 2;
static int b = 4;

test(Map!(i => i ^^ 2, a, b));
writeln(a); // 2
writeln(b); // 4

test(Map!((ref i) => i *= i, a, b));
writeln(a); // 4
writeln(b); // 16

static void testRef(ref int a, ref int b)
{
    writeln(a++); // 16
    writeln(b++); // 256
}

testRef(Map!(function ref(ref i) => i *= i, a, b));
writeln(a); // 17
writeln(b); // 257

```
 
  template **Alias**(alias a)  
  
template **Alias**(T) 
Allows `alias`ing of any single symbol, type or compile-time expression. 


 Not everything can be directly aliased. An alias cannot be declared of - for example - a literal: 
```
alias a = 4; //Error

```
 With this template any single entity can be aliased: 
```
alias b = Alias!4; //OK

```
 

 
See Also:
To alias more than one thing at once, use [`AliasSeq`](#AliasSeq).
 
Examples:


```
// Without Alias this would fail if Args[0] was e.g. a value and
// some logic would be needed to detect when to use enum instead
alias Head(Args...) = Alias!(Args[0]);
alias Tail(Args...) = Args[1 .. $];

alias Blah = AliasSeq!(3, int, "hello");
static assert(Head!Blah == 3);
static assert(is(Head!(Tail!Blah) == int));
static assert((Tail!Blah)[1] == "hello");

```
 
 
Examples:


```
alias a = Alias!(123);
static assert(a == 123);

enum abc = 1;
alias b = Alias!(abc);
static assert(b == 1);

alias c = Alias!(3 + 4);
static assert(c == 7);

alias concat = (s0, s1) => s0 ~ s1;
alias d = Alias!(concat("Hello", " World!"));
static assert(d == "Hello World!");

alias e = Alias!(int);
static assert(is(e == int));

alias f = Alias!(AliasSeq!(int));
static assert(!is(typeof(f[0]))); //not an AliasSeq
static assert(is(f == int));

auto g = 6;
alias h = Alias!g;
++h;
writeln(g); // 7

```
 
  enum auto **staticIndexOf**(T, TList...);   
  
enum auto **staticIndexOf**(alias T, TList...);  
Returns the index of the first occurrence of T in the sequence TList. If not found, -1 is returned.



Examples:


```
import std.stdio;

void foo()
{
    writefln("The index of long is %s",
             staticIndexOf!(long, AliasSeq!(int, long, double)));
    // prints: The index of long is 1
}

```
 
  template **Erase**(T, TList...)  
  
template **Erase**(alias T, TList...) 
Returns an `AliasSeq` created from TList with the first occurrence, if any, of T removed.



Examples:


```
alias Types = AliasSeq!(int, long, double, char);
alias TL = Erase!(long, Types);
static assert(is(TL == AliasSeq!(int, double, char)));

```
 
  template **EraseAll**(T, TList...)  
  
template **EraseAll**(alias T, TList...) 
Returns an `AliasSeq` created from TList with the all occurrences, if any, of T removed.



Examples:


```
alias Types = AliasSeq!(int, long, long, int);

alias TL = EraseAll!(long, Types);
static assert(is(TL == AliasSeq!(int, int)));

```
 
  template **NoDuplicates**(TList...) 
Returns an `AliasSeq` created from TList with the all duplicate types removed.



Examples:


```
alias Types = AliasSeq!(int, long, long, int, float);

alias TL = NoDuplicates!(Types);
static assert(is(TL == AliasSeq!(int, long, float)));

```
 
  template **Replace**(T, U, TList...)  
  
template **Replace**(alias T, U, TList...)  
  
template **Replace**(T, alias U, TList...)  
  
template **Replace**(alias T, alias U, TList...) 
Returns an `AliasSeq` created from TList with the first occurrence of T, if found, replaced with U.



Examples:


```
alias Types = AliasSeq!(int, long, long, int, float);

alias TL = Replace!(long, char, Types);
static assert(is(TL == AliasSeq!(int, char, long, int, float)));

```
 
  template **ReplaceAll**(T, U, TList...)  
  
template **ReplaceAll**(alias T, U, TList...)  
  
template **ReplaceAll**(T, alias U, TList...)  
  
template **ReplaceAll**(alias T, alias U, TList...) 
Returns an `AliasSeq` created from TList with all occurrences of T, if found, replaced with U.



Examples:


```
alias Types = AliasSeq!(int, long, long, int, float);

alias TL = ReplaceAll!(long, char, Types);
static assert(is(TL == AliasSeq!(int, char, char, int, float)));

```
 
  template **Reverse**(TList...) 
Returns an `AliasSeq` created from TList with the order reversed.



Examples:


```
alias Types = AliasSeq!(int, long, long, int, float, byte, ubyte, short, ushort, uint);

alias TL = Reverse!(Types);
static assert(is(TL == AliasSeq!(uint, ushort, short, ubyte, byte, float, int, long, long, int)));

```
 
  template **MostDerived**(T, TList...) 
Returns the type from TList that is the most derived from type T. If none are found, T is returned.



Examples:


```
class A { }
class B : A { }
class C : B { }
alias Types = AliasSeq!(A, C, B);

MostDerived!(Object, Types) x;  // x is declared as type C
static assert(is(typeof(x) == C));

```
 
  template **DerivedToFront**(TList...) 
Returns an `AliasSeq` with the elements of TList sorted so that the most derived types come first.



Examples:


```
class A { }
class B : A { }
class C : B { }
alias Types = AliasSeq!(A, C, B);

alias TL = DerivedToFront!(Types);
static assert(is(TL == AliasSeq!(C, B, A)));

```
 
  template **staticMap**(alias F, Args...) 
Evaluates to `AliasSeq!(F!(T[0]), F!(T[1]), ..., F!(T[$ - 1]))`.



Examples:


```
import std.traits : Unqual;
alias TL = staticMap!(Unqual, int, const int, immutable int, uint, ubyte, byte, short, ushort);
static assert(is(TL == AliasSeq!(int, int, int, uint, ubyte, byte, short, ushort)));

```
 
  template **allSatisfy**(alias F, T...) 
Tests whether all given items satisfy a template predicate, i.e. evaluates to `F!(T[0]) && F!(T[1]) && ... && F!(T[$ - 1])`. 


Evaluation is *not* short-circuited if a false result is encountered; the template predicate must be instantiable with all the given items.

 
Examples:


```
import std.traits : isIntegral;

static assert(!allSatisfy!(isIntegral, int, double));
static assert( allSatisfy!(isIntegral, int, long));

```
 
  template **anySatisfy**(alias F, T...) 
Tests whether any given items satisfy a template predicate, i.e. evaluates to `F!(T[0]) || F!(T[1]) || ... || F!(T[$ - 1])`. 


Evaluation is short-circuited if a true result is encountered; the template predicate must be instantiable with one of the given items.

 
Examples:


```
import std.traits : isIntegral;

static assert(!anySatisfy!(isIntegral, string, double));
static assert( anySatisfy!(isIntegral, int, double));

```
 
  template **Filter**(alias pred, TList...) 
Filters an `AliasSeq` using a template predicate. Returns an `AliasSeq` of the elements which satisfy the predicate.



Examples:


```
import std.traits : isNarrowString, isUnsigned;

alias Types1 = AliasSeq!(string, wstring, dchar[], char[], dstring, int);
alias TL1 = Filter!(isNarrowString, Types1);
static assert(is(TL1 == AliasSeq!(string, wstring, char[])));

alias Types2 = AliasSeq!(int, byte, ubyte, dstring, dchar, uint, ulong);
alias TL2 = Filter!(isUnsigned, Types2);
static assert(is(TL2 == AliasSeq!(ubyte, uint, ulong)));

```
 
  template **templateNot**(alias pred) 
Negates the passed template predicate.



Examples:


```
import std.traits : isPointer;

alias isNoPointer = templateNot!isPointer;
static assert(!isNoPointer!(int*));
static assert(allSatisfy!(isNoPointer, string, char, float));

```
 
  template **templateAnd**(Preds...) 
Combines several template predicates using logical AND, i.e. constructs a new predicate which evaluates to true for a given input T if and only if all of the passed predicates are true for T. 


The predicates are evaluated from left to right, aborting evaluation in a short-cut manner if a false result is encountered, in which case the latter instantiations do not need to compile.

 
Examples:


```
import std.traits : isNumeric, isUnsigned;

alias storesNegativeNumbers = templateAnd!(isNumeric, templateNot!isUnsigned);
static assert(storesNegativeNumbers!int);
static assert(!storesNegativeNumbers!string && !storesNegativeNumbers!uint);

// An empty sequence of predicates always yields true.
alias alwaysTrue = templateAnd!();
static assert(alwaysTrue!int);

```
 
  template **templateOr**(Preds...) 
Combines several template predicates using logical OR, i.e. constructs a new predicate which evaluates to true for a given input T if and only at least one of the passed predicates is true for T. 


The predicates are evaluated from left to right, aborting evaluation in a short-cut manner if a true result is encountered, in which case the latter instantiations do not need to compile.

 
Examples:


```
import std.traits : isPointer, isUnsigned;

alias isPtrOrUnsigned = templateOr!(isPointer, isUnsigned);
static assert( isPtrOrUnsigned!uint &&  isPtrOrUnsigned!(short*));
static assert(!isPtrOrUnsigned!int  && !isPtrOrUnsigned!(string));

// An empty sequence of predicates never yields true.
alias alwaysFalse = templateOr!();
static assert(!alwaysFalse!int);

```
 
  template **aliasSeqOf**(alias iter) if (isIterable!(typeof(iter)) && !isInfinite!(typeof(iter))) 
Converts any foreach-iterable entity (e.g. an input range) to an alias sequence. 



Parameters:


|  |  |
| --- | --- |
| iter | the entity to convert into an `AliasSeq`. It must be able to be able to be iterated over using a [foreach-statement](https://dlang.org/spec/statement.html#foreach-statement). |


 
Returns:
An `AliasSeq` containing the values produced by iterating over `iter`.
 
Examples:


```
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.string : capitalize;

struct S
{
    int a;
    int c;
    int b;
}

alias capMembers = aliasSeqOf!([__traits(allMembers, S)].sort().map!capitalize());
static assert(capMembers[0] == "A");
static assert(capMembers[1] == "B");
static assert(capMembers[2] == "C");

```
 
 
Examples:


```
static immutable REF = [0, 1, 2, 3];
foreach (I, V; aliasSeqOf!([0, 1, 2, 3]))
{
    static assert(V == I);
    static assert(V == REF[I]);
}

```
 
  template **ApplyLeft**(alias Template, args...)  
  
template **ApplyRight**(alias Template, args...) 
[Partially applies](http://en.wikipedia.org/wiki/Partial_application) Template by binding its first (left) or last (right) arguments to args. 


Behaves like the identity function when args is empty. 

 
Parameters:


|  |  |
| --- | --- |
| Template | template to partially apply |
| args | arguments to bind |


 
Returns:
Template with arity smaller than or equal to Template

 
Examples:


```
// enum bool isImplicitlyConvertible(From, To)
import std.traits : isImplicitlyConvertible;

static assert(allSatisfy!(
    ApplyLeft!(isImplicitlyConvertible, ubyte),
    short, ushort, int, uint, long, ulong));

static assert(is(Filter!(ApplyRight!(isImplicitlyConvertible, short),
    ubyte, string, short, float, int) == AliasSeq!(ubyte, short)));

```
 
 
Examples:


```
import std.traits : hasMember, ifTestable;

struct T1
{
    bool foo;
}

struct T2
{
    struct Test
    {
        bool opCast(T : bool)() { return true; }
    }

    Test foo;
}

static assert(allSatisfy!(ApplyRight!(hasMember, "foo"), T1, T2));
static assert(allSatisfy!(ApplyRight!(ifTestable, a => a.foo), T1, T2));

```
 
 
Examples:


```
import std.traits : Largest;

alias Types = AliasSeq!(byte, short, int, long);

static assert(is(staticMap!(ApplyLeft!(Largest, short), Types) ==
            AliasSeq!(short, short, int, long)));
static assert(is(staticMap!(ApplyLeft!(Largest, int), Types) ==
            AliasSeq!(int, int, int, long)));

```
 
 
Examples:


```
import std.traits : FunctionAttribute, SetFunctionAttributes;

static void foo() @system;
static int bar(int) @system;

alias SafeFunctions = AliasSeq!(
    void function() @safe,
    int function(int) @safe);

static assert(is(staticMap!(ApplyRight!(
    SetFunctionAttributes, "D", FunctionAttribute.safe),
    typeof(&foo), typeof(&bar)) == SafeFunctions));

```
 
  template **Repeat**(size\_t n, TList...) 
Creates an `AliasSeq` which repeats `TList` exactly `n` times.



Examples:


```
alias ImInt0 = Repeat!(0, int);
static assert(is(ImInt0 == AliasSeq!()));

alias ImInt1 = Repeat!(1, immutable(int));
static assert(is(ImInt1 == AliasSeq!(immutable(int))));

alias Real3 = Repeat!(3, real);
static assert(is(Real3 == AliasSeq!(real, real, real)));

alias Real12 = Repeat!(4, Real3);
static assert(is(Real12 == AliasSeq!(real, real, real, real, real, real,
    real, real, real, real, real, real)));

alias Composite = AliasSeq!(uint, int);
alias Composite2 = Repeat!(2, Composite);
static assert(is(Composite2 == AliasSeq!(uint, int, uint, int)));

alias ImInt10 = Repeat!(10, int);
static assert(is(ImInt10 == AliasSeq!(int, int, int, int, int, int, int, int, int, int)));

```
 
 
Examples:


```
auto staticArray(T, size_t n)(Repeat!(n, T) elems)
{
    T[n] a = [elems];
    return a;
}

auto a = staticArray!(long, 3)(3, 1, 4);
assert(is(typeof(a) == long[3]));
writeln(a); // [3, 1, 4]

```
 
  template **staticSort**(alias cmp, Seq...) 
Sorts an [`AliasSeq`](#AliasSeq) using `cmp`. 



Parameters
 cmp = A template that returns a `bool` (if its first argument is less than the second one) or an `int` (-1 means less than, 0 means equal, 1 means greater than) 
 Seq = The [`AliasSeq`](#AliasSeq) to sort 
Returns:
The sorted alias sequence
 
Examples:


```
alias Nums = AliasSeq!(7, 2, 3, 23);
enum Comp(int N1, int N2) = N1 < N2;
static assert(AliasSeq!(2, 3, 7, 23) == staticSort!(Comp, Nums));

```
 
 
Examples:


```
alias Types = AliasSeq!(uint, short, ubyte, long, ulong);
enum Comp(T1, T2) = __traits(isUnsigned, T2) - __traits(isUnsigned, T1);
static assert(is(AliasSeq!(uint, ubyte, ulong, short, long) == staticSort!(Comp,
    Types)));

```
 
  template **staticIsSorted**(alias cmp, Seq...) 
Checks if an [`AliasSeq`](#AliasSeq) is sorted according to `cmp`. 



Parameters
 cmp = A template that returns a `bool` (if its first argument is less than the second one) or an `int` (-1 means less than, 0 means equal, 1 means greater than) 
 Seq = The [`AliasSeq`](#AliasSeq) to check 
Returns:

`true` if `Seq` is sorted; otherwise `false`

 
Examples:


```
enum Comp(int N1, int N2) = N1 < N2;
static assert( staticIsSorted!(Comp, 2, 2));
static assert( staticIsSorted!(Comp, 2, 3, 7, 23));
static assert(!staticIsSorted!(Comp, 7, 2, 3, 23));

```
 
 
Examples:


```
enum Comp(T1, T2) = __traits(isUnsigned, T2) - __traits(isUnsigned, T1);
static assert( staticIsSorted!(Comp, uint, ubyte, ulong, short, long));
static assert(!staticIsSorted!(Comp, uint, short, ubyte, long, ulong));

```
 
  template **Stride**(int stepSize, Args...) if (stepSize != 0) 
Selects a subset of `Args` by stepping with fixed `stepSize` over the sequence. A negative `stepSize` starts iteration with the last element. 



Parameters:


|  |  |
| --- | --- |
| stepSize | Number of elements to increment on each iteration. Can't be `0`. |
| Args | Template arguments. |


 
Returns:
An `AliasSeq` filtered by the selected stride.
 
Examples:


```
static assert(is(Stride!(1, short, int, long) == AliasSeq!(short, int, long)));
static assert(is(Stride!(2, short, int, long) == AliasSeq!(short, long)));
static assert(is(Stride!(-1, short, int, long) == AliasSeq!(long, int, short)));
static assert(is(Stride!(-2, short, int, long) == AliasSeq!(long, short)));

alias attribs = AliasSeq!(short, int, long, ushort, uint, ulong);
static assert(is(Stride!(3, attribs) == AliasSeq!(short, ushort)));
static assert(is(Stride!(3, attribs[1 .. $]) == AliasSeq!(int, uint)));
static assert(is(Stride!(-3, attribs) == AliasSeq!(ulong, long)));

```
 
  template **Instantiate**(alias Template, Params...) 
Instantiates the given template with the given parameters. 


Used to work around syntactic limitations of D with regard to instantiating a template from an alias sequence (e.g. `T[0]!(...)` is not valid) or a template returning another template (e.g. `Foo!(Bar)!(Baz)` is not allowed). 

 
Parameters:


|  |  |
| --- | --- |
| Template | The template to instantiate. |
| Params | The parameters with which to instantiate the template. |


 
Returns:
The instantiated template.
 
Examples:


```
// ApplyRight combined with Instantiate can be used to apply various
// templates to the same parameters.
import std.string : leftJustify, center, rightJustify;
alias functions = staticMap!(ApplyRight!(Instantiate, string),
                             leftJustify, center, rightJustify);
string result = "";
static foreach (f; functions)
{
    {
        auto x = &f; // not a template, but a function instantiation
        result ~= x("hello", 7);
        result ~= ";";
    }
}

writeln(result); // "hello  ; hello ;  hello;"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_meta.html>

std.numeric
===========

 This module is a port of a growing fragment of the numeric header in Alexander Stepanov's [Standard Template Library](https://en.wikipedia.org/wiki/Standard_Template_Library), with a few additions. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org), Don Clugston, Robert Jacques, Ilya Yaroshenko 
 
Source
 [std/numeric.d](https://github.com/dlang/phobos/blob/master/std/numeric.d)

 
enum **CustomFloatFlags**: int;  
Format flags for CustomFloat.

 
**signed** 
Adds a sign bit to allow for signed numbers.

  **storeNormalized** 
Store values in normalized form by default. The actual precision of the significand is extended by 1 bit by assuming an implicit leading bit of 1 instead of 0. i.e. `1.nnnn` instead of `0.nnnn`. True for all [IEE754](https://en.wikipedia.org/wiki/IEEE_floating_point) types

  **allowDenorm** 
Stores the significand in  [IEEE754 denormalized](https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers) form when the exponent is 0. Required to express the value 0.

  **infinity** 
Allows the storage of  [IEEE754 infinity](https://en.wikipedia.org/wiki/IEEE_754-1985#Positive_and_negative_infinity) values.

  **nan** 
Allows the storage of [IEEE754 Not a Number](https://en.wikipedia.org/wiki/NaN) values.

  **probability** 
If set, select an exponent bias such that max\_exp = 1. i.e. so that the maximum value is >= 1.0 and < 2.0. Ignored if the exponent bias is manually specified.

  **negativeUnsigned** 
If set, unsigned custom floats are assumed to be negative.

  **allowDenormZeroOnly** 
If set, 0 is the only allowed  [IEEE754 denormalized](https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers) number. Requires allowDenorm and storeNormalized.

  **ieee** 
Include all of the [IEEE754](https://en.wikipedia.org/wiki/IEEE_floating_point) options.

  **none** 
Include none of the above options.

    template **CustomFloat**(uint bits) if (bits == 8 || bits == 16 || bits == 32 || bits == 64 || bits == 80)  
  
template **CustomFloat**(uint precision, uint exponentWidth, CustomFloatFlags flags = CustomFloatFlags.ieee) if (((flags & flags.signed) + precision + exponentWidth) % 8 == 0 && (precision + exponentWidth > 0))  
  
struct **CustomFloat**(uint precision, uint exponentWidth, CustomFloatFlags flags, uint bias) if (isCorrectCustomFloat(precision, exponentWidth, flags));  
Allows user code to define custom floating-point formats. These formats are for storage only; all operations on them are performed by first implicitly extracting them to `real` first. After the operation is completed the result can be stored in a custom floating-point value via assignment.



Examples:


```
import std.math : sin, cos;

// Define a 16-bit floating point values
CustomFloat!16                                x;     // Using the number of bits
CustomFloat!(10, 5)                           y;     // Using the precision and exponent width
CustomFloat!(10, 5,CustomFloatFlags.ieee)     z;     // Using the precision, exponent width and format flags
CustomFloat!(10, 5,CustomFloatFlags.ieee, 15) w;     // Using the precision, exponent width, format flags and exponent offset bias

// Use the 16-bit floats mostly like normal numbers
w = x*y - 1;

// Functions calls require conversion
z = sin(+x)           + cos(+y);                     // Use unary plus to concisely convert to a real
z = sin(x.get!float)  + cos(y.get!float);            // Or use get!T
z = sin(cast(float) x) + cos(cast(float) y);           // Or use cast(T) to explicitly convert

// Define a 8-bit custom float for storing probabilities
alias Probability = CustomFloat!(4, 4, CustomFloatFlags.ieee^CustomFloatFlags.probability^CustomFloatFlags.signed );
auto p = Probability(0.5);

```
 
  template **FPTemporary**(F) if (isFloatingPoint!F) 
Defines the fastest type to use when storing temporaries of a calculation intended to ultimately yield a result of type `F` (where `F` must be one of `float`, `double`, or `real`). When doing a multi-step computation, you may want to store intermediate results as `FPTemporary!F`. 


The necessity of `FPTemporary` stems from the optimized floating-point operations and registers present in virtually all processors. When adding numbers in the example above, the addition may in fact be done in `real` precision internally. In that case, storing the intermediate `result` in `double format` is not only less precise, it is also (surprisingly) slower, because a conversion from `real` to `double` is performed every pass through the loop. This being a lose-lose situation, `FPTemporary!F` has been defined as the *fastest* type to use for calculations at precision `F`. There is no need to define a type for the *most accurate* calculations, as that is always `real`.   
  
 Finally, there is no guarantee that using `FPTemporary!F` will always be fastest, as the speed of floating-point calculations depends on very many factors.

 
Examples:


```
import std.math : approxEqual;

// Average numbers in an array
double avg(in double[] a)
{
    if (a.length == 0) return 0;
    FPTemporary!double result = 0;
    foreach (e; a) result += e;
    return result / a.length;
}

auto a = [1.0, 2.0, 3.0];
assert(approxEqual(avg(a), 2));

```
 
  template **secantMethod**(alias fun) 
Implements the [secant method](http://tinyurl.com/2zb9yr) for finding a root of the function `fun` starting from points `[xn_1, x_n]` (ideally close to the root). `Num` may be `float`, `double`, or `real`.



Examples:


```
import std.math : approxEqual, cos;

float f(float x)
{
    return cos(x) - x*x*x;
}
auto x = secantMethod!(f)(0f, 1f);
assert(approxEqual(x, 0.865474));

```
 
  T **findRoot**(T, DF, DT)(scope DF f, const T a, const T b, scope DT tolerance)  
 Constraints: if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R, R) && isFloatingPoint!R);   
  
T **findRoot**(T, DF)(scope DF f, const T a, const T b);  
Find a real root of a real function f(x) via bracketing. 


Given a function `f` and a range `[a .. b]` such that `f(a)` and `f(b)` have opposite signs or at least one of them equals ±0, returns the value of `x` in the range which is closest to a root of `f(x)`. If `f(x)` has more than one root in the range, one will be chosen arbitrarily. If `f(x)` returns NaN, NaN will be returned; otherwise, this algorithm is guaranteed to succeed.   
  
 Uses an algorithm based on TOMS748, which uses inverse cubic interpolation whenever possible, otherwise reverting to parabolic or secant interpolation. Compared to TOMS748, this implementation improves worst-case performance by a factor of more than 100, and typical performance by a factor of 2. For 80-bit reals, most problems require 8 to 15 calls to `f(x)` to achieve full machine precision. The worst-case performance (pathological cases) is approximately twice the number of bits. 

 
References
 "On Enclosing Simple Roots of Nonlinear Equations", G. Alefeld, F.A. Potra, Yixun Shi, Mathematics of Computation 61, pp733-744 (1993). Fortran code available from [www.netlib.org](http://%20www.netlib.org) as algorithm TOMS478.
  Tuple!(T, T, R, R) **findRoot**(T, R, DF, DT)(scope DF f, const T ax, const T bx, const R fax, const R fbx, scope DT tolerance)  
 Constraints: if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R) && isFloatingPoint!R);   
  
Tuple!(T, T, R, R) **findRoot**(T, R, DF)(scope DF f, const T ax, const T bx, const R fax, const R fbx);   
  
T **findRoot**(T, R)(scope R delegate(T) f, const T a, const T b, scope bool delegate(T lo, T hi) tolerance = (T a, T b) => false);  
Find root of a real function f(x) by bracketing, allowing the termination condition to be specified. 



Parameters:


|  |  |
| --- | --- |
| DF `f` | Function to be analyzed |
| T `ax` | Left bound of initial range of `f` known to contain the root. |
| T `bx` | Right bound of initial range of `f` known to contain the root. |
| R `fax` | Value of `f(ax)`. |
| R `fbx` | Value of `f(bx)`. `fax` and `fbx` should have opposite signs. (`f(ax)` and `f(bx)` are commonly known in advance.) |
| DT `tolerance` | Defines an early termination condition. Receives the current upper and lower bounds on the root. The delegate must return `true` when these bounds are acceptable. If this function always returns `false`, full machine precision will be achieved. |


 
Returns:
A tuple consisting of two ranges. The first two elements are the range (in `x`) of the root, while the second pair of elements are the corresponding function values at those points. If an exact root was found, both of the first two elements will contain the root, and the second pair of elements will be 0.
  Tuple!(T, "x", Unqual!(ReturnType!DF), "y", T, "error") **findLocalMin**(T, DF)(scope DF f, const T ax, const T bx, const T relTolerance = sqrt(T.epsilon), const T absTolerance = sqrt(T.epsilon))  
 Constraints: if (isFloatingPoint!T && \_\_traits(compiles, () { T \_ = DF.init(T.init); } )); 
 
Find a real minimum of a real function `f(x)` via bracketing. Given a function `f` and a range `(ax .. bx)`, returns the value of `x` in the range which is closest to a minimum of `f(x)`. `f` is never evaluted at the endpoints of `ax` and `bx`. If `f(x)` has more than one minimum in the range, one will be chosen arbitrarily. If `f(x)` returns NaN or -Infinity, `(x, f(x), NaN)` will be returned; otherwise, this algorithm is guaranteed to succeed. 



Parameters:


|  |  |
| --- | --- |
| DF `f` | Function to be analyzed |
| T `ax` | Left bound of initial range of f known to contain the minimum. |
| T `bx` | Right bound of initial range of f known to contain the minimum. |
| T `relTolerance` | Relative tolerance. |
| T `absTolerance` | Absolute tolerance. |


 
Preconditions
 `ax` and `bx` shall be finite reals.   
 `relTolerance` shall be normal positive real.   
 `absTolerance` shall be normal positive real no less then `T.epsilon*2`. 
 
Returns:
A tuple consisting of `x`, `y = f(x)` and `error = 3 * (absTolerance * fabs(x) + relTolerance)`. The method used is a combination of golden section search and successive parabolic interpolation. Convergence is never much slower than that for a Fibonacci search. 
 
References
 "Algorithms for Minimization without Derivatives", Richard Brent, Prentice-Hall, Inc. (1973) 
 
See Also:

[`findRoot`](#findRoot), [`std.math.isNormal`](std_math#isNormal)

 
Examples:


```
import std.math : approxEqual;

auto ret = findLocalMin((double x) => (x-4)^^2, -1e7, 1e7);
assert(ret.x.approxEqual(4.0));
assert(ret.y.approxEqual(0.0));

```
 
  CommonType!(ElementType!Range1, ElementType!Range2) **euclideanDistance**(Range1, Range2)(Range1 a, Range2 b)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2);   
  
CommonType!(ElementType!Range1, ElementType!Range2) **euclideanDistance**(Range1, Range2, F)(Range1 a, Range2 b, F limit)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2); 
 
Computes [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between input ranges `a` and `b`. The two ranges must have the same length. The three-parameter version stops computation as soon as the distance is greater than or equal to `limit` (this is useful to save computation if a small distance is sought).

  CommonType!(ElementType!Range1, ElementType!Range2) **dotProduct**(Range1, Range2)(Range1 a, Range2 b)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2 && !(isArray!Range1 && isArray!Range2));   
  
CommonType!(F1, F2) **dotProduct**(F1, F2)(in F1[] avector, in F2[] bvector);   
  
F **dotProduct**(F, uint N)(ref scope const F[N] a, ref scope const F[N] b)  
 Constraints: if (N <= 16); 
 
Computes the [dot product](https://en.wikipedia.org/wiki/Dot_product) of input ranges `a` and `b`. The two ranges must have the same length. If both ranges define length, the check is done once; otherwise, it is done at each iteration.

  CommonType!(ElementType!Range1, ElementType!Range2) **cosineSimilarity**(Range1, Range2)(Range1 a, Range2 b)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2); 
 
Computes the [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) of input ranges `a` and `b`. The two ranges must have the same length. If both ranges define length, the check is done once; otherwise, it is done at each iteration. If either range has all-zero elements, return 0.

  bool **normalize**(R)(R range, ElementType!R sum = 1)  
 Constraints: if (isForwardRange!R); 
 
Normalizes values in `range` by multiplying each element with a number chosen such that values sum up to `sum`. If elements in `range` sum to zero, assigns `sum / range.length` to all. Normalization makes sense only if all elements in `range` are positive. `normalize` assumes that is the case without checking it. 



Returns:

`true` if normalization completed normally, `false` if all elements in `range` were zero or if `range` is empty.
 
Examples:


```
double[] a = [];
assert(!normalize(a));
a = [ 1.0, 3.0 ];
assert(normalize(a));
writeln(a); // [0.25, 0.75]
assert(normalize!(typeof(a))(a, 50)); // a = [12.5, 37.5]
a = [ 0.0, 0.0 ];
assert(!normalize(a));
writeln(a); // [0.5, 0.5]

```
 
  ElementType!Range **sumOfLog2s**(Range)(Range r)  
 Constraints: if (isInputRange!Range && isFloatingPoint!(ElementType!Range)); 
 
Compute the sum of binary logarithms of the input range `r`. The error of this method is much smaller than with a naive sum of log2.



Examples:


```
import std.math : isNaN;

writeln(sumOfLog2s(new double[0])); // 0
writeln(sumOfLog2s([0.0L])); // -real.infinity
writeln(sumOfLog2s([-0.0L])); // -real.infinity
writeln(sumOfLog2s([2.0L])); // 1
assert(sumOfLog2s([-2.0L]).isNaN());
assert(sumOfLog2s([real.nan]).isNaN());
assert(sumOfLog2s([-real.nan]).isNaN());
writeln(sumOfLog2s([real.infinity])); // real.infinity
assert(sumOfLog2s([-real.infinity]).isNaN());
writeln(sumOfLog2s([0.25, 0.25, 0.25, 0.125])); // -9

```
 
  ElementType!Range **entropy**(Range)(Range r)  
 Constraints: if (isInputRange!Range);   
  
ElementType!Range **entropy**(Range, F)(Range r, F max)  
 Constraints: if (isInputRange!Range && !is(CommonType!(ElementType!Range, F) == void)); 
 
Computes [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of input range `r` in bits. This function assumes (without checking) that the values in `r` are all in `[0, 1]`. For the entropy to be meaningful, often `r` should be normalized too (i.e., its values should sum to 1). The two-parameter version stops evaluating as soon as the intermediate result is greater than or equal to `max`.

  CommonType!(ElementType!Range1, ElementType!Range2) **kullbackLeiblerDivergence**(Range1, Range2)(Range1 a, Range2 b)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2); 
 
Computes the [Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between input ranges `a` and `b`, which is the sum `ai * log(ai / bi)`. The base of logarithm is 2. The ranges are assumed to contain elements in `[0, 1]`. Usually the ranges are normalized probability distributions, but this is not required or checked by `kullbackLeiblerDivergence`. If any element `bi` is zero and the corresponding element `ai` nonzero, returns infinity. (Otherwise, if `ai == 0 && bi == 0`, the term `ai * log(ai / bi)` is considered zero.) If the inputs are normalized, the result is positive.



Examples:


```
import std.math : approxEqual;

double[] p = [ 0.0, 0, 0, 1 ];
writeln(kullbackLeiblerDivergence(p, p)); // 0
double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ];
writeln(kullbackLeiblerDivergence(p1, p1)); // 0
writeln(kullbackLeiblerDivergence(p, p1)); // 2
writeln(kullbackLeiblerDivergence(p1, p)); // double.infinity
double[] p2 = [ 0.2, 0.2, 0.2, 0.4 ];
assert(approxEqual(kullbackLeiblerDivergence(p1, p2), 0.0719281));
assert(approxEqual(kullbackLeiblerDivergence(p2, p1), 0.0780719));

```
 
  CommonType!(ElementType!Range1, ElementType!Range2) **jensenShannonDivergence**(Range1, Range2)(Range1 a, Range2 b)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2 && is(CommonType!(ElementType!Range1, ElementType!Range2)));   
  
CommonType!(ElementType!Range1, ElementType!Range2) **jensenShannonDivergence**(Range1, Range2, F)(Range1 a, Range2 b, F limit)  
 Constraints: if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(CommonType!(ElementType!Range1, ElementType!Range2).init >= F.init) : bool)); 
 
Computes the [Jensen-Shannon divergence](https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence) between `a` and `b`, which is the sum `(ai * log(2 * ai / (ai + bi)) + bi * log(2 * bi / (ai + bi))) / 2`. The base of logarithm is 2. The ranges are assumed to contain elements in `[0, 1]`. Usually the ranges are normalized probability distributions, but this is not required or checked by `jensenShannonDivergence`. If the inputs are normalized, the result is bounded within `[0, 1]`. The three-parameter version stops evaluations as soon as the intermediate result is greater than or equal to `limit`.



Examples:


```
import std.math : approxEqual;

double[] p = [ 0.0, 0, 0, 1 ];
writeln(jensenShannonDivergence(p, p)); // 0
double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ];
writeln(jensenShannonDivergence(p1, p1)); // 0
assert(approxEqual(jensenShannonDivergence(p1, p), 0.548795));
double[] p2 = [ 0.2, 0.2, 0.2, 0.4 ];
assert(approxEqual(jensenShannonDivergence(p1, p2), 0.0186218));
assert(approxEqual(jensenShannonDivergence(p2, p1), 0.0186218));
assert(approxEqual(jensenShannonDivergence(p2, p1, 0.005), 0.00602366));

```
 
  F **gapWeightedSimilarity**(alias comp = "a == b", R1, R2, F)(R1 s, R2 t, F lambda)  
 Constraints: if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2); 
 
The so-called "all-lengths gap-weighted string kernel" computes a similarity measure between `s` and `t` based on all of their common subsequences of all lengths. Gapped subsequences are also included. 


To understand what `gapWeightedSimilarity(s, t, lambda)` computes, consider first the case `lambda = 1` and the strings `s = ["Hello", "brave", "new", "world"]` and `t = ["Hello", "new", "world"]`. In that case, `gapWeightedSimilarity` counts the following matches:   
  
 1. three matches of length 1, namely `"Hello"`, `"new"`, and `"world"`;
2. three matches of length 2, namely (`"Hello", "new"`), (`"Hello", "world"`), and (`"new", "world"`);
3. one match of length 3, namely (`"Hello", "new", "world"`).

   
  
 The call `gapWeightedSimilarity(s, t, 1)` simply counts all of these matches and adds them up, returning 7.   
  
 
```
string[] s = ["Hello", "brave", "new", "world"];
string[] t = ["Hello", "new", "world"];
assert(gapWeightedSimilarity(s, t, 1) == 7);

```
   
  
 Note how the gaps in matching are simply ignored, for example (`"Hello", "new"`) is deemed as good a match as (`"new", "world"`). This may be too permissive for some applications. To eliminate gapped matches entirely, use `lambda = 0`:   
  
 
```
string[] s = ["Hello", "brave", "new", "world"];
string[] t = ["Hello", "new", "world"];
assert(gapWeightedSimilarity(s, t, 0) == 4);

```
   
  
 The call above eliminated the gapped matches (`"Hello", "new"`), (`"Hello", "world"`), and (`"Hello", "new", "world"`) from the tally. That leaves only 4 matches.   
  
 The most interesting case is when gapped matches still participate in the result, but not as strongly as ungapped matches. The result will be a smooth, fine-grained similarity measure between the input strings. This is where values of `lambda` between 0 and 1 enter into play: gapped matches are *exponentially penalized with the number of gaps* with base `lambda`. This means that an ungapped match adds 1 to the return value; a match with one gap in either string adds `lambda` to the return value; ...; a match with a total of `n` gaps in both strings adds `pow(lambda, n)` to the return value. In the example above, we have 4 matches without gaps, 2 matches with one gap, and 1 match with three gaps. The latter match is (`"Hello", "world"`), which has two gaps in the first string and one gap in the second string, totaling to three gaps. Summing these up we get `4 + 2 * lambda + pow(lambda, 3)`.   
  
 
```
string[] s = ["Hello", "brave", "new", "world"];
string[] t = ["Hello", "new", "world"];
assert(gapWeightedSimilarity(s, t, 0.5) == 4 + 0.5 * 2 + 0.125);

```
   
  
 `gapWeightedSimilarity` is useful wherever a smooth similarity measure between sequences allowing for approximate matches is needed. The examples above are given with words, but any sequences with elements comparable for equality are allowed, e.g. characters or numbers. `gapWeightedSimilarity` uses a highly optimized dynamic programming implementation that needs `16 * min(s.length, t.length)` extra bytes of memory and Ο(`s.length * t.length`) time to complete.

  Select!(isFloatingPoint!F, F, double) **gapWeightedSimilarityNormalized**(alias comp = "a == b", R1, R2, F)(R1 s, R2 t, F lambda, F sSelfSim = F.init, F tSelfSim = F.init)  
 Constraints: if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2); 
 
The similarity per `gapWeightedSimilarity` has an issue in that it grows with the lengths of the two strings, even though the strings are not actually very similar. For example, the range `["Hello", "world"]` is increasingly similar with the range `["Hello", "world", "world", "world",...]` as more instances of `"world"` are appended. To prevent that, `gapWeightedSimilarityNormalized` computes a normalized version of the similarity that is computed as `gapWeightedSimilarity(s, t, lambda) / sqrt(gapWeightedSimilarity(s, t, lambda) * gapWeightedSimilarity(s, t, lambda))`. The function `gapWeightedSimilarityNormalized` (a so-called normalized kernel) is bounded in `[0, 1]`, reaches `0` only for ranges that don't match in any position, and `1` only for identical ranges. 


The optional parameters `sSelfSim` and `tSelfSim` are meant for avoiding duplicate computation. Many applications may have already computed `gapWeightedSimilarity(s, s, lambda)` and/or `gapWeightedSimilarity(t, t, lambda)`. In that case, they can be passed as `sSelfSim` and `tSelfSim`, respectively.

 
Examples:


```
import std.math : approxEqual, sqrt;

string[] s = ["Hello", "brave", "new", "world"];
string[] t = ["Hello", "new", "world"];
writeln(gapWeightedSimilarity(s, s, 1)); // 15
writeln(gapWeightedSimilarity(t, t, 1)); // 7
writeln(gapWeightedSimilarity(s, t, 1)); // 7
assert(approxEqual(gapWeightedSimilarityNormalized(s, t, 1),
                7.0 / sqrt(15.0 * 7), 0.01));

```
 
  struct **GapWeightedSimilarityIncremental**(Range, F = double) if (isRandomAccessRange!Range && hasLength!Range);   
  
GapWeightedSimilarityIncremental!(R, F) **gapWeightedSimilarityIncremental**(R, F)(R r1, R r2, F penalty);  
Similar to `gapWeightedSimilarity`, just works in an incremental manner by first revealing the matches of length 1, then gapped matches of length 2, and so on. The memory requirement is Ο(`s.length * t.length`). The time complexity is Ο(`s.length * t.length`) time for computing each step. Continuing on the previous example: 


The implementation is based on the pseudocode in Fig. 4 of the paper ["Efﬁcient Computation of Gapped Substring Kernels on Large Alphabets"](http://jmlr.csail.mit.edu/papers/volume6/rousu05a/rousu05a.pdf) by Rousu et al., with additional algorithmic and systems-level optimizations.

 
Examples:


```
string[] s = ["Hello", "brave", "new", "world"];
string[] t = ["Hello", "new", "world"];
auto simIter = gapWeightedSimilarityIncremental(s, t, 1.0);
assert(simIter.front == 3); // three 1-length matches
simIter.popFront();
assert(simIter.front == 3); // three 2-length matches
simIter.popFront();
assert(simIter.front == 1); // one 3-length match
simIter.popFront();
assert(simIter.empty);     // no more match

```
 
 
this(Range s, Range t, F lambda);  
Constructs an object given two ranges `s` and `t` and a penalty `lambda`. Constructor completes in Ο(`s.length * t.length`) time and computes all matches of length 1.

  ref GapWeightedSimilarityIncremental **opSlice**();  

Returns:

`this`.
  void **popFront**();  
Computes the match of the popFront length. Completes in Ο(`s.length * t.length`) time.

  @property F **front**();  

Returns:
The gapped similarity at the current match length (initially 1, grows with each call to `popFront`).
  @property bool **empty**();  

Returns:
Whether there are more matches.
    T **gcd**(T)(T a, T b)  
 Constraints: if (isIntegral!T);   
  
auto **gcd**(T)(T a, T b)  
 Constraints: if (!isIntegral!T && is(typeof(T.init % T.init)) && is(typeof(T.init == 0 || T.init > 0))); 
 
Computes the greatest common divisor of `a` and `b` by using an efficient algorithm such as [Euclid's](https://en.wikipedia.org/wiki/Euclidean_algorithm) or [Stein's](https://en.wikipedia.org/wiki/Binary_GCD_algorithm) algorithm. 



Parameters:


|  |  |
| --- | --- |
| T | Any numerical type that supports the modulo operator `%`. If bit-shifting `<<` and `>>` are also supported, Stein's algorithm will be used; otherwise, Euclid's algorithm is used as a fallback. |


 
Returns:
The greatest common divisor of the given arguments.
 
Examples:


```
writeln(gcd(2 * 5 * 7 * 7, 5 * 7 * 11)); // 5 * 7
const int a = 5 * 13 * 23 * 23, b = 13 * 59;
writeln(gcd(a, b)); // 13

```
 
  class **Fft**;  
A class for performing fast Fourier transforms of power of two sizes. This class encapsulates a large amount of state that is reusable when performing multiple FFTs of sizes smaller than or equal to that specified in the constructor. This results in substantial speedups when performing multiple FFTs with a known maximum size. However, a free function API is provided for convenience if you need to perform a one-off FFT. 



References
 [en.wikipedia.org/wiki/Cooley%E2%80%93Tukey\_FFT\_algorithm](http://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm)

 
this(size\_t size);  
Create an `Fft` object for computing fast Fourier transforms of power of two sizes of `size` or smaller. `size` must be a power of two.

  const Complex!F[] **fft**(F = double, R)(R range)  
 Constraints: if (isFloatingPoint!F && isRandomAccessRange!R); 
 
Compute the Fourier transform of range using the Ο(`N log N`) Cooley-Tukey Algorithm. `range` must be a random-access range with slicing and a length equal to `size` as provided at the construction of this object. The contents of range can be either numeric types, which will be interpreted as pure real values, or complex types with properties or members `.re` and `.im` that can be read. 



Note
 Pure real FFTs are automatically detected and the relevant optimizations are performed. 
 
Returns:
An array of complex numbers representing the transformed data in the frequency domain. 
 
Conventions
 The exponent is negative and the factor is one, i.e., output[j] := sum[ exp(-2 PI i j k / N) input[k] ].
  const void **fft**(Ret, R)(R range, Ret buf)  
 Constraints: if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret); 
 
Same as the overload, but allows for the results to be stored in a user- provided buffer. The buffer must be of the same length as range, must be a random-access range, must have slicing, and must contain elements that are complex-like. This means that they must have a .re and a .im member or property that can be both read and written and are floating point numbers.

  const Complex!F[] **inverseFft**(F = double, R)(R range)  
 Constraints: if (isRandomAccessRange!R && isComplexLike!(ElementType!R) && isFloatingPoint!F); 
 
Computes the inverse Fourier transform of a range. The range must be a random access range with slicing, have a length equal to the size provided at construction of this object, and contain elements that are either of type std.complex.Complex or have essentially the same compile-time interface. 



Returns:
The time-domain signal. 
 
Conventions
 The exponent is positive and the factor is 1/N, i.e., output[j] := (1 / N) sum[ exp(+2 PI i j k / N) input[k] ].
  const void **inverseFft**(Ret, R)(R range, Ret buf)  
 Constraints: if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret); 
 
Inverse FFT that allows a user-supplied buffer to be provided. The buffer must be a random access range with slicing, and its elements must be some complex-like type.

    Complex!F[] **fft**(F = double, R)(R range);   
  
void **fft**(Ret, R)(R range, Ret buf);   
  
Complex!F[] **inverseFft**(F = double, R)(R range);   
  
void **inverseFft**(Ret, R)(R range, Ret buf);  
Convenience functions that create an `Fft` object, run the FFT or inverse FFT and return the result. Useful for one-off FFTs. 



Note
 In addition to convenience, these functions are slightly more efficient than manually creating an Fft object for a single use, as the Fft object is deterministically destroyed before these functions return.
  pure nothrow @nogc @safe size\_t **decimalToFactorial**(ulong decimal, ref ubyte[21] fac);  
This function transforms `decimal` value into a value in the factorial number system stored in `fac`. 


A factorial number is constructed as: `fac[0] * 0! + fac[1] * 1! + ... fac[20] * 20!` 

 
Parameters:


|  |  |
| --- | --- |
| ulong `decimal` | The decimal value to convert into the factorial number system. |
| ubyte[21] `fac` | The array to store the factorial number. The array is of size 21 as `ulong.max` requires 21 digits in the factorial number system. |


 
Returns:
A variable storing the number of digits of the factorial number stored in `fac`.
 
Examples:


```
ubyte[21] fac;
size_t idx = decimalToFactorial(2982, fac);

writeln(fac[0]); // 4
writeln(fac[1]); // 0
writeln(fac[2]); // 4
writeln(fac[3]); // 1
writeln(fac[4]); // 0
writeln(fac[5]); // 0
writeln(fac[6]); // 0

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_numeric.html>

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`](std_stdio). 


 

| Category | Functions |
| --- | --- |
| General | [`exists`](#exists) [`isDir`](#isDir) [`isFile`](#isFile) [`isSymlink`](#isSymlink) [`rename`](#rename) [`thisExePath`](#thisExePath) |
| Directories | [`chdir`](#chdir) [`dirEntries`](#dirEntries) [`getcwd`](#getcwd) [`mkdir`](#mkdir) [`mkdirRecurse`](#mkdirRecurse) [`rmdir`](#rmdir) [`rmdirRecurse`](#rmdirRecurse) [`tempDir`](#tempDir) |
| Files | [`append`](#append) [`copy`](#copy) [`read`](#read) [`readText`](#readText) [`remove`](#remove) [`slurp`](#slurp) [`write`](#write) |
| Symlinks | [`symlink`](#symlink) [`readLink`](#readLink) |
| Attributes | [`attrIsDir`](#attrIsDir) [`attrIsFile`](#attrIsFile) [`attrIsSymlink`](#attrIsSymlink) [`getAttributes`](#getAttributes) [`getLinkAttributes`](#getLinkAttributes) [`getSize`](#getSize) [`setAttributes`](#setAttributes) |
| Timestamp | [`getTimes`](#getTimes) [`getTimesWin`](#getTimesWin) [`setTimes`](#setTimes) [`timeLastModified`](#timeLastModified) [`timeLastAccessed`](#timeLastAccessed) [`timeStatusChanged`](#timeStatusChanged) |
| Other | [`DirEntry`](#DirEntry) [`FileException`](#FileException) [`PreserveAttributes`](#PreserveAttributes) [`SpanMode`](#SpanMode) [`getAvailableDiskSpace`](#getAvailableDiskSpace) |

   
  
 

 
See Also:
The [official tutorial](http://ddili.org/ders/d.en/files.html) for an introduction to working with files in D, module [`std.stdio`](std_stdio) for opening files and manipulating them via handles, and module [`std.path`](std_path) for manipulating path strings. 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/file.d](https://github.com/dlang/phobos/blob/master/std/file.d)

 
class **FileException**: object.Exception;  
Exception thrown for file I/O errors.



Examples:


```
import std.exception : assertThrown;

assertThrown!FileException("non.existing.file.".readText);

```
 
 
immutable uint **errno**;  
OS error code.

  pure @safe this(scope const(char)[] name, scope const(char)[] msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Constructor which takes an error message. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `name` | Name of file for which the error occurred. |
| const(char)[] `msg` | Message describing the error. |
| string `file` | The file where the error occurred. |
| size\_t `line` | The line where the error occurred. |


  @trusted this(scope const(char)[] name, uint errno = .errno, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Constructor which takes the error number ([GetLastError](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=GetLastError) in Windows, errno in POSIX). 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `name` | Name of file for which the error occurred. |
| uint `errno` | The error number. |
| string `file` | The file where the error occurred. Defaults to `__FILE__`. |
| size\_t `line` | The line where the error occurred. Defaults to `__LINE__`. |


    void[] **read**(R)(R name, size\_t upTo = size\_t.max)  
 Constraints: if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isInfinite!R && !isConvertibleToString!R);   
  
void[] **read**(R)(auto ref R name, size\_t upTo = size\_t.max)  
 Constraints: if (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. 



Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |
| size\_t `upTo` | if present, the maximum number of bytes to read |


 
Returns:
Untyped array of bytes read. 
 
Throws:

[`FileException`](#FileException) on error.
 
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
writeln(read(deleteme, 2)); // "12"
writeln(read(deleteme.byChar)); // "1234"
writeln((cast(const(ubyte)[])read(deleteme)).length); // 4

```
 
  S **readText**(S = string, R)(auto ref R name)  
 Constraints: if (isSomeString!S && (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R))); 
 
Reads and validates (using [`std.utf.validate`](std_utf#validate)) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail. 



Parameters:


|  |  |
| --- | --- |
| S | the string type of the file |
| R `name` | string or range of characters representing the file name |


 
Returns:
Array of characters read. 
 
Throws:

[`FileException`](#FileException) if there is an error reading the file, [`std.utf.UTFException`](std_utf#UTFException) on UTF decoding error.
 
Examples:
Read file with UTF-8 text. 
```
write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
writeln(content); // "abc"

```
 
  void **write**(R)(R name, const void[] buffer)  
 Constraints: if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);   
  
void **write**(R)(auto ref R name, const void[] buffer)  
 Constraints: if (isConvertibleToString!R); 
 
Write `buffer` to file `name`. 


Creates the file if it does not already exist. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |
| void[] `buffer` | data to be written to file |


 
Throws:

[`FileException`](#FileException) on error. 
 
See Also:
[`std.stdio.toFile`](std_stdio#toFile)
 
Examples:


```
scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
writeln(cast(int[])read(deleteme)); // a

```
 
  void **append**(R)(R name, const void[] buffer)  
 Constraints: if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);   
  
void **append**(R)(auto ref R name, const void[] buffer)  
 Constraints: if (isConvertibleToString!R); 
 
Appends `buffer` to file `name`. 


Creates the file if it does not already exist. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |
| void[] `buffer` | data to be appended to file |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
int[] b = [ 13, 21 ];
append(deleteme, b);
writeln(cast(int[])read(deleteme)); // a ~ b

```
 
  void **rename**(RF, RT)(RF from, RT to)  
 Constraints: if ((isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF) && !isConvertibleToString!RF && (isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT) && !isConvertibleToString!RT);   
  
void **rename**(RF, RT)(auto ref RF from, auto ref RT to)  
 Constraints: if (isConvertibleToString!RF || isConvertibleToString!RT); 
 
Rename file `from` to `to`, moving it between directories if required. If the target file exists, it is overwritten. 


It is not possible to rename a file across different mount points or drives. On POSIX, the operation is atomic. That means, if `to` already exists there will be no time period during the operation where `to` is missing. See [manpage for rename](http://man7.org/linux/man-pages/man2/rename.2.html) for more details. 

 
Parameters:


|  |  |
| --- | --- |
| RF `from` | string or range of characters representing the existing file name |
| RT `to` | string or range of characters representing the target file name |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();

t1.write("1");
t1.rename(t2);
writeln(t2.readText); // "1"

t1.write("2");
t1.rename(t2);
writeln(t2.readText); // "2"

```
 
  void **remove**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **remove**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Delete file `name`. 



Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
import std.exception : assertThrown;

deleteme.write("Hello");
writeln(deleteme.readText); // "Hello"

deleteme.remove;
assertThrown!FileException(deleteme.readText);

```
 
  ulong **getSize**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
ulong **getSize**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Get size of file `name` in bytes. 



Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |


 
Returns:
The size of file in bytes. 
 
Throws:

[`FileException`](#FileException) on error (e.g., file not found).
 
Examples:


```
scope(exit) deleteme.remove;

// create a file of size 1
write(deleteme, "a");
writeln(getSize(deleteme)); // 1

// create a file of size 3
write(deleteme, "abc");
writeln(getSize(deleteme)); // 3

```
 
  void **getTimes**(R)(R name, out SysTime accessTime, out SysTime modificationTime)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **getTimes**(R)(auto ref R name, out SysTime accessTime, out SysTime modificationTime)  
 Constraints: if (isConvertibleToString!R); 
 
Get the access and modified times of file or folder `name`. 



Parameters:


|  |  |
| --- | --- |
| R `name` | File/Folder name to get times for. |
| SysTime `accessTime` | Time the file/folder was last accessed. |
| SysTime `modificationTime` | Time the file/folder was last modified. |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
import std.datetime : abs, SysTime;

scope(exit) deleteme.remove;
write(deleteme, "a");

SysTime accessTime, modificationTime;

getTimes(deleteme, accessTime, modificationTime);

import std.datetime : Clock, seconds;
auto currTime = Clock.currTime();
enum leeway = 5.seconds;

auto diffAccess = accessTime - currTime;
auto diffModification = modificationTime - currTime;
assert(abs(diffAccess) <= leeway);
assert(abs(diffModification) <= leeway);

```
 
  void **getTimesWin**(R)(R name, out SysTime fileCreationTime, out SysTime fileAccessTime, out SysTime fileModificationTime)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); 
 
This function is Windows-Only. 


Get creation/access/modified times of file `name`.   
  
 This is the same as `getTimes` except that it also gives you the file creation time - which isn't possible on POSIX systems. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | File name to get times for. |
| SysTime `fileCreationTime` | Time the file was created. |
| SysTime `fileAccessTime` | Time the file was last accessed. |
| SysTime `fileModificationTime` | Time the file was last modified. |


 
Throws:

[`FileException`](#FileException) on error.
  void **setTimes**(R)(R name, SysTime accessTime, SysTime modificationTime)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **setTimes**(R)(auto ref R name, SysTime accessTime, SysTime modificationTime)  
 Constraints: if (isConvertibleToString!R); 
 
Set access/modified times of file or folder `name`. 



Parameters:


|  |  |
| --- | --- |
| R `name` | File/Folder name to get times for. |
| SysTime `accessTime` | Time the file/folder was last accessed. |
| SysTime `modificationTime` | Time the file/folder was last modified. |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
import std.datetime : DateTime, hnsecs, SysTime;

scope(exit) deleteme.remove;
write(deleteme, "a");

SysTime accessTime = SysTime(DateTime(2010, 10, 4, 0, 0, 30));
SysTime modificationTime = SysTime(DateTime(2018, 10, 4, 0, 0, 30));
setTimes(deleteme, accessTime, modificationTime);

SysTime accessTimeResolved, modificationTimeResolved;
getTimes(deleteme, accessTimeResolved, modificationTimeResolved);

writeln(accessTime); // accessTimeResolved
writeln(modificationTime); // modificationTimeResolved

```
 
  SysTime **timeLastModified**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
SysTime **timeLastModified**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Returns the time that the given file was last modified. 



Parameters:


|  |  |
| --- | --- |
| R `name` | the name of the file to check |


 
Returns:
A [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). 
 
Throws:

[`FileException`](#FileException) if the given file does not exist.
 
Examples:


```
import std.datetime : abs, DateTime, hnsecs, SysTime;
scope(exit) deleteme.remove;

import std.datetime : Clock, seconds;
auto currTime = Clock.currTime();
enum leeway = 5.seconds;
deleteme.write("bb");
assert(abs(deleteme.timeLastModified - currTime) <= leeway);

```
 
  SysTime **timeLastModified**(R)(R name, SysTime returnIfMissing)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R)); 
 
Returns the time that the given file was last modified. If the file does not exist, returns `returnIfMissing`. 


A frequent usage pattern occurs in build automation tools such as [make](http://gnu.org/software/make) or [ant](http://%20%20%20%20en.wikipedia.org/wiki/Apache_Ant). To check whether file  `target` must be rebuilt from file `source` (i.e., `target` is older than `source` or does not exist), use the comparison below. The code throws a [`FileException`](#FileException) if `source` does not exist (as it should). On the other hand, the `SysTime.min` default makes a non-existing `target` seem infinitely old so the test correctly prompts building it. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | The name of the file to get the modification time for. |
| SysTime `returnIfMissing` | The time to return if the given file does not exist. |


 
Returns:
A [`std.datetime.systime.SysTime`](std_datetime_systime#SysTime). 
 
Example


```
if (source.timeLastModified >= target.timeLastModified(SysTime.min))
{
    // must (re)build
}
else
{
    // target is up-to-date
}

```
 
Examples:


```
import std.datetime : SysTime;

writeln("file.does.not.exist".timeLastModified(SysTime.min)); // SysTime.min

auto source = deleteme ~ "source";
auto target = deleteme ~ "target";
scope(exit) source.remove, target.remove;

source.write(".");
assert(target.timeLastModified(SysTime.min) < source.timeLastModified);
target.write(".");
assert(target.timeLastModified(SysTime.min) >= source.timeLastModified);

```
 
  pure nothrow SysTime **timeLastModified**()(auto ref stat\_t statbuf);  
This function is POSIX-Only. 


Returns the time that the given file was last modified. 

 
Parameters:


|  |  |
| --- | --- |
| stat\_t `statbuf` | stat\_t retrieved from file. |


  pure nothrow SysTime **timeLastAccessed**()(auto ref stat\_t statbuf);  
This function is POSIX-Only. 


Returns the time that the given file was last accessed. 

 
Parameters:


|  |  |
| --- | --- |
| stat\_t `statbuf` | stat\_t retrieved from file. |


  pure nothrow SysTime **timeStatusChanged**()(auto ref stat\_t statbuf);  
This function is POSIX-Only. 


Returns the time that the given file was last changed. 

 
Parameters:


|  |  |
| --- | --- |
| stat\_t `statbuf` | stat\_t retrieved from file. |


  bool **exists**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
bool **exists**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Determine whether the given file (or directory) exists. 



Parameters:


|  |  |
| --- | --- |
| R `name` | string or range of characters representing the file name |


 
Returns:
true if the file name specified as input exists
 
Examples:


```
auto f = deleteme ~ "does.not.exist";
assert(!f.exists);

f.write("hello");
assert(f.exists);

f.remove;
assert(!f.exists);

```
 
  uint **getAttributes**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
uint **getAttributes**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Returns the attributes of the given file. 


Note that the file attributes on Windows and POSIX systems are completely different. On Windows, they're what is returned by  [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx), whereas on POSIX systems, they're the `st_mode` value which is part of the `stat struct` gotten by calling the [`stat`](http://en.wikipedia.org/wiki/Stat_%28Unix%29) function.   
  
 On POSIX systems, if the given file is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | The file to get the attributes of. |


 
Returns:
The attributes of the file as a `uint`. 
 
Throws:

[`FileException`](#FileException) on error.
 
Examples:
getAttributes with a file 
```
import std.exception : assertThrown;

auto f = deleteme ~ "file";
scope(exit) f.remove;

assert(!f.exists);
assertThrown!FileException(f.getAttributes);

f.write(".");
auto attributes = f.getAttributes;
assert(!attributes.attrIsDir);
assert(attributes.attrIsFile);

```
 
 
Examples:
getAttributes with a directory 
```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
scope(exit) dir.rmdir;

assert(!dir.exists);
assertThrown!FileException(dir.getAttributes);

dir.mkdir;
auto attributes = dir.getAttributes;
assert(attributes.attrIsDir);
assert(!attributes.attrIsFile);

```
 
  uint **getLinkAttributes**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
uint **getLinkAttributes**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
If the given file is a symbolic link, then this returns the attributes of the symbolic link itself rather than file that it points to. If the given file is *not* a symbolic link, then this function returns the same result as getAttributes. 


On Windows, getLinkAttributes is identical to getAttributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | The file to get the symbolic link attributes of. |


 
Returns:
the attributes 
 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
import std.exception : assertThrown;

auto source = deleteme ~ "source";
auto target = deleteme ~ "target";

assert(!source.exists);
assertThrown!FileException(source.getLinkAttributes);

// symlinking isn't available on Windows
version (Posix)
{
    scope(exit) source.remove, target.remove;

    target.write("target");
    target.symlink(source);
    writeln(source.readText); // "target"
    assert(source.isSymlink);
    assert(source.getLinkAttributes.attrIsSymlink);
}

```
 
 
Examples:
if the file is no symlink, getLinkAttributes behaves like getAttributes 
```
import std.exception : assertThrown;

auto f = deleteme ~ "file";
scope(exit) f.remove;

assert(!f.exists);
assertThrown!FileException(f.getLinkAttributes);

f.write(".");
auto attributes = f.getLinkAttributes;
assert(!attributes.attrIsDir);
assert(attributes.attrIsFile);

```
 
 
Examples:
if the file is no symlink, getLinkAttributes behaves like getAttributes 
```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
scope(exit) dir.rmdir;

assert(!dir.exists);
assertThrown!FileException(dir.getLinkAttributes);

dir.mkdir;
auto attributes = dir.getLinkAttributes;
assert(attributes.attrIsDir);
assert(!attributes.attrIsFile);

```
 
  void **setAttributes**(R)(R name, uint attributes)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **setAttributes**(R)(auto ref R name, uint attributes)  
 Constraints: if (isConvertibleToString!R); 
 
Set the attributes of the given file. 


For example, a programmatic equivalent of Unix's `chmod +x name` to make a file executable is `name.setAttributes(name.getAttributes | octal!700)`. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | the file name |
| uint `attributes` | the attributes to set the file to |


 
Throws:

[`FileException`](#FileException) if the given file does not exist.
 
Examples:
setAttributes with a file 
```
import std.exception : assertThrown;
import std.conv : octal;

auto f = deleteme ~ "file";
version (Posix)
{
    scope(exit) f.remove;

    assert(!f.exists);
    assertThrown!FileException(f.setAttributes(octal!777));

    f.write(".");
    auto attributes = f.getAttributes;
    assert(!attributes.attrIsDir);
    assert(attributes.attrIsFile);

    f.setAttributes(octal!777);
    attributes = f.getAttributes;

    writeln((attributes & 1023)); // octal!777
}

```
 
 
Examples:
setAttributes with a directory 
```
import std.exception : assertThrown;
import std.conv : octal;

auto dir = deleteme ~ "dir";
version (Posix)
{
    scope(exit) dir.rmdir;

    assert(!dir.exists);
    assertThrown!FileException(dir.setAttributes(octal!777));

    dir.mkdir;
    auto attributes = dir.getAttributes;
    assert(attributes.attrIsDir);
    assert(!attributes.attrIsFile);

    dir.setAttributes(octal!777);
    attributes = dir.getAttributes;

    writeln((attributes & 1023)); // octal!777
}

```
 
  @property bool **isDir**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
@property bool **isDir**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Returns whether the given file is a directory. 



Parameters:


|  |  |
| --- | --- |
| R `name` | The path to the file. |


 
Returns:
true if name specifies a directory 
 
Throws:

[`FileException`](#FileException) if the given file does not exist.
 
Examples:


```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
auto f = deleteme ~ "f";
scope(exit) dir.rmdir, f.remove;

assert(!dir.exists);
assertThrown!FileException(dir.isDir);

dir.mkdir;
assert(dir.isDir);

f.write(".");
assert(!f.isDir);

```
 
  pure nothrow @nogc @safe bool **attrIsDir**(uint attributes);  
Returns whether the given file attributes are for a directory. 



Parameters:


|  |  |
| --- | --- |
| uint `attributes` | The file attributes. |


 
Returns:
true if attributes specifies a directory
 
Examples:


```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
auto f = deleteme ~ "f";
scope(exit) dir.rmdir, f.remove;

assert(!dir.exists);
assertThrown!FileException(dir.getAttributes.attrIsDir);

dir.mkdir;
assert(dir.isDir);
assert(dir.getAttributes.attrIsDir);

f.write(".");
assert(!f.isDir);
assert(!f.getAttributes.attrIsDir);

```
 
  @property bool **isFile**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
@property bool **isFile**(R)(auto ref R name)  
 Constraints: if (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. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | The path to the file. |


 
Returns:
true if name specifies a file 
 
Throws:

[`FileException`](#FileException) if the given file does not exist.
 
Examples:


```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
auto f = deleteme ~ "f";
scope(exit) dir.rmdir, f.remove;

dir.mkdir;
assert(!dir.isFile);

assert(!f.exists);
assertThrown!FileException(f.isFile);

f.write(".");
assert(f.isFile);

```
 
  pure nothrow @nogc @safe bool **attrIsFile**(uint attributes);  
Returns whether the given file attributes are for a file. 


On Windows, if a file is not a directory, it's a file. So, either `attrIsFile` or `attrIsDir` will return `true` for the attributes of any given file.   
  
 On POSIX systems, if `attrIsFile` 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 `attrIsFile` and `attrIsDir` to be `false` for a particular file (in which case, it's a special file). If a file is a special file, you can use the attributes to check what type of special file it is (see the man page for `stat` for more information). 

 
Parameters:


|  |  |
| --- | --- |
| uint `attributes` | The file attributes. |


 
Returns:
true if the given file attributes are for a file 
 
Example


```
assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf")));
assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));

```
 
Examples:


```
import std.exception : assertThrown;

auto dir = deleteme ~ "dir";
auto f = deleteme ~ "f";
scope(exit) dir.rmdir, f.remove;

dir.mkdir;
assert(!dir.isFile);
assert(!dir.getAttributes.attrIsFile);

assert(!f.exists);
assertThrown!FileException(f.getAttributes.attrIsFile);

f.write(".");
assert(f.isFile);
assert(f.getAttributes.attrIsFile);

```
 
  @property bool **isSymlink**(R)(R name)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
@property bool **isSymlink**(R)(auto ref R name)  
 Constraints: if (isConvertibleToString!R); 
 
Returns whether the given file is a symbolic link. 


On Windows, returns `true` when the file is either a symbolic link or a junction point. 

 
Parameters:


|  |  |
| --- | --- |
| R `name` | The path to the file. |


 
Returns:
true if name is a symbolic link 
 
Throws:

[`FileException`](#FileException) if the given file does not exist.
 
Examples:


```
import std.exception : assertThrown;

auto source = deleteme ~ "source";
auto target = deleteme ~ "target";

assert(!source.exists);
assertThrown!FileException(source.isSymlink);

// symlinking isn't available on Windows
version (Posix)
{
    scope(exit) source.remove, target.remove;

    target.write("target");
    target.symlink(source);
    writeln(source.readText); // "target"
    assert(source.isSymlink);
    assert(source.getLinkAttributes.attrIsSymlink);
}

```
 
  pure nothrow @nogc @safe bool **attrIsSymlink**(uint attributes);  
Returns whether the given file attributes are for a symbolic link. 


On Windows, return `true` when the file is either a symbolic link or a junction point. 

 
Parameters:


|  |  |
| --- | --- |
| uint `attributes` | The file attributes. |


 
Returns:
true if attributes are for a symbolic link 
 
Example


```
core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink");

assert(!getAttributes("/tmp/alink").isSymlink);
assert(getLinkAttributes("/tmp/alink").isSymlink);

```
 
Examples:


```
import std.exception : assertThrown;

auto source = deleteme ~ "source";
auto target = deleteme ~ "target";

assert(!source.exists);
assertThrown!FileException(source.getLinkAttributes.attrIsSymlink);

// symlinking isn't available on Windows
version (Posix)
{
    scope(exit) source.remove, target.remove;

    target.write("target");
    target.symlink(source);
    writeln(source.readText); // "target"
    assert(source.isSymlink);
    assert(source.getLinkAttributes.attrIsSymlink);
}

```
 
  void **chdir**(R)(R pathname)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **chdir**(R)(auto ref R pathname)  
 Constraints: if (isConvertibleToString!R); 
 
Change directory to `pathname`. Equivalent to `cd` on Windows and POSIX. 



Parameters:


|  |  |
| --- | --- |
| R `pathname` | the directory to step into |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.path : buildPath;

auto cwd = getcwd;
auto dir = deleteme ~ "dir";
dir.mkdir;
scope(exit) cwd.chdir, dir.rmdirRecurse;

dir.buildPath("a").write(".");
dir.chdir; // step into dir
"b".write(".");
dirEntries(".", SpanMode.shallow).equal(
    [".".buildPath("b"), ".".buildPath("a")]
);

```
 
  void **mkdir**(R)(R pathname)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **mkdir**(R)(auto ref R pathname)  
 Constraints: if (isConvertibleToString!R); 
 
Make a new directory `pathname`. 



Parameters:


|  |  |
| --- | --- |
| R `pathname` | the path of the directory to make |


 
Throws:

[`FileException`](#FileException) on POSIX or [`WindowsException`](#WindowsException) on Windows if an error occured.
 
Examples:


```
import std.file : mkdir;

auto dir = deleteme ~ "dir";
scope(exit) dir.rmdir;

dir.mkdir;
assert(dir.exists);

```
 
 
Examples:


```
import std.exception : assertThrown;
assertThrown("a/b/c/d/e".mkdir);

```
 
  @safe void **mkdirRecurse**(scope const(char)[] pathname);  
Make directory and all parent directories as needed. 


Does nothing if the directory specified by `pathname` already exists. 

 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `pathname` | the full path of the directory to create |


 
Throws:

[`FileException`](#FileException) on error.
 
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);

```
 
 
Examples:


```
import std.exception : assertThrown;

scope(exit) deleteme.remove;
deleteme.write("a");

// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);

```
 
  void **rmdir**(R)(R pathname)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);   
  
void **rmdir**(R)(auto ref R pathname)  
 Constraints: if (isConvertibleToString!R); 
 
Remove directory `pathname`. 



Parameters:


|  |  |
| --- | --- |
| R `pathname` | Range or string specifying the directory name |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
auto dir = deleteme ~ "dir";

dir.mkdir;
assert(dir.exists);
dir.rmdir;
assert(!dir.exists);

```
 
  void **symlink**(RO, RL)(RO original, RL link)  
 Constraints: if ((isInputRange!RO && !isInfinite!RO && isSomeChar!(ElementEncodingType!RO) || isConvertibleToString!RO) && (isInputRange!RL && !isInfinite!RL && isSomeChar!(ElementEncodingType!RL) || isConvertibleToString!RL)); 
 
This function is POSIX-Only. 


Creates a symbolic link (symlink). 

 
Parameters:


|  |  |
| --- | --- |
| RO `original` | The file that is being linked. This is the target path that's stored in the symlink. A relative path is relative to the created symlink. |
| RL `link` | The symlink to create. A relative path is relative to the current working directory. |


 
Throws:

[`FileException`](#FileException) on error (which includes if the symlink already exists).
  string **readLink**(R)(R link)  
 Constraints: if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isConvertibleToString!R); 
 
This function is POSIX-Only. 


Returns the path to the file pointed to by a symlink. Note that the path could be either relative or absolute depending on the symlink. If the path is relative, it's relative to the symlink, not the current working directory. 

 
Throws:

[`FileException`](#FileException) on error.
  @trusted string **getcwd**();  
Get the current working directory. 



Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
auto s = getcwd();
assert(s.length);

```
 
  @trusted string **thisExePath**();  
Returns the full path of the current executable. 



Returns:
The path of the executable as a `string`. 
 
Throws:
[`Exception`](object#Exception)
 
Examples:


```
import std.path : isAbsolute;
auto path = thisExePath();

assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);

```
 
  struct **DirEntry**;  
Info on a file, similar to what you'd get from stat on a POSIX system.

 
@safe this(string path);  
Constructs a `DirEntry` for the given file (or directory). 



Parameters:


|  |  |
| --- | --- |
| string `path` | The file (or directory) to get a DirEntry for. |


 
Throws:

[`FileException`](#FileException) if the file does not exist.
  const @property @safe string **name**();  
Returns the path to the file represented by this `DirEntry`. 



Example


```
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(de1.name == "/etc/fonts/fonts.conf");

auto de2 = DirEntry("/usr/share/include");
assert(de2.name == "/usr/share/include");

```
  @property @safe bool **isDir**();  
Returns whether the file represented by this `DirEntry` is a directory. 



Example


```
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(!de1.isDir);

auto de2 = DirEntry("/usr/share/include");
assert(de2.isDir);

```
  @property @safe bool **isFile**();  
Returns whether the file represented by this `DirEntry` 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`.   
  
 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 `attributes` or `statBuf` to get more information about a special file (see the stat man page for more details). 

 
Example


```
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(de1.isFile);

auto de2 = DirEntry("/usr/share/include");
assert(!de2.isFile);

```
  @property @safe bool **isSymlink**();  
Returns whether the file represented by this `DirEntry` is a symbolic link. 


On Windows, return `true` when the file is either a symbolic link or a junction point.

  @property @safe ulong **size**();  
Returns the size of the the file represented by this `DirEntry` in bytes.

  const @property @safe SysTime **timeCreated**();  
This function is Windows-Only. 


Returns the creation time of the file represented by this `DirEntry`.

  @property @safe SysTime **timeLastAccessed**();  
Returns the time that the file represented by this `DirEntry` was last accessed. 


Note that many file systems do not update the access time for files (generally for performance reasons), so there's a good chance that `timeLastAccessed` will return the same value as `timeLastModified`.

  @property @safe SysTime **timeLastModified**();  
Returns the time that the file represented by this `DirEntry` was last modified.

  const @property @safe SysTime **timeStatusChanged**();  
This function is POSIX-Only. 


Returns the time that the file represented by this `DirEntry` was last changed (not only in contents, but also in permissions or ownership).

  @property @safe uint **attributes**();  
Returns the attributes of the file represented by this `DirEntry`. 


Note that the file attributes on Windows and POSIX systems are completely different. On, Windows, they're what is returned by `GetFileAttributes` [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx) Whereas, an POSIX systems, they're the `st_mode` value which is part of the `stat` struct gotten by calling `stat`.   
  
 On POSIX systems, if the file represented by this `DirEntry` is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.

  @property @safe uint **linkAttributes**();  
On POSIX systems, if the file represented by this `DirEntry` is a symbolic link, then `linkAttributes` are the attributes of the symbolic link itself. Otherwise, `linkAttributes` is identical to `attributes`. 


On Windows, `linkAttributes` is identical to `attributes`. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links.

  @property @safe stat\_t **statBuf**();  
This function is POSIX-Only. 


The `stat` struct gotten from calling `stat`.

    PreserveAttributes **preserveAttributesDefault**;  
Defaults to `Yes.preserveAttributes` on Windows, and the opposite on all other platforms.

  void **copy**(RF, RT)(RF from, RT to, PreserveAttributes preserve = preserveAttributesDefault)  
 Constraints: if (isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) && !isConvertibleToString!RF && isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) && !isConvertibleToString!RT);   
  
void **copy**(RF, RT)(auto ref RF from, auto ref RT to, PreserveAttributes preserve = preserveAttributesDefault)  
 Constraints: if (isConvertibleToString!RF || isConvertibleToString!RT); 
 
Copy file `from` to file `to`. File timestamps are preserved. File attributes are preserved, if `preserve` equals `Yes.preserveAttributes`. On Windows only `Yes.preserveAttributes` (the default on Windows) is supported. If the target file exists, it is overwritten. 



Parameters:


|  |  |
| --- | --- |
| RF `from` | string or range of characters representing the existing file name |
| RT `to` | string or range of characters representing the target file name |
| PreserveAttributes `preserve` | whether to preserve the file attributes |


 
Throws:

[`FileException`](#FileException) on error.
 
Examples:


```
auto source = deleteme ~ "source";
auto target = deleteme ~ "target";
auto targetNonExistent = deleteme ~ "target2";

scope(exit) source.remove, target.remove, targetNonExistent.remove;

source.write("source");
target.write("target");

writeln(target.readText); // "target"

source.copy(target);
writeln(target.readText); // "source"

source.copy(targetNonExistent);
writeln(targetNonExistent.readText); // "source"

```
 
  @safe void **rmdirRecurse**(scope const(char)[] pathname);   
  
@safe void **rmdirRecurse**(ref DirEntry de);   
  
@safe void **rmdirRecurse**(DirEntry de);  
Remove directory and all of its content and subdirectories, recursively. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `pathname` | the path of the directory to completely remove |
| DirEntry `de` | The [`DirEntry`](#DirEntry) to remove |


 
Throws:

[`FileException`](#FileException) if there is an error (including if the given file is not a directory).
 
Examples:


```
import std.path : buildPath;

auto dir = deleteme.buildPath("a", "b", "c");

dir.mkdirRecurse;
assert(dir.exists);

deleteme.rmdirRecurse;
assert(!dir.exists);
assert(!deleteme.exists);

```
 
  enum **SpanMode**: int;  
Dictates directory spanning policy for dirEntries (see below).



Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
root.buildPath("animals", "dog").mkdir;
root.buildPath("plants").mkdir;

alias removeRoot = (e) => e.relativePath(root);

root.dirEntries(SpanMode.shallow).map!removeRoot.equal(
    ["plants", "animals"]);

root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    ["plants", "animals/dog", "animals/cat", "animals"]);

root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["plants", "animals", "animals/dog", "animals/cat"]);

```
 
 
**shallow** 
Only spans one directory.

  **depth** 
Spans the directory in  [depth-first **post**-order](https://en.wikipedia.org/wiki/Tree_traversal#Post-order), i.e. the content of any subdirectory is spanned before that subdirectory itself. Useful e.g. when recursively deleting files.

  **breadth** 
Spans the directory in [depth-first **pre**-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order), i.e. the content of any subdirectory is spanned right after that subdirectory itself. 


Note that `SpanMode.breadth` will not result in all directory members occurring before any subdirectory members, i.e. it is not true  [breadth-first traversal](https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search).

    auto **dirEntries**(string path, SpanMode mode, bool followSymlink = true);   
  
auto **dirEntries**(string path, string pattern, SpanMode mode, bool followSymlink = true);  
Returns an [input range](std_range_primitives#isInputRange) of `DirEntry` that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type `string` if only the name is needed, or `DirEntry` if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname). 



Parameters:


|  |  |
| --- | --- |
| string `path` | The directory to iterate over. If empty, the current directory will be iterated. |
| string `pattern` | Optional string with wildcards, such as  "\*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under  [`std.path.globMatch`](std_path#globMatch). |
| SpanMode `mode` | Whether the directory's sub-directories should be iterated in depth-first post-order ([`depth`](#depth)), depth-first pre-order ([`breadth`](#breadth)), or not at all ([`shallow`](#shallow)). |
| bool `followSymlink` | Whether symbolic links which point to directories should be treated as directories and their contents iterated over. |


 
Returns:
An [input range](std_range_primitives#isInputRange) of [`DirEntry`](#DirEntry). 
 
Throws:

[`FileException`](#FileException) if the directory does not exist. 
 
Example


```
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

```
 
Examples:
Duplicate functionality of D1's `std.file.listdir()`: 
```
string[] listdir(string pathname)
{
    import std.algorithm;
    import std.array;
    import std.file;
    import std.path;

    return std.file.dirEntries(pathname, SpanMode.shallow)
        .filter!(a => a.isFile)
        .map!(a => std.path.baseName(a.name))
        .array;
}

void main(string[] args)
{
    import std.stdio;

    string[] files = listdir(args[1]);
    writefln("%s", files);
 }

```
 
  Select!(Types.length == 1, Types[0][], Tuple!Types[]) **slurp**(Types...)(string filename, scope const(char)[] format);  
Reads a file line by line and parses the line into a single value or a [`std.typecons.Tuple`](std_typecons#Tuple) of values depending on the length of `Types`. The lines are parsed using the specified format string. The format string is passed to [`std.format.formattedRead`](std_format#formattedRead), and therefore must conform to the format string specification outlined in [`std.format`](std_format). 



Parameters:


|  |  |
| --- | --- |
| Types | the types that each of the elements in the line should be returned as |
| string `filename` | the name of the file to read |
| const(char)[] `format` | the format string to use when reading |


 
Returns:
If only one type is passed, then an array of that type. Otherwise, an array of [`std.typecons.Tuple`](std_typecons#Tuple)s. 
 
Throws:

`Exception` if the format string is malformed. Also, throws `Exception` if any of the lines in the file are not fully consumed by the call to [`std.format.formattedRead`](std_format#formattedRead). Meaning that no empty lines or lines with extra characters are allowed.
 
Examples:


```
import std.typecons : tuple;

scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

write(deleteme, "12 12.25\n345 1.125"); // deleteme is the name of a temporary file

// Load file; each line is an int followed by comma, whitespace and a
// double.
auto a = slurp!(int, double)(deleteme, "%s %s");
writeln(a.length); // 2
writeln(a[0]); // tuple(12, 12.25)
writeln(a[1]); // tuple(345, 1.125)

```
 
  @trusted string **tempDir**();  
Returns the path to a directory for temporary files. 


The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.   
  
 The POSIX `tempDir` algorithm is inspired by Python's [`tempfile.tempdir`](http://docs.python.org/library/tempfile.html#tempfile.tempdir). 

 
Returns:
On Windows, this function returns the result of calling the Windows API function [`GetTempPath`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx). On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist: 1. The directory given by the `TMPDIR` environment variable.
2. The directory given by the `TEMP` environment variable.
3. The directory given by the `TMP` environment variable.
4. `/tmp`
5. `/var/tmp`
6. `/usr/tmp`

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


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

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

myFile.write("hello");
writeln(myFile.readText); // "hello"

```
 
  @safe ulong **getAvailableDiskSpace**(scope const(char)[] path);  
Returns the available disk space based on a given path. On Windows, `path` must be a directory; on POSIX systems, it can be a file or directory. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `path` | on Windows, it must be a directory; on POSIX it can be a file or directory |


 
Returns:
Available space in bytes 
 
Throws:

[`FileException`](#FileException) in case of failure
 
Examples:


```
import std.exception : assertThrown;

auto space = getAvailableDiskSpace(".");
assert(space > 0);

assertThrown!FileException(getAvailableDiskSpace("ThisFileDoesNotExist123123"));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_file.html>

std.process
===========

 Functions for starting and interacting with other processes, and for working with the current process' execution environment. 



Process handling

* [`spawnProcess`](#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`](#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`](#spawnProcess) documentation for examples. [`tryWait`](#tryWait) is similar to `wait`, but does not block if the process has not yet terminated.
* [`pipeProcess`](#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`](#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`](#spawnShell), [`pipeShell`](#pipeShell) and [`executeShell`](#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`](#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`](#spawnProcess) | [`spawnShell`](#spawnShell) |
| Automatic input/output redirection using pipes | [`pipeProcess`](#pipeProcess) | [`pipeShell`](#pipeShell) |
| Execute and wait for completion, collect output | [`execute`](#execute) | [`executeShell`](#executeShell) |

 
Other functionality

* [`pipe`](#pipe) is used to create unidirectional pipes.
* [`environment`](#environment) is an interface through which the current process' environment variables can be read and manipulated.
* [`escapeShellCommand`](#escapeShellCommand) and [`escapeShellFileName`](#escapeShellFileName) are useful for constructing shell command lines in a portable way.

 
Authors:

[Lars Tandle Kyllingstad](https://github.com/kyllingstad), [Steven Schveighoffer](https://github.com/schveiguy), [Vladimir Panteleev](http://thecybershadow.net) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Source
 [std/process.d](https://github.com/dlang/phobos/blob/master/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`](#environment), [`thisProcessID`](#thisProcessID) and [`thisThreadID`](#thisThreadID).
 
abstract class **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.

 
static @safe string **opIndex**(scope const(char)[] name);  
 Retrieves the value of the environment variable with the given `name`. 
```
auto path = environment["PATH"];

```
 



Throws:

[`Exception`](object#Exception) if the environment variable does not exist, or [`std.utf.UTFException`](std_utf#UTFException) if the variable contains invalid UTF-16 characters (Windows only). 
 
See Also:

[`environment.get`](#environment.get), which doesn't throw on failure.
  static @safe string **get**(scope const(char)[] name, string defaultValue = null);  
Retrieves the value of the environment variable with the given `name`, or a default value if the variable doesn't exist. 


 Unlike [`environment.opIndex`](#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.
}

```
 

 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `name` | name of the environment variable to retrieve |
| string `defaultValue` | default value to return if the environment variable doesn't exist. |


 
Returns:
the value of the environment variable if found, otherwise `null` if the environment doesn't exist. 
 
Throws:

[`std.utf.UTFException`](std_utf#UTFException) if the variable contains invalid UTF-16 characters (Windows only).
  static @trusted inout(char)[] **opIndexAssign**(inout char[] value, scope const(char)[] name);  
Assigns the given `value` to the environment variable with the given `name`. If `value` is null the variable is removed from environment. 


 If the variable does not exist, it will be created. If it already exists, it will be overwritten. 
```
environment["foo"] = "bar";

```
 

 
Throws:

[`Exception`](object#Exception) if the environment variable could not be added (e.g. if the name is invalid). 
 
Note
 On some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g. [glibc](https://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access).
  static nothrow @nogc @trusted void **remove**(scope const(char)[] name);  
Removes the environment variable with the given `name`. 


If the variable isn't in the environment, this function returns successfully without doing anything. 

 
Note
 On some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g. [glibc](https://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access).
  @trusted bool **opBinaryRight**(string op : "in")(scope const(char)[] name);  
Identify whether a variable is defined in the environment. 


Because it doesn't return the value, this function is cheaper than `get`. However, if you do need the value as well, you should just check the return of `get` for `null` instead of using this function first. 

 
Example


```
// good usage
if ("MY_ENV_FLAG" in environment)
    doSomething();

// bad usage
if ("MY_ENV_VAR" in environment)
    doSomething(environment["MY_ENV_VAR"]);

// do this instead
if (auto var = environment.get("MY_ENV_VAR"))
    doSomething(var);

```
  static @trusted string[string] **toAA**();  
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`). 
 
Throws:

[`Exception`](object#Exception) if the environment variables could not be retrieved (Windows only).
    nothrow @property @trusted int **thisProcessID**();  
Returns the process ID of the current process, which is guaranteed to be unique on the system. 



Example


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

```
  nothrow @property @trusted ThreadID **thisThreadID**();  
Returns the process ID of the current thread, which is guaranteed to be unique within the current process. 



Returns:
A [`core.thread.ThreadID`](core_thread#ThreadID) value for the calling thread. 
 
Example


```
writefln("Current thread ID: %s", thisThreadID);

```
  @safe Pid **spawnProcess**(scope const(char[])[] args, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, const string[string] env = null, Config config = Config.none, scope const char[] workDir = null);   
  
@trusted Pid **spawnProcess**(scope const(char[])[] args, const string[string] env, Config config = Config.none, scope const(char)[] workDir = null);   
  
@trusted Pid **spawnProcess**(scope const(char)[] program, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null);   
  
@trusted Pid **spawnProcess**(scope const(char)[] program, const string[string] env, Config config = Config.none, scope const(char)[] workDir = null);  
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`](#wait) on the returned [`Pid`](#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`](#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 [`std.stdio.File`](std_stdio#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`](#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. 
Parameters:


|  |  |
| --- | --- |
| const(char[])[] `args` | An array which contains the program name as the zeroth element and any command-line arguments in the following elements. |
| File `stdin` | The standard input stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for reading. By default the child process inherits the parent's input stream. |
| File `stdout` | The standard output stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for writing. By default the child process inherits the parent's output stream. |
| File `stderr` | The standard error stream of the child process. This can be any [`std.stdio.File`](std_stdio#File) that is opened for writing. By default the child process inherits the parent's error stream. |
| string[string] `env` | Additional environment variables for the child process. |
| Config `config` | Flags that control process creation. See [`Config`](#Config) for an overview of available flags. |
| char[] `workDir` | The working directory for the new process. By default the child process inherits the parent's working directory. |


 
Returns:
A [`Pid`](#Pid) object that corresponds to the spawned process. 
 
Throws:

[`ProcessException`](#ProcessException) on failure to start the process.  
 [`std.stdio.StdioException`](std_stdio#StdioException) on failure to pass one of the streams to the child process (Windows only).  
 [`core.exception.RangeError`](core_exception#RangeError) if `args` is empty.
  @safe Pid **spawnShell**(scope const(char)[] command, File stdin = std.stdio.stdin, File stdout = std.stdio.stdout, File stderr = std.stdio.stderr, scope const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null, scope string shellPath = nativeShell);   
  
@trusted Pid **spawnShell**(scope const(char)[] command, scope const string[string] env, Config config = Config.none, scope const(char)[] workDir = null, scope string shellPath = nativeShell);  
A variation on [`spawnProcess`](#spawnProcess) that runs the given command through the current user's preferred command interpreter (aka. shell). 


The string `command` is passed verbatim to the shell, and is therefore subject to its rules about command structure, argument/filename quoting and escaping of special characters. The path to the shell executable defaults to [`nativeShell`](#nativeShell).   
  
 In all other respects this function works just like `spawnProcess`. Please refer to the [`spawnProcess`](#spawnProcess) documentation for descriptions of the other function parameters, the return value and any exceptions that may be thrown. 
```
// Run the command/program "foo" on the file named "my file.txt", and
// redirect its output into foo.log.
auto pid = spawnShell(`foo "my file.txt" > foo.log`);
wait(pid);

```
 

 
See Also:

[`escapeShellCommand`](#escapeShellCommand), which may be helpful in constructing a properly quoted and escaped shell command line for the current platform.
  enum **Config**: int;  
Flags that control the behaviour of process creation functions in this module. Most flags only apply to [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell). 


Use bitwise OR to combine flags. 

 
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();
}

```
 
**newEnv** 
By default, the child process inherits the parent's environment, and any environment variables passed to [`spawnProcess`](#spawnProcess) will be added to it. If this flag is set, the only variables in the child process' environment will be those given to spawnProcess.

  
**retainStdin**  
  
**retainStdout**  
  
**retainStderr**
 
Unless the child process inherits the standard input/output/error streams of its parent, one almost always wants the streams closed in the parent when [`spawnProcess`](#spawnProcess) returns. Therefore, by default, this is done. If this is not desirable, pass any of these options to spawnProcess.

  **suppressConsole** 
On Windows, if the child process is a console application, this flag will prevent the creation of a console window. Otherwise, it will be ignored. On POSIX, `suppressConsole` has no effect.

  **inheritFDs** 
On POSIX, open [file descriptors](http://en.wikipedia.org/wiki/File_descriptor) are by default inherited by the child process. As this may lead to subtle bugs when pipes or multiple threads are involved, [`spawnProcess`](#spawnProcess) ensures that all file descriptors except the ones that correspond to standard input/output/error are closed in the child process when it starts. Use `inheritFDs` to prevent this. 


On Windows, this option has no effect, and any handles which have been explicitly marked as inheritable will always be inherited by the child process.

  **detached** 
Spawn process in detached state. This removes the need in calling [`wait`](#wait) to clean up the process resources. 



Note
 Calling [`wait`](#wait) or [`kill`](#kill) with the resulting `Pid` is invalid.
  **stderrPassThrough** 
By default, the [`execute`](#execute) and [`executeShell`](#executeShell) functions will capture child processes' both stdout and stderr. This can be undesirable if the standard output is to be processed or otherwise used by the invoking program, as `execute`'s result would then contain a mix of output and warning/error messages. 


Specify this flag when calling `execute` or `executeShell` to cause invoked processes' stderr stream to be sent to  [`std.stdio.stderr`](std_stdio#stderr), and only capture and return standard output.   
  
 This flag has no effect on [`spawnProcess`](#spawnProcess) or [`spawnShell`](#spawnShell).

    class **Pid**;  
A handle that corresponds to a spawned process.

 
const pure nothrow @property @safe int **processID**();  
The process ID number. 


This is a number that uniquely identifies the process on the operating system, for at least as long as the process is running. Once [`wait`](#wait) has been called on the [`Pid`](#Pid), this method will return an invalid (negative) process ID.

  pure nothrow @nogc @property @safe pid\_t **osHandle**();  
An operating system handle to the process. 


This handle is used to specify the process in OS-specific APIs. On POSIX, this function returns a `core.sys.posix.sys.types.pid_t` with the same value as [`Pid.processID`](#Pid.processID), while on Windows it returns a `core.sys.windows.windows.HANDLE`.   
  
 Once [`wait`](#wait) has been called on the [`Pid`](#Pid), this method will return an invalid handle.

    @safe int **wait**(Pid pid);  
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](http://en.wikipedia.org/wiki/Zombie_process)" – 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`](#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). 
 
Throws:

[`ProcessException`](#ProcessException) on failure or on attempt to wait for detached process. 
 
Example
 See the [`spawnProcess`](#spawnProcess) documentation. 
 
See Also:

[`tryWait`](#tryWait), for a non-blocking function.
  @safe auto **tryWait**(Pid pid);  
A non-blocking version of [`wait`](#wait). 


If the process associated with `pid` has already terminated, `tryWait` has the exact same effect as `wait`. In this case, it returns a tuple where the `terminated` field is set to `true` and the `status` field has the same interpretation as the return value of `wait`.   
  
 If the process has *not* yet terminated, this function differs from `wait` in that does not wait for this to happen, but instead returns immediately. The `terminated` field of the returned tuple will then be set to `false`, while the `status` field will always be 0 (zero). `wait` or `tryWait` should then be called again on the same `Pid` at some later time; not only to get the exit code, but also to avoid the process becoming a "zombie" when it finally terminates. (See [`wait`](#wait) for details). 

 
Returns:
An `std.typecons.Tuple!(bool, "terminated", int, "status")`. 
 
Throws:

[`ProcessException`](#ProcessException) on failure or on attempt to wait for detached process. 
 
Example


```
auto pid = spawnProcess("dmd myapp.d");
scope(exit) wait(pid);
...
auto dmd = tryWait(pid);
if (dmd.terminated)
{
    if (dmd.status == 0) writeln("Compilation succeeded!");
    else writeln("Compilation failed");
}
else writeln("Still compiling...");
...

```
 Note that in this example, the first `wait` call will have no effect if the process has already terminated by the time `tryWait` is called. In the opposite case, however, the `scope` statement ensures that we always wait for the process if it hasn't terminated by the time we reach the end of the scope.  void **kill**(Pid pid);   
  
void **kill**(Pid pid, int codeOrSignal);  
Attempts to terminate the process associated with `pid`. 


The effect of this function, as well as the meaning of `codeOrSignal`, is highly platform dependent. Details are given below. Common to all platforms is that this function only *initiates* termination of the process, and returns immediately. It does not wait for the process to end, nor does it guarantee that the process does in fact get terminated.   
  
 Always call [`wait`](#wait) to wait for a process to complete, even if `kill` has been called on it. 

 
Windows specific
 The process will be [forcefully and abruptly terminated](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714%28v=vs.100%29.aspx). If `codeOrSignal` is specified, it must be a nonnegative number which will be used as the exit code of the process. If not, the process wil exit with code 1. Do not use `codeOrSignal = 259`, as this is a special value (aka. [STILL\_ACTIVE](http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189.aspx)) used by Windows to signal that a process has in fact *not* terminated yet. 


```
auto pid = spawnProcess("some_app");
kill(pid, 10);
assert(wait(pid) == 10);

```
 
POSIX specific
 A [signal](http://en.wikipedia.org/wiki/Unix_signal) will be sent to the process, whose value is given by `codeOrSignal`. Depending on the signal sent, this may or may not terminate the process. Symbolic constants for various [POSIX signals](http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals) are defined in `core.sys.posix.signal`, which corresponds to the [`signal.h` POSIX header](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html). If `codeOrSignal` is omitted, the `SIGTERM` signal will be sent. (This matches the behaviour of the [`_kill`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/kill.html) shell command.) 


```
import core.sys.posix.signal : SIGKILL;
auto pid = spawnProcess("some_app");
kill(pid, SIGKILL);
assert(wait(pid) == -SIGKILL); // Negative return value on POSIX!

```
 
Throws:

[`ProcessException`](#ProcessException) on error (e.g. if codeOrSignal is invalid). or on attempt to kill detached process. Note that failure to terminate the process is considered a "normal" outcome, not an error.  


  @trusted Pipe **pipe**();  
Creates a unidirectional pipe. 


Data is written to one end of the pipe and read from the other. 
```
auto p = pipe();
p.writeEnd.writeln("Hello World");
p.writeEnd.flush();
assert(p.readEnd.readln().chomp() == "Hello World");

```
 Pipes can, for example, be used for interprocess communication by spawning a new process and passing one end of the pipe to the child, while the parent uses the other end. (See also [`pipeProcess`](#pipeProcess) and [`pipeShell`](#pipeShell) for an easier way of doing this.) 
```
// Use cURL to download the dlang.org front page, pipe its
// output to grep to extract a list of links to ZIP files,
// and write the list to the file "D downloads.txt":
auto p = pipe();
auto outFile = File("D downloads.txt", "w");
auto cpid = spawnProcess(["curl", "http://dlang.org/download.html"],
                         std.stdio.stdin, p.writeEnd);
scope(exit) wait(cpid);
auto gpid = spawnProcess(["grep", "-o", `http://\S*\.zip`],
                         p.readEnd, outFile);
scope(exit) wait(gpid);

```
 

 
Returns:
A [`Pipe`](#Pipe) object that corresponds to the created pipe. 
 
Throws:

[`std.stdio.StdioException`](std_stdio#StdioException) on failure.
  struct **Pipe**;  
An interface to a pipe created by the [`pipe`](#pipe) function.

 
nothrow @property @safe File **readEnd**();  
The read end of the pipe.

  nothrow @property @safe File **writeEnd**();  
The write end of the pipe.

  @safe void **close**();  
Closes both ends of the pipe. 


Normally it is not necessary to do this manually, as [`std.stdio.File`](std_stdio#File) objects are automatically closed when there are no more references to them.   
  
 Note that if either end of the pipe has been passed to a child process, it will only be closed in the parent process. (What happens in the child process is platform dependent.) 

 
Throws:

[`std.exception.ErrnoException`](std_exception#ErrnoException) if an error occurs.
    @safe ProcessPipes **pipeProcess**(scope const(char[])[] args, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null);   
  
@safe ProcessPipes **pipeProcess**(scope const(char)[] program, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null);   
  
@safe ProcessPipes **pipeShell**(scope const(char)[] command, Redirect redirect = Redirect.all, const string[string] env = null, Config config = Config.none, scope const(char)[] workDir = null, string shellPath = nativeShell);  
Starts a new process, creating pipes to redirect its standard input, output and/or error streams. 


`pipeProcess` and `pipeShell` are convenient wrappers around [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell), respectively, and automate the task of redirecting one or more of the child process' standard streams through pipes. Like the functions they wrap, these functions return immediately, leaving the child process to execute in parallel with the invoking process. It is recommended to always call [`wait`](#wait) on the returned [`ProcessPipes.pid`](#ProcessPipes.pid), as detailed in the documentation for `wait`.   
  
 The `args`/`program`/`command`, `env` and `config` parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details. 

 
Parameters:


|  |  |
| --- | --- |
| const(char[])[] `args` | An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See [`spawnProcess`](#spawnProcess) for details.) |
| const(char)[] `program` | The program name, *without* command-line arguments. (See [`spawnProcess`](#spawnProcess) for details.) |
| const(char)[] `command` | A shell command which is passed verbatim to the command interpreter. (See [`spawnShell`](#spawnShell) for details.) |
| Redirect `redirect` | Flags that determine which streams are redirected, and how. See [`Redirect`](#Redirect) for an overview of available flags. |
| string[string] `env` | Additional environment variables for the child process. (See [`spawnProcess`](#spawnProcess) for details.) |
| Config `config` | Flags that control process creation. See [`Config`](#Config) for an overview of available flags, and note that the `retainStd...` flags have no effect in this function. |
| const(char)[] `workDir` | The working directory for the new process. By default the child process inherits the parent's working directory. |
| string `shellPath` | The path to the shell to use to run the specified program. By default this is [`nativeShell`](#nativeShell). |


 
Returns:
A [`ProcessPipes`](#ProcessPipes) object which contains [`std.stdio.File`](std_stdio#File) handles that communicate with the redirected streams of the child process, along with a [`Pid`](#Pid) object that corresponds to the spawned process. 
 
Throws:

[`ProcessException`](#ProcessException) on failure to start the process.  
 [`std.stdio.StdioException`](std_stdio#StdioException) on failure to redirect any of the streams.  
 
 
Example


```
// my_application writes to stdout and might write to stderr
auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
scope(exit) wait(pipes.pid);

// Store lines of output.
string[] output;
foreach (line; pipes.stdout.byLine) output ~= line.idup;

// Store lines of errors.
string[] errors;
foreach (line; pipes.stderr.byLine) errors ~= line.idup;


// sendmail expects to read from stdin
pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin);
pipes.stdin.writeln("To: you");
pipes.stdin.writeln("From: me");
pipes.stdin.writeln("Subject: dlang");
pipes.stdin.writeln("");
pipes.stdin.writeln(message);

// a single period tells sendmail we are finished
pipes.stdin.writeln(".");

// but at this point sendmail might not see it, we need to flush
pipes.stdin.flush();

// sendmail happens to exit on ".", but some you have to close the file:
pipes.stdin.close();

// otherwise this wait will wait forever
wait(pipes.pid);


```
  enum **Redirect**: int;  
Flags that can be passed to [`pipeProcess`](#pipeProcess) and [`pipeShell`](#pipeShell) to specify which of the child process' standard streams are redirected. Use bitwise OR to combine flags.

 

**stdin**  
  
**stdout**  
  
**stderr**
 
Redirect the standard input, output or error streams, respectively.

  **all** 
Redirect all three streams. This is equivalent to `Redirect.stdin | Redirect.stdout | Redirect.stderr`.

  **stderrToStdout** 
Redirect the standard error stream into the standard output stream. This can not be combined with `Redirect.stderr`.

  **stdoutToStderr** 
Redirect the standard output stream into the standard error stream. This can not be combined with `Redirect.stdout`.

    struct **ProcessPipes**;  
Object which contains [`std.stdio.File`](std_stdio#File) handles that allow communication with a child process through its standard streams.

 
nothrow @property @safe Pid **pid**();  
The [`Pid`](#Pid) of the child process.

  nothrow @property @safe File **stdin**();  
An [`std.stdio.File`](std_stdio#File) that allows writing to the child process' standard input stream. 



Throws:

[`Error`](object#Error) if the child process' standard input stream hasn't been redirected.
  nothrow @property @safe File **stdout**();  
An [`std.stdio.File`](std_stdio#File) that allows reading from the child process' standard output stream. 



Throws:

[`Error`](object#Error) if the child process' standard output stream hasn't been redirected.
  nothrow @property @safe File **stderr**();  
An [`std.stdio.File`](std_stdio#File) that allows reading from the child process' standard error stream. 



Throws:

[`Error`](object#Error) if the child process' standard error stream hasn't been redirected.
    @safe auto **execute**(scope const(char[])[] args, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null);   
  
@safe auto **execute**(scope const(char)[] program, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null);   
  
@safe auto **executeShell**(scope const(char)[] command, const string[string] env = null, Config config = Config.none, size\_t maxOutput = size\_t.max, scope const(char)[] workDir = null, string shellPath = nativeShell);  
Executes the given program or shell command and returns its exit code and output. 


`execute` and `executeShell` start a new process using [`spawnProcess`](#spawnProcess) and [`spawnShell`](#spawnShell), respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code. 
```
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

```
   
  
 The `args`/`program`/`command`, `env` and `config` parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details. 

 
Parameters:


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


 
Returns:
An `std.typecons.Tuple!(int, "status", string, "output")`. 
 
POSIX specific
 If the process is terminated by a signal, the `status` field of the return value will contain a negative number whose absolute value is the signal number. (See [`wait`](#wait) for details.) 
 
Throws:

[`ProcessException`](#ProcessException) on failure to start the process.  
 [`std.stdio.StdioException`](std_stdio#StdioException) on failure to capture output.
  class **ProcessException**: object.Exception;  
An exception that signals a problem with starting or waiting for a process.

  @property @safe string **userShell**();  
Determines the path to the current user's preferred command interpreter. 


On Windows, this function returns the contents of the COMSPEC environment variable, if it exists. Otherwise, it returns the result of [`nativeShell`](#nativeShell).   
  
 On POSIX, `userShell` returns the contents of the SHELL environment variable, if it exists and is non-empty. Otherwise, it returns the result of [`nativeShell`](#nativeShell).

  pure nothrow @nogc @property @safe string **nativeShell**();  
The platform-specific native shell path. 


This function returns `"cmd.exe"` on Windows, `"/bin/sh"` on POSIX, and `"/system/bin/sh"` on Android.

  pure @safe string **escapeShellCommand**(scope const(char[])[] args...);  
Escapes an argv-style argument array to be used with [`spawnShell`](#spawnShell), [`pipeShell`](#pipeShell) or [`executeShell`](#executeShell). 
```
string url = "http://dlang.org/";
executeShell(escapeShellCommand("wget", url, "-O", "dlang-index.html"));

```
 


Concatenate multiple `escapeShellCommand` and [`escapeShellFileName`](#escapeShellFileName) results to use shell redirection or piping operators. 
```
executeShell(
    escapeShellCommand("curl", "http://dlang.org/download.html") ~
    "|" ~
    escapeShellCommand("grep", "-o", `http://\S*\.zip`) ~
    ">" ~
    escapeShellFileName("D download links.txt"));

```
 

 
Throws:

[`Exception`](object#Exception) if any part of the command line contains unescapable characters (NUL on all platforms, as well as CR and LF on Windows).
  pure nothrow @trusted string **escapeWindowsArgument**(scope const(char)[] arg);  
Quotes a command-line argument in a manner conforming to the behavior of [CommandLineToArgvW](http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx).

  pure nothrow @trusted string **escapeShellFileName**(scope const(char)[] fileName);  
Escapes a filename to be used for shell redirection with [`spawnShell`](#spawnShell), [`pipeShell`](#pipeShell) or [`executeShell`](#executeShell).

  int **execv**(in string pathname, in string[] argv);   
  
int **execve**(in string pathname, in string[] argv, in string[] envp);   
  
int **execvp**(in string pathname, in string[] argv);   
  
int **execvpe**(in string pathname, in string[] argv, in string[] envp);  
Replaces the current process by executing a command, `pathname`, with the arguments in `argv`. 


This function is Posix-Only.   
  
 Typically, the first element of `argv` is the command being executed, i.e. `argv[0] == pathname`. The 'p' versions of `exec` search the PATH environment variable for  `pathname`. The 'e' versions additionally take the new process' environment variables as an array of strings of the form key=value.   
  
 Does not return on success (the current process will have been replaced). Returns -1 on failure with no indication of the underlying error. 

 
Windows specific
 These functions are only supported on POSIX platforms, as the Windows operating systems do not provide the ability to overwrite the current process image with another. In single-threaded programs it is possible to approximate the effect of `execv*` by using [`spawnProcess`](#spawnProcess) and terminating the current process once the child process has returned. For example: 


```
auto commandLine = [ "program", "arg1", "arg2" ];
version (Posix)
{
    execv(commandLine[0], commandLine);
    throw new Exception("Failed to execute program");
}
else version (Windows)
{
    import core.stdc.stdlib : _Exit;
    _Exit(wait(spawnProcess(commandLine)));
}

```
 This is, however, NOT equivalent to POSIX' `execv*`. For one thing, the executed program is started as a separate process, with all this entails. Secondly, in a multithreaded program, other threads will continue to do work while the current thread is waiting for the child process to complete. A better option may sometimes be to terminate the current program immediately after spawning the child process. This is the behaviour exhibited by the [`__exec`](http://msdn.microsoft.com/en-us/library/431x4c1w.aspx) functions in Microsoft's C runtime library, and it is how D's now-deprecated Windows `execv*` functions work. Example: 
```
auto commandLine = [ "program", "arg1", "arg2" ];
version (Posix)
{
    execv(commandLine[0], commandLine);
    throw new Exception("Failed to execute program");
}
else version (Windows)
{
    spawnProcess(commandLine);
    import core.stdc.stdlib : _exit;
    _exit(0);
}

```
  void **browse**(scope const(char)[] url);  
Start up the browser and set it to viewing the page at url.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_process.html>

std.signals
===========

 Signals and Slots are an implementation of the Observer Pattern. Essentially, when a Signal is emitted, a list of connected Observers (called slots) are called. 


There have been several D implementations of Signals and Slots. This version makes use of several new features in D, which make using it simpler and less error prone. In particular, it is no longer necessary to instrument the slots. 

 
References
 [A Deeper Look at Signals and Slots](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=A%20Deeper%20Look%20at%20Signals%20and%20Slots)  
 [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern)  
 [Wikipedia](http://en.wikipedia.org/wiki/Signals_and_slots)  
 [Boost Signals](http://boost.org/doc/html/signals.html)  
 [Qt](http://qt-project.org/doc/qt-5/signalsandslots.html)  
 
 There has been a great deal of discussion in the D newsgroups over this, and several implementations: [signal slots library](http://www.digitalmars.com/d/archives/digitalmars/D/announce/signal_slots_library_4825.html)  
 [Signals and Slots in D](http://www.digitalmars.com/d/archives/digitalmars/D/Signals_and_Slots_in_D_42387.html)  
 [Dynamic binding -- Qt's Signals and Slots vs Objective-C](http://www.digitalmars.com/d/archives/digitalmars/D/Dynamic_binding_--_Qt_s_Signals_and_Slots_vs_Objective-C_42260.html)  
 [Dissecting the SS](http://www.digitalmars.com/d/archives/digitalmars/D/Dissecting_the_SS_42377.html)  
 [about harmonia](http://www.digitalmars.com/d/archives/digitalmars/D/dwt/about_harmonia_454.html)  
 [Another event handling module](http://www.digitalmars.com/d/archives/digitalmars/D/announce/1502.html)  
 [Suggestion: signal/slot mechanism](http://www.digitalmars.com/d/archives/digitalmars/D/41825.html)  
 [Signals and slots?](http://www.digitalmars.com/d/archives/digitalmars/D/13251.html)  
 [Signals and slots ready for evaluation](http://www.digitalmars.com/d/archives/digitalmars/D/10714.html)  
 [Signals & Slots for Walter](http://www.digitalmars.com/d/archives/digitalmars/D/1393.html)  
 [Signal/Slot mechanism?](http://www.digitalmars.com/d/archives/28456.html)  
 [Modern Features?](http://www.digitalmars.com/d/archives/19470.html)  
 [Delegates vs interfaces](http://www.digitalmars.com/d/archives/16592.html)  
 [The importance of component programming (properties, signals and slots, etc)](http://www.digitalmars.com/d/archives/16583.html)  
 [signals and slots](http://www.digitalmars.com/d/archives/16368.html)  
 
Bugs:

Slots can only be delegates formed from class objects or interfaces to class objects. If a delegate to something else is passed to connect(), such as a struct member function, a nested function, a COM interface or a closure, undefined behavior will result. Not safe for multiple threads operating on the same signals or slots. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/signals.d](https://github.com/dlang/phobos/blob/master/std/signals.d) 
 
template **Signal**(T1...) 
Mixin to create a signal within a class object. 


Different signals can be added to a class by naming the mixins.

 
Examples:


```
import std.signals;

int observedMessageCounter = 0;

class Observer
{   // our slot
    void watch(string msg, int value)
    {
        switch (observedMessageCounter++)
        {
            case 0:
                writeln(msg); // "setting new value"
                writeln(value); // 4
                break;
            case 1:
                writeln(msg); // "setting new value"
                writeln(value); // 6
                break;
            default:
                assert(0, "Unknown observation");
        }
    }
}

class Observer2
{   // our slot
    void watch(string msg, int value)
    {
    }
}

class Foo
{
    int value() { return _value; }

    int value(int v)
    {
        if (v != _value)
        {   _value = v;
            // call all the connected slots with the two parameters
            emit("setting new value", v);
        }
        return v;
    }

    // Mix in all the code we need to make Foo into a signal
    mixin Signal!(string, int);

  private :
    int _value;
}

Foo a = new Foo;
Observer o = new Observer;
auto o2 = new Observer2;
auto o3 = new Observer2;
auto o4 = new Observer2;
auto o5 = new Observer2;

a.value = 3;                // should not call o.watch()
a.connect(&o.watch);        // o.watch is the slot
a.connect(&o2.watch);
a.connect(&o3.watch);
a.connect(&o4.watch);
a.connect(&o5.watch);
a.value = 4;                // should call o.watch()
a.disconnect(&o.watch);     // o.watch is no longer a slot
a.disconnect(&o3.watch);
a.disconnect(&o5.watch);
a.disconnect(&o4.watch);
a.disconnect(&o2.watch);
a.value = 5;                // so should not call o.watch()
a.connect(&o2.watch);
a.connect(&o.watch);        // connect again
a.value = 6;                // should call o.watch()
destroy(o);                 // destroying o should automatically disconnect it
a.value = 7;                // should not call o.watch()

writeln(observedMessageCounter); // 2

```
 
 
alias **slot\_t** = void delegate(T1);  
A slot is implemented as a delegate. The slot\_t is the type of the delegate. The delegate must be to an instance of a class or an interface to a class instance. Delegates to struct instances or nested functions must not be used as slots.

  final void **emit**(T1 i);  
Call each of the connected slots, passing the argument(s) i to them. Nested call will be ignored.

  final void **connect**(slot\_t slot);  
Add a slot to the list of slots to be called when emit() is called.

  final void **disconnect**(slot\_t slot);  
Remove a slot from the list of slots to be called when emit() is called.

  final void **disconnectAll**();  
Disconnect all the slots.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_signals.html>

std.stdint
==========

 D constrains integral types to specific sizes. But efficiency of different sizes varies from machine to machine, pointer sizes vary, and the maximum integer size varies. **stdint** offers a portable way of trading off size vs efficiency, in a manner compatible with the stdint.h definitions in C. 


In the table below, the **exact alias**es are types of exactly the specified number of bits. The **at least alias**es are at least the specified number of bits large, and can be larger. The **fast alias**es are the fastest integral type supported by the processor that is at least as wide as the specified number of bits.   
  
 The aliases are:   
  
 

| Exact Alias | Description | At Least Alias | Description | Fast Alias | Description |
| --- | --- | --- | --- | --- | --- |
| int8\_t | exactly 8 bits signed | int\_least8\_t | at least 8 bits signed | int\_fast8\_t | fast 8 bits signed |
| uint8\_t | exactly 8 bits unsigned | uint\_least8\_t | at least 8 bits unsigned | uint\_fast8\_t | fast 8 bits unsigned |  
  

| int16\_t | exactly 16 bits signed | int\_least16\_t | at least 16 bits signed | int\_fast16\_t | fast 16 bits signed |
| uint16\_t | exactly 16 bits unsigned | uint\_least16\_t | at least 16 bits unsigned | uint\_fast16\_t | fast 16 bits unsigned |  
  

| int32\_t | exactly 32 bits signed | int\_least32\_t | at least 32 bits signed | int\_fast32\_t | fast 32 bits signed |
| uint32\_t | exactly 32 bits unsigned | uint\_least32\_t | at least 32 bits unsigned | uint\_fast32\_t | fast 32 bits unsigned |  
  

| int64\_t | exactly 64 bits signed | int\_least64\_t | at least 64 bits signed | int\_fast64\_t | fast 64 bits signed |
| uint64\_t | exactly 64 bits unsigned | uint\_least64\_t | at least 64 bits unsigned | uint\_fast64\_t | fast 64 bits unsigned |

   
  
 The ptr aliases are integral types guaranteed to be large enough to hold a pointer without losing bits:   
  
 

| Alias | Description |
| --- | --- |
| intptr\_t | signed integral type large enough to hold a pointer |
| uintptr\_t | unsigned integral type large enough to hold a pointer |

   
  
 The max aliases are the largest integral types:   
  
 

| Alias | Description |
| --- | --- |
| intmax\_t | the largest signed integral type |
| uintmax\_t | the largest unsigned integral type |

 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/stdint.d](https://github.com/dlang/phobos/blob/master/std/stdint.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_stdint.html>

std.parallelism
===============

 `std.parallelism` implements high-level primitives for SMP parallelism. These include parallel foreach, parallel reduce, parallel eager map, pipelining and future/promise parallelism. `std.parallelism` is recommended when the same operation is to be executed in parallel on different data, or when a function is to be executed in a background thread and its result returned to a well-defined main thread. For communication between arbitrary threads, see `std.concurrency`. 


`std.parallelism` is based on the concept of a `Task`. A `Task` is an object that represents the fundamental unit of work in this library and may be executed in parallel with any other `Task`. Using `Task` directly allows programming with a future/promise paradigm. All other supported parallelism paradigms (parallel foreach, map, reduce, pipelining) represent an additional level of abstraction over `Task`. They automatically create one or more `Task` objects, or closely related types that are conceptually identical but not part of the public API.   
  
 After creation, a `Task` may be executed in a new thread, or submitted to a `TaskPool` for execution. A `TaskPool` encapsulates a task queue and its worker threads. Its purpose is to efficiently map a large number of `Task`s onto a smaller number of threads. A task queue is a FIFO queue of `Task` objects that have been submitted to the `TaskPool` and are awaiting execution. A worker thread is a thread that is associated with exactly one task queue. It executes the `Task` at the front of its queue when the queue has work available, or sleeps when no work is available. Each task queue is associated with zero or more worker threads. If the result of a `Task` is needed before execution by a worker thread has begun, the `Task` can be removed from the task queue and executed immediately in the thread where the result is needed. 

 
Warning
 Unless marked as `@trusted` or `@safe`, artifacts in this module allow implicit data sharing between threads and cannot guarantee that client code is free from low level data races. 
 
Source
 [std/parallelism.d](https://github.com/dlang/phobos/blob/master/std/parallelism.d) 
 
Author
 David Simcha 
 
License:
[Boost License 1.0](http://boost.org/LICENSE_1_0.txt)
 
struct **Task**(alias fun, Args...);  
`Task` represents the fundamental unit of work. A `Task` may be executed in parallel with any other `Task`. Using this struct directly allows future/promise parallelism. In this paradigm, a function (or delegate or other callable) is executed in a thread other than the one it was called from. The calling thread does not block while the function is being executed. A call to `workForce`, `yieldForce`, or `spinForce` is used to ensure that the `Task` has finished executing and to obtain the return value, if any. These functions and `done` also act as full memory barriers, meaning that any memory writes made in the thread that executed the `Task` are guaranteed to be visible in the calling thread after one of these functions returns. 


The [`std.parallelism.task`](std_parallelism#task) and [`std.parallelism.scopedTask`](std_parallelism#scopedTask) functions can be used to create an instance of this struct. See `task` for usage examples.   
  
 Function results are returned from `yieldForce`, `spinForce` and `workForce` by ref. If `fun` returns by ref, the reference will point to the returned reference of `fun`. Otherwise it will point to a field in this struct.   
  
 Copying of this struct is disabled, since it would provide no useful semantics. If you want to pass this struct around, you should do so by reference or pointer. 

 
Bugs:
Changes to `ref` and `out` arguments are not propagated to the call site, only to `args` in this struct.
 
alias **args** = \_args[1 .. \_\_dollar];  
The arguments the function was called with. Changes to `out` and `ref` arguments will be visible here.

  alias **ReturnType** = typeof(fun(\_args));  
The return type of the function called by this `Task`. This can be `void`.

  @property ref @trusted ReturnType **spinForce**();  
If the `Task` isn't started yet, execute it in the current thread. If it's done, return its return value, if any. If it's in progress, busy spin until it's done, then return the return value. If it threw an exception, rethrow that exception. 


This function should be used when you expect the result of the `Task` to be available on a timescale shorter than that of an OS context switch.

  @property ref @trusted ReturnType **yieldForce**();  
If the `Task` isn't started yet, execute it in the current thread. If it's done, return its return value, if any. If it's in progress, wait on a condition variable. If it threw an exception, rethrow that exception. 


This function should be used for expensive functions, as waiting on a condition variable introduces latency, but avoids wasted CPU cycles.

  @property ref @trusted ReturnType **workForce**();  
If this `Task` was not started yet, execute it in the current thread. If it is finished, return its result. If it is in progress, execute any other `Task` from the `TaskPool` instance that this `Task` was submitted to until this one is finished. If it threw an exception, rethrow that exception. If no other tasks are available or this `Task` was executed using `executeInNewThread`, wait on a condition variable.

  @property @trusted bool **done**();  
Returns `true` if the `Task` is finished executing. 



Throws:
Rethrows any exception thrown during the execution of the `Task`.
  @trusted void **executeInNewThread**();   
  
@trusted void **executeInNewThread**(int priority);  
Create a new thread for executing this `Task`, execute it in the newly created thread, then terminate the thread. This can be used for future/promise parallelism. An explicit priority may be given to the `Task`. If one is provided, its value is forwarded to `core.thread.Thread.priority`. See [`std.parallelism.task`](std_parallelism#task) for usage example.

    auto **task**(alias fun, Args...)(Args args);  
Creates a `Task` on the GC heap that calls an alias. This may be executed via `Task.executeInNewThread` or by submitting to a [`std.parallelism.TaskPool`](std_parallelism#TaskPool). A globally accessible instance of `TaskPool` is provided by [`std.parallelism.taskPool`](std_parallelism#taskPool). 



Returns:
A pointer to the `Task`. 
 
Example


```
// Read two files into memory at the same time.
import std.file;

void main()
{
    // Create and execute a Task for reading
    // foo.txt.
    auto file1Task = task!read("foo.txt");
    file1Task.executeInNewThread();

    // Read bar.txt in parallel.
    auto file2Data = read("bar.txt");

    // Get the results of reading foo.txt.
    auto file1Data = file1Task.yieldForce;
}

```
 
```
// Sorts an array using a parallel quick sort algorithm.
// The first partition is done serially.  Both recursion
// branches are then executed in parallel.
//
// Timings for sorting an array of 1,000,000 doubles on
// an Athlon 64 X2 dual core machine:
//
// This implementation:               176 milliseconds.
// Equivalent serial implementation:  280 milliseconds
void parallelSort(T)(T[] data)
{
    // Sort small subarrays serially.
    if (data.length < 100)
    {
         std.algorithm.sort(data);
         return;
    }

    // Partition the array.
    swap(data[$ / 2], data[$ - 1]);
    auto pivot = data[$ - 1];
    bool lessThanPivot(T elem) { return elem < pivot; }

    auto greaterEqual = partition!lessThanPivot(data[0..$ - 1]);
    swap(data[$ - greaterEqual.length - 1], data[$ - 1]);

    auto less = data[0..$ - greaterEqual.length - 1];
    greaterEqual = data[$ - greaterEqual.length..$];

    // Execute both recursion branches in parallel.
    auto recurseTask = task!parallelSort(greaterEqual);
    taskPool.put(recurseTask);
    parallelSort(less);
    recurseTask.yieldForce;
}

```
  auto **task**(F, Args...)(F delegateOrFp, Args args)  
 Constraints: if (is(typeof(delegateOrFp(args))) && !isSafeTask!F); 
 
Creates a `Task` on the GC heap that calls a function pointer, delegate, or class/struct with overloaded opCall. 



Example


```
// Read two files in at the same time again,
// but this time use a function pointer instead
// of an alias to represent std.file.read.
import std.file;

void main()
{
    // Create and execute a Task for reading
    // foo.txt.
    auto file1Task = task(&read!string, "foo.txt", size_t.max);
    file1Task.executeInNewThread();

    // Read bar.txt in parallel.
    auto file2Data = read("bar.txt");

    // Get the results of reading foo.txt.
    auto file1Data = file1Task.yieldForce;
}

```
 
Notes
 This function takes a non-scope delegate, meaning it can be used with closures. If you can't allocate a closure due to objects on the stack that have scoped destruction, see `scopedTask`, which takes a scope delegate.
  @trusted auto **task**(F, Args...)(F fun, Args args)  
 Constraints: if (is(typeof(fun(args))) && isSafeTask!F); 
 
Version of `task` usable from `@safe` code. Usage mechanics are identical to the non-@safe case, but safety introduces some restrictions: 


1. `fun` must be @safe or @trusted.
2. `F` must not have any unshared aliasing as defined by [`std.traits.hasUnsharedAliasing`](std_traits#hasUnsharedAliasing). This means it may not be an unshared delegate or a non-shared class or struct with overloaded `opCall`. This also precludes accepting template alias parameters.
3. `Args` must not have unshared aliasing.
4. `fun` must not return by reference.
5. The return type must not have unshared aliasing unless `fun` is `pure` or the `Task` is executed via `executeInNewThread` instead of using a `TaskPool`.


  auto **scopedTask**(alias fun, Args...)(Args args);   
  
auto **scopedTask**(F, Args...)(scope F delegateOrFp, Args args)  
 Constraints: if (is(typeof(delegateOrFp(args))) && !isSafeTask!F);   
  
@trusted auto **scopedTask**(F, Args...)(F fun, Args args)  
 Constraints: if (is(typeof(fun(args))) && isSafeTask!F); 
 
These functions allow the creation of `Task` objects on the stack rather than the GC heap. The lifetime of a `Task` created by `scopedTask` cannot exceed the lifetime of the scope it was created in. 


`scopedTask` might be preferred over `task`: 1. When a `Task` that calls a delegate is being created and a closure cannot be allocated due to objects on the stack that have scoped destruction. The delegate overload of `scopedTask` takes a `scope` delegate.
2. As a micro-optimization, to avoid the heap allocation associated with `task` or with the creation of a closure.

 Usage is otherwise identical to `task`. 

 
Notes
 `Task` objects created using `scopedTask` will automatically call `Task.yieldForce` in their destructor if necessary to ensure the `Task` is complete before the stack frame they reside on is destroyed.
  alias **totalCPUs** = \_\_lazilyInitializedConstant!(immutable(uint), 4294967295u, totalCPUsImpl).\_\_lazilyInitializedConstant;  
The total number of CPU cores available on the current machine, as reported by the operating system.

  class **TaskPool**;  
This class encapsulates a task queue and a set of worker threads. Its purpose is to efficiently map a large number of `Task`s onto a smaller number of threads. A task queue is a FIFO queue of `Task` objects that have been submitted to the `TaskPool` and are awaiting execution. A worker thread is a thread that executes the `Task` at the front of the queue when one is available and sleeps when the queue is empty. 


This class should usually be used via the global instantiation available via the [`std.parallelism.taskPool`](std_parallelism#taskPool) property. Occasionally it is useful to explicitly instantiate a `TaskPool`: 1. When you want `TaskPool` instances with multiple priorities, for example a low priority pool and a high priority pool.
2. When the threads in the global task pool are waiting on a synchronization primitive (for example a mutex), and you want to parallelize the code that needs to run before these threads can be resumed.

 

 
Note
 The worker threads in this pool will not stop until `stop` or `finish` is called, even if the main thread has finished already. This may lead to programs that never end. If you do not want this behaviour, you can set `isDaemon` to true.
 
@trusted this();  
Default constructor that initializes a `TaskPool` with `totalCPUs` - 1 worker threads. The minus 1 is included because the main thread will also be available to do work. 



Note
 On single-core machines, the primitives provided by `TaskPool` operate transparently in single-threaded mode.
  @trusted this(size\_t nWorkers);  
Allows for custom number of worker threads.

  ParallelForeach!R **parallel**(R)(R range, size\_t workUnitSize);   
  
ParallelForeach!R **parallel**(R)(R range);  
Implements a parallel foreach loop over a range. This works by implicitly creating and submitting one `Task` to the `TaskPool` for each worker thread. A work unit is a set of consecutive elements of `range` to be processed by a worker thread between communication with any other thread. The number of elements processed per work unit is controlled by the `workUnitSize` parameter. Smaller work units provide better load balancing, but larger work units avoid the overhead of communicating with other threads frequently to fetch the next work unit. Large work units also avoid false sharing in cases where the range is being modified. The less time a single iteration of the loop takes, the larger `workUnitSize` should be. For very expensive loop bodies, `workUnitSize` should be 1. An overload that chooses a default work unit size is also available. 



Example


```
// Find the logarithm of every number from 1 to
// 10_000_000 in parallel.
auto logs = new double[10_000_000];

// Parallel foreach works with or without an index
// variable.  It can be iterate by ref if range.front
// returns by ref.

// Iterate over logs using work units of size 100.
foreach (i, ref elem; taskPool.parallel(logs, 100))
{
    elem = log(i + 1.0);
}

// Same thing, but use the default work unit size.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel foreach:  388 milliseconds
// Regular foreach:   619 milliseconds
foreach (i, ref elem; taskPool.parallel(logs))
{
    elem = log(i + 1.0);
}

```
 
Notes
 The memory usage of this implementation is guaranteed to be constant in `range.length`. 
 Breaking from a parallel foreach loop via a break, labeled break, labeled continue, return or goto statement throws a `ParallelForeachError`. In the case of non-random access ranges, parallel foreach buffers lazily to an array of size `workUnitSize` before executing the parallel portion of the loop. The exception is that, if a parallel foreach is executed over a range returned by `asyncBuf` or `map`, the copying is elided and the buffers are simply swapped. In this case `workUnitSize` is ignored and the work unit size is set to the buffer size of `range`. A memory barrier is guaranteed to be executed on exit from the loop, so that results produced by all threads are visible in the calling thread. **Exception Handling**: When at least one exception is thrown from inside a parallel foreach loop, the submission of additional `Task` objects is terminated as soon as possible, in a non-deterministic manner. All executing or enqueued work units are allowed to complete. Then, all exceptions that were thrown by any work unit are chained using `Throwable.next` and rethrown. The order of the exception chaining is non-deterministic.  template **amap**(functions...)  
auto **amap**(Args...)(Args args)  
 Constraints: if (isRandomAccessRange!(Args[0])); 
 
Eager parallel map. The eagerness of this function means it has less overhead than the lazily evaluated `TaskPool.map` and should be preferred where the memory requirements of eagerness are acceptable. `functions` are the functions to be evaluated, passed as template alias parameters in a style similar to [`std.algorithm.iteration.map`](std_algorithm_iteration#map). The first argument must be a random access range. For performance reasons, amap will assume the range elements have not yet been initialized. Elements will be overwritten without calling a destructor nor doing an assignment. As such, the range must not contain meaningful data: either un-initialized objects, or objects in their `.init` state. 



```
auto numbers = iota(100_000_000.0);

// Find the square roots of numbers.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel eager map:                   0.802 s
// Equivalent serial implementation:     1.768 s
auto squareRoots = taskPool.amap!sqrt(numbers);

```
   
  
 Immediately after the range argument, an optional work unit size argument may be provided. Work units as used by `amap` are identical to those defined for parallel foreach. If no work unit size is provided, the default work unit size is used.   
  
 
```
// Same thing, but make work unit size 100.
auto squareRoots = taskPool.amap!sqrt(numbers, 100);

```
   
  
 An output range for returning the results may be provided as the last argument. If one is not provided, an array of the proper type will be allocated on the garbage collected heap. If one is provided, it must be a random access range with assignable elements, must have reference semantics with respect to assignment to its elements, and must have the same length as the input range. Writing to adjacent elements from different threads must be safe.   
  
 
```
// Same thing, but explicitly allocate an array
// to return the results in.  The element type
// of the array may be either the exact type
// returned by functions or an implicit conversion
// target.
auto squareRoots = new float[numbers.length];
taskPool.amap!sqrt(numbers, squareRoots);

// Multiple functions, explicit output range, and
// explicit work unit size.
auto results = new Tuple!(float, real)[numbers.length];
taskPool.amap!(sqrt, log)(numbers, 100, results);

```
 

 
Note
 A memory barrier is guaranteed to be executed after all results are written but before returning so that results produced by all threads are visible in the calling thread. 
 
Tips
 To perform the mapping operation in place, provide the same range for the input and output range. 
 To parallelize the copying of a range with expensive to evaluate elements to an array, pass an identity function (a function that just returns whatever argument is provided to it) to `amap`. **Exception Handling**: When at least one exception is thrown from inside the map functions, the submission of additional `Task` objects is terminated as soon as possible, in a non-deterministic manner. All currently executing or enqueued work units are allowed to complete. Then, all exceptions that were thrown from any work unit are chained using `Throwable.next` and rethrown. The order of the exception chaining is non-deterministic.    template **map**(functions...)  
auto **map**(S)(S source, size\_t bufSize = 100, size\_t workUnitSize = size\_t.max)  
 Constraints: if (isInputRange!S); 
 
A semi-lazy parallel map that can be used for pipelining. The map functions are evaluated for the first `bufSize` elements and stored in a buffer and made available to `popFront`. Meanwhile, in the background a second buffer of the same size is filled. When the first buffer is exhausted, it is swapped with the second buffer and filled while the values from what was originally the second buffer are read. This implementation allows for elements to be written to the buffer without the need for atomic operations or synchronization for each write, and enables the mapping function to be evaluated efficiently in parallel. 


`map` has more overhead than the simpler procedure used by `amap` but avoids the need to keep all results in memory simultaneously and works with non-random access ranges. 

 
Parameters:


|  |  |
| --- | --- |
| S `source` | The [input range](std_range_primitives#isInputRange) to be mapped. If `source` is not random access it will be lazily buffered to an array of size `bufSize` before the map function is evaluated. (For an exception to this rule, see Notes.) |
| size\_t `bufSize` | The size of the buffer to store the evaluated elements. |
| size\_t `workUnitSize` | The number of elements to evaluate in a single `Task`. Must be less than or equal to `bufSize`, and should be a fraction of `bufSize` such that all worker threads can be used. If the default of size\_t.max is used, workUnitSize will be set to the pool-wide default. |


 
Returns:
An input range representing the results of the map. This range has a length iff `source` has a length. 
 
Notes
 If a range returned by `map` or `asyncBuf` is used as an input to `map`, then as an optimization the copying from the output buffer of the first range to the input buffer of the second range is elided, even though the ranges returned by `map` and `asyncBuf` are non-random access ranges. This means that the `bufSize` parameter passed to the current call to `map` will be ignored and the size of the buffer will be the buffer size of `source`. 
 
Example


```
// Pipeline reading a file, converting each line
// to a number, taking the logarithms of the numbers,
// and performing the additions necessary to find
// the sum of the logarithms.

auto lineRange = File("numberList.txt").byLine();
auto dupedLines = std.algorithm.map!"a.idup"(lineRange);
auto nums = taskPool.map!(to!double)(dupedLines);
auto logs = taskPool.map!log10(nums);

double sum = 0;
foreach (elem; logs)
{
    sum += elem;
}

```
 **Exception Handling**: Any exceptions thrown while iterating over `source` or computing the map function are re-thrown on a call to `popFront` or, if thrown during construction, are simply allowed to propagate to the caller. In the case of exceptions thrown while computing the map function, the exceptions are chained as in `TaskPool.amap`.    auto **asyncBuf**(S)(S source, size\_t bufSize = 100)  
 Constraints: if (isInputRange!S); 
 
Given a `source` range that is expensive to iterate over, returns an [input range](std_range_primitives#isInputRange) that asynchronously buffers the contents of `source` into a buffer of `bufSize` elements in a worker thread, while making previously buffered elements from a second buffer, also of size `bufSize`, available via the range interface of the returned object. The returned range has a length iff `hasLength!S`. `asyncBuf` is useful, for example, when performing expensive operations on the elements of ranges that represent data on a disk or network. 



Example


```
import std.conv, std.stdio;

void main()
{
    // Fetch lines of a file in a background thread
    // while processing previously fetched lines,
    // dealing with byLine's buffer recycling by
    // eagerly duplicating every line.
    auto lines = File("foo.txt").byLine();
    auto duped = std.algorithm.map!"a.idup"(lines);

    // Fetch more lines in the background while we
    // process the lines already read into memory
    // into a matrix of doubles.
    double[][] matrix;
    auto asyncReader = taskPool.asyncBuf(duped);

    foreach (line; asyncReader)
    {
        auto ls = line.split("\t");
        matrix ~= to!(double[])(ls);
    }
}

```
 **Exception Handling**: Any exceptions thrown while iterating over `source` are re-thrown on a call to `popFront` or, if thrown during construction, simply allowed to propagate to the caller.  auto **asyncBuf**(C1, C2)(C1 next, C2 empty, size\_t initialBufSize = 0, size\_t nBuffers = 100)  
 Constraints: if (is(typeof(C2.init()) : bool) && (Parameters!C1.length == 1) && (Parameters!C2.length == 0) && isArray!(Parameters!C1[0])); 
 
Given a callable object `next` that writes to a user-provided buffer and a second callable object `empty` that determines whether more data is available to write via `next`, returns an input range that asynchronously calls `next` with a set of size `nBuffers` of buffers and makes the results available in the order they were obtained via the input range interface of the returned object. Similarly to the input range overload of `asyncBuf`, the first half of the buffers are made available via the range interface while the second half are filled and vice-versa. 



Parameters:


|  |  |
| --- | --- |
| C1 `next` | A callable object that takes a single argument that must be an array with mutable elements. When called, `next` writes data to the array provided by the caller. |
| C2 `empty` | A callable object that takes no arguments and returns a type implicitly convertible to `bool`. This is used to signify that no more data is available to be obtained by calling `next`. |
| size\_t `initialBufSize` | The initial size of each buffer. If `next` takes its array by reference, it may resize the buffers. |
| size\_t `nBuffers` | The number of buffers to cycle through when calling `next`. |


 
Example


```
// Fetch lines of a file in a background
// thread while processing previously fetched
// lines, without duplicating any lines.
auto file = File("foo.txt");

void next(ref char[] buf)
{
    file.readln(buf);
}

// Fetch more lines in the background while we
// process the lines already read into memory
// into a matrix of doubles.
double[][] matrix;
auto asyncReader = taskPool.asyncBuf(&next, &file.eof);

foreach (line; asyncReader)
{
    auto ls = line.split("\t");
    matrix ~= to!(double[])(ls);
}

```
 **Exception Handling**: Any exceptions thrown while iterating over `range` are re-thrown on a call to `popFront`. 
Warning
 Using the range returned by this function in a parallel foreach loop will not work because buffers may be overwritten while the task that processes them is in queue. This is checked for at compile time and will result in a static assertion failure.
  template **reduce**(functions...)  
auto **reduce**(Args...)(Args args);  
Parallel reduce on a random access range. Except as otherwise noted, usage is similar to [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce). There is also [`fold`](#fold) which does the same thing with a different parameter order. 


 This function works by splitting the range to be reduced into work units, which are slices to be reduced in parallel. Once the results from all work units are computed, a final serial reduction is performed on these results to compute the final answer. Therefore, care must be taken to choose the seed value appropriately.   
  
 Because the reduction is being performed in parallel, `functions` must be associative. For notational simplicity, let # be an infix operator representing `functions`. Then, (a # b) # c must equal a # (b # c). Floating point addition is not associative even though addition in exact arithmetic is. Summing floating point numbers using this function may give different results than summing serially. However, for many practical purposes floating point addition can be treated as associative.   
  
 Note that, since `functions` are assumed to be associative, additional optimizations are made to the serial portion of the reduction algorithm. These take advantage of the instruction level parallelism of modern CPUs, in addition to the thread-level parallelism that the rest of this module exploits. This can lead to better than linear speedups relative to [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce), especially for fine-grained benchmarks like dot products.   
  
 An explicit seed may be provided as the first argument. If provided, it is used as the seed for all work units and for the final reduction of results from all work units. Therefore, if it is not the identity value for the operation being performed, results may differ from those generated by [`std.algorithm.iteration.reduce`](std_algorithm_iteration#reduce) or depending on how many work units are used. The next argument must be the range to be reduced. 
```
// Find the sum of squares of a range in parallel, using
// an explicit seed.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// Parallel reduce:                     72 milliseconds
// Using std.algorithm.reduce instead:  181 milliseconds
auto nums = iota(10_000_000.0f);
auto sumSquares = taskPool.reduce!"a + b"(
    0.0, std.algorithm.map!"a * a"(nums)
);

```
   
  
 If no explicit seed is provided, the first element of each work unit is used as a seed. For the final reduction, the result from the first work unit is used as the seed. 
```
// Find the sum of a range in parallel, using the first
// element of each work unit as the seed.
auto sum = taskPool.reduce!"a + b"(nums);

```
   
  
 An explicit work unit size may be specified as the last argument. Specifying too small a work unit size will effectively serialize the reduction, as the final reduction of the result of each work unit will dominate computation time. If `TaskPool.size` for this instance is zero, this parameter is ignored and one work unit is used. 
```
// Use a work unit size of 100.
auto sum2 = taskPool.reduce!"a + b"(nums, 100);

// Work unit size of 100 and explicit seed.
auto sum3 = taskPool.reduce!"a + b"(0.0, nums, 100);

```
   
  
 Parallel reduce supports multiple functions, like `std.algorithm.reduce`. 
```
// Find both the min and max of nums.
auto minMax = taskPool.reduce!(min, max)(nums);
assert(minMax[0] == reduce!min(nums));
assert(minMax[1] == reduce!max(nums));

```
   
  
 **Exception Handling**:   
  
 After this function is finished executing, any exceptions thrown are chained together via `Throwable.next` and rethrown. The chaining order is non-deterministic. 

 
See Also:

[`fold`](#fold) is functionally equivalent to [`reduce`](#reduce) except the range parameter comes first and there is no need to use [`tuple`](std_typecons#tuple) for multiple seeds.
    template **fold**(functions...)  
auto **fold**(Args...)(Args args);  
Implements the homonym function (also known as `accumulate`, `compress`, `inject`, or `foldl`) present in various programming languages of functional flavor. 


`fold` is functionally equivalent to [`reduce`](#reduce) except the range parameter comes first and there is no need to use  [`tuple`](std_typecons#tuple) for multiple seeds.   
  
 There may be one or more callable entities (`functions` argument) to apply. 

 
Parameters:


|  |  |
| --- | --- |
| Args `args` | Just the range to fold over; or the range and one seed per function; or the range, one seed per function, and the work unit size |


 
Returns:
The accumulated result as a single value for single function and as a tuple of values for multiple functions 
 
See Also:
Similar to [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold), `fold` is a wrapper around [`reduce`](#reduce). 
 
Example


```
static int adder(int a, int b)
{
    return a + b;
}
static int multiplier(int a, int b)
{
    return a * b;
}

// Just the range
auto x = taskPool.fold!adder([1, 2, 3, 4]);
assert(x == 10);

// The range and the seeds (0 and 1 below; also note multiple
// functions in this example)
auto y = taskPool.fold!(adder, multiplier)([1, 2, 3, 4], 0, 1);
assert(y[0] == 10);
assert(y[1] == 24);

// The range, the seed (0), and the work unit size (20)
auto z = taskPool.fold!adder([1, 2, 3, 4], 0, 20);
assert(z == 10);

```
    const nothrow @property @safe size\_t **workerIndex**();  
Gets the index of the current thread relative to this `TaskPool`. Any thread not in this pool will receive an index of 0. The worker threads in this pool receive unique indices of 1 through `this.size`. 


This function is useful for maintaining worker-local resources. 

 
Example


```
// Execute a loop that computes the greatest common
// divisor of every number from 0 through 999 with
// 42 in parallel.  Write the results out to
// a set of files, one for each thread.  This allows
// results to be written out without any synchronization.

import std.conv, std.range, std.numeric, std.stdio;

void main()
{
    auto filesHandles = new File[taskPool.size + 1];
    scope(exit) {
        foreach (ref handle; fileHandles)
        {
            handle.close();
        }
    }

    foreach (i, ref handle; fileHandles)
    {
        handle = File("workerResults" ~ to!string(i) ~ ".txt");
    }

    foreach (num; parallel(iota(1_000)))
    {
        auto outHandle = fileHandles[taskPool.workerIndex];
        outHandle.writeln(num, '\t', gcd(num, 42));
    }
}

```
  struct **WorkerLocalStorage**(T);  
Struct for creating worker-local storage. Worker-local storage is thread-local storage that exists only for worker threads in a given `TaskPool` plus a single thread outside the pool. It is allocated on the garbage collected heap in a way that avoids false sharing, and doesn't necessarily have global scope within any thread. It can be accessed from any worker thread in the `TaskPool` that created it, and one thread outside this `TaskPool`. All threads outside the pool that created a given instance of worker-local storage share a single slot. 


Since the underlying data for this struct is heap-allocated, this struct has reference semantics when passed between functions.   
  
 The main uses cases for `WorkerLocalStorageStorage` are: 1. Performing parallel reductions with an imperative, as opposed to functional, programming style. In this case, it's useful to treat `WorkerLocalStorageStorage` as local to each thread for only the parallel portion of an algorithm.
2. Recycling temporary buffers across iterations of a parallel foreach loop.

 

 
Example


```
// Calculate pi as in our synopsis example, but
// use an imperative instead of a functional style.
immutable n = 1_000_000_000;
immutable delta = 1.0L / n;

auto sums = taskPool.workerLocalStorage(0.0L);
foreach (i; parallel(iota(n)))
{
    immutable x = ( i - 0.5L ) * delta;
    immutable toAdd = delta / ( 1.0 + x * x );
    sums.get += toAdd;
}

// Add up the results from each worker thread.
real pi = 0;
foreach (threadResult; sums.toRange)
{
    pi += 4.0L * threadResult;
}

```
 
@property ref auto **get**(this Qualified)();  
Get the current thread's instance. Returns by ref. Note that calling `get` from any thread outside the `TaskPool` that created this instance will return the same reference, so an instance of worker-local storage should only be accessed from one thread outside the pool that created it. If this rule is violated, undefined behavior will result. 


If assertions are enabled and `toRange` has been called, then this WorkerLocalStorage instance is no longer worker-local and an assertion failure will result when calling this method. This is not checked when assertions are disabled for performance reasons.

  @property void **get**(T val);  
Assign a value to the current thread's instance. This function has the same caveats as its overload.

  @property WorkerLocalStorageRange!T **toRange**();  
Returns a range view of the values for all threads, which can be used to further process the results of each thread after running the parallel part of your algorithm. Do not use this method in the parallel portion of your algorithm. 


Calling this function sets a flag indicating that this struct is no longer worker-local, and attempting to use the `get` method again will result in an assertion failure if assertions are enabled.

    struct **WorkerLocalStorageRange**(T);  
Range primitives for worker-local storage. The purpose of this is to access results produced by each worker thread from a single thread once you are no longer using the worker-local storage from multiple threads. Do not use this struct in the parallel portion of your algorithm. 


The proper way to instantiate this object is to call `WorkerLocalStorage.toRange`. Once instantiated, this object behaves as a finite random-access range with assignable, lvalue elements and a length equal to the number of worker threads in the `TaskPool` that created it plus 1.

  WorkerLocalStorage!T **workerLocalStorage**(T)(lazy T initialVal = T.init);  
Creates an instance of worker-local storage, initialized with a given value. The value is `lazy` so that you can, for example, easily create one instance of a class for each worker. For usage example, see the `WorkerLocalStorage` struct.

  @trusted void **stop**();  
Signals to all worker threads to terminate as soon as they are finished with their current `Task`, or immediately if they are not executing a `Task`. `Task`s that were in queue will not be executed unless a call to `Task.workForce`, `Task.yieldForce` or `Task.spinForce` causes them to be executed. 


Use only if you have waited on every `Task` and therefore know the queue is empty, or if you speculatively executed some tasks and no longer need the results.

  @trusted void **finish**(bool blocking = false);  
Signals worker threads to terminate when the queue becomes empty. 


If blocking argument is true, wait for all worker threads to terminate before returning. This option might be used in applications where task results are never consumed-- e.g. when `TaskPool` is employed as a rudimentary scheduler for tasks which communicate by means other than return values. 

 
Warning
 Calling this function with `blocking = true` from a worker thread that is a member of the same `TaskPool` that `finish` is being called on will result in a deadlock.
  const pure nothrow @property @safe size\_t **size**();  
Returns the number of worker threads in the pool.

  void **put**(alias fun, Args...)(ref Task!(fun, Args) task)  
 Constraints: if (!isSafeReturn!(typeof(task)));   
  
void **put**(alias fun, Args...)(Task!(fun, Args)\* task)  
 Constraints: if (!isSafeReturn!(typeof(\*task))); 
 
Put a `Task` object on the back of the task queue. The `Task` object may be passed by pointer or reference. 



Example


```
import std.file;

// Create a task.
auto t = task!read("foo.txt");

// Add it to the queue to be executed.
taskPool.put(t);

```
 
Notes
 @trusted overloads of this function are called for `Task`s if [`std.traits.hasUnsharedAliasing`](std_traits#hasUnsharedAliasing) is false for the `Task`'s return type or the function the `Task` executes is `pure`. `Task` objects that meet all other requirements specified in the `@trusted` overloads of `task` and `scopedTask` may be created and executed from `@safe` code via `Task.executeInNewThread` but not via `TaskPool`. 
 While this function takes the address of variables that may be on the stack, some overloads are marked as @trusted. `Task` includes a destructor that waits for the task to complete before destroying the stack frame it is allocated on. Therefore, it is impossible for the stack frame to be destroyed before the task is complete and no longer referenced by a `TaskPool`.  @property @trusted bool **isDaemon**();   
  
@property @trusted void **isDaemon**(bool newVal);  
These properties control whether the worker threads are daemon threads. A daemon thread is automatically terminated when all non-daemon threads have terminated. A non-daemon thread will prevent a program from terminating as long as it has not terminated. 


If any `TaskPool` with non-daemon threads is active, either `stop` or `finish` must be called on it before the program can terminate.   
  
 The worker treads in the `TaskPool` instance returned by the `taskPool` property are daemon by default. The worker threads of manually instantiated task pools are non-daemon by default. 

 
Note
 For a size zero pool, the getter arbitrarily returns true and the setter has no effect.
  @property @trusted int **priority**();   
  
@property @trusted void **priority**(int newPriority);  
These functions allow getting and setting the OS scheduling priority of the worker threads in this `TaskPool`. They forward to `core.thread.Thread.priority`, so a given priority value here means the same thing as an identical priority value in `core.thread`. 



Note
 For a size zero pool, the getter arbitrarily returns `core.thread.Thread.PRIORITY_MIN` and the setter has no effect.
    @property @trusted TaskPool **taskPool**();  
Returns a lazily initialized global instantiation of `TaskPool`. This function can safely be called concurrently from multiple non-worker threads. The worker threads in this pool are daemon threads, meaning that it is not necessary to call `TaskPool.stop` or `TaskPool.finish` before terminating the main thread.

  @property @trusted uint **defaultPoolThreads**();   
  
@property @trusted void **defaultPoolThreads**(uint newVal);  
These properties get and set the number of worker threads in the `TaskPool` instance returned by `taskPool`. The default value is `totalCPUs` - 1. Calling the setter after the first call to `taskPool` does not changes number of worker threads in the instance returned by `taskPool`.

  ParallelForeach!R **parallel**(R)(R range);   
  
ParallelForeach!R **parallel**(R)(R range, size\_t workUnitSize);  
Convenience functions that forwards to `taskPool.parallel`. The purpose of these is to make parallel foreach less verbose and more readable. 



Example


```
// Find the logarithm of every number from
// 1 to 1_000_000 in parallel, using the
// default TaskPool instance.
auto logs = new double[1_000_000];

foreach (i, ref elem; parallel(logs))
{
    elem = log(i + 1.0);
}

```
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_parallelism.html>

std.range.interfaces
====================

 This module is a submodule of [`std.range`](std_range). 


The main [`std.range`](std_range) module provides template-based tools for working with ranges, but sometimes an object-based interface for ranges is needed, such as when runtime polymorphism is required. For this purpose, this submodule provides a number of object and `interface` definitions that can be used to wrap around range objects created by the [`std.range`](std_range) templates.   
  
 

|  |  |
| --- | --- |
| [`InputRange`](#InputRange) | Wrapper for input ranges.  |
| [`InputAssignable`](#InputAssignable) | Wrapper for input ranges with assignable elements.  |
| [`ForwardRange`](#ForwardRange) | Wrapper for forward ranges.  |
| [`ForwardAssignable`](#ForwardAssignable) | Wrapper for forward ranges with assignable elements.  |
| [`BidirectionalRange`](#BidirectionalRange) | Wrapper for bidirectional ranges.  |
| [`BidirectionalAssignable`](#BidirectionalAssignable) | Wrapper for bidirectional ranges with assignable elements.  |
| [`RandomAccessFinite`](#RandomAccessFinite) | Wrapper for finite random-access ranges.  |
| [`RandomAccessAssignable`](#RandomAccessAssignable) | Wrapper for finite random-access ranges with assignable elements.  |
| [`RandomAccessInfinite`](#RandomAccessInfinite) | Wrapper for infinite random-access ranges.  |
| [`OutputRange`](#OutputRange) | Wrapper for output ranges.  |
| [`OutputRangeObject`](#OutputRangeObject) | Class that implements the `OutputRange` interface and wraps the `put` methods in virtual functions.  |
| [`outputRangeObject`](#outputRangeObject) | Convenience function for creating an `OutputRangeObject` with a base range of type R that accepts types E.  |
| [`InputRangeObject`](#InputRangeObject) | Class that implements the `InputRange` interface and wraps the input range methods in virtual functions.  |
| [`inputRangeObject`](#inputRangeObject) | Convenience function for creating an `InputRangeObject` of the proper type.  |
| [`MostDerivedInputRange`](#MostDerivedInputRange) | Returns the interface type that best matches the range.  |

   
  
 

 
Source
 [std/range/interfaces.d](https://github.com/dlang/phobos/blob/master/std/range/interfaces.d) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com), David Simcha, and [Jonathan M Davis](http://jmdavisprog.com). Credit for some of the ideas in building this module goes to [Leonardo Maffi](http://fantascienza.net/leonardo/so/).
 
interface **InputRange**(E);  
These interfaces are intended to provide virtual function-based wrappers around input ranges with element type E. This is useful where a well-defined binary interface is required, such as when a DLL function or virtual function needs to accept a generic range as a parameter. Note that [isInputRange](std_range_primitives#isInputRange) and friends check for conformance to structural interfaces not for implementation of these `interface` types. 



Limitations
 These interfaces are not capable of forwarding `ref` access to elements. 
 Infiniteness of the wrapped range is not propagated. Length is not propagated in the case of non-random access ranges. 
See Also:
[`inputRangeObject`](#inputRangeObject)
 
Examples:


```
import std.algorithm.iteration : map;
import std.range : iota;

void useRange(InputRange!int range) {
    // Function body.
}

// Create a range type.
auto squares = map!"a * a"(iota(10));

// Wrap it in an interface.
auto squaresWrapped = inputRangeObject(squares);

// Use it.
useRange(squaresWrapped);

```
 
 
@property E **front**();  E **moveFront**();  void **popFront**();  @property bool **empty**();  int **opApply**(scope int delegate(E));   
  
int **opApply**(scope int delegate(size\_t, E));  
`foreach` iteration uses opApply, since one delegate call per loop iteration is faster than three virtual function calls.

    interface **ForwardRange**(E): InputRange!E;  
Interface for a forward range of type `E`.

 
@property ForwardRange!E **save**();    interface **BidirectionalRange**(E): ForwardRange!E;  
Interface for a bidirectional range of type `E`.

 
@property BidirectionalRange!E **save**();  @property E **back**();  E **moveBack**();  void **popBack**();    interface **RandomAccessFinite**(E): BidirectionalRange!E;  
Interface for a finite random access range of type `E`.

 
@property RandomAccessFinite!E **save**();  E **opIndex**(size\_t);  E **moveAt**(size\_t);  @property size\_t **length**();  alias **opDollar** = length;  RandomAccessFinite!E **opSlice**(size\_t, size\_t);    interface **RandomAccessInfinite**(E): ForwardRange!E;  
Interface for an infinite random access range of type `E`.

 
E **moveAt**(size\_t);  @property RandomAccessInfinite!E **save**();  E **opIndex**(size\_t);    interface **InputAssignable**(E): InputRange!E;  
Adds assignable elements to InputRange.

 
@property void **front**(E newVal);    interface **ForwardAssignable**(E): InputAssignable!E, ForwardRange!E;  
Adds assignable elements to ForwardRange.

 
@property ForwardAssignable!E **save**();    interface **BidirectionalAssignable**(E): ForwardAssignable!E, BidirectionalRange!E;  
Adds assignable elements to BidirectionalRange.

 
@property BidirectionalAssignable!E **save**();  @property void **back**(E newVal);    interface **RandomFiniteAssignable**(E): RandomAccessFinite!E, BidirectionalAssignable!E;  
Adds assignable elements to RandomAccessFinite.

 
@property RandomFiniteAssignable!E **save**();  void **opIndexAssign**(E val, size\_t index);    interface **OutputRange**(E);  
Interface for an output range of type `E`. Usage is similar to the `InputRange` interface and descendants.

 
void **put**(E);    class **OutputRangeObject**(R, E...): staticMap!(OutputRange, E);  
Implements the `OutputRange` interface for all types E and wraps the `put` method for each type `E` in a virtual function.

 
this(R range);    template **MostDerivedInputRange**(R) if (isInputRange!(Unqual!R)) 
Returns the interface type that best matches `R`.

  template **InputRangeObject**(R) if (isInputRange!(Unqual!R)) 
Implements the most derived interface that `R` works with and wraps all relevant range primitives in virtual functions. If `R` is already derived from the `InputRange` interface, aliases itself away.

  InputRangeObject!R **inputRangeObject**(R)(R range)  
 Constraints: if (isInputRange!R); 
 
Convenience function for creating an `InputRangeObject` of the proper type. See [`InputRange`](#InputRange) for an example.

  template **outputRangeObject**(E...) 
Convenience function for creating an `OutputRangeObject` with a base range of type `R` that accepts types `E`.



Examples:


```
import std.array;
auto app = appender!(uint[])();
auto appWrapped = outputRangeObject!(uint, uint[])(app);
static assert(is(typeof(appWrapped) : OutputRange!(uint[])));
static assert(is(typeof(appWrapped) : OutputRange!(uint)));

```
 
 
OutputRangeObject!(R, E) **outputRangeObject**(R)(R range);    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_range_interfaces.html>

std.net.curl
============

 Networking client functionality as provided by [libcurl](http://curl.haxx.se/libcurl). The libcurl library must be installed on the system in order to use this module. 




| Category | Functions |
| --- | --- |
| High level | [*download*](#download) [*upload*](#upload) [*get*](#get) [*post*](#post) [*put*](#put) [*del*](#del) [*options*](#options) [*trace*](#trace) [*connect*](#connect) [*byLine*](#byLine) [*byChunk*](#byChunk) [*byLineAsync*](#byLineAsync) [*byChunkAsync*](#byChunkAsync) |
| Low level | [*HTTP*](#HTTP) [*FTP*](#FTP) [*SMTP*](#SMTP) |

 
Note
 You may need to link to the **curl** library, e.g. by adding `"libs": ["curl"]` to your **dub.json** file if you are using [DUB](http://code.dlang.org). 
 Windows x86 note: A DMD compatible libcurl static library can be downloaded from the dlang.org [download archive page](http://downloads.dlang.org/other/index.html). This module is not available for iOS, tvOS or watchOS. Compared to using libcurl directly this module allows simpler client code for common uses, requires no unsafe operations, and integrates better with the rest of the language. Futhermore it provides [range](std_range) access to protocols supported by libcurl both synchronously and asynchronously. A high level and a low level API are available. The high level API is built entirely on top of the low level one. The high level API is for commonly used functionality such as HTTP/FTP get. The [`byLineAsync`](#byLineAsync) and [`byChunkAsync`](#byChunkAsync) provides asynchronous [range](std_range) that performs the request in another thread while handling a line/chunk in the current thread. The low level API allows for streaming and other advanced features. 

Cheat Sheet| Function Name | Description |
|  *High level* |
| [`download`](#download) | `download("ftp.digitalmars.com/sieve.ds", "/tmp/downloaded-ftp-file")` downloads file from URL to file system. |
| [`upload`](#upload) | `upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");` uploads file from file system to URL. |
| [`get`](#get) | `get("dlang.org")` returns a char[] containing the dlang.org web page. |
| [`put`](#put) | `put("dlang.org", "Hi")` returns a char[] containing the dlang.org web page. after a HTTP PUT of "hi" |
| [`post`](#post) | `post("dlang.org", "Hi")` returns a char[] containing the dlang.org web page. after a HTTP POST of "hi" |
| [`byLine`](#byLine) | `byLine("dlang.org")` returns a range of char[] containing the dlang.org web page. |
| [`byChunk`](#byChunk) | `byChunk("dlang.org", 10)` returns a range of ubyte[10] containing the dlang.org web page. |
| [`byLineAsync`](#byLineAsync) | `byLineAsync("dlang.org")` returns a range of char[] containing the dlang.org web page asynchronously. |
| [`byChunkAsync`](#byChunkAsync) | `byChunkAsync("dlang.org", 10)` returns a range of ubyte[10] containing the dlang.org web page asynchronously. |
|  *Low level*  |
| [`HTTP`](#HTTP) | `HTTP` struct for advanced usage |
| [`FTP`](#FTP) | `FTP` struct for advanced usage |
| [`SMTP`](#SMTP) | `SMTP` struct for advanced usage |

 
Example


```
import std.net.curl, std.stdio;

// Return a char[] containing the content specified by a URL
auto content = get("dlang.org");

// Post data and return a char[] containing the content specified by a URL
auto content = post("mydomain.com/here.cgi", ["name1" : "value1", "name2" : "value2"]);

// Get content of file from ftp server
auto content = get("ftp.digitalmars.com/sieve.ds");

// Post and print out content line by line. The request is done in another thread.
foreach (line; byLineAsync("dlang.org", "Post data"))
    writeln(line);

// Get using a line range and proxy settings
auto client = HTTP();
client.proxy = "1.2.3.4";
foreach (line; byLine("dlang.org", client))
    writeln(line);

```
 For more control than the high level functions provide, use the low level API: 
Example


```
import std.net.curl, std.stdio;

// GET with custom data receivers
auto http = HTTP("dlang.org");
http.onReceiveHeader =
    (in char[] key, in char[] value) { writeln(key, ": ", value); };
http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
http.perform();

```
 First, an instance of the reference-counted HTTP struct is created. Then the custom delegates are set. These will be called whenever the HTTP instance receives a header and a data buffer, respectively. In this simple example, the headers are written to stdout and the data is ignored. If the request should be stopped before it has finished then return something less than data.length from the onReceive callback. See [`onReceiveHeader`](#onReceiveHeader)/[`onReceive`](#onReceive) for more information. Finally the HTTP request is effected by calling perform(), which is synchronous. 
Source
 [std/net/curl.d](https://github.com/dlang/phobos/blob/master/std/net/curl.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Jonas Drewsen. Some of the SMTP code contributed by Jimmy Cao. 
 
Credits
 The functionally is based on [libcurl](http://curl.haxx.se/libcurl). LibCurl is licensed under an MIT/X derivative license.
 
struct **AutoProtocol**;  

Example


```
import std.net.curl;
// Two requests below will do the same.
char[] content;

// Explicit connection provided
content = get!HTTP("dlang.org");

// Guess connection type by looking at the URL
content = get!AutoProtocol("ftp://foo.com/file");
// and since AutoProtocol is default this is the same as
content = get("ftp://foo.com/file");
// and will end up detecting FTP from the url and be the same as
content = get!FTP("ftp://foo.com/file");

```
  void **download**(Conn = AutoProtocol)(const(char)[] url, string saveToPath, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn); 
 
HTTP/FTP download to local file system. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to download |
| string `saveToPath` | path to store the downloaded content on local disk |
| Conn `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. |


 
Example


```
import std.net.curl;
download("https://httpbin.org/get", "/tmp/downloaded-http-file");

```
  void **upload**(Conn = AutoProtocol)(string loadFromPath, const(char)[] url, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn); 
 
Upload file from local files system using the HTTP or FTP protocol. 



Parameters:


|  |  |
| --- | --- |
| string `loadFromPath` | path load data from local disk. |
| const(char)[] `url` | resource to upload to |
| Conn `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. |


 
Example


```
import std.net.curl;
upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");
upload("/tmp/downloaded-http-file", "https://httpbin.org/post");

```
  T[] **get**(Conn = AutoProtocol, T = char)(const(char)[] url, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn && (is(T == char) || is(T == ubyte))); 
 
HTTP/FTP get content. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to get |
| Conn `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `char`, content will be converted from the connection character set (specified in HTTP response headers or FTP connection properties, both ISO-8859-1 by default) to UTF-8. |


 
Example


```
import std.net.curl;
auto content = get("https://httpbin.org/get");

```
 
Returns:
A T[] range containing the content of the resource pointed to by the URL. 
 
Throws:

`CurlException` on error. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **post**(T = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte));   
  
T[] **post**(T = char)(const(char)[] url, string[string] postDict, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte)); 
 
HTTP post content. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to post to |
| string[string] `postDict` | data to send as the body of the request. An associative array of `string` is accepted and will be encoded using www-form-urlencoding |
| const(PostUnit)[] `postData` | data to send as the body of the request. An array of an arbitrary type is accepted and will be cast to ubyte[] before sending it. |
| HTTP `conn` | HTTP connection to use |
| T | The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `char`, content will be converted from the connection character set (specified in HTTP response headers or FTP connection properties, both ISO-8859-1 by default) to UTF-8. |


 
Examples:


```
import std.net.curl;

auto content1 = post("https://httpbin.org/post", ["name1" : "value1", "name2" : "value2"]);
auto content2 = post("https://httpbin.org/post", [1,2,3,4]);

```
 
 
Returns:
A T[] range containing the content of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **put**(Conn = AutoProtocol, T = char, PutUnit)(const(char)[] url, const(PutUnit)[] putData, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn && (is(T == char) || is(T == ubyte))); 
 
HTTP/FTP put content. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to put |
| const(PutUnit)[] `putData` | data to send as the body of the request. An array of an arbitrary type is accepted and will be cast to ubyte[] before sending it. |
| Conn `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. If asking for `char`, content will be converted from the connection character set (specified in HTTP response headers or FTP connection properties, both ISO-8859-1 by default) to UTF-8. |


 
Example


```
import std.net.curl;
auto content = put("https://httpbin.org/put",
                     "Putting this data");

```
 
Returns:
A T[] range containing the content of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  void **del**(Conn = AutoProtocol)(const(char)[] url, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn); 
 
HTTP/FTP delete content. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to delete |
| Conn `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. |


 
Example


```
import std.net.curl;
del("https://httpbin.org/delete");

```
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **options**(T = char)(const(char)[] url, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte)); 
 
HTTP options request. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource make a option call to |
| HTTP `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. |


 
Example


```
import std.net.curl;
auto http = HTTP();
options("https://httpbin.org/headers", http);
writeln("Allow set to " ~ http.responseHeaders["Allow"]);

```
 
Returns:
A T[] range containing the options of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **trace**(T = char)(const(char)[] url, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte)); 
 
HTTP trace request. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource make a trace call to |
| HTTP `conn` | connection to use e.g. FTP or HTTP. The default AutoProtocol will guess connection type and create a new instance for this call only. The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. |


 
Example


```
import std.net.curl;
trace("https://httpbin.org/headers");

```
 
Returns:
A T[] range containing the trace info of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **connect**(T = char)(const(char)[] url, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte)); 
 
HTTP connect request. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource make a connect to |
| HTTP `conn` | HTTP connection to use The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. |


 
Example


```
import std.net.curl;
connect("https://httpbin.org/headers");

```
 
Returns:
A T[] range containing the connect info of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  T[] **patch**(T = char, PatchUnit)(const(char)[] url, const(PatchUnit)[] patchData, HTTP conn = HTTP())  
 Constraints: if (is(T == char) || is(T == ubyte)); 
 
HTTP patch content. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | resource to patch |
| const(PatchUnit)[] `patchData` | data to send as the body of the request. An array of an arbitrary type is accepted and will be cast to ubyte[] before sending it. |
| HTTP `conn` | HTTP connection to use The template parameter `T` specifies the type to return. Possible values are `char` and `ubyte` to return `char[]` or `ubyte[]`. |


 
Example


```
auto http = HTTP();
http.addRequestHeader("Content-Type", "application/json");
auto content = patch("https://httpbin.org/patch", `{"title": "Patched Title"}`, http);

```
 
Returns:
A T[] range containing the content of the resource pointed to by the URL. 
 
See Also:
[`HTTP.Method`](#HTTP.Method)
  auto **byLine**(Conn = AutoProtocol, Terminator = char, Char = char)(const(char)[] url, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator); 
 
HTTP/FTP fetch content as a range of lines. 


A range of lines is returned when the request is complete. If the method or other request properties is to be customized then set the `conn` parameter with a HTTP/FTP instance that has these properties set. 

 
Example


```
import std.net.curl, std.stdio;
foreach (line; byLine("dlang.org"))
    writeln(line);

```
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | The url to receive content from |
| KeepTerminator `keepTerminator` | `Yes.keepTerminator` signals that the line terminator should be returned as part of the lines in the range. |
| Terminator `terminator` | The character that terminates a line |
| Conn `conn` | The connection to use e.g. HTTP or FTP. |


 
Returns:
A range of Char[] with the content of the resource pointer to by the URL
  auto **byChunk**(Conn = AutoProtocol)(const(char)[] url, size\_t chunkSize = 1024, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn); 
 
HTTP/FTP fetch content as a range of chunks. 


A range of chunks is returned when the request is complete. If the method or other request properties is to be customized then set the `conn` parameter with a HTTP/FTP instance that has these properties set. 

 
Example


```
import std.net.curl, std.stdio;
foreach (chunk; byChunk("dlang.org", 100))
    writeln(chunk); // chunk is ubyte[100]

```
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | The url to receive content from |
| size\_t `chunkSize` | The size of each chunk |
| Conn `conn` | The connection to use e.g. HTTP or FTP. |


 
Returns:
A range of ubyte[chunkSize] with the content of the resource pointer to by the URL
  auto **byLineAsync**(Conn = AutoProtocol, Terminator = char, Char = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', size\_t transmitBuffers = 10, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator);   
  
auto **byLineAsync**(Conn = AutoProtocol, Terminator = char, Char = char)(const(char)[] url, KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a', size\_t transmitBuffers = 10, Conn conn = Conn());  
HTTP/FTP fetch content as a range of lines asynchronously. 


A range of lines is returned immediately and the request that fetches the lines is performed in another thread. If the method or other request properties is to be customized then set the `conn` parameter with a HTTP/FTP instance that has these properties set.   
  
 If `postData` is non-null the method will be set to `post` for HTTP requests.   
  
 The background thread will buffer up to transmitBuffers number of lines before it stops receiving data from network. When the main thread reads the lines from the range it frees up buffers and allows for the background thread to receive more data from the network.   
  
 If no data is available and the main thread accesses the range it will block until data becomes available. An exception to this is the `wait(Duration)` method on the [`LineInputRange`](#LineInputRange). This method will wait at maximum for the specified duration and return true if data is available. 

 
Example


```
import std.net.curl, std.stdio;
// Get some pages in the background
auto range1 = byLineAsync("www.google.com");
auto range2 = byLineAsync("www.wikipedia.org");
foreach (line; byLineAsync("dlang.org"))
    writeln(line);

// Lines already fetched in the background and ready
foreach (line; range1) writeln(line);
foreach (line; range2) writeln(line);

```
 
```
import std.net.curl, std.stdio;
// Get a line in a background thread and wait in
// main thread for 2 seconds for it to arrive.
auto range3 = byLineAsync("dlang.com");
if (range3.wait(dur!"seconds"(2)))
    writeln(range3.front);
else
    writeln("No line received after 2 seconds!");

```
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | The url to receive content from |
| const(PostUnit)[] `postData` | Data to HTTP Post |
| KeepTerminator `keepTerminator` | `Yes.keepTerminator` signals that the line terminator should be returned as part of the lines in the range. |
| Terminator `terminator` | The character that terminates a line |
| size\_t `transmitBuffers` | The number of lines buffered asynchronously |
| Conn `conn` | The connection to use e.g. HTTP or FTP. |


 
Returns:
A range of Char[] with the content of the resource pointer to by the URL.
  auto **byChunkAsync**(Conn = AutoProtocol, PostUnit)(const(char)[] url, const(PostUnit)[] postData, size\_t chunkSize = 1024, size\_t transmitBuffers = 10, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn);   
  
auto **byChunkAsync**(Conn = AutoProtocol)(const(char)[] url, size\_t chunkSize = 1024, size\_t transmitBuffers = 10, Conn conn = Conn())  
 Constraints: if (isCurlConn!Conn); 
 
HTTP/FTP fetch content as a range of chunks asynchronously. 


A range of chunks is returned immediately and the request that fetches the chunks is performed in another thread. If the method or other request properties is to be customized then set the `conn` parameter with a HTTP/FTP instance that has these properties set.   
  
 If `postData` is non-null the method will be set to `post` for HTTP requests.   
  
 The background thread will buffer up to transmitBuffers number of chunks before is stops receiving data from network. When the main thread reads the chunks from the range it frees up buffers and allows for the background thread to receive more data from the network.   
  
 If no data is available and the main thread access the range it will block until data becomes available. An exception to this is the `wait(Duration)` method on the [`ChunkInputRange`](#ChunkInputRange). This method will wait at maximum for the specified duration and return true if data is available. 

 
Example


```
import std.net.curl, std.stdio;
// Get some pages in the background
auto range1 = byChunkAsync("www.google.com", 100);
auto range2 = byChunkAsync("www.wikipedia.org");
foreach (chunk; byChunkAsync("dlang.org"))
    writeln(chunk); // chunk is ubyte[100]

// Chunks already fetched in the background and ready
foreach (chunk; range1) writeln(chunk);
foreach (chunk; range2) writeln(chunk);

```
 
```
import std.net.curl, std.stdio;
// Get a line in a background thread and wait in
// main thread for 2 seconds for it to arrive.
auto range3 = byChunkAsync("dlang.com", 10);
if (range3.wait(dur!"seconds"(2)))
    writeln(range3.front);
else
    writeln("No chunk received after 2 seconds!");

```
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `url` | The url to receive content from |
| const(PostUnit)[] `postData` | Data to HTTP Post |
| size\_t `chunkSize` | The size of the chunks |
| size\_t `transmitBuffers` | The number of chunks buffered asynchronously |
| Conn `conn` | The connection to use e.g. HTTP or FTP. |


 
Returns:
A range of ubyte[chunkSize] with the content of the resource pointer to by the URL.
  struct **HTTP**;  
HTTP client functionality. 



Example
 Get with custom data receivers: 
 
```
import std.net.curl, std.stdio;

auto http = HTTP("https://dlang.org");
http.onReceiveHeader =
    (in char[] key, in char[] value) { writeln(key ~ ": " ~ value); };
http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
http.perform();

```
 Put with data senders: 
```
import std.net.curl, std.stdio;

auto http = HTTP("https://dlang.org");
auto msg = "Hello world";
http.contentLength = msg.length;
http.onSend = (void[] data)
{
    auto m = cast(void[]) msg;
    size_t len = m.length > data.length ? data.length : m.length;
    if (len == 0) return len;
    data[0 .. len] = m[0 .. len];
    msg = msg[len..$];
    return len;
};
http.perform();

```
 Tracking progress: 
```
import std.net.curl, std.stdio;

auto http = HTTP();
http.method = HTTP.Method.get;
http.url = "http://upload.wikimedia.org/wikipedia/commons/" ~
           "5/53/Wikipedia-logo-en-big.png";
http.onReceive = (ubyte[] data) { return data.length; };
http.onProgress = (size_t dltotal, size_t dlnow,
                   size_t ultotal, size_t ulnow)
{
    writeln("Progress ", dltotal, ", ", dlnow, ", ", ultotal, ", ", ulnow);
    return 0;
};
http.perform();

```
 
See Also:
[RFC2616](http://www.ietf.org/rfc/rfc2616.txt)
 
alias **AuthMethod** = etc.c.curl.CurlAuth;  
Authentication method equal to [`etc.c.curl.CurlAuth`](etc_c_curl#CurlAuth)

  alias **TimeCond** = etc.c.curl.CurlTimeCond;  
Time condition enumeration as an alias of [`etc.c.curl.CurlTimeCond`](etc_c_curl#CurlTimeCond) 


[RFC2616 Section 14.25](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25)

  static HTTP **opCall**(const(char)[] url);  
Constructor taking the url as parameter.

  static HTTP **opCall**();  HTTP **dup**();  CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError);  
Perform a http request. 


After the HTTP client has been setup and possibly assigned callbacks the `perform()` method will start performing the request towards the specified server. 

 
Parameters:


|  |  |
| --- | --- |
| ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error |


  @property void **url**(const(char)[] **url**);  
The URL to specify the location of the resource.

  @property void **caInfo**(const(char)[] caFile);  
Set the CA certificate bundle file to use for SSL peer verification

  alias **requestPause** = etc.c.curl.CurlReadFunc.pause;  
Value to return from `onSend`/`onReceive` delegates in order to pause a request

  alias **requestAbort** = etc.c.curl.CurlReadFunc.abort;  
Value to return from onSend delegate in order to abort a request

  @property bool **isStopped**();  
True if the instance is stopped. A stopped instance is not usable.

  void **shutdown**();  
Stop and invalidate this instance.

  @property void **verbose**(bool on);  
Set verbose. This will print request information to stderr.

  @property void **dataTimeout**(Duration d);  
Set timeout for activity on connection.

  @property void **operationTimeout**(Duration d);  
Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc.

  @property void **connectTimeout**(Duration d);  
Set timeout for connecting.

  @property void **proxy**(const(char)[] host);  
Proxy 



See
 [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **proxyPort**(ushort port);  
Proxy port 



See
 [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT)

  alias **CurlProxy** = etc.c.curl.**CurlProxy**;  
Type of proxy

  @property void **proxyType**(CurlProxy type);  
Proxy type 



See
 [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **dnsTimeout**(Duration d);  
DNS lookup timeout.

  @property void **netInterface**(const(char)[] i);   
  
@property void **netInterface**(const(ubyte)[4] i);   
  
@property void **netInterface**(InternetAddress i);  
The network interface to use in form of the the IP of the interface. 



Example


```
theprotocol.netInterface = "192.168.1.32";
theprotocol.netInterface = [ 192, 168, 1, 32 ];

```
 
See
 [`std.socket.InternetAddress`](std_socket#InternetAddress)

  @property void **localPort**(ushort port);  
Set the local outgoing port to use. 



Parameters:


|  |  |
| --- | --- |
| ushort `port` | the first outgoing port number to try and use |


  @property void **localPortRange**(ushort range);  
Set the local outgoing port range to use. This can be used together with the localPort property. 



Parameters:


|  |  |
| --- | --- |
| ushort `range` | if the first port is occupied then try this many port number forwards |


  @property void **tcpNoDelay**(bool on);  
Set the tcp no-delay socket option on or off. 



See
 [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY)

  void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = "");  
Set the user name, password and optionally domain for authentication purposes. 


Some protocols may need authentication in some cases. Use this function to provide credentials. 

 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |
| const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name |


  void **setProxyAuthentication**(const(char)[] username, const(char)[] password);  
Set the user name and password for proxy authentication. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |


  @property void **onSend**(size\_t delegate(void[]) callback);  
The event handler that gets called when data is needed for sending. The length of the `void[]` specifies the maximum number of bytes that can be sent. 



Returns:
The callback returns the number of elements in the buffer that have been filled and are ready to send. The special value `.abortRequest` can be returned in order to abort the current request. The special value `.pauseRequest` can be returned in order to pause the current request. 
 
Example


```
import std.net.curl;
string msg = "Hello world";
auto client = HTTP("dlang.org");
client.onSend = delegate size_t(void[] data)
{
    auto m = cast(void[]) msg;
    size_t length = m.length > data.length ? data.length : m.length;
    if (length == 0) return 0;
    data[0 .. length] = m[0 .. length];
    msg = msg[length..$];
    return length;
};
client.perform();

```
  @property void **onReceive**(size\_t delegate(ubyte[]) callback);  
The event handler that receives incoming data. Be sure to copy the incoming ubyte[] since it is not guaranteed to be valid after the callback returns. 



Returns:
The callback returns the incoming bytes read. If not the entire array is the request will abort. The special value .pauseRequest can be returned in order to pause the current request. 
 
Example


```
import std.net.curl, std.stdio;
auto client = HTTP("dlang.org");
client.onReceive = (ubyte[] data)
{
    writeln("Got data", to!(const(char)[])(data));
    return data.length;
};
client.perform();

```
  @property void **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback);  
Register an event handler that gets called to inform of upload/download progress. 



Callback parameters



|  |  |
| --- | --- |
| `dlTotal` | total bytes to download |
| `dlNow` | currently downloaded bytes |
| `ulTotal` | total bytes to upload |
| `ulNow` | currently uploaded bytes |

 Connection type used when the URL should be used to auto detect the protocol. This struct is used as placeholder for the connection parameter when calling the high level API and the connection type (HTTP/FTP) should be guessed by inspecting the URL parameter. The rules for guessing the protocol are: 1, if URL starts with ftp://, ftps:// or ftp. then FTP connection is assumed. 2, HTTP connection otherwise. 
Callback returns
 Return 0 to signal success, return non-zero to abort transfer. 
 
Example


```
import std.net.curl, std.stdio;
auto client = HTTP("dlang.org");
client.onProgress = delegate int(size_t dl, size_t dln, size_t ul, size_t uln)
{
    writeln("Progress: downloaded ", dln, " of ", dl);
    writeln("Progress: uploaded ", uln, " of ", ul);
    return 0;
};
client.perform();

```
  void **clearRequestHeaders**();  
Clear all outgoing headers.

  void **addRequestHeader**(const(char)[] name, const(char)[] value);  
Add a header e.g. "X-CustomField: Something is fishy". 


There is no remove header functionality. Do a [`clearRequestHeaders`](#clearRequestHeaders) and set the needed headers instead. 

 
Example


```
import std.net.curl;
auto client = HTTP();
client.addRequestHeader("X-Custom-ABC", "This is the custom value");
auto content = get("dlang.org", client);

```
  static @property string **defaultUserAgent**();  
The default "User-Agent" value send with a request. It has the form "Phobos-std.net.curl/*PHOBOS\_VERSION* (libcurl/*CURL\_VERSION*)"

  void **setUserAgent**(const(char)[] userAgent);  
Set the value of the user agent request header field. 


By default a request has it's "User-Agent" field set to  [`defaultUserAgent`](#%20defaultUserAgent) even if `setUserAgent` was never called. Pass an empty string to suppress the "User-Agent" field altogether.

  CurlCode **getTiming**(CurlInfo timing, ref double val);  
Get various timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The value is usable only if the return value is equal to `etc.c.curl.CurlError.ok`. 



Parameters:


|  |  |
| --- | --- |
| CurlInfo `timing` | one of the timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The values are: `etc.c.curl.CurlInfo.namelookup_time`, `etc.c.curl.CurlInfo.connect_time`, `etc.c.curl.CurlInfo.pretransfer_time`, `etc.c.curl.CurlInfo.starttransfer_time`, `etc.c.curl.CurlInfo.redirect_time`, `etc.c.curl.CurlInfo.appconnect_time`, `etc.c.curl.CurlInfo.total_time`. |
| double `val` | the actual value of the inquired timing. |


 
Returns:
The return code of the operation. The value stored in val should be used only if the return value is `etc.c.curl.CurlInfo.ok`. 
 
Example


```
import std.net.curl;
import etc.c.curl : CurlError, CurlInfo;

auto client = HTTP("dlang.org");
client.perform();

double val;
CurlCode code;

code = client.getTiming(CurlInfo.namelookup_time, val);
assert(code == CurlError.ok);

```
  @property string[string] **responseHeaders**();  
The headers read from a successful response. 

  @property void **method**(Method m);   
  
@property Method **method**();  
HTTP method used.

  @property StatusLine **statusLine**();  
HTTP status line of last response. One call to perform may result in several requests because of redirection.

  void **setCookie**(const(char)[] cookie);  
Set the active cookie string e.g. "name1=value1;name2=value2"

  void **setCookieJar**(const(char)[] path);  
Set a file path to where a cookie jar should be read/stored.

  void **flushCookieJar**();  
Flush cookie jar to disk.

  void **clearSessionCookies**();  
Clear session cookies.

  void **clearAllCookies**();  
Clear all cookies.

  void **setTimeCondition**(HTTP.TimeCond cond, SysTime timestamp);  
Set time condition on the request. 



Parameters:


|  |  |
| --- | --- |
| HTTP.TimeCond `cond` | `CurlTimeCond.{none,ifmodsince,ifunmodsince,lastmod}` |
| SysTime `timestamp` | Timestamp for the condition [RFC2616 Section 14.25](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25) |


  @property void **postData**(const(void)[] data);  
Specifying data to post when not using the onSend callback. 


The data is NOT copied by the library. Content-Type will default to application/octet-stream. Data is not converted or encoded by this method. 

 
Example


```
import std.net.curl, std.stdio;
auto http = HTTP("http://www.mydomain.com");
http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
http.postData = [1,2,3,4,5];
http.perform();

```
  @property void **postData**(const(char)[] data);  
Specifying data to post when not using the onSend callback. 


The data is NOT copied by the library. Content-Type will default to text/plain. Data is not converted or encoded by this method. 

 
Example


```
import std.net.curl, std.stdio;
auto http = HTTP("http://www.mydomain.com");
http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
http.postData = "The quick....";
http.perform();

```
  void **setPostData**(const(void)[] data, string contentType);  
Specify data to post when not using the onSend callback, with user-specified Content-Type. 



Parameters:


|  |  |
| --- | --- |
| const(void)[] `data` | Data to post. |
| string `contentType` | MIME type of the data, for example, "text/plain" or "application/octet-stream". See also:  [Internet media type](http://en.wikipedia.org/wiki/Internet_media_type) on Wikipedia. 
```
import std.net.curl;
auto http = HTTP("http://onlineform.example.com");
auto data = "app=login&username=bob&password=s00perS3kret";
http.setPostData(data, "application/x-www-form-urlencoded");
http.onReceive = (ubyte[] data) { return data.length; };
http.perform();

```
 |


  @property void **onReceiveHeader**(void delegate(in char[] key, in char[] value) callback);  
Set the event handler that receives incoming headers. 


The callback will receive a header field key, value as parameter. The `const(char)[]` arrays are not valid after the delegate has returned. 

 
Example


```
import std.net.curl, std.stdio;
auto http = HTTP("dlang.org");
http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
http.onReceiveHeader = (in char[] key, in char[] value) { writeln(key, " = ", value); };
http.perform();

```
  @property void **onReceiveStatusLine**(void delegate(StatusLine) callback);  
Callback for each received StatusLine. 


Notice that several callbacks can be done for each call to `perform()` due to redirections. 

 
See Also:
[`StatusLine`](#StatusLine)
  @property void **contentLength**(ulong len);  
The content length in bytes when using request that has content e.g. POST/PUT and not using chunked transfer. Is set as the "Content-Length" header. Set to ulong.max to reset to chunked transfer.

  @property void **authenticationMethod**(AuthMethod authMethod);  
Authentication method as specified in [`AuthMethod`](#AuthMethod).

  @property void **maxRedirects**(uint maxRedirs);  
Set max allowed redirections using the location header. uint.max for infinite.

  enum **Method**: int;  
The standard HTTP methods : [RFC2616 Section 5.1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1)

 
**head** **get** **post** **put** **del** **options** **trace** **connect** **patch**   struct **StatusLine**;  
HTTP status line ie. the first line returned in an HTTP response. 


If authentication or redirections are done then the status will be for the last response received.

 
ushort **majorVersion**;  
Major HTTP version ie. 1 in HTTP/1.0.

  ushort **minorVersion**;  
Minor HTTP version ie. 0 in HTTP/1.0.

  ushort **code**;  
HTTP status line code e.g. 200.

  string **reason**;  
HTTP status line reason string.

  @safe void **reset**();  
Reset this status line

  const string **toString**();      struct **FTP**;  
FTP client functionality. 



See Also:
[RFC959](http://tools.ietf.org/html/rfc959)
 
static FTP **opCall**(const(char)[] url);  
FTP access to the specified url.

  static FTP **opCall**();  FTP **dup**();  CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError);  
Performs the ftp request as it has been configured. 


After a FTP client has been setup and possibly assigned callbacks the  `perform()` method will start performing the actual communication with the server. 

 
Parameters:


|  |  |
| --- | --- |
| ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error |


  @property void **url**(const(char)[] **url**);  
The URL to specify the location of the resource.

  alias **requestPause** = etc.c.curl.CurlReadFunc.pause;  
Value to return from `onSend`/`onReceive` delegates in order to pause a request

  alias **requestAbort** = etc.c.curl.CurlReadFunc.abort;  
Value to return from onSend delegate in order to abort a request

  @property bool **isStopped**();  
True if the instance is stopped. A stopped instance is not usable.

  void **shutdown**();  
Stop and invalidate this instance.

  @property void **verbose**(bool on);  
Set verbose. This will print request information to stderr.

  @property void **dataTimeout**(Duration d);  
Set timeout for activity on connection.

  @property void **operationTimeout**(Duration d);  
Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc.

  @property void **connectTimeout**(Duration d);  
Set timeout for connecting.

  @property void **proxy**(const(char)[] host);  
Proxy 



See
 [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **proxyPort**(ushort port);  
Proxy port 



See
 [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT)

  alias **CurlProxy** = etc.c.curl.**CurlProxy**;  
Type of proxy

  @property void **proxyType**(CurlProxy type);  
Proxy type 



See
 [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **dnsTimeout**(Duration d);  
DNS lookup timeout.

  @property void **netInterface**(const(char)[] i);   
  
@property void **netInterface**(const(ubyte)[4] i);   
  
@property void **netInterface**(InternetAddress i);  
The network interface to use in form of the the IP of the interface. 



Example


```
theprotocol.netInterface = "192.168.1.32";
theprotocol.netInterface = [ 192, 168, 1, 32 ];

```
 
See
 [`std.socket.InternetAddress`](std_socket#InternetAddress)

  @property void **localPort**(ushort port);  
Set the local outgoing port to use. 



Parameters:


|  |  |
| --- | --- |
| ushort `port` | the first outgoing port number to try and use |


  @property void **localPortRange**(ushort range);  
Set the local outgoing port range to use. This can be used together with the localPort property. 



Parameters:


|  |  |
| --- | --- |
| ushort `range` | if the first port is occupied then try this many port number forwards |


  @property void **tcpNoDelay**(bool on);  
Set the tcp no-delay socket option on or off. 



See
 [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY)

  void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = "");  
Set the user name, password and optionally domain for authentication purposes. 


Some protocols may need authentication in some cases. Use this function to provide credentials. 

 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |
| const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name |


  void **setProxyAuthentication**(const(char)[] username, const(char)[] password);  
Set the user name and password for proxy authentication. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |


  @property void **onSend**(size\_t delegate(void[]) callback);  
The event handler that gets called when data is needed for sending. The length of the `void[]` specifies the maximum number of bytes that can be sent. 



Returns:
The callback returns the number of elements in the buffer that have been filled and are ready to send. The special value `.abortRequest` can be returned in order to abort the current request. The special value `.pauseRequest` can be returned in order to pause the current request.
  @property void **onReceive**(size\_t delegate(ubyte[]) callback);  
The event handler that receives incoming data. Be sure to copy the incoming ubyte[] since it is not guaranteed to be valid after the callback returns. 



Returns:
The callback returns the incoming bytes read. If not the entire array is the request will abort. The special value .pauseRequest can be returned in order to pause the current request.
  @property void **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback);  
The event handler that gets called to inform of upload/download progress. 



Callback parameters



|  |  |
| --- | --- |
| `dlTotal` | total bytes to download |
| `dlNow` | currently downloaded bytes |
| `ulTotal` | total bytes to upload |
| `ulNow` | currently uploaded bytes |

 Connection type used when the URL should be used to auto detect the protocol. This struct is used as placeholder for the connection parameter when calling the high level API and the connection type (HTTP/FTP) should be guessed by inspecting the URL parameter. The rules for guessing the protocol are: 1, if URL starts with ftp://, ftps:// or ftp. then FTP connection is assumed. 2, HTTP connection otherwise. 
Callback returns
 Return 0 from the callback to signal success, return non-zero to abort transfer.
  void **clearCommands**();  
Clear all commands send to ftp server.

  void **addCommand**(const(char)[] command);  
Add a command to send to ftp server. 


There is no remove command functionality. Do a [`clearCommands`](#clearCommands) and set the needed commands instead. 

 
Example


```
import std.net.curl;
auto client = FTP();
client.addCommand("RNFR my_file.txt");
client.addCommand("RNTO my_renamed_file.txt");
upload("my_file.txt", "ftp.digitalmars.com", client);

```
  @property void **encoding**(string name);   
  
@property string **encoding**();  
Connection encoding. Defaults to ISO-8859-1.

  @property void **contentLength**(ulong len);  
The content length in bytes of the ftp data.

  CurlCode **getTiming**(CurlInfo timing, ref double val);  
Get various timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The value is usable only if the return value is equal to `etc.c.curl.CurlError.ok`. 



Parameters:


|  |  |
| --- | --- |
| CurlInfo `timing` | one of the timings defined in [`etc.c.curl.CurlInfo`](etc_c_curl#CurlInfo). The values are: `etc.c.curl.CurlInfo.namelookup_time`, `etc.c.curl.CurlInfo.connect_time`, `etc.c.curl.CurlInfo.pretransfer_time`, `etc.c.curl.CurlInfo.starttransfer_time`, `etc.c.curl.CurlInfo.redirect_time`, `etc.c.curl.CurlInfo.appconnect_time`, `etc.c.curl.CurlInfo.total_time`. |
| double `val` | the actual value of the inquired timing. |


 
Returns:
The return code of the operation. The value stored in val should be used only if the return value is `etc.c.curl.CurlInfo.ok`. 
 
Example


```
import std.net.curl;
import etc.c.curl : CurlError, CurlInfo;

auto client = FTP();
client.addCommand("RNFR my_file.txt");
client.addCommand("RNTO my_renamed_file.txt");
upload("my_file.txt", "ftp.digitalmars.com", client);

double val;
CurlCode code;

code = client.getTiming(CurlInfo.namelookup_time, val);
assert(code == CurlError.ok);

```
    struct **SMTP**;  
Basic SMTP protocol support. 



Example


```
import std.net.curl;

// Send an email with SMTPS
auto smtp = SMTP("smtps://smtp.gmail.com");
smtp.setAuthentication("from.addr@gmail.com", "password");
smtp.mailTo = ["<to.addr@gmail.com>"];
smtp.mailFrom = "<from.addr@gmail.com>";
smtp.message = "Example Message";
smtp.perform();

```
 
See Also:
[RFC2821](http://www.ietf.org/rfc/rfc2821.txt)
 
static SMTP **opCall**(const(char)[] url);  
Sets to the URL of the SMTP server.

  static SMTP **opCall**();  CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError);  
Performs the request as configured. 



Parameters:


|  |  |
| --- | --- |
| ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error |


  @property void **url**(const(char)[] **url**);  
The URL to specify the location of the resource.

  alias **requestPause** = etc.c.curl.CurlReadFunc.pause;  
Value to return from `onSend`/`onReceive` delegates in order to pause a request

  alias **requestAbort** = etc.c.curl.CurlReadFunc.abort;  
Value to return from onSend delegate in order to abort a request

  @property bool **isStopped**();  
True if the instance is stopped. A stopped instance is not usable.

  void **shutdown**();  
Stop and invalidate this instance.

  @property void **verbose**(bool on);  
Set verbose. This will print request information to stderr.

  @property void **dataTimeout**(Duration d);  
Set timeout for activity on connection.

  @property void **operationTimeout**(Duration d);  
Set maximum time an operation is allowed to take. This includes dns resolution, connecting, data transfer, etc.

  @property void **connectTimeout**(Duration d);  
Set timeout for connecting.

  @property void **proxy**(const(char)[] host);  
Proxy 



See
 [proxy](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **proxyPort**(ushort port);  
Proxy port 



See
 [proxy\_port](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT)

  alias **CurlProxy** = etc.c.curl.**CurlProxy**;  
Type of proxy

  @property void **proxyType**(CurlProxy type);  
Proxy type 



See
 [proxy\_type](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY)

  @property void **dnsTimeout**(Duration d);  
DNS lookup timeout.

  @property void **netInterface**(const(char)[] i);   
  
@property void **netInterface**(const(ubyte)[4] i);   
  
@property void **netInterface**(InternetAddress i);  
The network interface to use in form of the the IP of the interface. 



Example


```
theprotocol.netInterface = "192.168.1.32";
theprotocol.netInterface = [ 192, 168, 1, 32 ];

```
 
See
 [`std.socket.InternetAddress`](std_socket#InternetAddress)

  @property void **localPort**(ushort port);  
Set the local outgoing port to use. 



Parameters:


|  |  |
| --- | --- |
| ushort `port` | the first outgoing port number to try and use |


  @property void **localPortRange**(ushort range);  
Set the local outgoing port range to use. This can be used together with the localPort property. 



Parameters:


|  |  |
| --- | --- |
| ushort `range` | if the first port is occupied then try this many port number forwards |


  @property void **tcpNoDelay**(bool on);  
Set the tcp no-delay socket option on or off. 



See
 [nodelay](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY)

  void **setAuthentication**(const(char)[] username, const(char)[] password, const(char)[] domain = "");  
Set the user name, password and optionally domain for authentication purposes. 


Some protocols may need authentication in some cases. Use this function to provide credentials. 

 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |
| const(char)[] `domain` | used for NTLM authentication only and is set to the NTLM domain name |


  void **setProxyAuthentication**(const(char)[] username, const(char)[] password);  
Set the user name and password for proxy authentication. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `username` | the username |
| const(char)[] `password` | the password |


  @property void **onSend**(size\_t delegate(void[]) callback);  
The event handler that gets called when data is needed for sending. The length of the `void[]` specifies the maximum number of bytes that can be sent. 



Returns:
The callback returns the number of elements in the buffer that have been filled and are ready to send. The special value `.abortRequest` can be returned in order to abort the current request. The special value `.pauseRequest` can be returned in order to pause the current request.
  @property void **onReceive**(size\_t delegate(ubyte[]) callback);  
The event handler that receives incoming data. Be sure to copy the incoming ubyte[] since it is not guaranteed to be valid after the callback returns. 



Returns:
The callback returns the incoming bytes read. If not the entire array is the request will abort. The special value .pauseRequest can be returned in order to pause the current request.
  @property void **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback);  
The event handler that gets called to inform of upload/download progress. 



Callback parameters



|  |  |
| --- | --- |
| `dlTotal` | total bytes to download |
| `dlNow` | currently downloaded bytes |
| `ulTotal` | total bytes to upload |
| `ulNow` | currently uploaded bytes |

 Connection type used when the URL should be used to auto detect the protocol. This struct is used as placeholder for the connection parameter when calling the high level API and the connection type (HTTP/FTP) should be guessed by inspecting the URL parameter. The rules for guessing the protocol are: 1, if URL starts with ftp://, ftps:// or ftp. then FTP connection is assumed. 2, HTTP connection otherwise. 
Callback returns
 Return 0 from the callback to signal success, return non-zero to abort transfer.
  @property void **mailFrom**()(const(char)[] sender);  
Setter for the sender's email address.

  void **mailTo**()(const(char)[][] recipients...);  
Setter for the recipient email addresses.

  @property void **message**(string msg);  
Sets the message body text.

    class **CurlException**: object.Exception;  
Exception thrown on errors in std.net.curl functions.

 
pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |
| Throwable `next` | The previous exception in the chain of exceptions, if any. |


    class **CurlTimeoutException**: std.net.curl.CurlException;  
Exception thrown on timeout errors in std.net.curl functions.

 
pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |
| Throwable `next` | The previous exception in the chain of exceptions, if any. |


    class **HTTPStatusException**: std.net.curl.CurlException;  
Exception thrown on HTTP request failures, e.g. 404 Not Found.

 
pure nothrow @safe this(int status, string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  

Parameters:


|  |  |
| --- | --- |
| int `status` | The HTTP status code. |
| string `msg` | The message for the exception. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |
| Throwable `next` | The previous exception in the chain of exceptions, if any. |


  immutable int **status**;  
The HTTP status code

    alias **CurlCode** = int;  
Equal to [`etc.c.curl.CURLcode`](etc_c_curl#CURLcode)

  alias **ThrowOnError** = std.typecons.Flag!"throwOnError".Flag;  
Flag to specify whether or not an exception is thrown on error.

  struct **Curl**;  
Wrapper to provide a better interface to libcurl than using the plain C API. It is recommended to use the `HTTP`/`FTP` etc. structs instead unless raw access to libcurl is needed. 



Warning
 This struct uses interior pointers for callbacks. Only allocate it on the stack if you never move or copy it. This also means passing by reference when passing Curl to other functions. Otherwise always allocate on the heap.
 
void **initialize**();  
Initialize the instance by creating a working curl handle.

  const @property bool **stopped**();  Curl **dup**();  
Duplicate this handle. 


The new handle will have all options set as the one it was duplicated from. An exception to this is that all options that cannot be shared across threads are reset thereby making it safe to use the duplicate in a new thread.

  void **shutdown**();  
Stop and invalidate this curl instance. 



Warning
 Do not call this from inside a callback handler e.g. `onReceive`.
  void **pause**(bool sendingPaused, bool receivingPaused);  
Pausing and continuing transfers.

  void **set**(CurlOption option, const(char)[] value);  
Set a string curl option. 



Parameters:


|  |  |
| --- | --- |
| CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation |
| const(char)[] `value` | The string |


  void **set**(CurlOption option, long value);  
Set a long curl option. 



Parameters:


|  |  |
| --- | --- |
| CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation |
| long `value` | The long |


  void **set**(CurlOption option, void\* value);  
Set a void\* curl option. 



Parameters:


|  |  |
| --- | --- |
| CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation |
| void\* `value` | The pointer |


  void **clear**(CurlOption option);  
Clear a pointer option. 



Parameters:


|  |  |
| --- | --- |
| CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation |


  void **clearIfSupported**(CurlOption option);  
Clear a pointer option. Does not raise an exception if the underlying libcurl does not support the option. Use sparingly. 



Parameters:


|  |  |
| --- | --- |
| CurlOption `option` | A [`etc.c.curl.CurlOption`](etc_c_curl#CurlOption) as found in the curl documentation |


  CurlCode **perform**(ThrowOnError throwOnError = Yes.throwOnError);  
perform the curl request by doing the HTTP,FTP etc. as it has been setup beforehand. 



Parameters:


|  |  |
| --- | --- |
| ThrowOnError `throwOnError` | whether to throw an exception or return a CurlCode on error |


  CurlCode **getTiming**(CurlInfo timing, ref double val);  
Get the various timings like name lookup time, total time, connect time etc. The timed category is passed through the timing parameter while the timing value is stored at val. The value is usable only if res is equal to `etc.c.curl.CurlError.ok`.

  @property void **onReceive**(size\_t delegate(InData) callback);  
The event handler that receives incoming data. 



Parameters:


|  |  |
| --- | --- |
| size\_t delegate(InData) `callback` | the callback that receives the `ubyte[]` data. Be sure to copy the incoming data and not store a slice. |


 
Returns:
The callback returns the incoming bytes read. If not the entire array is the request will abort. The special value HTTP.pauseRequest can be returned in order to pause the current request. 
 
Example


```
import std.net.curl, std.stdio;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");
curl.onReceive = (ubyte[] data) { writeln("Got data", to!(const(char)[])(data)); return data.length;};
curl.perform();

```
  @property void **onReceiveHeader**(void delegate(in char[]) callback);  
The event handler that receives incoming headers for protocols that uses headers. 



Parameters:


|  |  |
| --- | --- |
| void delegate(in char[]) `callback` | the callback that receives the header string. Make sure the callback copies the incoming params if it needs to store it because they are references into the backend and may very likely change. |


 
Example


```
import std.net.curl, std.stdio;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");
curl.onReceiveHeader = (in char[] header) { writeln(header); };
curl.perform();

```
  @property void **onSend**(size\_t delegate(OutData) callback);  
The event handler that gets called when data is needed for sending. 



Parameters:


|  |  |
| --- | --- |
| size\_t delegate(OutData) `callback` | the callback that has a `void[]` buffer to be filled |


 
Returns:
The callback returns the number of elements in the buffer that have been filled and are ready to send. The special value `Curl.abortRequest` can be returned in order to abort the current request. The special value `Curl.pauseRequest` can be returned in order to pause the current request. 
 
Example


```
import std.net.curl;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");

string msg = "Hello world";
curl.onSend = (void[] data)
{
    auto m = cast(void[]) msg;
    size_t length = m.length > data.length ? data.length : m.length;
    if (length == 0) return 0;
    data[0 .. length] = m[0 .. length];
    msg = msg[length..$];
    return length;
};
curl.perform();

```
  @property void **onSeek**(CurlSeek delegate(long, CurlSeekPos) callback);  
The event handler that gets called when the curl backend needs to seek the data to be sent. 



Parameters:


|  |  |
| --- | --- |
| CurlSeek delegate(long, CurlSeekPos) `callback` | the callback that receives a seek offset and a seek position [`etc.c.curl.CurlSeekPos`](etc_c_curl#CurlSeekPos) |


 
Returns:
The callback returns the success state of the seeking [`etc.c.curl.CurlSeek`](etc_c_curl#CurlSeek) 
 
Example


```
import std.net.curl;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");
curl.onSeek = (long p, CurlSeekPos sp)
{
    return CurlSeek.cantseek;
};
curl.perform();

```
  @property void **onSocketOption**(int delegate(curl\_socket\_t, CurlSockType) callback);  
The event handler that gets called when the net socket has been created but a `connect()` call has not yet been done. This makes it possible to set misc. socket options. 



Parameters:


|  |  |
| --- | --- |
| int delegate(curl\_socket\_t, CurlSockType) `callback` | the callback that receives the socket and socket type [`etc.c.curl.CurlSockType`](etc_c_curl#CurlSockType) |


 
Returns:
Return 0 from the callback to signal success, return 1 to signal error and make curl close the socket 
 
Example


```
import std.net.curl;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");
curl.onSocketOption = delegate int(curl_socket_t s, CurlSockType t) { /+ do stuff +/ };
curl.perform();

```
  @property void **onProgress**(int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) callback);  
The event handler that gets called to inform of upload/download progress. 



Parameters:


|  |  |
| --- | --- |
| int delegate(size\_t dlTotal, size\_t dlNow, size\_t ulTotal, size\_t ulNow) `callback` | the callback that receives the (total bytes to download, currently downloaded bytes, total bytes to upload, currently uploaded bytes). |


 
Returns:
Return 0 from the callback to signal success, return non-zero to abort transfer 
 
Example


```
import std.net.curl, std.stdio;
Curl curl;
curl.initialize();
curl.set(CurlOption.url, "http://dlang.org");
curl.onProgress = delegate int(size_t dltotal, size_t dlnow, size_t ultotal, size_t ulnow)
{
    writeln("Progress: downloaded bytes ", dlnow, " of ", dltotal);
    writeln("Progress: uploaded bytes ", ulnow, " of ", ultotal);
    return 0;
};
curl.perform();

```
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_net_curl.html>

std.path
========

 This module is used to manipulate path strings. 


All functions, with the exception of [`expandTilde`](#expandTilde) (and in some cases [`absolutePath`](#absolutePath) and [`relativePath`](#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 [`std.file.isDir`](std_file#isDir) and [`std.file.exists`](std_file#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`](#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`](#isValidFilename) and [`isValidPath`](#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`](#absolutePath) [`asAbsolutePath`](#asAbsolutePath) [`asNormalizedPath`](#asNormalizedPath) [`asRelativePath`](#asRelativePath) [`buildNormalizedPath`](#buildNormalizedPath) [`buildPath`](#buildPath) [`chainPath`](#chainPath) [`expandTilde`](#expandTilde) |
| Partitioning | [`baseName`](#baseName) [`dirName`](#dirName) [`dirSeparator`](#dirSeparator) [`driveName`](#driveName) [`pathSeparator`](#pathSeparator) [`pathSplitter`](#pathSplitter) [`relativePath`](#relativePath) [`rootName`](#rootName) [`stripDrive`](#stripDrive) |
| Validation | [`isAbsolute`](#isAbsolute) [`isDirSeparator`](#isDirSeparator) [`isRooted`](#isRooted) [`isValidFilename`](#isValidFilename) [`isValidPath`](#isValidPath) |
| Extension | [`defaultExtension`](#defaultExtension) [`extension`](#extension) [`setExtension`](#setExtension) [`stripExtension`](#stripExtension) [`withDefaultExtension`](#withDefaultExtension) [`withExtension`](#withExtension) |
| Other | [`filenameCharCmp`](#filenameCharCmp) [`filenameCmp`](#filenameCmp) [`globMatch`](#globMatch) [`CaseSensitive`](#CaseSensitive) |

 

 
Authors:
Lars Tandle Kyllingstad, [Walter Bright](http://digitalmars.com), Grzegorz Adam Hankiewicz, Thomas Kühne, [Andrei Alexandrescu](http://erdani.org) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt) 
 
Source
 [std/path.d](https://github.com/dlang/phobos/blob/master/std/path.d)

 
enum string **dirSeparator**;  
String used to separate directory names in a path. Under POSIX this is a slash, under Windows a backslash.

  enum string **pathSeparator**;  
Path separator string. A colon under POSIX, a semicolon under Windows.

  pure nothrow @nogc @safe bool **isDirSeparator**(dchar c);  
Determines whether the given character is a directory separator. 


On Windows, this includes both `\` and `/`. On POSIX, it's just `/`.

 
Examples:


```
version (Windows)
{
    assert( '/'.isDirSeparator);
    assert( '\\'.isDirSeparator);
}
else
{
    assert( '/'.isDirSeparator);
    assert(!'\\'.isDirSeparator);
}

```
 
  enum **CaseSensitive**: bool;  
This `enum` is used as a template argument to functions which compare file names, and determines whether the comparison is case sensitive or not.



Examples:


```
writeln(baseName!(CaseSensitive.no)("dir/file.EXT", ".ext")); // "file"
assert(baseName!(CaseSensitive.yes)("dir/file.EXT", ".ext") != "file");

version (Posix)
    writeln(relativePath!(CaseSensitive.no)("/FOO/bar", "/foo/baz")); // "../bar"
else
    writeln(relativePath!(CaseSensitive.no)(`c:\FOO\bar`, `c:\foo\baz`)); // `..\bar`

```
 
 
**no** 
File names are case insensitive

  **yes** 
File names are case sensitive

  **osDefault** 
The default (or most common) setting for the current platform. That is, `no` on Windows and Mac OS X, and `yes` on all POSIX systems except Darwin (Linux, \*BSD, etc.).

    auto **baseName**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **baseName**(C)(C[] path)  
 Constraints: if (isSomeChar!C);   
  
pure @safe inout(C)[] **baseName**(CaseSensitive cs = CaseSensitive.osDefault, C, C1)(inout(C)[] path, in C1[] suffix)  
 Constraints: if (isSomeChar!C && isSomeChar!C1); 
 

Parameters:


|  |  |
| --- | --- |
| cs | Whether or not suffix matching is case-sensitive. |
| R `path` | A path name. It can be a string, or any random-access range of characters. |
| C1[] `suffix` | An optional suffix to be removed from the file name. |


 
Returns:
The name of the file in the path name, without any leading directory and with an optional suffix chopped off. If `suffix` is specified, it will be compared to `path` using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details. 
 
Note
 This function *only* strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use [`stripExtension`](#stripExtension). To obtain the filename without leading directories and without an extension, combine the functions like this: 


```
assert(baseName(stripExtension("dir/file.ext")) == "file");

```
 
Standards:
This function complies with  [the POSIX requirements for the 'basename' shell utility](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html) (with suitable adaptations for Windows paths).
 
Examples:


```
writeln(baseName("dir/file.ext")); // "file.ext"
writeln(baseName("dir/file.ext", ".ext")); // "file"
writeln(baseName("dir/file.ext", ".xyz")); // "file.ext"
writeln(baseName("dir/filename", "name")); // "file"
writeln(baseName("dir/subdir/")); // "subdir"

version (Windows)
{
    writeln(baseName(`d:file.ext`)); // "file.ext"
    writeln(baseName(`d:\dir\file.ext`)); // "file.ext"
}

```
 
  auto **dirName**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **dirName**(C)(C[] path)  
 Constraints: if (isSomeChar!C); 
 
Returns the parent directory of `path`. On Windows, this includes the drive letter if present. If `path` is a relative path and the parent directory is the current working directory, returns `"."`. 



Parameters:


|  |  |
| --- | --- |
| R `path` | A path name. |


 
Returns:
A slice of `path` or `"."`. 
 
Standards:
This function complies with  [the POSIX requirements for the 'dirname' shell utility](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html) (with suitable adaptations for Windows paths).
 
Examples:


```
writeln(dirName("")); // "."
writeln(dirName("file"w)); // "."
writeln(dirName("dir/"d)); // "."
writeln(dirName("dir///")); // "."
writeln(dirName("dir/file"w.dup)); // "dir"
writeln(dirName("dir///file"d.dup)); // "dir"
writeln(dirName("dir/subdir/")); // "dir"
writeln(dirName("/dir/file"w)); // "/dir"
writeln(dirName("/file"d)); // "/"
writeln(dirName("/")); // "/"
writeln(dirName("///")); // "/"

version (Windows)
{
    writeln(dirName(`dir\`)); // `.`
    writeln(dirName(`dir\\\`)); // `.`
    writeln(dirName(`dir\file`)); // `dir`
    writeln(dirName(`dir\\\file`)); // `dir`
    writeln(dirName(`dir\subdir\`)); // `dir`
    writeln(dirName(`\dir\file`)); // `\dir`
    writeln(dirName(`\file`)); // `\`
    writeln(dirName(`\`)); // `\`
    writeln(dirName(`\\\`)); // `\`
    writeln(dirName(`d:`)); // `d:`
    writeln(dirName(`d:file`)); // `d:`
    writeln(dirName(`d:\`)); // `d:\`
    writeln(dirName(`d:\file`)); // `d:\`
    writeln(dirName(`d:\dir\file`)); // `d:\dir`
    writeln(dirName(`\\server\share\dir\file`)); // `\\server\share\dir`
    writeln(dirName(`\\server\share\file`)); // `\\server\share`
    writeln(dirName(`\\server\share\`)); // `\\server\share`
    writeln(dirName(`\\server\share`)); // `\\server\share`
}

```
 
  auto **rootName**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **rootName**(C)(C[] path)  
 Constraints: if (isSomeChar!C); 
 
Returns the root directory of the specified path, or `null` if the path is not rooted. 



Parameters:


|  |  |
| --- | --- |
| R `path` | A path name. |


 
Returns:
A slice of `path`.
 
Examples:


```
assert(rootName("") is null);
assert(rootName("foo") is null);
writeln(rootName("/")); // "/"
writeln(rootName("/foo/bar")); // "/"

version (Windows)
{
    assert(rootName("d:foo") is null);
    writeln(rootName(`d:\foo`)); // `d:\`
    writeln(rootName(`\\server\share\foo`)); // `\\server\share`
    writeln(rootName(`\\server\share`)); // `\\server\share`
}

```
 
  auto **driveName**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **driveName**(C)(C[] path)  
 Constraints: if (isSomeChar!C); 
 
Get the drive portion of a path. 



Parameters:


|  |  |
| --- | --- |
| R `path` | string or range of characters |


 
Returns:
A slice of `path` that is the drive, or an empty range if the drive is not specified. In the case of UNC paths, the network share is returned. Always returns an empty range on POSIX.
 
Examples:


```
import std.range : empty;
version (Posix)  assert(driveName("c:/foo").empty);
version (Windows)
{
    assert(driveName(`dir\file`).empty);
    writeln(driveName(`d:file`)); // "d:"
    writeln(driveName(`d:\file`)); // "d:"
    writeln(driveName("d:")); // "d:"
    writeln(driveName(`\\server\share\file`)); // `\\server\share`
    writeln(driveName(`\\server\share\`)); // `\\server\share`
    writeln(driveName(`\\server\share`)); // `\\server\share`

    static assert(driveName(`d:\file`) == "d:");
}

```
 
  auto **stripDrive**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **stripDrive**(C)(C[] path)  
 Constraints: if (isSomeChar!C); 
 
Strips the drive from a Windows path. On POSIX, the path is returned unaltered. 



Parameters:


|  |  |
| --- | --- |
| R `path` | A pathname |


 
Returns:
A slice of path without the drive component.
 
Examples:


```
version (Windows)
{
    writeln(stripDrive(`d:\dir\file`)); // `\dir\file`
    writeln(stripDrive(`\\server\share\dir\file`)); // `\dir\file`
}

```
 
  auto **extension**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); 
 

Parameters:


|  |  |
| --- | --- |
| R `path` | A path name. |


 
Returns:
The extension part of a file name, including the dot. If there is no extension, `null` is returned.
 
Examples:


```
import std.range : empty;
assert(extension("file").empty);
writeln(extension("file.")); // "."
writeln(extension("file.ext"w)); // ".ext"
writeln(extension("file.ext1.ext2"d)); // ".ext2"
assert(extension(".foo".dup).empty);
writeln(extension(".foo.ext"w.dup)); // ".ext"

static assert(extension("file").empty);
static assert(extension("file.ext") == ".ext");

```
 
  auto **stripExtension**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R);   
  
auto **stripExtension**(C)(C[] path)  
 Constraints: if (isSomeChar!C); 
 
Remove extension from path. 



Parameters:


|  |  |
| --- | --- |
| R `path` | string or range to be sliced |


 
Returns:
slice of path with the extension (if any) stripped off
 
Examples:


```
writeln(stripExtension("file")); // "file"
writeln(stripExtension("file.ext")); // "file"
writeln(stripExtension("file.ext1.ext2")); // "file.ext1"
writeln(stripExtension("file.")); // "file"
writeln(stripExtension(".file")); // ".file"
writeln(stripExtension(".file.ext")); // ".file"
writeln(stripExtension("dir/file.ext")); // "dir/file"

```
 
  immutable(C1)[] **setExtension**(C1, C2)(in C1[] path, in C2[] ext)  
 Constraints: if (isSomeChar!C1 && !is(C1 == immutable) && is(immutable(C1) == immutable(C2)));   
  
immutable(C1)[] **setExtension**(C1, C2)(immutable(C1)[] path, const(C2)[] ext)  
 Constraints: if (isSomeChar!C1 && is(immutable(C1) == immutable(C2))); 
 
Sets or replaces an extension. 


If the filename already has an extension, it is replaced. If not, the extension is simply appended to the filename. Including a leading dot in `ext` is optional.   
  
 If the extension is empty, this function is equivalent to [`stripExtension`](#stripExtension).   
  
 This function normally allocates a new string (the possible exception being the case when path is immutable and doesn't already have an extension). 

 
Parameters:


|  |  |
| --- | --- |
| C1[] `path` | A path name |
| C2[] `ext` | The new extension |


 
Returns:
A string containing the path given by `path`, but where the extension has been set to `ext`. 
 
See Also:

[`withExtension`](#withExtension) which does not allocate and returns a lazy range.
 
Examples:


```
writeln(setExtension("file", "ext")); // "file.ext"
writeln(setExtension("file"w, ".ext"w)); // "file.ext"
writeln(setExtension("file."d, "ext"d)); // "file.ext"
writeln(setExtension("file.", ".ext")); // "file.ext"
writeln(setExtension("file.old"w, "new"w)); // "file.new"
writeln(setExtension("file.old"d, ".new"d)); // "file.new"

```
 
  auto **withExtension**(R, C)(R path, C[] ext)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R && isSomeChar!C);   
  
auto **withExtension**(C1, C2)(C1[] path, C2[] ext)  
 Constraints: if (isSomeChar!C1 && isSomeChar!C2); 
 
Replace existing extension on filespec with new one. 



Parameters:


|  |  |
| --- | --- |
| R `path` | string or random access range representing a filespec |
| C[] `ext` | the new extension |


 
Returns:
Range with `path`'s extension (if any) replaced with `ext`. The element encoding type of the returned range will be the same as `path`'s. 
 
See Also:
[`setExtension`](#setExtension)
 
Examples:


```
import std.array;
writeln(withExtension("file", "ext").array); // "file.ext"
writeln(withExtension("file"w, ".ext"w).array); // "file.ext"
writeln(withExtension("file.ext"w, ".").array); // "file."

import std.utf : byChar, byWchar;
writeln(withExtension("file".byChar, "ext").array); // "file.ext"
writeln(withExtension("file"w.byWchar, ".ext"w).array); // "file.ext"w
writeln(withExtension("file.ext"w.byWchar, ".").array); // "file."w

```
 
  immutable(C1)[] **defaultExtension**(C1, C2)(in C1[] path, in C2[] ext)  
 Constraints: if (isSomeChar!C1 && is(immutable(C1) == immutable(C2))); 
 

Parameters:


|  |  |
| --- | --- |
| C1[] `path` | A path name. |
| C2[] `ext` | The default extension to use. |


 
Returns:
The path given by `path`, with the extension given by `ext` appended if the path doesn't already have one. Including the dot in the extension is optional. This function always allocates a new string, except in the case when path is immutable and already has an extension.
 
Examples:


```
writeln(defaultExtension("file", "ext")); // "file.ext"
writeln(defaultExtension("file", ".ext")); // "file.ext"
writeln(defaultExtension("file.", "ext")); // "file."
writeln(defaultExtension("file.old", "new")); // "file.old"
writeln(defaultExtension("file.old", ".new")); // "file.old"

```
 
  auto **withDefaultExtension**(R, C)(R path, C[] ext)  
 Constraints: if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R && isSomeChar!C);   
  
auto **withDefaultExtension**(C1, C2)(C1[] path, C2[] ext)  
 Constraints: if (isSomeChar!C1 && isSomeChar!C2); 
 
Set the extension of `path` to `ext` if `path` doesn't have one. 



Parameters:


|  |  |
| --- | --- |
| R `path` | filespec as string or range |
| C[] `ext` | extension, may have leading '.' |


 
Returns:
range with the result
 
Examples:


```
import std.array;
writeln(withDefaultExtension("file", "ext").array); // "file.ext"
writeln(withDefaultExtension("file"w, ".ext").array); // "file.ext"w
writeln(withDefaultExtension("file.", "ext").array); // "file."
writeln(withDefaultExtension("file", "").array); // "file."

import std.utf : byChar, byWchar;
writeln(withDefaultExtension("file".byChar, "ext").array); // "file.ext"
writeln(withDefaultExtension("file"w.byWchar, ".ext").array); // "file.ext"w
writeln(withDefaultExtension("file.".byChar, "ext"d).array); // "file."
writeln(withDefaultExtension("file".byChar, "").array); // "file."

```
 
  immutable(ElementEncodingType!(ElementType!Range))[] **buildPath**(Range)(Range segments)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range));   
  
pure nothrow @safe immutable(C)[] **buildPath**(C)(const(C)[][] paths...)  
 Constraints: if (isSomeChar!C); 
 
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`](#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. 

 
Parameters:


|  |  |
| --- | --- |
| Range `segments` | An [input range](std_range_primitives#isInputRange) of segments to assemble the path from. |


 
Returns:
The assembled path.
 
Examples:


```
version (Posix)
{
    writeln(buildPath("foo", "bar", "baz")); // "foo/bar/baz"
    writeln(buildPath("/foo/", "bar/baz")); // "/foo/bar/baz"
    writeln(buildPath("/foo", "/bar")); // "/bar"
}

version (Windows)
{
    writeln(buildPath("foo", "bar", "baz")); // `foo\bar\baz`
    writeln(buildPath(`c:\foo`, `bar\baz`)); // `c:\foo\bar\baz`
    writeln(buildPath("foo", `d:\bar`)); // `d:\bar`
    writeln(buildPath("foo", `\bar`)); // `\bar`
    writeln(buildPath(`c:\foo`, `\bar`)); // `c:\bar`
}

```
 
  auto **chainPath**(R1, R2, Ranges...)(R1 r1, R2 r2, Ranges ranges)  
 Constraints: if ((isRandomAccessRange!R1 && hasSlicing!R1 && hasLength!R1 && isSomeChar!(ElementType!R1) || isNarrowString!R1 && !isConvertibleToString!R1) && (isRandomAccessRange!R2 && hasSlicing!R2 && hasLength!R2 && isSomeChar!(ElementType!R2) || isNarrowString!R2 && !isConvertibleToString!R2) && (Ranges.length == 0 || is(typeof(chainPath(r2, ranges))))); 
 
Concatenate path segments together to form one path. 



Parameters:


|  |  |
| --- | --- |
| R1 `r1` | first segment |
| R2 `r2` | second segment |
| Ranges `ranges` | 0 or more segments |


 
Returns:
Lazy range which is the concatenation of r1, r2 and ranges with path separators. The resulting element type is that of r1. 
 
See Also:
[`buildPath`](#buildPath)
 
Examples:


```
import std.array;
version (Posix)
{
    writeln(chainPath("foo", "bar", "baz").array); // "foo/bar/baz"
    writeln(chainPath("/foo/", "bar/baz").array); // "/foo/bar/baz"
    writeln(chainPath("/foo", "/bar").array); // "/bar"
}

version (Windows)
{
    writeln(chainPath("foo", "bar", "baz").array); // `foo\bar\baz`
    writeln(chainPath(`c:\foo`, `bar\baz`).array); // `c:\foo\bar\baz`
    writeln(chainPath("foo", `d:\bar`).array); // `d:\bar`
    writeln(chainPath("foo", `\bar`).array); // `\bar`
    writeln(chainPath(`c:\foo`, `\bar`).array); // `c:\bar`
}

import std.utf : byChar;
version (Posix)
{
    writeln(chainPath("foo", "bar", "baz").array); // "foo/bar/baz"
    writeln(chainPath("/foo/".byChar, "bar/baz").array); // "/foo/bar/baz"
    writeln(chainPath("/foo", "/bar".byChar).array); // "/bar"
}

version (Windows)
{
    writeln(chainPath("foo", "bar", "baz").array); // `foo\bar\baz`
    writeln(chainPath(`c:\foo`.byChar, `bar\baz`).array); // `c:\foo\bar\baz`
    writeln(chainPath("foo", `d:\bar`).array); // `d:\bar`
    writeln(chainPath("foo", `\bar`.byChar).array); // `\bar`
    writeln(chainPath(`c:\foo`, `\bar`w).array); // `c:\bar`
}

```
 
  pure nothrow @safe immutable(C)[] **buildNormalizedPath**(C)(const(C[])[] paths...)  
 Constraints: if (isSomeChar!C); 
 
Performs the same task as [`buildPath`](#buildPath), while at the same time resolving current/parent directory symbols (`"."` and `".."`) and removing superfluous directory separators. It will return "." if the path leads to the starting directory. On Windows, slashes are replaced with backslashes. 


Using buildNormalizedPath on null paths will always return null.   
  
 Note that this function does not resolve symbolic links.   
  
 This function always allocates memory to hold the resulting path. Use [`asNormalizedPath`](#asNormalizedPath) to not allocate memory. 

 
Parameters:


|  |  |
| --- | --- |
| const(C[])[] `paths` | An array of paths to assemble. |


 
Returns:
The assembled path.
 
Examples:


```
writeln(buildNormalizedPath("foo", "..")); // "."

version (Posix)
{
    writeln(buildNormalizedPath("/foo/./bar/..//baz/")); // "/foo/baz"
    writeln(buildNormalizedPath("../foo/.")); // "../foo"
    writeln(buildNormalizedPath("/foo", "bar/baz/")); // "/foo/bar/baz"
    writeln(buildNormalizedPath("/foo", "/bar/..", "baz")); // "/baz"
    writeln(buildNormalizedPath("foo/./bar", "../../", "../baz")); // "../baz"
    writeln(buildNormalizedPath("/foo/./bar", "../../baz")); // "/baz"
}

version (Windows)
{
    writeln(buildNormalizedPath(`c:\foo\.\bar/..\\baz\`)); // `c:\foo\baz`
    writeln(buildNormalizedPath(`..\foo\.`)); // `..\foo`
    writeln(buildNormalizedPath(`c:\foo`, `bar\baz\`)); // `c:\foo\bar\baz`
    writeln(buildNormalizedPath(`c:\foo`, `bar/..`)); // `c:\foo`
    assert(buildNormalizedPath(`\\server\share\foo`, `..\bar`) ==
            `\\server\share\bar`);
}

```
 
  auto **asNormalizedPath**(R)(R path)  
 Constraints: if (isSomeChar!(ElementEncodingType!R) && (isRandomAccessRange!R && hasSlicing!R && hasLength!R || isNarrowString!R) && !isConvertibleToString!R); 
 
Normalize a path by resolving current/parent directory symbols (`"."` and `".."`) and removing superfluous directory separators. It will return "." if the path leads to the starting directory. On Windows, slashes are replaced with backslashes. 


Using asNormalizedPath on empty paths will always return an empty path.   
  
 Does not resolve symbolic links.   
  
 This function always allocates memory to hold the resulting path. Use [`buildNormalizedPath`](#buildNormalizedPath) to allocate memory and return a string. 

 
Parameters:


|  |  |
| --- | --- |
| R `path` | string or random access range representing the path to normalize |


 
Returns:
normalized path as a forward range
 
Examples:


```
import std.array;
writeln(asNormalizedPath("foo/..").array); // "."

version (Posix)
{
    writeln(asNormalizedPath("/foo/./bar/..//baz/").array); // "/foo/baz"
    writeln(asNormalizedPath("../foo/.").array); // "../foo"
    writeln(asNormalizedPath("/foo/bar/baz/").array); // "/foo/bar/baz"
    writeln(asNormalizedPath("/foo/./bar/../../baz").array); // "/baz"
}

version (Windows)
{
    writeln(asNormalizedPath(`c:\foo\.\bar/..\\baz\`).array); // `c:\foo\baz`
    writeln(asNormalizedPath(`..\foo\.`).array); // `..\foo`
    writeln(asNormalizedPath(`c:\foo\bar\baz\`).array); // `c:\foo\bar\baz`
    writeln(asNormalizedPath(`c:\foo\bar/..`).array); // `c:\foo`
    assert(asNormalizedPath(`\\server\share\foo\..\bar`).array ==
            `\\server\share\bar`);
}

```
 
  auto **pathSplitter**(R)(R path)  
 Constraints: if ((isRandomAccessRange!R && hasSlicing!R || isNarrowString!R) && !isConvertibleToString!R); 
 
Slice up a path into its elements. 



Parameters:


|  |  |
| --- | --- |
| R `path` | string or slicable random access range |


 
Returns:
bidirectional range of slices of `path`

 
Examples:


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

assert(equal(pathSplitter("/"), ["/"]));
assert(equal(pathSplitter("/foo/bar"), ["/", "foo", "bar"]));
assert(equal(pathSplitter("foo/../bar//./"), ["foo", "..", "bar", "."]));

version (Posix)
{
    assert(equal(pathSplitter("//foo/bar"), ["/", "foo", "bar"]));
}

version (Windows)
{
    assert(equal(pathSplitter(`foo\..\bar\/.\`), ["foo", "..", "bar", "."]));
    assert(equal(pathSplitter("c:"), ["c:"]));
    assert(equal(pathSplitter(`c:\foo\bar`), [`c:\`, "foo", "bar"]));
    assert(equal(pathSplitter(`c:foo\bar`), ["c:foo", "bar"]));
}

```
 
  bool **isRooted**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); 
 
Determines whether a path starts at a root directory. 



Parameters:


|  |  |
| --- | --- |
| R `path` | A path name. |


 
Returns:
Whether a path starts at a root directory. On POSIX, this function returns true if and only if the path starts with a slash (/). On Windows, this function returns true if the path starts at the root directory of the current drive, of some other drive, or of a network drive.
 
Examples:


```
version (Posix)
{
    assert( isRooted("/"));
    assert( isRooted("/foo"));
    assert(!isRooted("foo"));
    assert(!isRooted("../foo"));
}

version (Windows)
{
    assert( isRooted(`\`));
    assert( isRooted(`\foo`));
    assert( isRooted(`d:\foo`));
    assert( isRooted(`\\foo\bar`));
    assert(!isRooted("foo"));
    assert(!isRooted("d:foo"));
}

```
 
  pure nothrow @safe bool **isAbsolute**(R)(R path)  
 Constraints: if (isRandomAccessRange!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)); 
 
Determines whether a path is absolute or not. 



Parameters:


|  |  |
| --- | --- |
| R `path` | A path name. |


 
Returns:
Whether a path is absolute or not. 
 
Example
 On POSIX, an absolute path starts at the root directory. (In fact, `_isAbsolute` is just an alias for [`isRooted`](#isRooted).) 


```
version (Posix)
{
    assert(isAbsolute("/"));
    assert(isAbsolute("/foo"));
    assert(!isAbsolute("foo"));
    assert(!isAbsolute("../foo"));
}

```
 On Windows, an absolute path starts at the root directory of a specific drive. Hence, it must start with `d:\` or `d:/`, where `d` is the drive letter. Alternatively, it may be a network path, i.e. a path starting with a double (back)slash. 
```
version (Windows)
{
    assert(isAbsolute(`d:\`));
    assert(isAbsolute(`d:\foo`));
    assert(isAbsolute(`\\foo\bar`));
    assert(!isAbsolute(`\`));
    assert(!isAbsolute(`\foo`));
    assert(!isAbsolute("d:foo"));
}

```
  pure @safe string **absolutePath**(string path, lazy string base = getcwd());  
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. 

 
Parameters:


|  |  |
| --- | --- |
| string `path` | the relative path to transform |
| string `base` | the base directory of the relative path |


 
Returns:
string of transformed path 
 
Throws:

`Exception` if the specified base directory is not absolute. 
 
See Also:

[`asAbsolutePath`](#asAbsolutePath) which does not allocate
 
Examples:


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

version (Windows)
{
    writeln(absolutePath(`some\file`, `c:\foo\bar`)); // `c:\foo\bar\some\file`
    writeln(absolutePath(`..\file`, `c:\foo\bar`)); // `c:\foo\bar\..\file`
    writeln(absolutePath(`c:\some\file`, `c:\foo\bar`)); // `c:\some\file`
    writeln(absolutePath(`\`, `c:\`)); // `c:\`
    writeln(absolutePath(`\some\file`, `c:\foo\bar`)); // `c:\some\file`
}

```
 
  auto **asAbsolutePath**(R)(R path)  
 Constraints: if ((isRandomAccessRange!R && isSomeChar!(ElementType!R) || isNarrowString!R) && !isConvertibleToString!R); 
 
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 the current working directory, which allocates memory.

 

 
Parameters:


|  |  |
| --- | --- |
| R `path` | the relative path to transform |


 
Returns:
the transformed path as a lazy range 
 
See Also:

[`absolutePath`](#absolutePath) which returns an allocated string
 
Examples:


```
import std.array;
writeln(asAbsolutePath(cast(string)null).array); // ""
version (Posix)
{
    writeln(asAbsolutePath("/foo").array); // "/foo"
}
version (Windows)
{
    writeln(asAbsolutePath("c:/foo").array); // "c:/foo"
}
asAbsolutePath("foo");

```
 
  string **relativePath**(CaseSensitive cs = CaseSensitive.osDefault)(string path, lazy string base = getcwd());  
Translates `path` into a relative path. 


The returned path is relative to `base`, which is by default taken to be the current working directory. If specified, `base` must be an absolute path, and it is always assumed to refer to a directory. If `path` and `base` refer to the same directory, the function returns `.`.   
  
 The following algorithm is used: 1. If `path` is a relative directory, return it unaltered.
2. Find a common root between `path` and `base`. If there is no common root, return `path` unaltered.
3. Prepare a string with as many `../` or `..\` as necessary to reach the common root from base path.
4. Append the remaining segments of `path` to the string and return.

   
  
 In the second step, path components are compared using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details.   
  
 This function allocates memory. 

 
Parameters:


|  |  |
| --- | --- |
| cs | Whether matching path name components against the base path should be case-sensitive or not. |
| string `path` | A path name. |
| string `base` | The base path to construct the relative path from. |


 
Returns:
The relative path. 
 
See Also:

[`asRelativePath`](#asRelativePath) which does not allocate memory 
 
Throws:

`Exception` if the specified base directory is not absolute.
 
Examples:


```
writeln(relativePath("foo")); // "foo"

version (Posix)
{
    writeln(relativePath("foo", "/bar")); // "foo"
    writeln(relativePath("/foo/bar", "/foo/bar")); // "."
    writeln(relativePath("/foo/bar", "/foo/baz")); // "../bar"
    writeln(relativePath("/foo/bar/baz", "/foo/woo/wee")); // "../../bar/baz"
    writeln(relativePath("/foo/bar/baz", "/foo/bar")); // "baz"
}
version (Windows)
{
    writeln(relativePath("foo", `c:\bar`)); // "foo"
    writeln(relativePath(`c:\foo\bar`, `c:\foo\bar`)); // "."
    writeln(relativePath(`c:\foo\bar`, `c:\foo\baz`)); // `..\bar`
    writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`)); // `..\..\bar\baz`
    writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\bar`)); // "baz"
    writeln(relativePath(`c:\foo\bar`, `d:\foo`)); // `c:\foo\bar`
}

```
 
  auto **asRelativePath**(CaseSensitive cs = CaseSensitive.osDefault, R1, R2)(R1 path, R2 base)  
 Constraints: if ((isNarrowString!R1 || isRandomAccessRange!R1 && hasSlicing!R1 && isSomeChar!(ElementType!R1) && !isConvertibleToString!R1) && (isNarrowString!R2 || isRandomAccessRange!R2 && hasSlicing!R2 && isSomeChar!(ElementType!R2) && !isConvertibleToString!R2)); 
 
Transforms `path` into a path relative to `base`. 


The returned path is relative to `base`, which is usually the current working directory. `base` must be an absolute path, and it is always assumed to refer to a directory. If `path` and `base` refer to the same directory, the function returns `'.'`.   
  
 The following algorithm is used: 1. If `path` is a relative directory, return it unaltered.
2. Find a common root between `path` and `base`. If there is no common root, return `path` unaltered.
3. Prepare a string with as many `../` or `..\` as necessary to reach the common root from base path.
4. Append the remaining segments of `path` to the string and return.

   
  
 In the second step, path components are compared using `filenameCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCmp`](#filenameCmp) documentation for details. 

 
Parameters:


|  |  |
| --- | --- |
| R1 `path` | path to transform |
| R2 `base` | absolute path |
| cs | whether filespec comparisons are sensitive or not; defaults to `CaseSensitive.osDefault` |


 
Returns:
a random access range of the transformed path 
 
See Also:
[`relativePath`](#relativePath)
 
Examples:


```
import std.array;
version (Posix)
{
    writeln(asRelativePath("foo", "/bar").array); // "foo"
    writeln(asRelativePath("/foo/bar", "/foo/bar").array); // "."
    writeln(asRelativePath("/foo/bar", "/foo/baz").array); // "../bar"
    writeln(asRelativePath("/foo/bar/baz", "/foo/woo/wee").array); // "../../bar/baz"
    writeln(asRelativePath("/foo/bar/baz", "/foo/bar").array); // "baz"
}
else version (Windows)
{
    writeln(asRelativePath("foo", `c:\bar`).array); // "foo"
    writeln(asRelativePath(`c:\foo\bar`, `c:\foo\bar`).array); // "."
    writeln(asRelativePath(`c:\foo\bar`, `c:\foo\baz`).array); // `..\bar`
    writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`).array); // `..\..\bar\baz`
    writeln(asRelativePath(`c:/foo/bar/baz`, `c:\foo\woo\wee`).array); // `..\..\bar\baz`
    writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\bar`).array); // "baz"
    writeln(asRelativePath(`c:\foo\bar`, `d:\foo`).array); // `c:\foo\bar`
    writeln(asRelativePath(`\\foo\bar`, `c:\foo`).array); // `\\foo\bar`
}
else
    static assert(0);

```
 
  pure nothrow @safe int **filenameCharCmp**(CaseSensitive cs = CaseSensitive.osDefault)(dchar a, dchar b);  
Compares filename characters. 


This function can perform a case-sensitive or a case-insensitive comparison. This is controlled through the `cs` template parameter which, if not specified, is given by [`CaseSensitive`](#CaseSensitive)`.osDefault`.   
  
 On Windows, the backslash and slash characters (`\` and `/`) are considered equal. 

 
Parameters:


|  |  |
| --- | --- |
| cs | Case-sensitivity of the comparison. |
| dchar `a` | A filename character. |
| dchar `b` | A filename character. |


 
Returns:

`< 0` if `a < b`, `0` if `a == b`, and `> 0` if `a > b`.
 
Examples:


```
writeln(filenameCharCmp('a', 'a')); // 0
assert(filenameCharCmp('a', 'b') < 0);
assert(filenameCharCmp('b', 'a') > 0);

version (linux)
{
    // Same as calling filenameCharCmp!(CaseSensitive.yes)(a, b)
    assert(filenameCharCmp('A', 'a') < 0);
    assert(filenameCharCmp('a', 'A') > 0);
}
version (Windows)
{
    // Same as calling filenameCharCmp!(CaseSensitive.no)(a, b)
    writeln(filenameCharCmp('a', 'A')); // 0
    assert(filenameCharCmp('a', 'B') < 0);
    assert(filenameCharCmp('A', 'b') < 0);
}

```
 
  int **filenameCmp**(CaseSensitive cs = CaseSensitive.osDefault, Range1, Range2)(Range1 filename1, Range2 filename2)  
 Constraints: if (isInputRange!Range1 && !isInfinite!Range1 && isSomeChar!(ElementEncodingType!Range1) && !isConvertibleToString!Range1 && isInputRange!Range2 && !isInfinite!Range2 && isSomeChar!(ElementEncodingType!Range2) && !isConvertibleToString!Range2); 
 
Compares file names and returns 


Individual characters are compared using `filenameCharCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not.   
  
 Treatment of invalid UTF encodings is implementation defined. 

 
Parameters:


|  |  |
| --- | --- |
| cs | case sensitivity |
| Range1 `filename1` | range for first file name |
| Range2 `filename2` | range for second file name |


 
Returns:

`< 0` if `filename1 < filename2`, `0` if `filename1 == filename2` and `> 0` if `filename1 > filename2`. 
 
See Also:
[`filenameCharCmp`](#filenameCharCmp)
 
Examples:


```
writeln(filenameCmp("abc", "abc")); // 0
assert(filenameCmp("abc", "abd") < 0);
assert(filenameCmp("abc", "abb") > 0);
assert(filenameCmp("abc", "abcd") < 0);
assert(filenameCmp("abcd", "abc") > 0);

version (linux)
{
    // Same as calling filenameCmp!(CaseSensitive.yes)(filename1, filename2)
    assert(filenameCmp("Abc", "abc") < 0);
    assert(filenameCmp("abc", "Abc") > 0);
}
version (Windows)
{
    // Same as calling filenameCmp!(CaseSensitive.no)(filename1, filename2)
    writeln(filenameCmp("Abc", "abc")); // 0
    writeln(filenameCmp("abc", "Abc")); // 0
    assert(filenameCmp("Abc", "abD") < 0);
    assert(filenameCmp("abc", "AbB") > 0);
}

```
 
  pure nothrow @safe bool **globMatch**(CaseSensitive cs = CaseSensitive.osDefault, C, Range)(Range path, const(C)[] pattern)  
 Constraints: if (isForwardRange!Range && !isInfinite!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range && isSomeChar!C && is(immutable(C) == immutable(ElementEncodingType!Range))); 
 
Matches a pattern against a path. 


Some characters of pattern have a special meaning (they are *meta-characters*) and can't be escaped. These are:   
  
 

|  |  |
| --- | --- |
| `*` | Matches 0 or more instances of any character. |
| `?` | Matches exactly one instance of any character. |
| `[`*chars*`]` | Matches one instance of any character that appears between the brackets. |
| `[!`*chars*`]` | Matches one instance of any character that does not appear between the brackets after the exclamation mark. |
| `{`*string1*`,`*string2*`,`…`}` | Matches either of the specified strings. |

   
  
 Individual characters are compared using `filenameCharCmp!cs`, where `cs` is an optional template parameter determining whether the comparison is case sensitive or not. See the [`filenameCharCmp`](#filenameCharCmp) documentation for details.   
  
 Note that directory separators and dots don't stop a meta-character from matching further portions of the path. 

 
Parameters:


|  |  |
| --- | --- |
| cs | Whether the matching should be case-sensitive |
| Range `path` | The path to be matched against |
| const(C)[] `pattern` | The glob pattern |


 
Returns:

`true` if pattern matches path, `false` otherwise. 
 
See Also:
[Wikipedia: glob (programming)](http://en.wikipedia.org/wiki/Glob_%28programming%29)
 
Examples:


```
assert(globMatch("foo.bar", "*"));
assert(globMatch("foo.bar", "*.*"));
assert(globMatch(`foo/foo\bar`, "f*b*r"));
assert(globMatch("foo.bar", "f???bar"));
assert(globMatch("foo.bar", "[fg]???bar"));
assert(globMatch("foo.bar", "[!gh]*bar"));
assert(globMatch("bar.fooz", "bar.{foo,bif}z"));
assert(globMatch("bar.bifz", "bar.{foo,bif}z"));

version (Windows)
{
    // Same as calling globMatch!(CaseSensitive.no)(path, pattern)
    assert(globMatch("foo", "Foo"));
    assert(globMatch("Goo.bar", "[fg]???bar"));
}
version (linux)
{
    // Same as calling globMatch!(CaseSensitive.yes)(path, pattern)
    assert(!globMatch("foo", "Foo"));
    assert(!globMatch("Goo.bar", "[fg]???bar"));
}

```
 
  bool **isValidFilename**(Range)(Range filename)  
 Constraints: if ((isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range); 
 
Checks that the given file or directory name is valid. 


The maximum length of `filename` is given by the constant `core.stdc.stdio.FILENAME_MAX`. (On Windows, this number is defined as the maximum number of UTF-16 code points, and the test will therefore only yield strictly correct results when `filename` is a string of `wchar`s.)   
  
 On Windows, the following criteria must be satisfied ([source](http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx)): * `filename` must not contain any characters whose integer representation is in the range 0-31.
* `filename` must not contain any of the following *reserved characters*: `<>:"/\|?*`
* `filename` may not end with a space (`' '`) or a period (`'.'`).

   
  
 On POSIX, `filename` may not contain a forward slash (`'/'`) or the null character (`'\0'`). 

 
Parameters:


|  |  |
| --- | --- |
| Range `filename` | string to check |


 
Returns:

`true` if and only if `filename` is not empty, not too long, and does not contain invalid characters.
 
Examples:


```
import std.utf : byCodeUnit;

assert(isValidFilename("hello.exe".byCodeUnit));

```
 
  bool **isValidPath**(Range)(Range path)  
 Constraints: if ((isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range); 
 
Checks whether `path` is a valid path. 


Generally, this function checks that `path` is not empty, and that each component of the path either satisfies [`isValidFilename`](#isValidFilename) or is equal to `"."` or `".."`.   
  
 **It does *not* check whether the path points to an existing file or directory; use [`std.file.exists`](std_file#exists) for this purpose.**   
  
 On Windows, some special rules apply: * If the second character of `path` is a colon (`':'`), the first character is interpreted as a drive letter, and must be in the range A-Z (case insensitive).
* If `path` is on the form `\\*server*\*share*\...` (UNC path), [`isValidFilename`](#isValidFilename) is applied to *server* and *share* as well.
* If `path` starts with `\\?\` (long UNC path), the only requirement for the rest of the string is that it does not contain the null character.
* If `path` starts with `\\.\` (Win32 device namespace) this function returns `false`; such paths are beyond the scope of this module.

 

 
Parameters:


|  |  |
| --- | --- |
| Range `path` | string or Range of characters to check |


 
Returns:
true if `path` is a valid path.
 
Examples:


```
assert(isValidPath("/foo/bar"));
assert(!isValidPath("/foo\0/bar"));
assert(isValidPath("/"));
assert(isValidPath("a"));

version (Windows)
{
    assert(isValidPath(`c:\`));
    assert(isValidPath(`c:\foo`));
    assert(isValidPath(`c:\foo\.\bar\\\..\`));
    assert(!isValidPath(`!:\foo`));
    assert(!isValidPath(`c::\foo`));
    assert(!isValidPath(`c:\foo?`));
    assert(!isValidPath(`c:\foo.`));

    assert(isValidPath(`\\server\share`));
    assert(isValidPath(`\\server\share\foo`));
    assert(isValidPath(`\\server\share\\foo`));
    assert(!isValidPath(`\\\server\share\foo`));
    assert(!isValidPath(`\\server\\share\foo`));
    assert(!isValidPath(`\\ser*er\share\foo`));
    assert(!isValidPath(`\\server\sha?e\foo`));
    assert(!isValidPath(`\\server\share\|oo`));

    assert(isValidPath(`\\?\<>:"?*|/\..\.`));
    assert(!isValidPath("\\\\?\\foo\0bar"));

    assert(!isValidPath(`\\.\PhysicalDisk1`));
    assert(!isValidPath(`\\`));
}

import std.utf : byCodeUnit;
assert(isValidPath("/foo/bar".byCodeUnit));

```
 
  nothrow @safe string **expandTilde**(string inputPath);  
Performs tilde expansion in paths on POSIX systems. On Windows, this function does nothing. 


There are two ways of using tilde expansion in a path. One involves using the tilde alone or followed by a path separator. In this case, the tilde will be expanded with the value of the environment variable `HOME`. The second way is putting a username after the tilde (i.e. `~john/Mail`). Here, the username will be searched for in the user database (i.e. `/etc/passwd` on Unix systems) and will expand to whatever path is stored there. The username is considered the string after the tilde ending at the first instance of a path separator.   
  
 Note that using the `~user` syntax may give different values from just `~` if the environment variable doesn't match the value stored in the user database.   
  
 When the environment variable version is used, the path won't be modified if the environment variable doesn't exist or it is empty. When the database version is used, the path won't be modified if the user doesn't exist in the database or there is not enough memory to perform the query.   
  
 This function performs several memory allocations. 

 
Parameters:


|  |  |
| --- | --- |
| string `inputPath` | The path name to expand. |


 
Returns:

`inputPath` with the tilde expanded, or just `inputPath` if it could not be expanded. For Windows, `expandTilde` merely returns its argument `inputPath`. 
 
Example


```
void processFile(string path)
{
    // Allow calling this function with paths such as ~/foo
    auto fullPath = expandTilde(path);
    ...
}

```
 
Examples:


```
version (Posix)
{
    import std.process : environment;

    auto oldHome = environment["HOME"];
    scope(exit) environment["HOME"] = oldHome;

    environment["HOME"] = "dmd/test";
    writeln(expandTilde("~/")); // "dmd/test/"
    writeln(expandTilde("~")); // "dmd/test"
}

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_path.html>

std.random
==========

 Facilities for random number generation. 


 

| Category | Functions |
| --- | --- |
| Uniform sampling | [`uniform`](#uniform) [`uniform01`](#uniform01) [`uniformDistribution`](#uniformDistribution) |
| Element sampling | [`choice`](#choice) [`dice`](#dice) |
| Range sampling | [`randomCover`](#randomCover) [`randomSample`](#randomSample) |
| Default Random Engines | [`rndGen`](#rndGen) [`Random`](#Random) [`unpredictableSeed`](#unpredictableSeed) |
| Linear Congruential Engines | [`MinstdRand`](#MinstdRand) [`MinstdRand0`](#MinstdRand0) [`LinearCongruentialEngine`](#LinearCongruentialEngine) |
| Mersenne Twister Engines | [`Mt19937`](#Mt19937) [`Mt19937_64`](#Mt19937_64) [`MersenneTwisterEngine`](#MersenneTwisterEngine) |
| Xorshift Engines | [`Xorshift`](#Xorshift) [`XorshiftEngine`](#XorshiftEngine) [`Xorshift32`](#Xorshift32) [`Xorshift64`](#Xorshift64) [`Xorshift96`](#Xorshift96) [`Xorshift128`](#Xorshift128) [`Xorshift160`](#Xorshift160) [`Xorshift192`](#Xorshift192) |
| Shuffle | [`partialShuffle`](#partialShuffle) [`randomShuffle`](#randomShuffle) |
| Traits | [`isSeedable`](#isSeedable) [`isUniformRNG`](#isUniformRNG) |

   
  
 Disclaimer: The random number generators and API provided in this module are not designed to be cryptographically secure, and are therefore unsuitable for cryptographic or security-related purposes such as generating authentication tokens or network sequence numbers. For such needs, please use a reputable cryptographic library instead.   
  
 The new-style generator objects hold their own state so they are immune of threading issues. The generators feature a number of well-known and well-documented methods of generating random numbers. An overall fast and reliable means to generate random numbers is the Mt19937 generator, which derives its name from "[Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) with a period of 2 to the power of 19937". In memory-constrained situations, [linear congruential generators](https://en.wikipedia.org/wiki/Linear_congruential_generator) such as `MinstdRand0` and `MinstdRand` might be useful. The standard library provides an alias Random for whichever generator it considers the most fit for the target environment.   
  
 In addition to random number generators, this module features distributions, which skew a generator's output statistical distribution in various ways. So far the uniform distribution for integers and real numbers have been implemented. 

 
Source
 [std/random.d](https://github.com/dlang/phobos/blob/master/std/random.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) Masahiro Nakagawa (Xorshift random generator) [Joseph Rushton Wakeling](http://braingam.es) (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from [mir-random](https://github.com/libmir/mir-random)) 
 
Credits
 The entire random number library architecture is derived from the excellent [C++0X](http://open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf) random number facility proposed by Jens Maurer and contributed to by researchers at the Fermi laboratory (excluding Xorshift).
 
enum bool **isUniformRNG**(Rng, ElementType);   
  
enum bool **isUniformRNG**(Rng);  
Test if Rng is a random-number generator. The overload taking a ElementType also makes sure that the Rng generates values of that type. 


A random-number generator has at least the following features: * it's an InputRange
* it has a 'bool isUniformRandom' field readable in CTFE


 
Examples:


```
struct NoRng
{
    @property uint front() {return 0;}
    @property bool empty() {return false;}
    void popFront() {}
}
static assert(!isUniformRNG!(NoRng));

struct validRng
{
    @property uint front() {return 0;}
    @property bool empty() {return false;}
    void popFront() {}

    enum isUniformRandom = true;
}
static assert(isUniformRNG!(validRng, uint));
static assert(isUniformRNG!(validRng));

```
 
  enum bool **isSeedable**(Rng, SeedType);   
  
enum bool **isSeedable**(Rng);  
Test if Rng is seedable. The overload taking a SeedType also makes sure that the Rng can be seeded with SeedType. 


A seedable random-number generator has the following additional features: * it has a 'seed(ElementType)' function


 
Examples:


```
struct validRng
{
    @property uint front() {return 0;}
    @property bool empty() {return false;}
    void popFront() {}

    enum isUniformRandom = true;
}
static assert(!isSeedable!(validRng, uint));
static assert(!isSeedable!(validRng));

struct seedRng
{
    @property uint front() {return 0;}
    @property bool empty() {return false;}
    void popFront() {}
    void seed(uint val){}
    enum isUniformRandom = true;
}
static assert(isSeedable!(seedRng, uint));
static assert(!isSeedable!(seedRng, ulong));
static assert(isSeedable!(seedRng));

```
 
  struct **LinearCongruentialEngine**(UIntType, UIntType a, UIntType c, UIntType m) if (isUnsigned!UIntType);  
Linear Congruential generator.



Examples:
Declare your own linear congruential engine 
```
alias CPP11LCG = LinearCongruentialEngine!(uint, 48271, 0, 2_147_483_647);

// seed with a constant
auto rnd = CPP11LCG(42);
auto n = rnd.front; // same for each run
writeln(n); // 2027382

```
 
 
Examples:
Declare your own linear congruential engine 
```
// glibc's LCG
alias GLibcLCG = LinearCongruentialEngine!(uint, 1103515245, 12345, 2_147_483_648);

// Seed with an unpredictable value
auto rnd = GLibcLCG(unpredictableSeed);
auto n = rnd.front; // different across runs

```
 
 
enum bool **isUniformRandom**;  
Mark this as a Rng

  enum bool **hasFixedRange**;  
Does this generator have a fixed range? (true).

  enum UIntType **min**;  
Lowest generated value (`1` if `c == 0`, `0` otherwise).

  enum UIntType **max**;  
Highest generated value (`modulus - 1`).

  enum UIntType **multiplier**;   
  
enum UIntType **increment**;   
  
enum UIntType **modulus**;  
The parameters of this distribution. The random number is x = (x \* multipler + increment) % modulus.

  pure nothrow @nogc @safe this(UIntType x0);  
Constructs a LinearCongruentialEngine generator seeded with `x0`.

  pure nothrow @nogc @safe void **seed**(UIntType x0 = 1);  
(Re)seeds the generator.

  pure nothrow @nogc @safe void **popFront**();  
Advances the random sequence.

  const pure nothrow @nogc @property @safe UIntType **front**();  
Returns the current number in the random sequence.

  const pure nothrow @nogc @property @safe typeof(this) **save**();  enum bool **empty**;  
Always `false` (random generators are infinite ranges).

    alias **MinstdRand0** = LinearCongruentialEngine!(uint, 16807u, 0u, 2147483647u).LinearCongruentialEngine;   
  
alias **MinstdRand** = LinearCongruentialEngine!(uint, 48271u, 0u, 2147483647u).LinearCongruentialEngine;  
Define LinearCongruentialEngine generators with well-chosen parameters. `MinstdRand0` implements Park and Miller's "minimal standard" [generator](http://wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator) that uses 16807 for the multiplier. `MinstdRand` implements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic.



Examples:


```
// seed with a constant
auto rnd0 = MinstdRand0(1);
auto n = rnd0.front;
 // same for each run
writeln(n); // 16807

// Seed with an unpredictable value
rnd0.seed(unpredictableSeed);
n = rnd0.front; // different across runs

```
 
  struct **MersenneTwisterEngine**(UIntType, size\_t w, size\_t n, size\_t m, size\_t r, UIntType a, size\_t u, UIntType d, size\_t s, UIntType b, size\_t t, UIntType c, size\_t l, UIntType f) if (isUnsigned!UIntType);  
The [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) generator.



Examples:


```
// seed with a constant
Mt19937 gen;
auto n = gen.front; // same for each run
writeln(n); // 3499211612

// Seed with an unpredictable value
gen.seed(unpredictableSeed);
n = gen.front; // different across runs

```
 
 
enum bool **isUniformRandom**;  
Mark this as a Rng

  enum size\_t **wordSize**;   
  
enum size\_t **stateSize**;   
  
enum size\_t **shiftSize**;   
  
enum size\_t **maskBits**;   
  
enum UIntType **xorMask**;   
  
enum size\_t **temperingU**;   
  
enum UIntType **temperingD**;   
  
enum size\_t **temperingS**;   
  
enum UIntType **temperingB**;   
  
enum size\_t **temperingT**;   
  
enum UIntType **temperingC**;   
  
enum size\_t **temperingL**;   
  
enum UIntType **initializationMultiplier**;  
Parameters for the generator.

  enum UIntType **min**;  
Smallest generated value (0).

  enum UIntType **max**;  
Largest generated value.

  enum UIntType **defaultSeed**;  
The default seed value.

  pure nothrow @nogc @safe this(UIntType value);  
Constructs a MersenneTwisterEngine object.

  pure nothrow @nogc @safe void **seed**()(UIntType value = defaultSeed);  
Seeds a MersenneTwisterEngine object. 



Note
 This seed function gives 2^w starting points (the lowest w bits of the value provided will be used). To allow the RNG to be started in any one of its internal states use the seed overload taking an InputRange.
  void **seed**(T)(T range)  
 Constraints: if (isInputRange!T && is(immutable(ElementType!T) == immutable(UIntType))); 
 
Seeds a MersenneTwisterEngine object using an InputRange. 



Throws:

`Exception` if the InputRange didn't provide enough elements to seed the generator. The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct.
  pure nothrow @nogc @safe void **popFront**();  
Advances the generator.

  const pure nothrow @nogc @property @safe UIntType **front**();  
Returns the current random value.

  const pure nothrow @nogc @property @safe typeof(this) **save**();  enum bool **empty**;  
Always `false`.

    alias **Mt19937** = MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine;  
A `MersenneTwisterEngine` instantiated with the parameters of the original engine [MT19937](http://math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html), generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937. Recommended for random number generation unless memory is severely restricted, in which case a [`LinearCongruentialEngine`](#LinearCongruentialEngine) would be the generator of choice.



Examples:


```
// seed with a constant
Mt19937 gen;
auto n = gen.front; // same for each run
writeln(n); // 3499211612

// Seed with an unpredictable value
gen.seed(unpredictableSeed);
n = gen.front; // different across runs

```
 
  alias **Mt19937\_64** = MersenneTwisterEngine!(ulong, 64LU, 312LU, 156LU, 31LU, 13043109905998158313LU, 29LU, 6148914691236517205LU, 17LU, 8202884508482404352LU, 37LU, 18444473444759240704LU, 43LU, 6364136223846793005LU).MersenneTwisterEngine;  
A `MersenneTwisterEngine` instantiated with the parameters of the original engine [MT19937-64](http://en.wikipedia.org/wiki/Mersenne_Twister), generating uniformly-distributed 64-bit numbers with a period of 2 to the power of 19937.



Examples:


```
// Seed with a constant
auto gen = Mt19937_64(12345);
auto n = gen.front; // same for each run
writeln(n); // 6597103971274460346

// Seed with an unpredictable value
gen.seed(unpredictableSeed!ulong);
n = gen.front; // different across runs

```
 
  struct **XorshiftEngine**(UIntType, uint nbits, int sa, int sb, int sc) if (isUnsigned!UIntType && !(sa > 0 && (sb > 0) && (sc > 0)));   
  
template **XorshiftEngine**(UIntType, int bits, int a, int b, int c) if (isUnsigned!UIntType && (a > 0) && (b > 0) && (c > 0)) 
Xorshift generator. Implemented according to [Xorshift RNGs](http://www.jstatsoft.org/v08/i14/paper) (Marsaglia, 2003) when the size is small. For larger sizes the generator uses Sebastino Vigna's optimization of using an index to avoid needing to rotate the internal array. 


Period is `2 ^^ nbits - 1` except for a legacy 192-bit uint version (see note below). 

 
Parameters:


|  |  |
| --- | --- |
| UIntType | Word size of this xorshift generator and the return type of `opCall`. |
| nbits | The number of bits of state of this generator. This must be a positive multiple of the size in bits of UIntType. If nbits is large this struct may occupy slightly more memory than this so it can use a circular counter instead of shifting the entire array. |
| sa | The direction and magnitude of the 1st shift. Positive means left, negative means right. |
| sb | The direction and magnitude of the 2nd shift. Positive means left, negative means right. |
| sc | The direction and magnitude of the 3rd shift. Positive means left, negative means right. |


 
Note
 For historical compatibility when `nbits == 192` and `UIntType` is `uint` a legacy hybrid PRNG is used consisting of a 160-bit xorshift combined with a 32-bit counter. This combined generator has period equal to the least common multiple of `2^^160 - 1` and `2^^32`. 
 Previous versions of `XorshiftEngine` did not provide any mechanism to specify the directions of the shifts, taking each shift as an unsigned magnitude. For backwards compatibility, because three shifts in the same direction cannot result in a full-period XorshiftEngine, when all three of `sa`, `sb`, `sc, are positive` XorshiftEngine` treats them as unsigned magnitudes and uses shift directions to match the old behavior of `XorshiftEngine`. Not every set of shifts results in a full-period xorshift generator. The template does not currently at compile-time perform a full check for maximum period but in a future version might reject parameters resulting in shorter periods. 
Examples:


```
alias Xorshift96  = XorshiftEngine!(uint, 96,  10, 5,  26);
auto rnd = Xorshift96(42);
auto num = rnd.front;  // same for each run
writeln(num); // 2704588748

```
 
 
enum bool **isUniformRandom**;  
Mark this as a Rng

  enum auto **empty**;  
Always `false` (random generators are infinite ranges).

  enum UIntType **min**;  
Smallest generated value.

  enum UIntType **max**;  
Largest generated value.

  pure nothrow @nogc @safe this()(UIntType x0);  
Constructs a `XorshiftEngine` generator seeded with x0. 



Parameters:


|  |  |
| --- | --- |
| UIntType `x0` | value used to deterministically initialize internal state |


  pure nothrow @nogc @safe void **seed**()(UIntType x0);  
(Re)seeds the generator. 



Parameters:


|  |  |
| --- | --- |
| UIntType `x0` | value used to deterministically initialize internal state |


  const pure nothrow @nogc @property @safe UIntType **front**();  
Returns the current number in the random sequence.

  pure nothrow @nogc @safe void **popFront**();  
Advances the random sequence.

  const pure nothrow @nogc @property @safe typeof(this) **save**();  
Captures a range state.

    alias **Xorshift32** = XorshiftEngine!(uint, 32u, 13, -17, 15).XorshiftEngine;   
  
alias **Xorshift64** = XorshiftEngine!(uint, 64u, 10, -13, -10).XorshiftEngine;   
  
alias **Xorshift96** = XorshiftEngine!(uint, 96u, 10, -5, -26).XorshiftEngine;   
  
alias **Xorshift128** = XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine;   
  
alias **Xorshift160** = XorshiftEngine!(uint, 160u, 2, -1, -4).XorshiftEngine;   
  
alias **Xorshift192** = XorshiftEngine!(uint, 192u, -2, 1, 4).XorshiftEngine;   
  
alias **Xorshift** = XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine;  
Define `XorshiftEngine` generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". `Xorshift` is a Xorshift128's alias because 128bits implementation is mostly used.



Examples:


```
// Seed with a constant
auto rnd = Xorshift(1);
auto num = rnd.front;  // same for each run
writeln(num); // 1405313047

// Seed with an unpredictable value
rnd.seed(unpredictableSeed);
num = rnd.front; // different across rnd

```
 
  nothrow @nogc @property @trusted uint **unpredictableSeed**();   
  
template **unpredictableSeed**(UIntType) if (isUnsigned!UIntType) 
A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run. 



Returns:
A single unsigned integer seed value, different on each successive call 
 
Note
 In general periodically 'reseeding' a PRNG does not improve its quality and in some cases may harm it. For an extreme example the Mersenne Twister has `2 ^^ 19937 - 1` distinct states but after `seed(uint)` is called it can only be in one of `2 ^^ 32` distinct states regardless of how excellent the source of entropy is.
 
Examples:


```
auto rnd = Random(unpredictableSeed);
auto n = rnd.front;
static assert(is(typeof(n) == uint));

```
 
  alias **Random** = MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine;  
The "default", "favorite", "suggested" random number generator type on the current platform. It is an alias for one of the previously-defined generators. You may want to use it if (1) you need to generate some nice random numbers, and (2) you don't care for the minutiae of the method being used.

  nothrow @nogc @property ref @safe Random **rndGen**();  
Global random number generator used by various functions in this module whenever no generator is specified. It is allocated per-thread and initialized to an unpredictable value for each thread. 



Returns:
A singleton instance of the default random number generator
 
Examples:


```
import std.algorithm.iteration : sum;
import std.range : take;
auto rnd = rndGen;
assert(rnd.take(3).sum > 0);

```
 
  auto **uniform**(string boundaries = "[)", T1, T2)(T1 a, T2 b)  
 Constraints: if (!is(CommonType!(T1, T2) == void));   
  
auto **uniform**(string boundaries = "[)", T1, T2, UniformRandomNumberGenerator)(T1 a, T2 b, ref UniformRandomNumberGenerator urng)  
 Constraints: if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRandomNumberGenerator); 
 
Generates a number between `a` and `b`. The `boundaries` parameter controls the shape of the interval (open vs. closed on either side). Valid values for `boundaries` are `"[]"`, `"(]"`, `"[)"`, and `"()"`. The default interval is closed to the left and open to the right. The version that does not take `urng` uses the default generator `rndGen`. 



Parameters:


|  |  |
| --- | --- |
| T1 `a` | lower bound of the uniform distribution |
| T2 `b` | upper bound of the uniform distribution |
| UniformRandomNumberGenerator `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
A single random variate drawn from the uniform distribution between `a` and `b`, whose type is the common type of these parameters
 
Examples:


```
auto rnd = Random(unpredictableSeed);

// Generate an integer in [0, 1023]
auto a = uniform(0, 1024, rnd);
assert(0 <= a && a < 1024);

// Generate a float in [0, 1)
auto b = uniform(0.0f, 1.0f, rnd);
assert(0 <= b && b < 1);

// Generate a float in [0, 1]
b = uniform!"[]"(0.0f, 1.0f, rnd);
assert(0 <= b && b <= 1);

// Generate a float in (0, 1)
b = uniform!"()"(0.0f, 1.0f, rnd);
assert(0 < b && b < 1);

```
 
 
Examples:
Create an array of random numbers using range functions and UFCS 
```
import std.array : array;
import std.range : generate, takeExactly;

int[] arr = generate!(() => uniform(0, 100)).takeExactly(10).array;
writeln(arr.length); // 10
assert(arr[0] >= 0 && arr[0] < 100);

```
 
  auto **uniform**(T, UniformRandomNumberGenerator)(ref UniformRandomNumberGenerator urng)  
 Constraints: if (!is(T == enum) && (isIntegral!T || isSomeChar!T) && isUniformRNG!UniformRandomNumberGenerator);   
  
auto **uniform**(T)()  
 Constraints: if (!is(T == enum) && (isIntegral!T || isSomeChar!T));   
  
auto **uniform**(E, UniformRandomNumberGenerator)(ref UniformRandomNumberGenerator urng)  
 Constraints: if (is(E == enum) && isUniformRNG!UniformRandomNumberGenerator);   
  
auto **uniform**(E)()  
 Constraints: if (is(E == enum)); 
 
Generates a uniformly-distributed number in the range `[T.min, T.max]` for any integral or character type `T`. If no random number generator is passed, uses the default `rndGen`. 


If an `enum` is used as type, the random variate is drawn with equal probability from any of the possible values of the enum `E`. 

 
Parameters:


|  |  |
| --- | --- |
| UniformRandomNumberGenerator `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
Random variate drawn from the uniform distribution across all possible values of the integral, character or enum type `T`.
 
Examples:


```
auto rnd = MinstdRand0(42);

writeln(rnd.uniform!ubyte); // 102
writeln(rnd.uniform!ulong); // 4838462006927449017

enum Fruit { apple, mango, pear }
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
writeln(rnd.uniform!Fruit); // Fruit.mango

```
 
  T **uniform01**(T = double)()  
 Constraints: if (isFloatingPoint!T);   
  
T **uniform01**(T = double, UniformRNG)(ref UniformRNG rng)  
 Constraints: if (isFloatingPoint!T && isUniformRNG!UniformRNG); 
 
Generates a uniformly-distributed floating point number of type `T` in the range [0, 1). If no random number generator is specified, the default RNG `rndGen` will be used as the source of randomness. 


`uniform01` offers a faster generation of random variates than the equivalent `uniform!"[)"(0.0, 1.0)` and so may be preferred for some applications. 

 
Parameters:


|  |  |
| --- | --- |
| UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
Floating-point random variate of type `T` drawn from the uniform distribution across the half-open interval [0, 1).
 
Examples:


```
import std.math : feqrel;

auto rnd = MinstdRand0(42);

// Generate random numbers in the range in the range [0, 1)
auto u1 = uniform01(rnd);
assert(u1 >= 0 && u1 < 1);

auto u2 = rnd.uniform01!float;
assert(u2 >= 0 && u2 < 1);

// Confirm that the random values with the initial seed 42 are 0.000328707 and 0.524587
assert(u1.feqrel(0.000328707) > 20);
assert(u2.feqrel(0.524587) > 20);

```
 
  F[] **uniformDistribution**(F = double)(size\_t n, F[] useThis = null)  
 Constraints: if (isFloatingPoint!F); 
 
Generates a uniform probability distribution of size `n`, i.e., an array of size `n` of positive numbers of type `F` that sum to `1`. If `useThis` is provided, it is used as storage.



Examples:


```
import std.algorithm.iteration : reduce;
import std.math : approxEqual;

auto a = uniformDistribution(5);
writeln(a.length); // 5
assert(approxEqual(reduce!"a + b"(a), 1));

a = uniformDistribution(10, a);
writeln(a.length); // 10
assert(approxEqual(reduce!"a + b"(a), 1));

```
 
  ref auto **choice**(Range, RandomGen = Random)(auto ref Range range, ref RandomGen urng)  
 Constraints: if (isRandomAccessRange!Range && hasLength!Range && isUniformRNG!RandomGen);   
  
ref auto **choice**(Range)(auto ref Range range);  
Returns a random, uniformly chosen, element `e` from the supplied `Range range`. If no random number generator is passed, the default `rndGen` is used. 



Parameters:


|  |  |
| --- | --- |
| Range `range` | a random access range that has the `length` property defined |
| RandomGen `urng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
A single random element drawn from the `range`. If it can, it will return a `ref` to the `range element`, otherwise it will return a copy.
 
Examples:


```
auto rnd = MinstdRand0(42);

auto elem  = [1, 2, 3, 4, 5].choice(rnd);
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
writeln(elem); // 3

```
 
  Range **randomShuffle**(Range, RandomGen)(Range r, ref RandomGen gen)  
 Constraints: if (isRandomAccessRange!Range && isUniformRNG!RandomGen);   
  
Range **randomShuffle**(Range)(Range r)  
 Constraints: if (isRandomAccessRange!Range); 
 
Shuffles elements of `r` using `gen` as a shuffler. `r` must be a random-access range with length. If no RNG is specified, `rndGen` will be used. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | random-access range whose elements are to be shuffled |
| RandomGen `gen` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
The shuffled random-access range.
 
Examples:


```
auto rnd = MinstdRand0(42);

auto arr = [1, 2, 3, 4, 5].randomShuffle(rnd);
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
writeln(arr); // [3, 5, 2, 4, 1]

```
 
  Range **partialShuffle**(Range, RandomGen)(Range r, in size\_t n, ref RandomGen gen)  
 Constraints: if (isRandomAccessRange!Range && isUniformRNG!RandomGen);   
  
Range **partialShuffle**(Range)(Range r, in size\_t n)  
 Constraints: if (isRandomAccessRange!Range); 
 
Partially shuffles the elements of `r` such that upon returning `r[0 .. n]` is a random subset of `r` and is randomly ordered. `r[n .. r.length]` will contain the elements not in `r[0 .. n]`. These will be in an undefined order, but will not be random in the sense that their order after `partialShuffle` returns will not be independent of their order before `partialShuffle` was called. 


`r` must be a random-access range with length. `n` must be less than or equal to `r.length`. If no RNG is specified, `rndGen` will be used. 

 
Parameters:


|  |  |
| --- | --- |
| Range `r` | random-access range whose elements are to be shuffled |
| size\_t `n` | number of elements of `r` to shuffle (counting from the beginning); must be less than `r.length` |
| RandomGen `gen` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
The shuffled random-access range.
 
Examples:


```
auto rnd = MinstdRand0(42);

auto arr = [1, 2, 3, 4, 5, 6];
arr = arr.dup.partialShuffle(1, rnd);

version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(arr == [2, 1, 3, 4, 5, 6]); // 1<->2

arr = arr.dup.partialShuffle(2, rnd);
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(arr == [1, 4, 3, 2, 5, 6]); // 1<->2, 2<->4

arr = arr.dup.partialShuffle(3, rnd);
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(arr == [5, 4, 6, 2, 1, 3]); // 1<->5, 2<->4, 3<->6

```
 
  size\_t **dice**(Rng, Num)(ref Rng rnd, Num[] proportions...)  
 Constraints: if (isNumeric!Num && isForwardRange!Rng);   
  
size\_t **dice**(R, Range)(ref R rnd, Range proportions)  
 Constraints: if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);   
  
size\_t **dice**(Range)(Range proportions)  
 Constraints: if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);   
  
size\_t **dice**(Num)(Num[] proportions...)  
 Constraints: if (isNumeric!Num); 
 
Rolls a dice with relative probabilities stored in `proportions`. Returns the index in `proportions` that was chosen. 



Parameters:


|  |  |
| --- | --- |
| Rng `rnd` | (optional) random number generator to use; if not specified, defaults to `rndGen` |
| Num[] `proportions` | forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value |


 
Returns:
Random variate drawn from the index values [0, ... `proportions.length` - 1], with the probability of getting an individual index value `i` being proportional to `proportions[i]`.
 
Examples:


```
auto x = dice(0.5, 0.5);   // x is 0 or 1 in equal proportions
auto y = dice(50, 50);     // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
                           // and 2 10% of the time

```
 
 
Examples:


```
auto rnd = MinstdRand0(42);
auto z = rnd.dice(70, 20, 10);
writeln(z); // 0
z = rnd.dice(30, 20, 40, 10);
writeln(z); // 2

```
 
  struct **RandomCover**(Range, UniformRNG = void) if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));   
  
auto **randomCover**(Range, UniformRNG)(Range r, auto ref UniformRNG rng)  
 Constraints: if (isRandomAccessRange!Range && isUniformRNG!UniformRNG);   
  
auto **randomCover**(Range)(Range r)  
 Constraints: if (isRandomAccessRange!Range); 
 
Covers a given range `r` in a random manner, i.e. goes through each element of `r` once and only once, just in a random order. `r` must be a random-access range with length. 


If no random number generator is passed to `randomCover`, the thread-global RNG rndGen will be used internally. 

 
Parameters:


|  |  |
| --- | --- |
| Range `r` | random-access range to cover |
| UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
Range whose elements consist of the elements of `r`, in random order. Will be a forward range if both `r` and `rng` are forward ranges, an [input range](std_range_primitives#isInputRange) otherwise.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
auto rnd = MinstdRand0(42);

version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(10.iota.randomCover(rnd).equal([7, 4, 2, 0, 1, 6, 8, 3, 9, 5]));

```
 
  struct **RandomSample**(Range, UniformRNG = void) if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));   
  
auto **randomSample**(Range)(Range r, size\_t n, size\_t total)  
 Constraints: if (isInputRange!Range);   
  
auto **randomSample**(Range)(Range r, size\_t n)  
 Constraints: if (isInputRange!Range && hasLength!Range);   
  
auto **randomSample**(Range, UniformRNG)(Range r, size\_t n, size\_t total, auto ref UniformRNG rng)  
 Constraints: if (isInputRange!Range && isUniformRNG!UniformRNG);   
  
auto **randomSample**(Range, UniformRNG)(Range r, size\_t n, auto ref UniformRNG rng)  
 Constraints: if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG); 
 
Selects a random subsample out of `r`, containing exactly `n` elements. The order of elements is the same as in the original range. The total length of `r` must be known. If `total` is passed in, the total number of sample is considered to be `total`. Otherwise, `RandomSample` uses `r.length`. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | range to sample from |
| size\_t `n` | number of elements to include in the sample; must be less than or equal to the total number of elements in `r` and/or the parameter `total` (if provided) |
| size\_t `total` | (semi-optional) number of elements of `r` from which to select the sample (counting from the beginning); must be less than or equal to the total number of elements in `r` itself. May be omitted if `r` has the `.length` property and the sample is to be drawn from all elements of `r`. |
| UniformRNG `rng` | (optional) random number generator to use; if not specified, defaults to `rndGen` |


 
Returns:
Range whose elements consist of a randomly selected subset of the elements of `r`, in the same order as these elements appear in `r` itself. Will be a forward range if both `r` and `rng` are forward ranges, an input range otherwise. `RandomSample` implements Jeffrey Scott Vitter's Algorithm D (see Vitter [1984](http://dx.doi.org/10.1145/358105.893), [1987](http://dx.doi.org/10.1145/23002.23003)), which selects a sample of size `n` in O(n) steps and requiring O(n) random variates, regardless of the size of the data being sampled. The exception to this is if traversing k elements on the input range is itself an O(k) operation (e.g. when sampling lines from an input file), in which case the sampling calculation will inevitably be of O(total). RandomSample will throw an exception if `total` is verifiably less than the total number of elements available in the input, or if `n > total`. If no random number generator is passed to `randomSample`, the thread-global RNG rndGen will be used internally.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
auto rnd = MinstdRand0(42);
assert(10.iota.randomSample(3, rnd).equal([7, 8, 9]));

```
 
 
const @property bool **empty**();   
  
@property ref auto **front**();   
  
void **popFront**();   
  
const @property typeof(this) **save**();   
  
const @property size\_t **length**();  
Range primitives.

  @property size\_t **index**();  
Returns the index of the visited record.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_random.html>

std.system
==========

 Information about the target operating system, environment, and CPU. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/system.d](https://github.com/dlang/phobos/blob/master/std/system.d)

 
enum **OS**: int;  
Operating system. 



Note
 This is for cases where you need a value representing the OS at runtime. If you're doing something which should compile differently on different OSes, then please use `version (Windows)`, `version (linux)`, etc. 
 
See Also:
[Predefined Versions](https://dlang.org/spec/version.html#PredefinedVersions)
 
**win32** 
Microsoft 32 bit Windows systems

  **win64** 
Microsoft 64 bit Windows systems

  **linux** 
All Linux Systems, except for Android

  **osx** 
Mac OS X

  **iOS** 
iOS

  **tvOS** 
tvOS

  **watchOS** 
watchOS

  **freeBSD** 
FreeBSD

  **netBSD** 
NetBSD

  **dragonFlyBSD** 
DragonFlyBSD

  **solaris** 
Solaris

  **android** 
Android

  **otherPosix** 
Other Posix Systems

    immutable OS **os**;  
The OS that the program was compiled for.

  enum **Endian**: int;  
Byte order endianness. 



Note
 This is intended for cases where you need to deal with endianness at runtime. If you're doing something which should compile differently depending on whether you're compiling on a big endian or little endian machine, then please use `version (BigEndian)` and `version (LittleEndian)`. 
 
See Also:
[Predefined Versions](https://dlang.org/spec/version.html#PredefinedVersions)
 
**bigEndian** 
Big endian byte order

  **littleEndian** 
Little endian byte order

    immutable Endian **endian**;  
The endianness that the program was compiled for.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_system.html>

std.math
========

 Contains the elementary mathematical functions (powers, roots, and trigonometric functions), and low-level floating-point operations. Mathematical special functions are available in `std.mathspecial`. 




| Category | Members |
| --- | --- |
| Constants | [*E*](#E) [*PI*](#PI) [*PI\_2*](#PI_2) [*PI\_4*](#PI_4) [*M\_1\_PI*](#M_1_PI) [*M\_2\_PI*](#M_2_PI) [*M\_2\_SQRTPI*](#M_2_SQRTPI) [*LN10*](#LN10) [*LN2*](#LN2) [*LOG2*](#LOG2) [*LOG2E*](#LOG2E) [*LOG2T*](#LOG2T) [*LOG10E*](#LOG10E) [*SQRT2*](#SQRT2) [*SQRT1\_2*](#SQRT1_2) |
| Classics | [*abs*](#abs) [*fabs*](#fabs) [*sqrt*](#sqrt) [*cbrt*](#cbrt) [*hypot*](#hypot) [*poly*](#poly) [*nextPow2*](#nextPow2) [*truncPow2*](#truncPow2) |
| Trigonometry | [*sin*](#sin) [*cos*](#cos) [*tan*](#tan) [*asin*](#asin) [*acos*](#acos) [*atan*](#atan) [*atan2*](#atan2) [*sinh*](#sinh) [*cosh*](#cosh) [*tanh*](#tanh) [*asinh*](#asinh) [*acosh*](#acosh) [*atanh*](#atanh) |
| Rounding | [*ceil*](#ceil) [*floor*](#floor) [*round*](#round) [*lround*](#lround) [*trunc*](#trunc) [*rint*](#rint) [*lrint*](#lrint) [*nearbyint*](#nearbyint) [*rndtol*](#rndtol) [*quantize*](#quantize) |
| Exponentiation & Logarithms | [*pow*](#pow) [*exp*](#exp) [*exp2*](#exp2) [*expm1*](#expm1) [*ldexp*](#ldexp) [*frexp*](#frexp) [*log*](#log) [*log2*](#log2) [*log10*](#log10) [*logb*](#logb) [*ilogb*](#ilogb) [*log1p*](#log1p) [*scalbn*](#scalbn) |
| Modulus | [*fmod*](#fmod) [*modf*](#modf) [*remainder*](#remainder) |
| Floating-point operations | [*approxEqual*](#approxEqual) [*feqrel*](#feqrel) [*fdim*](#fdim) [*fmax*](#fmax) [*fmin*](#fmin) [*fma*](#fma) [*isClose*](#isClose) [*nextDown*](#nextDown) [*nextUp*](#nextUp) [*nextafter*](#nextafter) [*NaN*](#NaN) [*getNaNPayload*](#getNaNPayload) [*cmp*](#cmp) |
| Introspection | [*isFinite*](#isFinite) [*isIdentical*](#isIdentical) [*isInfinity*](#isInfinity) [*isNaN*](#isNaN) [*isNormal*](#isNormal) [*isSubnormal*](#isSubnormal) [*signbit*](#signbit) [*sgn*](#sgn) [*copysign*](#copysign) [*isPowerOf2*](#isPowerOf2) |
| Hardware Control | [*IeeeFlags*](#IeeeFlags) [*FloatingPointControl*](#FloatingPointControl) |

  The functionality closely follows the IEEE754-2008 standard for floating-point arithmetic, including the use of camelCase names rather than C99-style lower case names. All of these functions behave correctly when presented with an infinity or NaN.   
  
 The following IEEE 'real' formats are currently supported: * 64 bit Big-endian 'double' (eg PowerPC)
* 128 bit Big-endian 'quadruple' (eg SPARC)
* 64 bit Little-endian 'double' (eg x86-SSE2)
* 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium)
* 128 bit Little-endian 'quadruple' (not implemented on any known processor!)
* Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support

 Unlike C, there is no global 'errno' variable. Consequently, almost all of these functions are pure nothrow. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger 
 
Source
 [std/math.d](https://github.com/dlang/phobos/blob/master/std/math.d)

 
enum real **E**;  
e = 2.718281...

  enum real **LOG2T**;  
log210 = 3.321928...

  enum real **LOG2E**;  
log2e = 1.442695...

  enum real **LOG2**;  
log102 = 0.301029...

  enum real **LOG10E**;  
log10e = 0.434294...

  enum real **LN2**;  
ln 2 = 0.693147...

  enum real **LN10**;  
ln 10 = 2.302585...

  enum real **PI**;  
π = 3.141592...

  enum real **PI\_2**;  
π / 2 = 1.570796...

  enum real **PI\_4**;  
π / 4 = 0.785398...

  enum real **M\_1\_PI**;  
1 / π = 0.318309...

  enum real **M\_2\_PI**;  
2 / π = 0.636619...

  enum real **M\_2\_SQRTPI**;  
2 / √π = 1.128379...

  enum real **SQRT2**;  
√2 = 1.414213...

  enum real **SQRT1\_2**;  
√½ = 0.707106...

  pure nothrow @nogc auto **abs**(Num)(Num x)  
 Constraints: if (is(immutable(Num) == immutable(short)) || is(immutable(Num) == immutable(byte)) || is(typeof(Num.init >= 0)) && is(typeof(-Num.init))); 
 
Calculates the absolute value of a number. 



Parameters:


|  |  |
| --- | --- |
| Num | (template parameter) type of number |
| Num `x` | real number value |


 
Returns:
The absolute value of the number. If floating-point or integral, the return type will be the same as the input. 
 
Limitations
 Does not work correctly for signed intergal types and value `Num`.min.
 
Examples:
ditto 
```
assert(isIdentical(abs(-0.0L), 0.0L));
assert(isNaN(abs(real.nan)));
writeln(abs(-real.infinity)); // real.infinity
writeln(abs(-56)); // 56
writeln(abs(2321312L)); // 2321312L

```
 
  pure nothrow @nogc @safe real **cos**(real x);   
  
pure nothrow @nogc @safe double **cos**(double x);   
  
pure nothrow @nogc @safe float **cos**(float x);  
Returns cosine of x. x is in radians. 




Special Values| x | cos(x) | invalid? |
| NAN | NAN | yes |
| ±∞ | NAN | yes |

 

 
Bugs:
Results are undefined if |x| >= 264.
 
Examples:


```
writeln(cos(0.0)); // 1.0
assert(cos(1.0).approxEqual(0.540));
assert(cos(3.0).approxEqual(-0.989));

```
 
  pure nothrow @nogc @safe real **sin**(real x);   
  
pure nothrow @nogc @safe double **sin**(double x);   
  
pure nothrow @nogc @safe float **sin**(float x);  
Returns [sine](http://en.wikipedia.org/wiki/Sine) of x. x is in [radians](http://en.wikipedia.org/wiki/Radian). 




Special Values| x  |  sin(x)  |  invalid? |
| NAN | NAN |  yes  |
| ±0.0 |  ±0.0 |  no  |
| ±∞ | NAN |  yes  |

 

 
Parameters:


|  |  |
| --- | --- |
| real `x` | angle in radians (not degrees) |


 
Returns:
sine of x 
 
See Also:

[*cos*](#cos) , [*tan*](#tan) , [*asin*](#asin) 
 
Bugs:
Results are undefined if |x| >= 264.
 
Examples:


```
import std.math : sin, PI;
import std.stdio : writefln;

void someFunc()
{
  real x = 30.0;
  auto result = sin(x * (PI / 180)); // convert degrees to radians
  writefln("The sine of %s degrees is %s", x, result);
}

```
 
  pure nothrow @nogc @safe real **tan**(real x);   
  
pure nothrow @nogc @safe double **tan**(double x);   
  
pure nothrow @nogc @safe float **tan**(float x);  
Returns tangent of x. x is in radians. 




Special Values| x | tan(x) | invalid? |
| NAN | NAN | yes |
| ±0.0 | ±0.0 | no |
| ±∞ | NAN | yes |



 
Examples:


```
assert(isIdentical(tan(0.0), 0.0));
assert(tan(PI).approxEqual(0));
assert(tan(PI / 3).approxEqual(sqrt(3.0)));

```
 
  pure nothrow @nogc @safe real **acos**(real x);   
  
pure nothrow @nogc @safe double **acos**(double x);   
  
pure nothrow @nogc @safe float **acos**(float x);  
Calculates the arc cosine of x, returning a value ranging from 0 to π. 




Special Values| x | acos(x) | invalid? |
| >1.0 | NAN | yes |
| <-1.0 | NAN | yes |
| NAN | NAN | yes |



 
Examples:


```
assert(acos(0.0).approxEqual(1.570));
assert(acos(0.5).approxEqual(std.math.PI / 3));
assert(acos(PI).isNaN);

```
 
  pure nothrow @nogc @safe real **asin**(real x);   
  
pure nothrow @nogc @safe double **asin**(double x);   
  
pure nothrow @nogc @safe float **asin**(float x);  
Calculates the arc sine of x, returning a value ranging from -π/2 to π/2. 




Special Values| x | asin(x) | invalid? |
| ±0.0 | ±0.0 | no |
| >1.0 | NAN | yes |
| <-1.0 | NAN | yes |



 
Examples:


```
assert(isIdentical(asin(0.0), 0.0));
assert(asin(0.5).approxEqual(PI / 6));
assert(asin(PI).isNaN);

```
 
  pure nothrow @nogc @safe real **atan**(real x);   
  
pure nothrow @nogc @safe double **atan**(double x);   
  
pure nothrow @nogc @safe float **atan**(float x);  
Calculates the arc tangent of x, returning a value ranging from -π/2 to π/2. 




Special Values| x | atan(x) | invalid? |
| ±0.0 | ±0.0 | no |
| ±∞ | NAN | yes |



 
Examples:


```
assert(isIdentical(atan(0.0), 0.0));
assert(atan(sqrt(3.0)).approxEqual(PI / 3));

```
 
  pure nothrow @nogc @trusted real **atan2**(real y, real x);   
  
pure nothrow @nogc @safe double **atan2**(double y, double x);   
  
pure nothrow @nogc @safe float **atan2**(float y, float x);  
Calculates the arc tangent of y / x, returning a value ranging from -π to π. 




Special Values| y | x | atan(y, x) |
| NAN | anything | NAN |
| anything | NAN | NAN |
| ±0.0 | >0.0 | ±0.0 |
| ±0.0 | +0.0 | ±0.0 |
| ±0.0 | <0.0 | ±π |
| ±0.0 | -0.0 | ±π |
| >0.0 | ±0.0 | π/2 |
| <0.0 | ±0.0 | -π/2 |
| >0.0 | ∞ | ±0.0 |
| ±∞ | anything | ±π/2 |
| >0.0 | -∞ | ±π |
| ±∞ | ∞ | ±π/4 |
| ±∞ | -∞ | ±3π/4 |



 
Examples:


```
assert(atan2(1.0, sqrt(3.0)).approxEqual(PI / 6));

```
 
  pure nothrow @nogc @safe real **cosh**(real x);   
  
pure nothrow @nogc @safe double **cosh**(double x);   
  
pure nothrow @nogc @safe float **cosh**(float x);  
Calculates the hyperbolic cosine of x. 




Special Values| x | cosh(x) | invalid? |
| ±∞ | ±0.0 | no |



 
Examples:


```
writeln(cosh(0.0)); // 1.0
assert(cosh(1.0).approxEqual((E + 1.0 / E) / 2));

```
 
  pure nothrow @nogc @safe real **sinh**(real x);   
  
pure nothrow @nogc @safe double **sinh**(double x);   
  
pure nothrow @nogc @safe float **sinh**(float x);  
Calculates the hyperbolic sine of x. 




Special Values| x | sinh(x) | invalid? |
| ±0.0 | ±0.0 | no |
| ±∞ | ±∞ | no |



 
Examples:


```
enum sinh1 = (E - 1.0 / E) / 2;
import std.meta : AliasSeq;
static foreach (F; AliasSeq!(float, double, real))
{
    assert(isIdentical(sinh(F(0.0)), F(0.0)));
    assert(sinh(F(1.0)).approxEqual(F(sinh1)));
}

```
 
  pure nothrow @nogc @safe real **tanh**(real x);   
  
pure nothrow @nogc @safe double **tanh**(double x);   
  
pure nothrow @nogc @safe float **tanh**(float x);  
Calculates the hyperbolic tangent of x. 




Special Values| x | tanh(x) | invalid? |
| ±0.0 | ±0.0 | no |
| ±∞ | ±1.0 | no |



 
Examples:


```
assert(isIdentical(tanh(0.0), 0.0));
assert(tanh(1.0).approxEqual(sinh(1.0) / cosh(1.0)));

```
 
  pure nothrow @nogc @safe real **acosh**(real x);   
  
pure nothrow @nogc @safe double **acosh**(double x);   
  
pure nothrow @nogc @safe float **acosh**(float x);  
Calculates the inverse hyperbolic cosine of x. 


Mathematically, acosh(x) = log(x + sqrt( x\*x - 1))   
  
 

| Domain X | Range Y |
| --- | --- |
|  1..∞ |  0..∞  |

   
  
 

Special Values|  x |  acosh(x)  |
| NAN | NAN |
|  <1 | NAN |
|  1 |  0  |
|  +∞ | +∞ |



 
Examples:


```
assert(isNaN(acosh(0.9)));
assert(isNaN(acosh(real.nan)));
assert(isIdentical(acosh(1.0), 0.0));
writeln(acosh(real.infinity)); // real.infinity
assert(isNaN(acosh(0.5)));

```
 
  pure nothrow @nogc @safe real **asinh**(real x);   
  
pure nothrow @nogc @safe double **asinh**(double x);   
  
pure nothrow @nogc @safe float **asinh**(float x);  
Calculates the inverse hyperbolic sine of x. 


 Mathematically, 
```
asinh(x) =  log( x + sqrt( x*x + 1 )) // if x >= +0
asinh(x) = -log(-x + sqrt( x*x + 1 )) // if x <= -0

```
   
  
 

Special Values| x |  asinh(x)  |
| NAN | NAN |
|  ±0 |  ±0  |
|  ±∞ | ±∞ |



 
Examples:


```
assert(isIdentical(asinh(0.0), 0.0));
assert(isIdentical(asinh(-0.0), -0.0));
writeln(asinh(real.infinity)); // real.infinity
writeln(asinh(-real.infinity)); // -real.infinity
assert(isNaN(asinh(real.nan)));

```
 
  pure nothrow @nogc @safe real **atanh**(real x);   
  
pure nothrow @nogc @safe double **atanh**(double x);   
  
pure nothrow @nogc @safe float **atanh**(float x);  
Calculates the inverse hyperbolic tangent of x, returning a value from ranging from -1 to 1. 


Mathematically, atanh(x) = log( (1+x)/(1-x) ) / 2   
  
 

| Domain X | Range Y |
| --- | --- |
|  -∞..∞ |  -1 .. 1  |

   
 

Special Values|  x |  acosh(x)  |
| NAN | NAN |
|  ±0 | ±0 |
|  -∞ | -0 |



 
Examples:


```
assert(isIdentical(atanh(0.0), 0.0));
assert(isIdentical(atanh(-0.0),-0.0));
assert(isNaN(atanh(real.nan)));
assert(isNaN(atanh(-real.infinity)));
writeln(atanh(0.0)); // 0

```
 
  pure nothrow @nogc @safe long **rndtol**(real x);   
  
pure nothrow @nogc @safe long **rndtol**(double x);   
  
pure nothrow @nogc @safe long **rndtol**(float x);  
Returns x rounded to a long value using the current rounding mode. If the integer value of x is greater than long.max, the result is indeterminate.



Examples:


```
writeln(rndtol(1.0)); // 1L
writeln(rndtol(1.2)); // 1L
writeln(rndtol(1.7)); // 2L
writeln(rndtol(1.0001)); // 1L

```
 
  pure nothrow @nogc @safe float **sqrt**(float x);   
  
pure nothrow @nogc @safe double **sqrt**(double x);   
  
pure nothrow @nogc @safe real **sqrt**(real x);  
Compute square root of x. 




Special Values| x | sqrt(x) | invalid? |
| -0.0 | -0.0 | no |
| <0.0 | NAN | yes |
| +∞ | +∞ | no |



 
Examples:


```
assert(sqrt(2.0).feqrel(1.4142) > 16);
assert(sqrt(9.0).feqrel(3.0) > 16);

assert(isNaN(sqrt(-1.0f)));
assert(isNaN(sqrt(-1.0)));
assert(isNaN(sqrt(-1.0L)));

```
 
  pure nothrow @nogc @trusted real **exp**(real x);   
  
pure nothrow @nogc @safe double **exp**(double x);   
  
pure nothrow @nogc @safe float **exp**(float x);  
Calculates ex. 




Special Values| x | ex |
| +∞ | +∞ |
| -∞ | +0.0 |
| NAN | NAN |



 
Examples:


```
writeln(exp(0.0)); // 1.0
assert(exp(3.0).feqrel(E * E * E) > 16);

```
 
  pure nothrow @nogc @trusted real **expm1**(real x);   
  
pure nothrow @nogc @safe double **expm1**(double x);   
  
pure nothrow @nogc @safe float **expm1**(float x);  
Calculates the value of the natural logarithm base (e) raised to the power of x, minus 1. 


For very small x, expm1(x) is more accurate than exp(x)-1.   
  
 

Special Values| x | ex-1 |
| ±0.0 | ±0.0 |
| +∞ | +∞ |
| -∞ | -1.0 |
| NAN | NAN |



 
Examples:


```
assert(isIdentical(expm1(0.0), 0.0));
assert(expm1(1.0).feqrel(1.71828) > 16);
assert(expm1(2.0).feqrel(6.3890) > 16);

```
 
  pure nothrow @nogc @trusted real **exp2**(real x);   
  
pure nothrow @nogc @safe double **exp2**(double x);   
  
pure nothrow @nogc @safe float **exp2**(float x);  
Calculates 2x. 




Special Values| x | exp2(x) |
| +∞ | +∞ |
| -∞ | +0.0 |
| NAN | NAN |



 
Examples:


```
assert(isIdentical(exp2(0.0), 1.0));
assert(exp2(2.0).feqrel(4.0) > 16);
assert(exp2(8.0).feqrel(256.0) > 16);

```
 
  pure nothrow @nogc @trusted T **frexp**(T)(const T value, out int exp)  
 Constraints: if (isFloatingPoint!T); 
 
Separate floating point value into significand and exponent. 



Returns:
Calculate and return *x* and *exp* such that value =*x*\*2exp and .5 <= |*x*| < 1.0 *x* has same sign as value. 

Special Values| value | returns | exp |
| ±0.0 | ±0.0 | 0 |
| +∞ | +∞ | int.max |
| -∞ | -∞ | int.min |
| ±NAN | ±NAN | int.min |



 
Examples:


```
int exp;
real mantissa = frexp(123.456L, exp);

assert(approxEqual(mantissa * pow(2.0L, cast(real) exp), 123.456L));

assert(frexp(-real.nan, exp) && exp == int.min);
assert(frexp(real.nan, exp) && exp == int.min);
assert(frexp(-real.infinity, exp) == -real.infinity && exp == int.min);
assert(frexp(real.infinity, exp) == real.infinity && exp == int.max);
assert(frexp(-0.0, exp) == -0.0 && exp == 0);
assert(frexp(0.0, exp) == 0.0 && exp == 0);

```
 
  pure nothrow @nogc @trusted int **ilogb**(T)(const T x)  
 Constraints: if (isFloatingPoint!T);   
  
pure nothrow @nogc @safe int **ilogb**(T)(const T x)  
 Constraints: if (isIntegral!T && isUnsigned!T);   
  
pure nothrow @nogc @safe int **ilogb**(T)(const T x)  
 Constraints: if (isIntegral!T && isSigned!T); 
 
Extracts the exponent of x as a signed integral value. 


If x is not a special value, the result is the same as `cast(int) logb(x)`.   
  
 

Special Values| x | ilogb(x) | Range error? |
| 0 | FP\_ILOGB0 | yes |
| ±∞ | int.max | no |
| NAN | FP\_ILOGBNAN | no |



 
Examples:


```
writeln(ilogb(1)); // 0
writeln(ilogb(3)); // 1
writeln(ilogb(3.0)); // 1
writeln(ilogb(100_000_000)); // 26

writeln(ilogb(0)); // FP_ILOGB0
writeln(ilogb(0.0)); // FP_ILOGB0
writeln(ilogb(double.nan)); // FP_ILOGBNAN
writeln(ilogb(double.infinity)); // int.max

```
 
  alias **FP\_ILOGB0** = core.stdc.math.**FP\_ILOGB0**;   
  
alias **FP\_ILOGBNAN** = core.stdc.math.**FP\_ILOGBNAN**;  
Special return values of [`ilogb`](#ilogb).



Examples:


```
writeln(ilogb(0)); // FP_ILOGB0
writeln(ilogb(0.0)); // FP_ILOGB0
writeln(ilogb(double.nan)); // FP_ILOGBNAN

```
 
  pure nothrow @nogc @safe real **ldexp**(real n, int exp);   
  
pure nothrow @nogc @safe double **ldexp**(double n, int exp);   
  
pure nothrow @nogc @safe float **ldexp**(float n, int exp);  
Compute n \* 2exp 



References
 frexp
 
Examples:


```
import std.meta : AliasSeq;
static foreach (T; AliasSeq!(float, double, real))
{{
    T r;

    r = ldexp(3.0L, 3);
    writeln(r); // 24

    r = ldexp(cast(T) 3.0, cast(int) 3);
    writeln(r); // 24

    T n = 3.0;
    int exp = 3;
    r = ldexp(n, exp);
    writeln(r); // 24
}}

```
 
  pure nothrow @nogc @safe real **log**(real x);  
Calculate the natural logarithm of x. 




Special Values| x | log(x) | divide by 0? | invalid? |
| ±0.0 | -∞ | yes | no |
| <0.0 | NAN | no | yes |
| +∞ | +∞ | no | no |



 
Examples:


```
assert(feqrel(log(E), 1) >= real.mant_dig - 1);

```
 
  pure nothrow @nogc @safe real **log10**(real x);  
Calculate the base-10 logarithm of x. 




Special Values| x | log10(x) | divide by 0? | invalid? |
| ±0.0 | -∞ | yes | no |
| <0.0 | NAN | no | yes |
| +∞ | +∞ | no | no |



 
Examples:


```
assert(fabs(log10(1000) - 3) < .000001);

```
 
  pure nothrow @nogc @safe real **log1p**(real x);  
Calculates the natural logarithm of 1 + x. 


For very small x, log1p(x) will be more accurate than log(1 + x).   
  
 

Special Values| x | log1p(x) | divide by 0? | invalid? |
| ±0.0 | ±0.0 | no | no |
| -1.0 | -∞ | yes | no |
| <-1.0 | -NAN | no | yes |
| +∞ | +∞ | no | no |



 
Examples:


```
assert(isIdentical(log1p(0.0), 0.0));
assert(log1p(1.0).feqrel(0.69314) > 16);

writeln(log1p(-1.0)); // -real.infinity
assert(isNaN(log1p(-2.0)));
assert(log1p(real.nan) is real.nan);
assert(log1p(-real.nan) is -real.nan);
writeln(log1p(real.infinity)); // real.infinity

```
 
  pure nothrow @nogc @safe real **log2**(real x);  
Calculates the base-2 logarithm of x: log2x 




Special Values| x | log2(x) | divide by 0? | invalid? |
| ±0.0 | -∞ | yes | no |
| <0.0 | NAN | no | yes |
| +∞ | +∞ | no | no |



 
Examples:


```
assert(approxEqual(log2(1024.0L), 10));

```
 
  nothrow @nogc @trusted real **logb**(real x);  
Extracts the exponent of x as a signed integral value. 


If x is subnormal, it is treated as if it were normalized. For a positive, finite x:   
  
 1 <= *x* \* FLT\_RADIX-logb(x) < FLT\_RADIX   
  
 

Special Values| x | logb(x) | divide by 0? |
| ±∞ | +∞ | no |
| ±0.0 | -∞ | yes |



 
Examples:


```
writeln(logb(1.0)); // 0
writeln(logb(100.0)); // 6

writeln(logb(0.0)); // -real.infinity
writeln(logb(real.infinity)); // real.infinity
writeln(logb(-real.infinity)); // real.infinity

```
 
  nothrow @nogc @trusted real **fmod**(real x, real y);  
Calculates the remainder from the calculation x/y. 



Returns:
The value of x - i \* y, where i is the number of times that y can be completely subtracted from x. The result has the same sign as x. 

Special Values| x | y | fmod(x, y) | invalid? |
| ±0.0 | not 0.0 | ±0.0 | no |
| ±∞ | anything | NAN | yes |
| anything | ±0.0 | NAN | yes |
| !=±∞ | ±∞ | x | no |



 
Examples:


```
assert(isIdentical(fmod(0.0, 1.0), 0.0));
assert(fmod(5.0, 3.0).feqrel(2.0) > 16);
assert(isNaN(fmod(5.0, 0.0)));

```
 
  nothrow @nogc @trusted real **modf**(real x, ref real i);  
Breaks x into an integral part and a fractional part, each of which has the same sign as x. The integral part is stored in i. 



Returns:
The fractional part of x. 

Special Values| x | i (on input) | modf(x, i) | i (on return) |
| ±∞ | anything | ±0.0 | ±∞ |



 
Examples:


```
real frac;
real intpart;

frac = modf(3.14159, intpart);
assert(intpart.feqrel(3.0) > 16);
assert(frac.feqrel(0.14159) > 16);

```
 
  pure nothrow @nogc @safe real **scalbn**(real x, int n);   
  
pure nothrow @nogc @safe double **scalbn**(double x, int n);   
  
pure nothrow @nogc @safe float **scalbn**(float x, int n);  
Efficiently calculates x \* 2n. 


scalbn handles underflow and overflow in the same fashion as the basic arithmetic operators.   
  
 

Special Values| x | scalb(x) |
| ±∞ | ±∞ |
| ±0.0 | ±0.0 |



 
Examples:


```
writeln(scalbn(0x1.2345678abcdefp0L, 999)); // 0x1.2345678abcdefp999L
writeln(scalbn(-real.infinity, 5)); // -real.infinity
writeln(scalbn(2.0, 10)); // 2048.0
writeln(scalbn(2048.0f, -10)); // 2.0f

```
 
  nothrow @nogc @trusted real **cbrt**(real x);  
Calculates the cube root of x. 




Special Values| *x* | cbrt(x) | invalid? |
| ±0.0 | ±0.0 | no |
| NAN | NAN | yes |
| ±∞ | ±∞ | no |



 
Examples:


```
assert(cbrt(1.0).feqrel(1.0) > 16);
assert(cbrt(27.0).feqrel(3.0) > 16);
assert(cbrt(15.625).feqrel(2.5) > 16);

```
 
  pure nothrow @nogc @safe real **fabs**(real x);   
  
pure nothrow @nogc @trusted double **fabs**(double d);   
  
pure nothrow @nogc @trusted float **fabs**(float f);  
Returns |x| 




Special Values| x | fabs(x) |
| ±0.0 | +0.0 |
| ±∞ | +∞ |



 
Examples:


```
assert(isIdentical(fabs(0.0f), 0.0f));
assert(isIdentical(fabs(-0.0f), 0.0f));
writeln(fabs(-10.0f)); // 10.0f

assert(isIdentical(fabs(0.0), 0.0));
assert(isIdentical(fabs(-0.0), 0.0));
writeln(fabs(-10.0)); // 10.0

assert(isIdentical(fabs(0.0L), 0.0L));
assert(isIdentical(fabs(-0.0L), 0.0L));
writeln(fabs(-10.0L)); // 10.0L

```
 
  pure nothrow @nogc @safe real **hypot**(real x, real y);  
Calculates the length of the hypotenuse of a right-angled triangle with sides of length x and y. The hypotenuse is the value of the square root of the sums of the squares of x and y: 


sqrt(x2 + y2)   
  
 Note that hypot(x, y), hypot(y, x) and hypot(x, -y) are equivalent.   
  
 

Special Values| x | y | hypot(x, y) | invalid? |
| x | ±0.0 | |x| | no |
| ±∞ | y | +∞ | no |
| ±∞ | NAN | +∞ | no |



 
Examples:


```
assert(hypot(1.0, 1.0).feqrel(1.4142) > 16);
assert(hypot(3.0, 4.0).feqrel(5.0) > 16);
writeln(hypot(real.infinity, 1.0)); // real.infinity
writeln(hypot(real.infinity, real.nan)); // real.infinity

```
 
  pure nothrow @nogc @trusted real **ceil**(real x);   
  
pure nothrow @nogc @trusted double **ceil**(double x);   
  
pure nothrow @nogc @trusted float **ceil**(float x);  
Returns the value of x rounded upward to the next integer (toward positive infinity).



Examples:


```
writeln(ceil(+123.456L)); // +124
writeln(ceil(-123.456L)); // -123
writeln(ceil(-1.234L)); // -1
writeln(ceil(-0.123L)); // 0
writeln(ceil(0.0L)); // 0
writeln(ceil(+0.123L)); // 1
writeln(ceil(+1.234L)); // 2
writeln(ceil(real.infinity)); // real.infinity
assert(isNaN(ceil(real.nan)));
assert(isNaN(ceil(real.init)));

```
 
  pure nothrow @nogc @trusted real **floor**(real x);   
  
pure nothrow @nogc @trusted double **floor**(double x);   
  
pure nothrow @nogc @trusted float **floor**(float x);  
Returns the value of x rounded downward to the next integer (toward negative infinity).



Examples:


```
writeln(floor(+123.456L)); // +123
writeln(floor(-123.456L)); // -124
writeln(floor(+123.0L)); // +123
writeln(floor(-124.0L)); // -124
writeln(floor(-1.234L)); // -2
writeln(floor(-0.123L)); // -1
writeln(floor(0.0L)); // 0
writeln(floor(+0.123L)); // 0
writeln(floor(+1.234L)); // 1
writeln(floor(real.infinity)); // real.infinity
assert(isNaN(floor(real.nan)));
assert(isNaN(floor(real.init)));

```
 
  Unqual!F **quantize**(alias rfunc = rint, F)(const F val, const F unit)  
 Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F); 
 
Round `val` to a multiple of `unit`. `rfunc` specifies the rounding function to use; by default this is `rint`, which uses the current rounding mode.



Examples:


```
writeln(12345.6789L.quantize(0.01L)); // 12345.68L
writeln(12345.6789L.quantize!floor(0.01L)); // 12345.67L
writeln(12345.6789L.quantize(22.0L)); // 12342.0L

```
 
 
Examples:


```
writeln(12345.6789L.quantize(0)); // 12345.6789L
assert(12345.6789L.quantize(real.infinity).isNaN);
assert(12345.6789L.quantize(real.nan).isNaN);
writeln(real.infinity.quantize(0.01L)); // real.infinity
assert(real.infinity.quantize(real.nan).isNaN);
assert(real.nan.quantize(0.01L).isNaN);
assert(real.nan.quantize(real.infinity).isNaN);
assert(real.nan.quantize(real.nan).isNaN);

```
 
  Unqual!F **quantize**(real base, alias rfunc = rint, F, E)(const F val, const E exp)  
 Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F && isIntegral!E);   
  
Unqual!F **quantize**(real base, long exp = 1, alias rfunc = rint, F)(const F val)  
 Constraints: if (is(typeof(rfunc(F.init)) : F) && isFloatingPoint!F); 
 
Round `val` to a multiple of `pow(base, exp)`. `rfunc` specifies the rounding function to use; by default this is `rint`, which uses the current rounding mode.



Examples:


```
writeln(12345.6789L.quantize!10(-2)); // 12345.68L
writeln(12345.6789L.quantize!(10, -2)); // 12345.68L
writeln(12345.6789L.quantize!(10, floor)(-2)); // 12345.67L
writeln(12345.6789L.quantize!(10, -2, floor)); // 12345.67L

writeln(12345.6789L.quantize!22(1)); // 12342.0L
writeln(12345.6789L.quantize!22); // 12342.0L

```
 
  pure nothrow @nogc @safe real **nearbyint**(real x);  
Rounds x to the nearest integer value, using the current rounding mode. 


Unlike the rint functions, nearbyint does not raise the FE\_INEXACT exception.

 
Examples:


```
writeln(nearbyint(0.4)); // 0
writeln(nearbyint(0.5)); // 0
writeln(nearbyint(0.6)); // 1
writeln(nearbyint(100.0)); // 100

assert(isNaN(nearbyint(real.nan)));
writeln(nearbyint(real.infinity)); // real.infinity
writeln(nearbyint(-real.infinity)); // -real.infinity

```
 
  pure nothrow @nogc @safe real **rint**(real x);   
  
pure nothrow @nogc @safe double **rint**(double x);   
  
pure nothrow @nogc @safe float **rint**(float x);  
Rounds x to the nearest integer value, using the current rounding mode. 


If the return value is not equal to x, the FE\_INEXACT exception is raised.   
  
 [`nearbyint`](#nearbyint) performs the same operation, but does not set the FE\_INEXACT exception.

 
Examples:


```
version (IeeeFlagsSupport) resetIeeeFlags();
writeln(rint(0.4)); // 0
version (IeeeFlagsSupport) assert(ieeeFlags.inexact);

writeln(rint(0.5)); // 0
writeln(rint(0.6)); // 1
writeln(rint(100.0)); // 100

assert(isNaN(rint(real.nan)));
writeln(rint(real.infinity)); // real.infinity
writeln(rint(-real.infinity)); // -real.infinity

```
 
  pure nothrow @nogc @trusted long **lrint**(real x);  
Rounds x to the nearest integer value, using the current rounding mode. 


This is generally the fastest method to convert a floating-point number to an integer. Note that the results from this function depend on the rounding mode, if the fractional part of x is exactly 0.5. If using the default rounding mode (ties round to even integers) lrint(4.5) == 4, lrint(5.5)==6.

 
Examples:


```
writeln(lrint(4.5)); // 4
writeln(lrint(5.5)); // 6
writeln(lrint(-4.5)); // -4
writeln(lrint(-5.5)); // -6

writeln(lrint(int.max - 0.5)); // 2147483646L
writeln(lrint(int.max + 0.5)); // 2147483648L
writeln(lrint(int.min - 0.5)); // -2147483648L
writeln(lrint(int.min + 0.5)); // -2147483648L

```
 
  nothrow @nogc @trusted auto **round**(real x);  
Return the value of x rounded to the nearest integer. If the fractional part of x is exactly 0.5, the return value is rounded away from zero. 



Returns:
A `real`.
 
Examples:


```
writeln(round(4.5)); // 5
writeln(round(5.4)); // 5
writeln(round(-4.5)); // -5
writeln(round(-5.1)); // -5

```
 
  nothrow @nogc @trusted long **lround**(real x);  
Return the value of x rounded to the nearest integer. 


If the fractional part of x is exactly 0.5, the return value is rounded away from zero.   
  
 This function is not implemented for Digital Mars C runtime.

 
Examples:


```
version (CRuntime_DigitalMars) {}
else
{
    writeln(lround(0.49)); // 0
    writeln(lround(0.5)); // 1
    writeln(lround(1.5)); // 2
}

```
 
  pure nothrow @nogc @trusted real **trunc**(real x);  
Returns the integer portion of x, dropping the fractional portion. This is also known as "chop" rounding. `pure` on all platforms.



Examples:


```
writeln(trunc(0.01)); // 0
writeln(trunc(0.49)); // 0
writeln(trunc(0.5)); // 0
writeln(trunc(1.5)); // 1

```
 
  nothrow @nogc @trusted real **remainder**(real x, real y);   
  
nothrow @nogc @trusted real **remquo**(real x, real y, out int n);  
Calculate the remainder x REM y, following IEC 60559. 


REM is the value of x - y \* n, where n is the integer nearest the exact value of x / y. If |n - x / y| == 0.5, n is even. If the result is zero, it has the same sign as x. Otherwise, the sign of the result is the sign of x / y. Precision mode has no effect on the remainder functions.   
  
 remquo returns `n` in the parameter `n`.   
  
 

Special Values| x | y | remainder(x, y) | n | invalid? |
| ±0.0 | not 0.0 | ±0.0 | 0.0 | no |
| ±∞ | anything | -NAN | ? | yes |
| anything | ±0.0 | ±NAN | ? | yes |
| != ±∞ | ±∞ | x | ? | no |



 
Examples:


```
assert(remainder(5.1, 3.0).feqrel(-0.9) > 16);
assert(remainder(-5.1, 3.0).feqrel(0.9) > 16);
writeln(remainder(0.0, 3.0)); // 0.0

assert(isNaN(remainder(1.0, 0.0)));
assert(isNaN(remainder(-1.0, 0.0)));

```
 
 
Examples:


```
int n;

assert(remquo(5.1, 3.0, n).feqrel(-0.9) > 16 && n == 2);
assert(remquo(-5.1, 3.0, n).feqrel(0.9) > 16 && n == -2);
assert(remquo(0.0, 3.0, n) == 0.0 && n == 0);

```
 
  struct **IeeeFlags**;  
IEEE exception status flags ('sticky bits') 


These flags indicate that an exceptional floating-point condition has occurred. They indicate that a NaN or an infinity has been generated, that a result is inexact, or that a signalling NaN has been encountered. If floating-point exceptions are enabled (unmasked), a hardware exception will be generated instead of setting these flags.

 
Examples:


```
static void func() {
    int a = 10 * 10;
}
pragma(inline, false) static void blockopt(ref real x) {}
real a = 3.5;
// Set all the flags to zero
resetIeeeFlags();
assert(!ieeeFlags.divByZero);
blockopt(a); // avoid constant propagation by the optimizer
// Perform a division by zero.
a /= 0.0L;
writeln(a); // real.infinity
assert(ieeeFlags.divByZero);
blockopt(a); // avoid constant propagation by the optimizer
// Create a NaN
a *= 0.0L;
assert(ieeeFlags.invalid);
assert(isNaN(a));

// Check that calling func() has no effect on the
// status flags.
IeeeFlags f = ieeeFlags;
func();
writeln(ieeeFlags); // f

```
 
 
const nothrow @nogc @property @safe bool **inexact**();  
The result cannot be represented exactly, so rounding occurred. 



Example
 `x = sin(0.1);`

  const nothrow @nogc @property @safe bool **underflow**();  
A zero was generated by underflow 



Example
 `x = real.min*real.epsilon/2;`

  const nothrow @nogc @property @safe bool **overflow**();  
An infinity was generated by overflow 



Example
 `x = real.max*2;`

  const nothrow @nogc @property @safe bool **divByZero**();  
An infinity was generated by division by zero 



Example
 `x = 3/0.0;`

  const nothrow @nogc @property @safe bool **invalid**();  
A machine NaN was generated. 



Example
 `x = real.infinity * 0.0;`

    nothrow @nogc @trusted void **resetIeeeFlags**();  
Set all of the floating-point status flags to false.



Examples:


```
pragma(inline, false) static void blockopt(ref real x) {}
resetIeeeFlags();
real a = 3.5;
blockopt(a); // avoid constant propagation by the optimizer
a /= 0.0L;
blockopt(a); // avoid constant propagation by the optimizer
writeln(a); // real.infinity
assert(ieeeFlags.divByZero);

resetIeeeFlags();
assert(!ieeeFlags.divByZero);

```
 
  pure nothrow @nogc @property @trusted IeeeFlags **ieeeFlags**();  

Returns:
snapshot of the current state of the floating-point status flags
 
Examples:


```
pragma(inline, false) static void blockopt(ref real x) {}
resetIeeeFlags();
real a = 3.5;
blockopt(a); // avoid constant propagation by the optimizer

a /= 0.0L;
writeln(a); // real.infinity
assert(ieeeFlags.divByZero);
blockopt(a); // avoid constant propagation by the optimizer

a *= 0.0L;
assert(isNaN(a));
assert(ieeeFlags.invalid);

```
 
  struct **FloatingPointControl**;  
Control the Floating point hardware 


Change the IEEE754 floating-point rounding mode and the floating-point hardware exceptions.   
  
 By default, the rounding mode is roundToNearest and all hardware exceptions are disabled. For most applications, debugging is easier if the *division by zero*, *overflow*, and *invalid operation* exceptions are enabled. These three are combined into a *severeExceptions* value for convenience. Note in particular that if *invalidException* is enabled, a hardware trap will be generated whenever an uninitialized floating-point variable is used.   
  
 All changes are temporary. The previous state is restored at the end of the scope.   
  
 

 
Example


```
{
    FloatingPointControl fpctrl;

    // Enable hardware exceptions for division by zero, overflow to infinity,
    // invalid operations, and uninitialized floating-point variables.
    fpctrl.enableExceptions(FloatingPointControl.severeExceptions);

    // This will generate a hardware exception, if x is a
    // default-initialized floating point variable:
    real x; // Add `= 0` or even `= real.nan` to not throw the exception.
    real y = x * 3.0;

    // The exception is only thrown for default-uninitialized NaN-s.
    // NaN-s with other payload are valid:
    real z = y * real.nan; // ok

    // The set hardware exceptions and rounding modes will be disabled when
    // leaving this scope.
}

```
 
Examples:


```
FloatingPointControl fpctrl;

fpctrl.rounding = FloatingPointControl.roundDown;
writeln(lrint(1.5)); // 1.0

fpctrl.rounding = FloatingPointControl.roundUp;
writeln(lrint(1.4)); // 2.0

fpctrl.rounding = FloatingPointControl.roundToNearest;
writeln(lrint(1.5)); // 2.0

```
 
 
alias **RoundingMode** = uint;  
**roundToNearest**  
  
**roundDown**  
  
**roundUp**  
  
**roundToZero**  
  
**roundingMask**
 
IEEE rounding modes. The default mode is roundToNearest. 


roundingMask = A mask of all rounding modes.

  nothrow @nogc @property @trusted void **rounding**(RoundingMode newMode);  
Change the floating-point hardware rounding mode 


 Changing the rounding mode in the middle of a function can interfere with optimizations of floating point expressions, as the optimizer assumes that the rounding mode does not change. It is best to change the rounding mode only at the beginning of the function, and keep it until the function returns. It is also best to add the line: 
```
pragma(inline, false);

```
 as the first line of the function so it will not get inlined. 

 
Parameters:


|  |  |
| --- | --- |
| RoundingMode `newMode` | the new rounding mode |


  static pure nothrow @nogc @property @trusted RoundingMode **rounding**();  

Returns:
the currently active rounding mode
  alias **ExceptionMask** = uint;  
**subnormalException**  
  
**inexactException**  
  
**underflowException**  
  
**overflowException**  
  
**divByZeroException**  
  
**invalidException**  
  
**severeExceptions**  
  
**allExceptions**
 
IEEE hardware exceptions. By default, all exceptions are masked (disabled). 


severeExceptions = The overflow, division by zero, and invalid exceptions.

  static pure nothrow @nogc @property @safe bool **hasExceptionTraps**();  

Returns:
true if the current FPU supports exception trapping
  nothrow @nogc @trusted void **enableExceptions**(ExceptionMask exceptions);  
Enable (unmask) specific hardware exceptions. Multiple exceptions may be ORed together.

  nothrow @nogc @trusted void **disableExceptions**(ExceptionMask exceptions);  
Disable (mask) specific hardware exceptions. Multiple exceptions may be ORed together.

  static pure nothrow @nogc @property @trusted ExceptionMask **enabledExceptions**();  

Returns:
the exceptions which are currently enabled (unmasked)
    pure nothrow @nogc @trusted bool **isNaN**(X)(X x)  
 Constraints: if (isFloatingPoint!X); 
 
Determines if x is NaN. 



Parameters:


|  |  |
| --- | --- |
| X `x` | a floating point number. |


 
Returns:

`true` if x is Nan.
 
Examples:


```
assert( isNaN(float.init));
assert( isNaN(-double.init));
assert( isNaN(real.nan));
assert( isNaN(-real.nan));
assert(!isNaN(cast(float) 53.6));
assert(!isNaN(cast(real)-53.6));

```
 
  pure nothrow @nogc @trusted bool **isFinite**(X)(X x);  
Determines if x is finite. 



Parameters:


|  |  |
| --- | --- |
| X `x` | a floating point number. |


 
Returns:

`true` if x is finite.
 
Examples:


```
assert( isFinite(1.23f));
assert( isFinite(float.max));
assert( isFinite(float.min_normal));
assert(!isFinite(float.nan));
assert(!isFinite(float.infinity));

```
 
  pure nothrow @nogc @trusted bool **isNormal**(X)(X x);  
Determines if x is normalized. 


A normalized number must not be zero, subnormal, infinite nor NAN. 

 
Parameters:


|  |  |
| --- | --- |
| X `x` | a floating point number. |


 
Returns:

`true` if x is normalized.
 
Examples:


```
float f = 3;
double d = 500;
real e = 10e+48;

assert(isNormal(f));
assert(isNormal(d));
assert(isNormal(e));
f = d = e = 0;
assert(!isNormal(f));
assert(!isNormal(d));
assert(!isNormal(e));
assert(!isNormal(real.infinity));
assert(isNormal(-real.max));
assert(!isNormal(real.min_normal/4));

```
 
  pure nothrow @nogc @trusted bool **isSubnormal**(X)(X x);  
Determines if x is subnormal. 


Subnormals (also known as "denormal number"), have a 0 exponent and a 0 most significant mantissa bit. 

 
Parameters:


|  |  |
| --- | --- |
| X `x` | a floating point number. |


 
Returns:

`true` if x is a denormal number.
 
Examples:


```
import std.meta : AliasSeq;

static foreach (T; AliasSeq!(float, double, real))
{{
    T f;
    for (f = 1.0; !isSubnormal(f); f /= 2)
        assert(f != 0);
}}

```
 
  pure nothrow @nogc @trusted bool **isInfinity**(X)(X x)  
 Constraints: if (isFloatingPoint!X); 
 
Determines if x is ±∞. 



Parameters:


|  |  |
| --- | --- |
| X `x` | a floating point number. |


 
Returns:

`true` if x is ±∞.
 
Examples:


```
assert(!isInfinity(float.init));
assert(!isInfinity(-float.init));
assert(!isInfinity(float.nan));
assert(!isInfinity(-float.nan));
assert(isInfinity(float.infinity));
assert(isInfinity(-float.infinity));
assert(isInfinity(-1.0f / 0.0f));

```
 
  pure nothrow @nogc @trusted bool **isIdentical**(real x, real y);  
Is the binary representation of x identical to y?



Examples:


```
assert( isIdentical(0.0, 0.0));
assert( isIdentical(1.0, 1.0));
assert( isIdentical(real.infinity, real.infinity));
assert( isIdentical(-real.infinity, -real.infinity));

assert(!isIdentical(0.0, -0.0));
assert(!isIdentical(real.nan, -real.nan));
assert(!isIdentical(real.infinity, -real.infinity));

```
 
  pure nothrow @nogc @trusted int **signbit**(X)(X x);  
Return 1 if sign bit of e is set, 0 if not.



Examples:


```
assert(!signbit(float.nan));
assert(signbit(-float.nan));
assert(!signbit(168.1234f));
assert(signbit(-168.1234f));
assert(!signbit(0.0f));
assert(signbit(-0.0f));
assert(signbit(-float.max));
assert(!signbit(float.max));

assert(!signbit(double.nan));
assert(signbit(-double.nan));
assert(!signbit(168.1234));
assert(signbit(-168.1234));
assert(!signbit(0.0));
assert(signbit(-0.0));
assert(signbit(-double.max));
assert(!signbit(double.max));

assert(!signbit(real.nan));
assert(signbit(-real.nan));
assert(!signbit(168.1234L));
assert(signbit(-168.1234L));
assert(!signbit(0.0L));
assert(signbit(-0.0L));
assert(signbit(-real.max));
assert(!signbit(real.max));

```
 
  pure nothrow @nogc @trusted R **copysign**(R, X)(R to, X from)  
 Constraints: if (isFloatingPoint!R && isFloatingPoint!X);   
  
pure nothrow @nogc @trusted R **copysign**(R, X)(X to, R from)  
 Constraints: if (isIntegral!X && isFloatingPoint!R); 
 

Parameters:


|  |  |
| --- | --- |
| R `to` | the numeric value to use |
| X `from` | the sign value to use |


 
Returns:
a value composed of to with from's sign bit.
 
Examples:


```
writeln(copysign(1.0, 1.0)); // 1.0
writeln(copysign(1.0, -0.0)); // -1.0
writeln(copysign(1UL, -1.0)); // -1.0
writeln(copysign(-1.0, -1.0)); // -1.0

writeln(copysign(real.infinity, -1.0)); // -real.infinity
assert(copysign(real.nan, 1.0) is real.nan);
assert(copysign(-real.nan, 1.0) is real.nan);
assert(copysign(real.nan, -1.0) is -real.nan);

```
 
  pure nothrow @nogc @safe F **sgn**(F)(F x)  
 Constraints: if (isFloatingPoint!F || isIntegral!F); 
 
Returns `-1` if `x < 0`, `x` if `x == 0`, `1` if `x > 0`, and NAN if x==NAN.



Examples:


```
writeln(sgn(168.1234)); // 1
writeln(sgn(-168.1234)); // -1
writeln(sgn(0.0)); // 0
writeln(sgn(-0.0)); // 0

```
 
  pure nothrow @nogc @trusted real **NaN**(ulong payload);  
Create a quiet NAN, storing an integer inside the payload. 


For floats, the largest possible payload is 0x3F\_FFFF. For doubles, it is 0x3\_FFFF\_FFFF\_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF\_FFFF\_FFFF\_FFFF.

 
Examples:


```
real a = NaN(1_000_000);
assert(isNaN(a));
writeln(getNaNPayload(a)); // 1_000_000

```
 
  pure nothrow @nogc @trusted ulong **getNaNPayload**(real x);  
Extract an integral payload from a NAN. 



Returns:
the integer payload as a ulong. For floats, the largest possible payload is 0x3F\_FFFF. For doubles, it is 0x3\_FFFF\_FFFF\_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF\_FFFF\_FFFF\_FFFF.
 
Examples:


```
real a = NaN(1_000_000);
assert(isNaN(a));
writeln(getNaNPayload(a)); // 1_000_000

```
 
  pure nothrow @nogc @trusted real **nextUp**(real x);   
  
pure nothrow @nogc @trusted double **nextUp**(double x);   
  
pure nothrow @nogc @trusted float **nextUp**(float x);  
Calculate the next largest floating point value after x. 


Return the least number greater than x that is representable as a real; thus, it gives the next point on the IEEE number line.   
  
 

Special Values| x |  nextUp(x)  |
|  -∞ |  -real.max  |
|  ±0.0 | real.min\_normal\*real.epsilon  |
|  real.max |  ∞  |
|  ∞ |  ∞  |
| NAN | NAN |



 
Examples:


```
assert(nextUp(1.0 - 1.0e-6).feqrel(0.999999) > 16);
assert(nextUp(1.0 - real.epsilon).feqrel(1.0) > 16);

```
 
  pure nothrow @nogc @safe real **nextDown**(real x);   
  
pure nothrow @nogc @safe double **nextDown**(double x);   
  
pure nothrow @nogc @safe float **nextDown**(float x);  
Calculate the next smallest floating point value before x. 


Return the greatest number less than x that is representable as a real; thus, it gives the previous point on the IEEE number line.   
  
 

Special Values| x |  nextDown(x)  |
|  ∞ |  real.max  |
|  ±0.0 | -real.min\_normal\*real.epsilon  |
|  -real.max |  -∞  |
|  -∞ |  -∞  |
| NAN | NAN |



 
Examples:


```
writeln(nextDown(1.0 + real.epsilon)); // 1.0

```
 
  pure nothrow @nogc @safe T **nextafter**(T)(const T x, const T y);  
Calculates the next representable value after x in the direction of y. 


If y > x, the result will be the next largest floating-point value; if y < x, the result will be the next smallest value. If x == y, the result is y. If x or y is a NaN, the result is a NaN. 

 
Remarks
 This function is not generally very useful; it's almost always better to use the faster functions nextUp() or nextDown() instead. 
 The FE\_INEXACT and FE\_OVERFLOW exceptions will be raised if x is finite and the function result is infinite. The FE\_INEXACT and FE\_UNDERFLOW exceptions will be raised if the function value is subnormal, and x is not equal to y. 
Examples:


```
float a = 1;
assert(is(typeof(nextafter(a, a)) == float));
assert(nextafter(a, a.infinity) > a);
assert(isNaN(nextafter(a, a.nan)));
assert(isNaN(nextafter(a.nan, a)));

double b = 2;
assert(is(typeof(nextafter(b, b)) == double));
assert(nextafter(b, b.infinity) > b);
assert(isNaN(nextafter(b, b.nan)));
assert(isNaN(nextafter(b.nan, b)));

real c = 3;
assert(is(typeof(nextafter(c, c)) == real));
assert(nextafter(c, c.infinity) > c);
assert(isNaN(nextafter(c, c.nan)));
assert(isNaN(nextafter(c.nan, c)));

```
 
  pure nothrow @nogc @safe real **fdim**(real x, real y);  
Returns the positive difference between x and y. 


Equivalent to `fmax(x-y, 0)`. 

 
Returns:


Special Values| x, y | fdim(x, y) |
| x > y | x - y |
| x <= y | +0.0 |


 
Examples:


```
writeln(fdim(2.0, 0.0)); // 2.0
writeln(fdim(-2.0, 0.0)); // 0.0
writeln(fdim(real.infinity, 2.0)); // real.infinity
assert(isNaN(fdim(real.nan, 2.0)));
assert(isNaN(fdim(2.0, real.nan)));
assert(isNaN(fdim(real.nan, real.nan)));

```
 
  pure nothrow @nogc @safe F **fmax**(F)(const F x, const F y)  
 Constraints: if (\_\_traits(isFloating, F)); 
 
Returns the larger of `x` and `y`. 


If one of the arguments is a `NaN`, the other is returned. 

 
See Also:

[`std.algorithm.comparison.max`](std_algorithm_comparison#max) is faster because it does not perform the `isNaN` test.
 
Examples:


```
import std.meta : AliasSeq;
static foreach (F; AliasSeq!(float, double, real))
{
    writeln(fmax(F(0.0), F(2.0))); // 2.0
    writeln(fmax(F(-2.0), 0.0)); // F(0.0)
    writeln(fmax(F.infinity, F(2.0))); // F.infinity
    writeln(fmax(F.nan, F(2.0))); // F(2.0)
    writeln(fmax(F(2.0), F.nan)); // F(2.0)
}

```
 
  pure nothrow @nogc @safe F **fmin**(F)(const F x, const F y)  
 Constraints: if (\_\_traits(isFloating, F)); 
 
Returns the smaller of `x` and `y`. 


If one of the arguments is a `NaN`, the other is returned. 

 
See Also:

[`std.algorithm.comparison.min`](std_algorithm_comparison#min) is faster because it does not perform the `isNaN` test.
 
Examples:


```
import std.meta : AliasSeq;
static foreach (F; AliasSeq!(float, double, real))
{
    writeln(fmin(F(0.0), F(2.0))); // 0.0
    writeln(fmin(F(-2.0), F(0.0))); // -2.0
    writeln(fmin(F.infinity, F(2.0))); // 2.0
    writeln(fmin(F.nan, F(2.0))); // 2.0
    writeln(fmin(F(2.0), F.nan)); // 2.0
}

```
 
  pure nothrow @nogc @safe real **fma**(real x, real y, real z);  
Returns (x \* y) + z, rounding only once according to the current rounding mode. 



Bugs:
Not currently implemented - rounds twice.
 
Examples:


```
writeln(fma(0.0, 2.0, 2.0)); // 2.0
writeln(fma(2.0, 2.0, 2.0)); // 6.0
writeln(fma(real.infinity, 2.0, 2.0)); // real.infinity
assert(fma(real.nan, 2.0, 2.0) is real.nan);
assert(fma(2.0, 2.0, real.nan) is real.nan);

```
 
  pure nothrow @nogc @trusted Unqual!F **pow**(F, G)(F x, G n)  
 Constraints: if (isFloatingPoint!F && isIntegral!G); 
 
Compute the value of x n, where n is an integer



Examples:


```
writeln(pow(2.0, 5)); // 32.0
assert(pow(1.5, 9).feqrel(38.4433) > 16);
assert(pow(real.nan, 2) is real.nan);
writeln(pow(real.infinity, 2)); // real.infinity

```
 
  pure nothrow @nogc @trusted typeof(Unqual!F.init \* Unqual!G.init) **pow**(F, G)(F x, G n)  
 Constraints: if (isIntegral!F && isIntegral!G); 
 
Compute the power of two integral numbers. 



Parameters:


|  |  |
| --- | --- |
| F `x` | base |
| G `n` | exponent |


 
Returns:
x raised to the power of n. If n is negative the result is 1 / pow(x, -n), which is calculated as integer division with remainder. This may result in a division by zero error. If both x and n are 0, the result is 1. 
 
Throws:
If x is 0 and n is negative, the result is the same as the result of a division by zero.
 
Examples:


```
writeln(pow(2, 3)); // 8
writeln(pow(3, 2)); // 9

writeln(pow(2, 10)); // 1_024
writeln(pow(2, 20)); // 1_048_576
writeln(pow(2, 30)); // 1_073_741_824

writeln(pow(0, 0)); // 1

writeln(pow(1, -5)); // 1
writeln(pow(1, -6)); // 1
writeln(pow(-1, -5)); // -1
writeln(pow(-1, -6)); // 1

writeln(pow(-2, 5)); // -32
writeln(pow(-2, -5)); // 0
writeln(pow(cast(double)-2, -5)); // -0.03125

```
 
  pure nothrow @nogc @trusted real **pow**(I, F)(I x, F y)  
 Constraints: if (isIntegral!I && isFloatingPoint!F); 
 
Computes integer to floating point powers.



Examples:


```
writeln(pow(2, 5.0)); // 32.0
writeln(pow(7, 3.0)); // 343.0
assert(pow(2, real.nan) is real.nan);
writeln(pow(2, real.infinity)); // real.infinity

```
 
  pure nothrow @nogc @trusted Unqual!(Largest!(F, G)) **pow**(F, G)(F x, G y)  
 Constraints: if (isFloatingPoint!F && isFloatingPoint!G); 
 
Calculates xy. 




Special Values| x | y | pow(x, y) | div 0 | invalid? |
| anything | ±0.0 | 1.0 | no | no |
| |x| > 1 | +∞ | +∞ | no | no |
| |x| < 1 | +∞ | +0.0 | no | no |
| |x| > 1 | -∞ | +0.0 | no | no |
| |x| < 1 | -∞ | +∞ | no | no |
| +∞ | > 0.0 | +∞ | no | no |
| +∞ | < 0.0 | +0.0 | no | no |
| -∞ | odd integer > 0.0 | -∞ | no | no |
| -∞ | > 0.0, not odd integer | +∞ | no | no |
| -∞ | odd integer < 0.0 | -0.0 | no | no |
| -∞ | < 0.0, not odd integer | +0.0 | no | no |
| ±1.0 | ±∞ | -NAN | no | yes |
| < 0.0 | finite, nonintegral | NAN | no | yes |
| ±0.0 | odd integer < 0.0 | ±∞ | yes | no |
| ±0.0 | < 0.0, not odd integer | +∞ | yes | no |
| ±0.0 | odd integer > 0.0 | ±0.0 | no | no |
| ±0.0 | > 0.0, not odd integer | +0.0 | no | no |



 
Examples:


```
writeln(pow(1.0, 2.0)); // 1.0
writeln(pow(0.0, 0.0)); // 1.0
assert(pow(1.5, 10.0).feqrel(57.665) > 16);

// special values
writeln(pow(1.5, real.infinity)); // real.infinity
writeln(pow(0.5, real.infinity)); // 0.0
writeln(pow(1.5, -real.infinity)); // 0.0
writeln(pow(0.5, -real.infinity)); // real.infinity
writeln(pow(real.infinity, 1.0)); // real.infinity
writeln(pow(real.infinity, -1.0)); // 0.0
writeln(pow(-real.infinity, 1.0)); // -real.infinity
writeln(pow(-real.infinity, 2.0)); // real.infinity
writeln(pow(-real.infinity, -1.0)); // -0.0
writeln(pow(-real.infinity, -2.0)); // 0.0
assert(pow(1.0, real.infinity) is -real.nan);
writeln(pow(0.0, -1.0)); // real.infinity
writeln(pow(real.nan, 0.0)); // 1.0

```
 
  Unqual!(Largest!(F, H)) **powmod**(F, G, H)(F x, G n, H m)  
 Constraints: if (isUnsigned!F && isUnsigned!G && isUnsigned!H); 
 
Computes the value of a positive integer `x`, raised to the power `n`, modulo `m`. 



Parameters:


|  |  |
| --- | --- |
| F `x` | base |
| G `n` | exponent |
| H `m` | modulus |


 
Returns:

`x` to the power `n`, modulo `m`. The return type is the largest of `x`'s and `m`'s type. The function requires that all values have unsigned types.
 
Examples:


```
writeln(powmod(1U, 10U, 3U)); // 1
writeln(powmod(3U, 2U, 6U)); // 3
writeln(powmod(5U, 5U, 15U)); // 5
writeln(powmod(2U, 3U, 5U)); // 3
writeln(powmod(2U, 4U, 5U)); // 1
writeln(powmod(2U, 5U, 5U)); // 2

```
 
  pure nothrow @nogc @trusted int **feqrel**(X)(const X x, const X y)  
 Constraints: if (isFloatingPoint!X); 
 
To what precision is x equal to y? 



Returns:
the number of mantissa bits which are equal in x and y. eg, 0x1.F8p+60 and 0x1.F1p+60 are equal to 5 bits of precision. 

Special Values| x | y | feqrel(x, y) |
| x | x | real.mant\_dig |
| x | >= 2\*x | 0 |
| x | <= x/2 | 0 |
| NAN | any | 0 |
| any | NAN | 0 |



 
Examples:


```
writeln(feqrel(2.0, 2.0)); // 53
writeln(feqrel(2.0f, 2.0f)); // 24
writeln(feqrel(2.0, double.nan)); // 0

// Test that numbers are within n digits of each
// other by testing if feqrel > n * log2(10)

// five digits
assert(feqrel(2.0, 2.00001) > 16);
// ten digits
assert(feqrel(2.0, 2.00000000001) > 33);

```
 
  pure nothrow @nogc @trusted Unqual!(CommonType!(T1, T2)) **poly**(T1, T2)(T1 x, in T2[] A)  
 Constraints: if (isFloatingPoint!T1 && isFloatingPoint!T2);   
  
pure nothrow @nogc @safe Unqual!(CommonType!(T1, T2)) **poly**(T1, T2, int N)(T1 x, ref const T2[N] A)  
 Constraints: if (isFloatingPoint!T1 && isFloatingPoint!T2 && (N > 0) && (N <= 10)); 
 
Evaluate polynomial A(x) = a0 + a1x + a2x2 + a3x3; ... 


Uses Horner's rule A(x) = a0 + x(a1 + x(a2 + x(a3 + ...))) 

 
Parameters:


|  |  |
| --- | --- |
| T1 `x` | the value to evaluate. |
| T2[] `A` | array of coefficients a0, a1, etc. |


 
Examples:


```
real x = 3.1L;
static real[] pp = [56.1L, 32.7L, 6];

writeln(poly(x, pp)); // (56.1L + (32.7L + 6.0L * x) * x)

```
 
  bool **approxEqual**(T, U, V)(T value, U reference, V maxRelDiff = 0.01, V maxAbsDiff = 1e-05);  
Computes whether a values is approximately equal to a reference value, admitting a maximum relative difference, and a maximum absolute difference. 



Parameters:


|  |  |
| --- | --- |
| T `value` | Value to compare. |
| U `reference` | Reference value. |
| V `maxRelDiff` | Maximum allowable difference relative to `reference`. Setting to 0.0 disables this check. Defaults to `1e-2`. |
| V `maxAbsDiff` | Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to `1e-5`. |


 
Returns:

`true` if `value` is approximately equal to `reference` under either criterium. It is sufficient, when `value`  satisfies one of the two criteria. If one item is a range, and the other is a single value, then the result is the logical and-ing of calling `approxEqual` on each element of the ranged item against the single item. If both items are ranges, then `approxEqual` returns `true` if and only if the ranges have the same number of elements and if `approxEqual` evaluates to `true` for each pair of elements. 
 
See Also:
Use [`feqrel`](#feqrel) to get the number of equal bits in the mantissa.
 
Examples:


```
assert(approxEqual(1.0, 1.0099));
assert(!approxEqual(1.0, 1.011));
assert(approxEqual(0.00001, 0.0));
assert(!approxEqual(0.00002, 0.0));

assert(approxEqual(3.0, [3, 3.01, 2.99])); // several reference values is strange
assert(approxEqual([3, 3.01, 2.99], 3.0)); // better

float[] arr1 = [ 1.0, 2.0, 3.0 ];
double[] arr2 = [ 1.001, 1.999, 3 ];
assert(approxEqual(arr1, arr2));

```
 
 
Examples:


```
// relative comparison depends on reference, make sure proper
// side is used when comparing range to single value. Based on
// https://issues.dlang.org/show_bug.cgi?id=15763
auto a = [2e-3 - 1e-5];
auto b = 2e-3 + 1e-5;
assert(a[0].approxEqual(b));
assert(!b.approxEqual(a[0]));
assert(a.approxEqual(b));
assert(!b.approxEqual(a));

```
 
 
Examples:


```
assert(!approxEqual(0.0,1e-15,1e-9,0.0));
assert(approxEqual(0.0,1e-15,1e-9,1e-9));
assert(!approxEqual(1.0,3.0,0.0,1.0));

assert(approxEqual(1.00000000099,1.0,1e-9,0.0));
assert(!approxEqual(1.0000000011,1.0,1e-9,0.0));

```
 
 
Examples:


```
// maybe unintuitive behavior
assert(approxEqual(1000.0,1010.0));
assert(approxEqual(9_090_000_000.0,9_000_000_000.0));
assert(approxEqual(0.0,1e30,1.0));
assert(approxEqual(0.00001,1e-30));
assert(!approxEqual(-1e-30,1e-30,1e-2,0.0));

```
 
  bool **isClose**(T, U, V = CommonType!(FloatingPointBaseType!T, FloatingPointBaseType!U))(T lhs, U rhs, V maxRelDiff = CommonDefaultFor!(T, U), V maxAbsDiff = 0.0);  
Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference. 



Parameters:


|  |  |
| --- | --- |
| T `lhs` | First item to compare. |
| U `rhs` | Second item to compare. |
| V `maxRelDiff` | Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of `lhs` and `rhs`: It is approximately half the number of decimal digits of precision of the smaller type. |
| V `maxAbsDiff` | Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to `0.0`. |


 
Returns:

`true` if the two items are approximately equal under either criterium. It is sufficient, when `value`  satisfies one of the two criteria. If one item is a range, and the other is a single value, then the result is the logical and-ing of calling `isClose` on each element of the ranged item against the single item. If both items are ranges, then `isClose` returns `true` if and only if the ranges have the same number of elements and if `isClose` evaluates to `true` for each pair of elements. 
 
See Also:
Use [`feqrel`](#feqrel) to get the number of equal bits in the mantissa.
 
Examples:


```
assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));

```
 
 
Examples:


```
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));

```
 
  pure nothrow @nogc @trusted int **cmp**(T)(const(T) x, const(T) y)  
 Constraints: if (isFloatingPoint!T); 
 
Defines a total order on all floating-point numbers. 


The order is defined as follows: * All numbers in [-∞, +∞] are ordered the same way as by built-in comparison, with the exception of -0.0, which is less than +0.0;
* If the sign bit is set (that is, it's 'negative'), NAN is less than any number; if the sign bit is not set (it is 'positive'), NAN is greater than any number;
* NANs of the same sign are ordered by the payload ('negative' ones - in reverse order).

 

 
Returns:
negative value if `x` precedes `y` in the order specified above; 0 if `x` and `y` are identical, and positive value otherwise. 
 
See Also:

[*isIdentical*](#isIdentical) 
 
Standards:
Conforms to IEEE 754-2008
 
Examples:
Most numbers are ordered naturally. 
```
assert(cmp(-double.infinity, -double.max) < 0);
assert(cmp(-double.max, -100.0) < 0);
assert(cmp(-100.0, -0.5) < 0);
assert(cmp(-0.5, 0.0) < 0);
assert(cmp(0.0, 0.5) < 0);
assert(cmp(0.5, 100.0) < 0);
assert(cmp(100.0, double.max) < 0);
assert(cmp(double.max, double.infinity) < 0);

writeln(cmp(1.0, 1.0)); // 0

```
 
 
Examples:
Positive and negative zeroes are distinct. 
```
assert(cmp(-0.0, +0.0) < 0);
assert(cmp(+0.0, -0.0) > 0);

```
 
 
Examples:
Depending on the sign, NANs go to either end of the spectrum. 
```
assert(cmp(-double.nan, -double.infinity) < 0);
assert(cmp(double.infinity, double.nan) < 0);
assert(cmp(-double.nan, double.nan) < 0);

```
 
 
Examples:

NANs of the same sign are ordered by the payload. 
```
assert(cmp(NaN(10), NaN(20)) < 0);
assert(cmp(-NaN(20), -NaN(10)) < 0);

```
 
  T **nextPow2**(T)(const T val)  
 Constraints: if (isIntegral!T);   
  
T **nextPow2**(T)(const T val)  
 Constraints: if (isFloatingPoint!T); 
 
Gives the next power of two after `val`. `T` can be any built-in numerical type. 


If the operation would lead to an over/underflow, this function will return `0`. 

 
Parameters:


|  |  |
| --- | --- |
| T `val` | any number |


 
Returns:
the next power of two after `val`

 
Examples:


```
writeln(nextPow2(2)); // 4
writeln(nextPow2(10)); // 16
writeln(nextPow2(4000)); // 4096

writeln(nextPow2(-2)); // -4
writeln(nextPow2(-10)); // -16

writeln(nextPow2(uint.max)); // 0
writeln(nextPow2(uint.min)); // 0
writeln(nextPow2(size_t.max)); // 0
writeln(nextPow2(size_t.min)); // 0

writeln(nextPow2(int.max)); // 0
writeln(nextPow2(int.min)); // 0
writeln(nextPow2(long.max)); // 0
writeln(nextPow2(long.min)); // 0

```
 
 
Examples:


```
writeln(nextPow2(2.1)); // 4.0
writeln(nextPow2(-2.0)); // -4.0
writeln(nextPow2(0.25)); // 0.5
writeln(nextPow2(-4.0)); // -8.0

writeln(nextPow2(double.max)); // 0.0
writeln(nextPow2(double.infinity)); // double.infinity

```
 
  T **truncPow2**(T)(const T val)  
 Constraints: if (isIntegral!T);   
  
T **truncPow2**(T)(const T val)  
 Constraints: if (isFloatingPoint!T); 
 
Gives the last power of two before `val`. <>> can be any built-in numerical type. 



Parameters:


|  |  |
| --- | --- |
| T `val` | any number |


 
Returns:
the last power of two before `val`

 
Examples:


```
writeln(truncPow2(3)); // 2
writeln(truncPow2(4)); // 4
writeln(truncPow2(10)); // 8
writeln(truncPow2(4000)); // 2048

writeln(truncPow2(-5)); // -4
writeln(truncPow2(-20)); // -16

writeln(truncPow2(uint.max)); // int.max + 1
writeln(truncPow2(uint.min)); // 0
writeln(truncPow2(ulong.max)); // long.max + 1
writeln(truncPow2(ulong.min)); // 0

writeln(truncPow2(int.max)); // (int.max / 2) + 1
writeln(truncPow2(int.min)); // int.min
writeln(truncPow2(long.max)); // (long.max / 2) + 1
writeln(truncPow2(long.min)); // long.min

```
 
 
Examples:


```
writeln(truncPow2(2.1)); // 2.0
writeln(truncPow2(7.0)); // 4.0
writeln(truncPow2(-1.9)); // -1.0
writeln(truncPow2(0.24)); // 0.125
writeln(truncPow2(-7.0)); // -4.0

writeln(truncPow2(double.infinity)); // double.infinity

```
 
  pure nothrow @nogc @safe bool **isPowerOf2**(X)(const X x)  
 Constraints: if (isNumeric!X); 
 
Check whether a number is an integer power of two. 


Note that only positive numbers can be integer powers of two. This function always return `false` if `x` is negative or zero. 

 
Parameters:


|  |  |
| --- | --- |
| X `x` | the number to test |


 
Returns:

`true` if `x` is an integer power of two.
 
Examples:


```
assert( isPowerOf2(1.0L));
assert( isPowerOf2(2.0L));
assert( isPowerOf2(0.5L));
assert( isPowerOf2(pow(2.0L, 96)));
assert( isPowerOf2(pow(2.0L, -77)));

assert(!isPowerOf2(-2.0L));
assert(!isPowerOf2(-0.5L));
assert(!isPowerOf2(0.0L));
assert(!isPowerOf2(4.315));
assert(!isPowerOf2(1.0L / 3.0L));

assert(!isPowerOf2(real.nan));
assert(!isPowerOf2(real.infinity));

```
 
 
Examples:


```
assert( isPowerOf2(1));
assert( isPowerOf2(2));
assert( isPowerOf2(1uL << 63));

assert(!isPowerOf2(-4));
assert(!isPowerOf2(0));
assert(!isPowerOf2(1337u));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_math.html>

std.regex
=========

 [Regular expressions](https://en.wikipedia.org/wiki/Regular_expression) are a commonly used method of pattern matching on strings, with *regex* being a catchy word for a pattern in this domain specific language. Typical problems usually solved by regular expressions include validation of user input and the ubiquitous find & replace in text processing utilities. 


 

| Category | Functions |
| --- | --- |
| Matching | [`bmatch`](#bmatch) [`match`](#match) [`matchAll`](#matchAll) [`matchFirst`](#matchFirst) |
| Building | [`ctRegex`](#ctRegex) [`escaper`](#escaper) [`regex`](#regex) |
| Replace | [`replace`](#replace) [`replaceAll`](#replaceAll) [`replaceAllInto`](#replaceAllInto) [`replaceFirst`](#replaceFirst) [`replaceFirstInto`](#replaceFirstInto) |
| Split | [`split`](#split) [`splitter`](#splitter) |
| Objects | [`Captures`](#Captures) [`Regex`](#Regex) [`RegexException`](#RegexException) [`RegexMatch`](#RegexMatch) [`Splitter`](#Splitter) [`StaticRegex`](#StaticRegex) |

   
  
 ### [Synopsis](#Synopsis)

 
```
import std.regex;
import std.stdio;
void main()
{
    // Print out all possible dd/mm/yy(yy) dates found in user input.
    auto r = regex(r"\b[0-9][0-9]?/[0-9][0-9]?/[0-9][0-9](?:[0-9][0-9])?\b");
    foreach (line; stdin.byLine)
    {
      // matchAll() returns a range that can be iterated
      // to get all subsequent matches.
      foreach (c; matchAll(line, r))
          writeln(c.hit);
    }
}
...

// Create a static regex at compile-time, which contains fast native code.
auto ctr = ctRegex!(`^.*/([^/]+)/?&dollar;`);

// It works just like a normal regex:
auto c2 = matchFirst("foo/bar", ctr);   // First match found here, if any
assert(!c2.empty);   // Be sure to check if there is a match before examining contents!
assert(c2[1] == "bar");   // Captures is a range of submatches: 0 = full match.

...
// multi-pattern regex
auto multi = regex([`\d+,\d+`,`(a-z]+):(\d+)`]);
auto m = "abc:43 12,34".matchAll(multi);
assert(m.front.whichPattern == 2);
assert(m.front[1] == "abc");
assert(m.front[2] == "43");
m.popFront();
assert(m.front.whichPattern == 1);
assert(m.front[1] == "12");
...

// The result of the `matchAll/matchFirst` is directly testable with if/assert/while.
// e.g. test if a string consists of letters:
assert(matchFirst("Letter", `^\p{L}+&dollar;`));

```
   
  
 ### [Syntax and general information](#Syntax%20and%20general%20information)

 The general usage guideline is to keep regex complexity on the side of simplicity, as its capabilities reside in purely character-level manipulation. As such it's ill-suited for tasks involving higher level invariants like matching an integer number *bounded* in an [a,b] interval. Checks of this sort of are better addressed by additional post-processing.   
  
 The basic syntax shouldn't surprise experienced users of regular expressions. For an introduction to `std.regex` see a [short tour](http://dlang.org/regular-expression.html) of the module API and its abilities.   
  
 There are other web resources on regular expressions to help newcomers, and a good [reference with tutorial](http://www.regular-expressions.info) can easily be found.   
  
 This library uses a remarkably common ECMAScript syntax flavor with the following extensions: * Named subexpressions, with Python syntax.
* Unicode properties such as Scripts, Blocks and common binary properties e.g Alphabetic, White\_Space, Hex\_Digit etc.
* Arbitrary length and complexity lookbehind, including lookahead in lookbehind and vise-versa.

   
  
 ###  Pattern syntax

 *std.regex operates on codepoint level, 'character' in this table denotes a single Unicode codepoint.* 

|  |  |
| --- | --- |
| Pattern element | Semantics  |
| Atoms | Match single characters  |
| *any character except [{|\*+?()^$*  | Matches the character itself.  |
| *.*  | In single line mode matches any character. Otherwise it matches any character except '\n' and '\r'.  |
| *[class]*  | Matches a single character that belongs to this character class.  |
| *[^class]*  | Matches a single character that does *not* belong to this character class. |
| *\cC*  | Matches the control character corresponding to letter C |
| *\xXX*  | Matches a character with hexadecimal value of XX.  |
| *\uXXXX*  | Matches a character with hexadecimal value of XXXX.  |
| *\U00YYYYYY*  | Matches a character with hexadecimal value of YYYYYY.  |
| *\f*  | Matches a formfeed character.  |
| *\n*  | Matches a linefeed character.  |
| *\r*  | Matches a carriage return character.  |
| *\t*  | Matches a tab character.  |
| *\v*  | Matches a vertical tab character.  |
| *\d*  | Matches any Unicode digit.  |
| *\D*  | Matches any character except Unicode digits.  |
| *\w*  | Matches any word character (note: this includes numbers). |
| *\W*  | Matches any non-word character. |
| *\s*  | Matches whitespace, same as \p{White\_Space}. |
| *\S*  | Matches any character except those recognized as *\s* .  |
| *\\*  | Matches \ character.  |
| *\c where c is one of [|\*+?()*  | Matches the character c itself.  |
| *\p{PropertyName}*  | Matches a character that belongs to the Unicode PropertyName set. Single letter abbreviations can be used without surrounding {,}.  |
|  *\P{PropertyName}*  | Matches a character that does not belong to the Unicode PropertyName set. Single letter abbreviations can be used without surrounding {,}.  |
| *\p{InBasicLatin}*  | Matches any character that is part of the BasicLatin Unicode *block*. |
| *\P{InBasicLatin}*  | Matches any character except ones in the BasicLatin Unicode *block*. |
| *\p{Cyrillic}*  | Matches any character that is part of Cyrillic *script*. |
| *\P{Cyrillic}*  | Matches any character except ones in Cyrillic *script*. |
| Quantifiers | Specify repetition of other elements |
| *\**  | Matches previous character/subexpression 0 or more times. Greedy version - tries as many times as possible. |
| *\*?*  | Matches previous character/subexpression 0 or more times. Lazy version - stops as early as possible. |
| *+*  | Matches previous character/subexpression 1 or more times. Greedy version - tries as many times as possible. |
| *+?*  | Matches previous character/subexpression 1 or more times. Lazy version - stops as early as possible. |
| *{n}*  | Matches previous character/subexpression exactly n times.  |
| *{n,}*  | Matches previous character/subexpression n times or more. Greedy version - tries as many times as possible.  |
| *{n,}?*  | Matches previous character/subexpression n times or more. Lazy version - stops as early as possible. |
| *{n,m}*  | Matches previous character/subexpression n to m times. Greedy version - tries as many times as possible, but no more than m times.  |
| *{n,m}?*  | Matches previous character/subexpression n to m times. Lazy version - stops as early as possible, but no less then n times. |
| Other | Subexpressions & alternations  |
| *(regex)*  |  Matches subexpression regex, saving matched portion of text for later retrieval.  |
| *(?#comment)*  | An inline comment that is ignored while matching. |
| *(?:regex)*  | Matches subexpression regex, *not* saving matched portion of text. Useful to speed up matching.  |
| *A|B*  | Matches subexpression A, or failing that, matches B.  |
| *(?P<name>regex)*  | Matches named subexpression regex labeling it with name 'name'. When referring to a matched portion of text, names work like aliases in addition to direct numbers.  |
| Assertions | Match position rather than character  |
| *^*  | Matches at the begining of input or line (in multiline mode). |
| *$*  | Matches at the end of input or line (in multiline mode).  |
| *\b*  | Matches at word boundary.  |
| *\B*  | Matches when *not* at word boundary.  |
| *(?=regex)*  | Zero-width lookahead assertion. Matches at a point where the subexpression regex could be matched starting from the current position.  |
| *(?!regex)*  | Zero-width negative lookahead assertion. Matches at a point where the subexpression regex could *not* be matched starting from the current position.  |
| *(?<=regex)*  | Zero-width lookbehind assertion. Matches at a point where the subexpression regex could be matched ending at the current position (matching goes backwards).  |
|  *(?<!regex)*  | Zero-width negative lookbehind assertion. Matches at a point where the subexpression regex could *not* be matched ending at the current position (matching goes backwards).  |

   
  
 ###  Character classes

 

|  |  |
| --- | --- |
| Pattern element | Semantics  |
| *Any atom*  | Has the same meaning as outside of a character class, except for ] which must be written as \] |
| *a-z*  | Includes characters a, b, c, ..., z.  |
| *[a||b], [a--b], [a~~b], [a&&b]*  |  Where a, b are arbitrary classes, means union, set difference, symmetric set difference, and intersection respectively. *Any sequence of character class elements implicitly forms a union.* |

   
  
 ###  Regex flags

 

|  |  |
| --- | --- |
| Flag | Semantics  |
| *g*  | Global regex, repeat over the whole input.  |
| *i*  | Case insensitive matching.  |
| *m*  | Multi-line mode, match ^, $ on start and end line separators as well as start and end of input. |
| *s*  | Single-line mode, makes . match '\n' and '\r' as well.  |
| *x*  | Free-form syntax, ignores whitespace in pattern, useful for formatting complex regular expressions.  |

   
  
 ### [Unicode support](#Unicode%20support)

   
  
 This library provides full Level 1 support\* according to [UTS 18](http://unicode.org/reports/tr18/). Specifically: * 1.1 Hex notation via any of \uxxxx, \U00YYYYYY, \xZZ.
* 1.2 Unicode properties.
* 1.3 Character classes with set operations.
* 1.4 Word boundaries use the full set of "word" characters.
* 1.5 Using simple casefolding to match case insensitively across the full range of codepoints.
* 1.6 Respecting line breaks as any of \u000A | \u000B | \u000C | \u000D | \u0085 | \u2028 | \u2029 | \u000D\u000A.
* 1.7 Operating on codepoint level.

 \*With exception of point 1.1.1, as of yet, normalization of input is expected to be enforced by user.   
  
 ### [Replace format string](#Replace%20format%20string)

   
  
 A set of functions in this module that do the substitution rely on a simple format to guide the process. In particular the table below applies to the `format` argument of [`replaceFirst`](#replaceFirst) and [`replaceAll`](#replaceAll).   
  
 The format string can reference parts of match using the following notation. 

|  |  |
| --- | --- |
| Format specifier | Replaced by  |
| *&dollar;&*  | the whole match.  |
| *&dollar;`*  | part of input *preceding* the match.  |
| *$'*  | part of input *following* the match.  |
| *$$*  | '$' character.  |
| *\c , where c is any character*  | the character c itself.  |
| *\\*  | '\' character.  |
| *&dollar;1 .. &dollar;99*  | submatch number 1 to 99 respectively.  |

   
  
 ### [Slicing and zero memory allocations orientation](#Slicing%20and%20zero%20memory%20allocations%20orientation)

   
  
 All matches returned by pattern matching functionality in this library are slices of the original input. The notable exception is the `replace` family of functions that generate a new string from the input.   
  
 In cases where producing the replacement is the ultimate goal [`replaceFirstInto`](#replaceFirstInto) and [`replaceAllInto`](#replaceAllInto) could come in handy as functions that avoid allocations even for replacement. 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:
Dmitry Olshansky, API and utility constructs are modeled after the original `std.regex` by Walter Bright and Andrei Alexandrescu. 
 
Source
 [std/regex/package.d](https://github.com/dlang/phobos/blob/master/std/regex/package.d) 
 
template **Regex**(Char) 
`Regex` object holds regular expression pattern in compiled form. 


Instances of this object are constructed via calls to `regex`. This is an intended form for caching and storage of frequently used regular expressions. 

 
Example
 Test if this object doesn't contain any compiled pattern. 


```
Regex!char r;
assert(r.empty);
r = regex(""); // Note: "" is a valid regex pattern.
assert(!r.empty);

```
 Getting a range of all the named captures in the regex. 
```
import std.range;
import std.algorithm;

auto re = regex(`(?P<name>\w+) = (?P<var>\d+)`);
auto nc = re.namedCaptures;
static assert(isRandomAccessRange!(typeof(nc)));
assert(!nc.empty);
assert(nc.length == 2);
assert(nc.equal(["name", "var"]));
assert(nc[0] == "name");
assert(nc[1..$].equal(["var"]));

```
  alias **StaticRegex** = Regex(Char);  
A `StaticRegex` is `Regex` object that contains D code specially generated at compile-time to speed up matching. 


No longer used, kept as alias to Regex for backwards compatibility.

  @trusted auto **regex**(S : C[], C)(const S[] patterns, const(char)[] flags = "")  
 Constraints: if (isSomeString!S);   
  
@trusted auto **regex**(S)(S pattern, const(char)[] flags = "")  
 Constraints: if (isSomeString!S); 
 
Compile regular expression pattern for the later execution. 



Returns:

`Regex` object that works on inputs having the same character width as `pattern`. 
 
Parameters:


|  |  |
| --- | --- |
| S `pattern` | A single regular expression to match. |
| S[] `patterns` | An array of regular expression strings. The resulting `Regex` object will match any expression; use [`whichPattern`](#whichPattern) to know which. |
| const(char)[] `flags` | The attributes (g, i, m, s and x accepted) |


 
Throws:

`RegexException` if there were any errors during compilation.
 
Examples:


```
void test(S)()
{
    // multi-pattern regex example
    S[] arr = [`([a-z]+):(\d+)`, `(\d+),\d+`];
    auto multi = regex(arr); // multi regex
    S str = "abc:43 12,34";
    auto m = str.matchAll(multi);
    writeln(m.front.whichPattern); // 1
    writeln(m.front[1]); // "abc"
    writeln(m.front[2]); // "43"
    m.popFront();
    writeln(m.front.whichPattern); // 2
    writeln(m.front[1]); // "12"
}

import std.meta : AliasSeq;
static foreach (C; AliasSeq!(string, wstring, dstring))
    // Test with const array of patterns - see https://issues.dlang.org/show_bug.cgi?id=20301
    static foreach (S; AliasSeq!(C, const C, immutable C))
        test!S();

```
 
  enum auto **ctRegex**(alias pattern, alias flags = []);  
Compile regular expression using CTFE and generate optimized native machine code for matching it. 



Returns:
StaticRegex object for faster matching. 
 
Parameters:


|  |  |
| --- | --- |
| pattern | Regular expression |
| flags | The attributes (g, i, m, s and x accepted) |


  struct **Captures**(R) if (isSomeString!R);  
`Captures` object contains submatches captured during a call to `match` or iteration over `RegexMatch` range. 


First element of range is the whole match.

 
Examples:


```
import std.range.primitives : popFrontN;

auto c = matchFirst("@abc#", regex(`(\w)(\w)(\w)`));
assert(c.pre == "@"); // Part of input preceding match
assert(c.post == "#"); // Immediately after match
assert(c.hit == c[0] && c.hit == "abc"); // The whole match
writeln(c[2]); // "b"
writeln(c.front); // "abc"
c.popFront();
writeln(c.front); // "a"
writeln(c.back); // "c"
c.popBack();
writeln(c.back); // "b"
popFrontN(c, 2);
assert(c.empty);

assert(!matchFirst("nothing", "something"));

// Captures that are not matched will be null.
c = matchFirst("ac", regex(`a(b)?c`));
assert(c);
assert(!c[1]);

```
 
 
@property R **pre**();  
Slice of input prior to the match.

  @property R **post**();  
Slice of input immediately after the match.

  @property R **hit**();  
Slice of matched portion of input.

  @property R **front**();   
  
@property R **back**();   
  
void **popFront**();   
  
void **popBack**();   
  
const @property bool **empty**();   
  
inout inout(R) **opIndex**()(size\_t i);  
Range interface.

  const nothrow @safe bool **opCast**(T : bool)();  
Explicit cast to bool. Useful as a shorthand for !(x.empty) in if and assert statements. 



```
import std.regex;

assert(!matchFirst("nothing", "something"));

```
 

  const nothrow @property @safe int **whichPattern**();  
Number of pattern matched counting, where 1 - the first pattern. Returns 0 on no match.



Examples:


```
import std.regex;
writeln(matchFirst("abc", "[0-9]+", "[a-z]+").whichPattern); // 2

```
 
  R **opIndex**(String)(String i)  
 Constraints: if (isSomeString!String); 
 
Lookup named submatch. 



```
import std.regex;
import std.range;

auto c = matchFirst("a = 42;", regex(`(?P<var>\w+)\s*=\s*(?P<value>\d+);`));
assert(c["var"] == "a");
assert(c["value"] == "42");
popFrontN(c, 2);
//named groups are unaffected by range primitives
assert(c["var"] =="a");
assert(c.front == "42");

```
 

  const @property size\_t **length**();  
Number of matches in this object.

  @property ref auto **captures**();  
A hook for compatibility with original std.regex.

    struct **RegexMatch**(R) if (isSomeString!R);  
A regex engine state, as returned by `match` family of functions. 


Effectively it's a forward range of Captures!R, produced by lazily searching for matches in a given input.

 
@property R **pre**();   
  
@property R **post**();   
  
@property R **hit**();  
Shorthands for front.pre, front.post, front.hit.

  inout @property inout(Captures!R) **front**();   
  
void **popFront**();   
  
auto **save**();  
 Functionality for processing subsequent matches of global regexes via range interface: 
```
import std.regex;
auto m = matchAll("Hello, world!", regex(`\w+`));
assert(m.front.hit == "Hello");
m.popFront();
assert(m.front.hit == "world");
m.popFront();
assert(m.empty);

```
 

  const @property bool **empty**();  
Test if this match object is empty.

  T **opCast**(T : bool)();  
Same as !(x.empty), provided for its convenience in conditional statements.

  inout @property inout(Captures!R) **captures**();  
Same as .front, provided for compatibility with original std.regex.

    auto **match**(R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R));   
  
auto **match**(R, String)(R input, String re)  
 Constraints: if (isSomeString!R && isSomeString!String); 
 
Start matching `input` to regex pattern `re`, using Thompson NFA matching scheme. 


The use of this function is discouraged - use either of [`matchAll`](#matchAll) or [`matchFirst`](#matchFirst).   
  
 Delegating the kind of operation to "g" flag is soon to be phased out along with the ability to choose the exact matching scheme. The choice of matching scheme to use depends highly on the pattern kind and can done automatically on case by case basis. 

 
Returns:
a `RegexMatch` object holding engine state after first match.
  auto **matchFirst**(R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R));   
  
auto **matchFirst**(R, String)(R input, String re)  
 Constraints: if (isSomeString!R && isSomeString!String);   
  
auto **matchFirst**(R, String)(R input, String[] re...)  
 Constraints: if (isSomeString!R && isSomeString!String); 
 
Find the first (leftmost) slice of the `input` that matches the pattern `re`. This function picks the most suitable regular expression engine depending on the pattern properties. 


`re` parameter can be one of three types: * Plain string(s), in which case it's compiled to bytecode before matching.
* Regex!char (wchar/dchar) that contains a pattern in the form of compiled bytecode.
* StaticRegex!char (wchar/dchar) that contains a pattern in the form of compiled native machine code.

 

 
Returns:

[`Captures`](#Captures) containing the extent of a match together with all submatches if there was a match, otherwise an empty [`Captures`](#Captures) object.
  auto **matchAll**(R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R));   
  
auto **matchAll**(R, String)(R input, String re)  
 Constraints: if (isSomeString!R && isSomeString!String);   
  
auto **matchAll**(R, String)(R input, String[] re...)  
 Constraints: if (isSomeString!R && isSomeString!String); 
 
Initiate a search for all non-overlapping matches to the pattern `re` in the given `input`. The result is a lazy range of matches generated as they are encountered in the input going left to right. 


This function picks the most suitable regular expression engine depending on the pattern properties.   
  
 `re` parameter can be one of three types: * Plain string(s), in which case it's compiled to bytecode before matching.
* Regex!char (wchar/dchar) that contains a pattern in the form of compiled bytecode.
* StaticRegex!char (wchar/dchar) that contains a pattern in the form of compiled native machine code.

 

 
Returns:

[`RegexMatch`](#RegexMatch) object that represents matcher state after the first match was found or an empty one if not present.
  auto **bmatch**(R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R));   
  
auto **bmatch**(R, String)(R input, String re)  
 Constraints: if (isSomeString!R && isSomeString!String); 
 
Start matching of `input` to regex pattern `re`, using traditional  [backtracking](https://en.wikipedia.org/wiki/Backtracking) matching scheme. 


The use of this function is discouraged - use either of [`matchAll`](#matchAll) or [`matchFirst`](#matchFirst).   
  
 Delegating the kind of operation to "g" flag is soon to be phased out along with the ability to choose the exact matching scheme. The choice of matching scheme to use depends highly on the pattern kind and can done automatically on case by case basis. 

 
Returns:
a `RegexMatch` object holding engine state after first match.
  R **replaceFirst**(R, C, RegEx)(R input, RegEx re, const(C)[] format)  
 Constraints: if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R)); 
 
Construct a new string from `input` by replacing the first match with a string generated from it according to the `format` specifier. 


To replace all matches use [`replaceAll`](#replaceAll). 

 
Parameters:


|  |  |
| --- | --- |
| R `input` | string to search |
| RegEx `re` | compiled regular expression to use |
| const(C)[] `format` | format string to generate replacements from, see [the format string](#Replace%20format%20string). |


 
Returns:
A string of the same type with the first match (if any) replaced. If no match is found returns the input string itself.
 
Examples:


```
writeln(replaceFirst("noon", regex("n"), "[&dollar;&]")); // "[n]oon"

```
 
  R **replaceFirst**(alias fun, R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R)); 
 
This is a general replacement tool that construct a new string by replacing matches of pattern `re` in the `input`. Unlike the other overload there is no format string instead captures are passed to to a user-defined functor `fun` that returns a new string to use as replacement. 


This version replaces the first match in `input`, see [`replaceAll`](#replaceAll) to replace the all of the matches. 

 
Returns:
A new string of the same type as `input` with all matches replaced by return values of `fun`. If no matches found returns the `input` itself.
 
Examples:


```
import std.conv : to;
string list = "#21 out of 46";
string newList = replaceFirst!(cap => to!string(to!int(cap.hit)+1))
    (list, regex(`[0-9]+`));
writeln(newList); // "#22 out of 46"

```
 
  @trusted void **replaceFirstInto**(Sink, R, C, RegEx)(ref Sink sink, R input, RegEx re, const(C)[] format)  
 Constraints: if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));   
  
@trusted void **replaceFirstInto**(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re)  
 Constraints: if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R)); 
 
A variation on [`replaceFirst`](#replaceFirst) that instead of allocating a new string on each call outputs the result piece-wise to the `sink`. In particular this enables efficient construction of a final output incrementally. 


Like in [`replaceFirst`](#replaceFirst) family of functions there is an overload for the substitution guided by the `format` string and the one with the user defined callback.

 
Examples:


```
import std.array;
string m1 = "first message\n";
string m2 = "second message\n";
auto result = appender!string();
replaceFirstInto(result, m1, regex(`([a-z]+) message`), "&dollar;1");
//equivalent of the above with user-defined callback
replaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`));
writeln(result.data); // "first\nsecond\n"

```
 
  @trusted R **replaceAll**(R, C, RegEx)(R input, RegEx re, const(C)[] format)  
 Constraints: if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R)); 
 
Construct a new string from `input` by replacing all of the fragments that match a pattern `re` with a string generated from the match according to the `format` specifier. 


To replace only the first match use [`replaceFirst`](#replaceFirst). 

 
Parameters:


|  |  |
| --- | --- |
| R `input` | string to search |
| RegEx `re` | compiled regular expression to use |
| const(C)[] `format` | format string to generate replacements from, see [the format string](#Replace%20format%20string). |


 
Returns:
A string of the same type as `input` with the all of the matches (if any) replaced. If no match is found returns the input string itself.
 
Examples:


```
// insert comma as thousands delimiter
auto re = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g");
writeln(replaceAll("12000 + 42100 = 54100", re, ",")); // "12,000 + 42,100 = 54,100"

```
 
  @trusted R **replaceAll**(alias fun, R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R)); 
 
This is a general replacement tool that construct a new string by replacing matches of pattern `re` in the `input`. Unlike the other overload there is no format string instead captures are passed to to a user-defined functor `fun` that returns a new string to use as replacement. 


This version replaces all of the matches found in `input`, see [`replaceFirst`](#replaceFirst) to replace the first match only. 

 
Returns:
A new string of the same type as `input` with all matches replaced by return values of `fun`. If no matches found returns the `input` itself. 
 
Parameters:


|  |  |
| --- | --- |
| R `input` | string to search |
| RegEx `re` | compiled regular expression |
| fun | delegate to use |


 
Examples:


```
string baz(Captures!(string) m)
{
    import std.string : toUpper;
    return toUpper(m.hit);
}
// Capitalize the letters 'a' and 'r':
auto s = replaceAll!(baz)("Strap a rocket engine on a chicken.",
        regex("[ar]"));
writeln(s); // "StRAp A Rocket engine on A chicken."

```
 
  @trusted void **replaceAllInto**(Sink, R, C, RegEx)(Sink sink, R input, RegEx re, const(C)[] format)  
 Constraints: if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));   
  
@trusted void **replaceAllInto**(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re)  
 Constraints: if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R)); 
 
A variation on [`replaceAll`](#replaceAll) that instead of allocating a new string on each call outputs the result piece-wise to the `sink`. In particular this enables efficient construction of a final output incrementally. 


As with [`replaceAll`](#replaceAll) there are 2 overloads - one with a format string, the other one with a user defined functor.

 
Examples:


```
// insert comma as thousands delimiter in fifty randomly produced big numbers
import std.array, std.conv, std.random, std.range;
static re = regex(`(?<=\d)(?=(\d\d\d)+\b)`, "g");
auto sink = appender!(char [])();
enum ulong min = 10UL ^^ 10, max = 10UL ^^ 19;
foreach (i; 0 .. 50)
{
    sink.clear();
    replaceAllInto(sink, text(uniform(min, max)), re, ",");
    foreach (pos; iota(sink.data.length - 4, 0, -4))
        writeln(sink.data[pos]); // ','
}

```
 
  R **replace**(alias scheme = match, R, C, RegEx)(R input, RegEx re, const(C)[] format)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R));   
  
R **replace**(alias fun, R, RegEx)(R input, RegEx re)  
 Constraints: if (isSomeString!R && isRegexFor!(RegEx, R)); 
 
Old API for replacement, operation depends on flags of pattern `re`. With "g" flag it performs the equivalent of [`replaceAll`](#replaceAll) otherwise it works the same as [`replaceFirst`](#replaceFirst). 


The use of this function is discouraged, please use [`replaceAll`](#replaceAll) or [`replaceFirst`](#replaceFirst) explicitly.

  struct **Splitter**(Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, alias RegEx = Regex) if (isSomeString!Range && isRegexFor!(RegEx, Range));   
  
Splitter!(keepSeparators, Range, RegEx) **splitter**(Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, RegEx)(Range r, RegEx pat)  
 Constraints: if (is(BasicElementOf!Range : dchar) && isRegexFor!(RegEx, Range)); 
 
Splits a string `r` using a regular expression `pat` as a separator. 



Parameters:


|  |  |
| --- | --- |
| keepSeparators | flag to specify if the matches should be in the resulting range |
| Range `r` | the string to split |
| RegEx `pat` | the pattern to split on |


 
Returns:
A lazy range of strings
 
Examples:


```
import std.algorithm.comparison : equal;
auto s1 = ", abc, de,  fg, hi, ";
assert(equal(splitter(s1, regex(", *")),
    ["", "abc", "de", "fg", "hi", ""]));

```
 
 
Examples:
Split on a pattern, but keep the matches in the resulting range 
```
import std.algorithm.comparison : equal;
import std.typecons : Yes;

auto pattern = regex(`([\.,])`);

assert("2003.04.05"
    .splitter!(Yes.keepSeparators)(pattern)
    .equal(["2003", ".", "04", ".", "05"]));

assert(",1,2,3"
    .splitter!(Yes.keepSeparators)(pattern)
    .equal([",", "1", ",", "2", ",", "3"]));

```
 
 
@property Range **front**();   
  
@property bool **empty**();   
  
void **popFront**();   
  
@property auto **save**();  
Forward range primitives.

    @trusted String[] **split**(String, RegEx)(String input, RegEx rx)  
 Constraints: if (isSomeString!String && isRegexFor!(RegEx, String)); 
 
An eager version of `splitter` that creates an array with splitted slices of `input`.

  alias **RegexException** = std.regex.internal.ir.**RegexException**;  
Exception object thrown in case of errors during regex compilation.

  auto **escaper**(Range)(Range r);  
A range that lazily produces a string output escaped to be used inside of a regular expression.



Examples:


```
import std.algorithm.comparison;
import std.regex;
string s = `This is {unfriendly} to *regex*`;
assert(s.escaper.equal(`This is \{unfriendly\} to \*regex\*`));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_regex.html>

std.range.primitives
====================

 This module is a submodule of [`std.range`](std_range). 


It defines the bidirectional and forward range primitives for arrays: [`empty`](#empty), [`front`](#front), [`back`](#back), [`popFront`](#popFront), [`popBack`](#popBack) and [`save`](#save).   
  
 It provides basic range functionality by defining several templates for testing whether a given object is a range, and what kind of range it is:   
  
 

|  |  |
| --- | --- |
| [`isInputRange`](#isInputRange) | Tests if something is an *input range*, defined to be something from which one can sequentially read data using the primitives `front`, `popFront`, and `empty`.  |
| [`isOutputRange`](#isOutputRange) | Tests if something is an *output range*, defined to be something to which one can sequentially write data using the [`put`](#put) primitive.  |
| [`isForwardRange`](#isForwardRange) | Tests if something is a *forward range*, defined to be an input range with the additional capability that one can save one's current position with the `save` primitive, thus allowing one to iterate over the same range multiple times.  |
| [`isBidirectionalRange`](#isBidirectionalRange) | Tests if something is a *bidirectional range*, that is, a forward range that allows reverse traversal using the primitives  `back` and `popBack`.  |
| [`isRandomAccessRange`](#isRandomAccessRange) | Tests if something is a *random access range*, which is a bidirectional range that also supports the array subscripting operation via the primitive `opIndex`.  |

   
  
 It also provides number of templates that test for various range capabilities:   
  
 

|  |  |
| --- | --- |
| [`hasMobileElements`](#hasMobileElements) | Tests if a given range's elements can be moved around using the primitives `moveFront`, `moveBack`, or `moveAt`.  |
| [`ElementType`](#ElementType) | Returns the element type of a given range.  |
| [`ElementEncodingType`](#ElementEncodingType) | Returns the encoding element type of a given range.  |
| [`hasSwappableElements`](#hasSwappableElements) | Tests if a range is a forward range with swappable elements.  |
| [`hasAssignableElements`](#hasAssignableElements) | Tests if a range is a forward range with mutable elements.  |
| [`hasLvalueElements`](#hasLvalueElements) | Tests if a range is a forward range with elements that can be passed by reference and have their address taken.  |
| [`hasLength`](#hasLength) | Tests if a given range has the `length` attribute.  |
| [`isInfinite`](#isInfinite) | Tests if a given range is an *infinite range*.  |
| [`hasSlicing`](#hasSlicing) | Tests if a given range supports the array slicing operation  `R[x .. y]`.  |

   
  
 Finally, it includes some convenience functions for manipulating ranges:   
  
 

|  |  |
| --- | --- |
| [`popFrontN`](#popFrontN) | Advances a given range by up to *n* elements.  |
| [`popBackN`](#popBackN) | Advances a given bidirectional range from the right by up to *n* elements.  |
| [`popFrontExactly`](#popFrontExactly) | Advances a given range by up exactly *n* elements.  |
| [`popBackExactly`](#popBackExactly) | Advances a given bidirectional range from the right by exactly *n* elements.  |
| [`moveFront`](#moveFront) | Removes the front element of a range.  |
| [`moveBack`](#moveBack) | Removes the back element of a bidirectional range.  |
| [`moveAt`](#moveAt) | Removes the *i*'th element of a random-access range.  |
| [`walkLength`](#walkLength) | Computes the length of any range in O(n) time.  |
| [`put`](#put) | Outputs element `e` to a range.  |

 

 
Source
 [std/range/primitives.d](https://github.com/dlang/phobos/blob/master/std/range/primitives.d) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com), David Simcha, and [Jonathan M Davis](http://jmdavisprog.com). Credit for some of the ideas in building this module goes to [Leonardo Maffi](http://fantascienza.net/leonardo/so/).
 
enum bool **isInputRange**(R);  
Returns `true` if `R` is an input range. An input range must define the primitives `empty`, `popFront`, and `front`. The following code should compile for any input range. 



```
R r;              // can define a range object
if (r.empty) {}   // can test for empty
r.popFront();     // can invoke popFront()
auto h = r.front; // can get the front of the range of non-void type

```
   
  
 The following are rules of input ranges are assumed to hold true in all Phobos code. These rules are not checkable at compile-time, so not conforming to these rules when writing ranges or range based code will result in undefined behavior.   
  
 * `r.empty` returns `false` if and only if there is more data available in the range.
* `r.empty` evaluated multiple times, without calling `r.popFront`, or otherwise mutating the range object or the underlying data, yields the same result for every evaluation.
* `r.front` returns the current element in the range. It may return by value or by reference.
* `r.front` can be legally evaluated if and only if evaluating `r.empty` has, or would have, equaled `false`.
* `r.front` evaluated multiple times, without calling `r.popFront`, or otherwise mutating the range object or the underlying data, yields the same result for every evaluation.
* `r.popFront` advances to the next element in the range.
* `r.popFront` can be called if and only if evaluating `r.empty` has, or would have, equaled `false`.

   
  
 Also, note that Phobos code assumes that the primitives `r.front` and `r.empty` are Ο(`1`) time complexity wise or "cheap" in terms of running time. Ο() statements in the documentation of range functions are made with this assumption. 

 
See Also:
The header of [`std.range`](std_range) for tutorials on ranges. 
 
Parameters:


|  |  |
| --- | --- |
| R | type to be tested |


 
Returns:

`true` if R is an input range, `false` if not
 
Examples:


```
struct A {}
struct B
{
    void popFront();
    @property bool empty();
    @property int front();
}
static assert(!isInputRange!A);
static assert( isInputRange!B);
static assert( isInputRange!(int[]));
static assert( isInputRange!(char[]));
static assert(!isInputRange!(char[4]));
static assert( isInputRange!(inout(int)[]));

static struct NotDefaultConstructible
{
    @disable this();
    void popFront();
    @property bool empty();
    @property int front();
}
static assert( isInputRange!NotDefaultConstructible);

static struct NotDefaultConstructibleOrCopyable
{
    @disable this();
    @disable this(this);
    void popFront();
    @property bool empty();
    @property int front();
}
static assert(isInputRange!NotDefaultConstructibleOrCopyable);

static struct Frontless
{
    void popFront();
    @property bool empty();
}
static assert(!isInputRange!Frontless);

static struct VoidFront
{
    void popFront();
    @property bool empty();
    void front();
}
static assert(!isInputRange!VoidFront);

```
 
  void **put**(R, E)(ref R r, E e);  
Outputs `e` to `r`. The exact effect is dependent upon the two types. Several cases are accepted, as described below. The code snippets are attempted in order, and the first to compile "wins" and gets evaluated. 


In this table "doPut" is a method that places `e` into `r`, using the correct primitive: `r.put(e)` if `R` defines `put`, `r.front = e` if `r` is an input range (followed by `r.popFront()`), or `r(e)` otherwise.   
  
 

| Code Snippet | Scenario |
| --- | --- |
| `r.doPut(e);` | `R` specifically accepts an `E`. |
| `r.doPut([ e ]);` | `R` specifically accepts an `E[]`. |
| `r.putChar(e);` | `R` accepts some form of string or character. put will transcode the character `e` accordingly. |
| `for (; !e.empty; e.popFront()) put(r, e.front);` | Copying range `E` into `R`. |

 

 
Tip
 `put` should *not* be used "UFCS-style", e.g. `r.put(e)`. Doing this may call `R.put` directly, by-passing any transformation feature provided by `Range.put`. `put(r, e)` is prefered.
 
Examples:
When an output range's `put` method only accepts elements of type `T`, use the global `put` to handle outputting a `T[]` to the range or vice-versa. 
```
import std.traits : isSomeChar;

static struct A
{
    string data;

    void put(C)(C c) if (isSomeChar!C)
    {
        data ~= c;
    }
}
static assert(isOutputRange!(A, char));

auto a = A();
put(a, "Hello");
writeln(a.data); // "Hello"

```
 
 
Examples:

`put` treats dynamic arrays as array slices, and will call `popFront` on the slice after an element has been copied. Be sure to save the position of the array before calling `put`. 
```
int[] a = [1, 2, 3], b = [10, 20];
auto c = a;
put(a, b);
writeln(c); // [10, 20, 3]
// at this point, a was advanced twice, so it only contains
// its last element while c represents the whole array
writeln(a); // [3]

```
 
 
Examples:
It's also possible to `put` any width strings or characters into narrow strings -- put does the conversion for you. Note that putting the same width character as the target buffer type is `nothrow`, but transcoding can throw a [`std.utf.UTFException`](std_utf#UTFException). 
```
// the elements must be mutable, so using string or const(char)[]
// won't compile
char[] s1 = new char[13];
auto r1 = s1;
put(r1, "Hello, World!"w);
writeln(s1); // "Hello, World!"

```
 
  enum bool **isOutputRange**(R, E);  
Returns `true` if `R` is an output range for elements of type `E`. An output range is defined functionally as a range that supports the operation `put(r, e)` as defined above. 



See Also:
The header of [`std.range`](std_range) for tutorials on ranges.
 
Examples:


```
void myprint(scope const(char)[] s) { }
static assert(isOutputRange!(typeof(&myprint), char));

static assert( isOutputRange!(char[], char));
static assert( isOutputRange!(dchar[], wchar));
static assert( isOutputRange!(dchar[], dchar));

```
 
  enum bool **isForwardRange**(R);  
Returns `true` if `R` is a forward range. A forward range is an input range `r` that can save "checkpoints" by saving `r.save` to another value of type `R`. Notable examples of input ranges that are *not* forward ranges are file/socket ranges; copying such a range will not save the position in the stream, and they most likely reuse an internal buffer as the entire stream does not sit in memory. Subsequently, advancing either the original or the copy will advance the stream, so the copies are not independent. 


The following code should compile for any forward range.   
  
 
```
static assert(isInputRange!R);
R r1;
auto s1 = r1.save;
static assert(is(typeof(s1) == R));

```
   
  
 Saving a range is not duplicating it; in the example above, `r1` and `r2` still refer to the same underlying data. They just navigate that data independently.   
  
 The semantics of a forward range (not checkable during compilation) are the same as for an input range, with the additional requirement that backtracking must be possible by saving a copy of the range object with `save` and using it later. 

 
See Also:
The header of [`std.range`](std_range) for tutorials on ranges.
 
Examples:


```
static assert(!isForwardRange!(int));
static assert( isForwardRange!(int[]));
static assert( isForwardRange!(inout(int)[]));

```
 
  enum bool **isBidirectionalRange**(R);  
Returns `true` if `R` is a bidirectional range. A bidirectional range is a forward range that also offers the primitives `back` and `popBack`. The following code should compile for any bidirectional range. 


The semantics of a bidirectional range (not checkable during compilation) are assumed to be the following (`r` is an object of type `R`):   
  
 * `r.back` returns (possibly a reference to) the last element in the range. Calling `r.back` is allowed only if calling `r.empty` has, or would have, returned `false`.

 

 
See Also:
The header of [`std.range`](std_range) for tutorials on ranges.
 
Examples:


```
alias R = int[];
R r = [0,1];
static assert(isForwardRange!R);           // is forward range
r.popBack();                               // can invoke popBack
auto t = r.back;                           // can get the back of the range
auto w = r.front;
static assert(is(typeof(t) == typeof(w))); // same type for front and back

```
 
  enum bool **isRandomAccessRange**(R);  
Returns `true` if `R` is a random-access range. A random-access range is a bidirectional range that also offers the primitive `opIndex`, OR an infinite forward range that offers `opIndex`. In either case, the range must either offer `length` or be infinite. The following code should compile for any random-access range. 


The semantics of a random-access range (not checkable during compilation) are assumed to be the following (`r` is an object of type `R`): * `r.opIndex(n)` returns a reference to the `n`th element in the range.

   
  
 Although `char[]` and `wchar[]` (as well as their qualified versions including `string` and `wstring`) are arrays, `isRandomAccessRange` yields `false` for them because they use variable-length encodings (UTF-8 and UTF-16 respectively). These types are bidirectional ranges only. 

 
See Also:
The header of [`std.range`](std_range) for tutorials on ranges.
 
Examples:


```
import std.traits : isAggregateType, isAutodecodableString;

alias R = int[];

// range is finite and bidirectional or infinite and forward.
static assert(isBidirectionalRange!R ||
              isForwardRange!R && isInfinite!R);

R r = [0,1];
auto e = r[1]; // can index
auto f = r.front;
static assert(is(typeof(e) == typeof(f))); // same type for indexed and front
static assert(!(isAutodecodableString!R && !isAggregateType!R)); // narrow strings cannot be indexed as ranges
static assert(hasLength!R || isInfinite!R); // must have length or be infinite

// &dollar; must work as it does with arrays if opIndex works with &dollar;
static if (is(typeof(r[$])))
{
    static assert(is(typeof(f) == typeof(r[$])));

    // &dollar; - 1 doesn't make sense with infinite ranges but needs to work
    // with finite ones.
    static if (!isInfinite!R)
        static assert(is(typeof(f) == typeof(r[$ - 1])));
}

```
 
  enum bool **hasMobileElements**(R);  
Returns `true` iff `R` is an input range that supports the `moveFront` primitive, as well as `moveBack` and `moveAt` if it's a bidirectional or random access range. These may be explicitly implemented, or may work via the default behavior of the module level functions `moveFront` and friends. The following code should compile for any range with mobile elements. 



```
alias E = ElementType!R;
R r;
static assert(isInputRange!R);
static assert(is(typeof(moveFront(r)) == E));
static if (isBidirectionalRange!R)
    static assert(is(typeof(moveBack(r)) == E));
static if (isRandomAccessRange!R)
    static assert(is(typeof(moveAt(r, 0)) == E));

```
 

 
Examples:


```
import std.algorithm.iteration : map;
import std.range : iota, repeat;

static struct HasPostblit
{
    this(this) {}
}

auto nonMobile = map!"a"(repeat(HasPostblit.init));
static assert(!hasMobileElements!(typeof(nonMobile)));
static assert( hasMobileElements!(int[]));
static assert( hasMobileElements!(inout(int)[]));
static assert( hasMobileElements!(typeof(iota(1000))));

static assert( hasMobileElements!( string));
static assert( hasMobileElements!(dstring));
static assert( hasMobileElements!( char[]));
static assert( hasMobileElements!(dchar[]));

```
 
  template **ElementType**(R) 
The element type of `R`. `R` does not have to be a range. The element type is determined as the type yielded by `r.front` for an object `r` of type `R`. For example, `ElementType!(T[])` is `T` if `T[]` isn't a narrow string; if it is, the element type is `dchar`. If `R` doesn't have `front`, `ElementType!R` is `void`.



Examples:


```
import std.range : iota;

// Standard arrays: returns the type of the elements of the array
static assert(is(ElementType!(int[]) == int));

// Accessing .front retrieves the decoded dchar
static assert(is(ElementType!(char[])  == dchar)); // rvalue
static assert(is(ElementType!(dchar[]) == dchar)); // lvalue

// Ditto
static assert(is(ElementType!(string) == dchar));
static assert(is(ElementType!(dstring) == immutable(dchar)));

// For ranges it gets the type of .front.
auto range = iota(0, 10);
static assert(is(ElementType!(typeof(range)) == int));

```
 
  template **ElementEncodingType**(R) 
The encoding element type of `R`. For narrow strings (`char[]`, `wchar[]` and their qualified variants including `string` and `wstring`), `ElementEncodingType` is the character type of the string. For all other types, `ElementEncodingType` is the same as `ElementType`.



Examples:


```
import std.range : iota;
// internally the range stores the encoded type
static assert(is(ElementEncodingType!(char[])  == char));

static assert(is(ElementEncodingType!(wstring) == immutable(wchar)));

static assert(is(ElementEncodingType!(byte[]) == byte));

auto range = iota(0, 10);
static assert(is(ElementEncodingType!(typeof(range)) == int));

```
 
  enum bool **hasSwappableElements**(R);  
Returns `true` if `R` is an input range and has swappable elements. The following code should compile for any range with swappable elements. 



```
R r;
static assert(isInputRange!R);
swap(r.front, r.front);
static if (isBidirectionalRange!R) swap(r.back, r.front);
static if (isRandomAccessRange!R) swap(r[0], r.front);

```
 

 
Examples:


```
static assert(!hasSwappableElements!(const int[]));
static assert(!hasSwappableElements!(const(int)[]));
static assert(!hasSwappableElements!(inout(int)[]));
static assert( hasSwappableElements!(int[]));

static assert(!hasSwappableElements!( string));
static assert(!hasSwappableElements!(dstring));
static assert(!hasSwappableElements!( char[]));
static assert( hasSwappableElements!(dchar[]));

```
 
  enum bool **hasAssignableElements**(R);  
Returns `true` if `R` is an input range and has mutable elements. The following code should compile for any range with assignable elements. 



```
R r;
static assert(isInputRange!R);
r.front = r.front;
static if (isBidirectionalRange!R) r.back = r.front;
static if (isRandomAccessRange!R) r[0] = r.front;

```
 

 
Examples:


```
static assert(!hasAssignableElements!(const int[]));
static assert(!hasAssignableElements!(const(int)[]));
static assert( hasAssignableElements!(int[]));
static assert(!hasAssignableElements!(inout(int)[]));

static assert(!hasAssignableElements!( string));
static assert(!hasAssignableElements!(dstring));
static assert(!hasAssignableElements!( char[]));
static assert( hasAssignableElements!(dchar[]));

```
 
  enum bool **hasLvalueElements**(R);  
Tests whether the range `R` has lvalue elements. These are defined as elements that can be passed by reference and have their address taken. The following code should compile for any range with lvalue elements. 
```
void passByRef(ref ElementType!R stuff);
...
static assert(isInputRange!R);
passByRef(r.front);
static if (isBidirectionalRange!R) passByRef(r.back);
static if (isRandomAccessRange!R) passByRef(r[0]);

```
 

  template **hasLength**(R) 
Yields `true` if `R` has a `length` member that returns a value of `size_t` type. `R` does not have to be a range. If `R` is a range, algorithms in the standard library are only guaranteed to support `length` with type `size_t`. 


Note that `length` is an optional primitive as no range must implement it. Some ranges do not store their length explicitly, some cannot compute it without actually exhausting the range (e.g. socket streams), and some other ranges may be infinite.   
  
 Although narrow string types (`char[]`, `wchar[]`, and their qualified derivatives) do define a `length` property, `hasLength` yields `false` for them. This is because a narrow string's length does not reflect the number of characters, but instead the number of encoding units, and as such is not useful with range-oriented algorithms. To use strings as random-access ranges with length, use [`std.string.representation`](std_string#representation) or [`std.utf.byCodeUnit`](std_utf#byCodeUnit).

 
Examples:


```
static assert(!hasLength!(char[]));
static assert( hasLength!(int[]));
static assert( hasLength!(inout(int)[]));

struct A { size_t length() { return 0; } }
struct B { @property size_t length() { return 0; } }
static assert( hasLength!(A));
static assert( hasLength!(B));

```
 
  template **isInfinite**(R) 
Returns `true` if `R` is an infinite input range. An infinite input range is an input range that has a statically-defined enumerated member called `empty` that is always `false`, for example: 



```
struct MyInfiniteRange
{
    enum bool empty = false;
    ...
}

```
 

 
Examples:


```
import std.range : Repeat;
static assert(!isInfinite!(int[]));
static assert( isInfinite!(Repeat!(int)));

```
 
  enum bool **hasSlicing**(R);  
Returns `true` if `R` offers a slicing operator with integral boundaries that returns a forward range type. 


For finite ranges, the result of `opSlice` must be of the same type as the original range type. If the range defines `opDollar`, then it must support subtraction.   
  
 For infinite ranges, when *not* using `opDollar`, the result of `opSlice` must be the result of [`take`](#take) or [`takeExactly`](#takeExactly) on the original range (they both return the same type for infinite ranges). However, when using `opDollar`, the result of `opSlice` must be that of the original range type.   
  
 The following expression must be true for `hasSlicing` to be `true`:   
  
 
```
    isForwardRange!R
    && !isNarrowString!R
    && is(ReturnType!((R r) => r[1 .. 1].length) == size_t)
    && (is(typeof(lvalueOf!R[1 .. 1]) == R) || isInfinite!R)
    && (!is(typeof(lvalueOf!R[0 .. $])) || is(typeof(lvalueOf!R[0 .. $]) == R))
    && (!is(typeof(lvalueOf!R[0 .. $])) || isInfinite!R
        || is(typeof(lvalueOf!R[0 .. $ - 1]) == R))
    && is(typeof((ref R r)
    {
        static assert(isForwardRange!(typeof(r[1 .. 2])));
    }));

```
 

 
Examples:


```
import std.range : takeExactly;
static assert( hasSlicing!(int[]));
static assert( hasSlicing!(const(int)[]));
static assert(!hasSlicing!(const int[]));
static assert( hasSlicing!(inout(int)[]));
static assert(!hasSlicing!(inout int []));
static assert( hasSlicing!(immutable(int)[]));
static assert(!hasSlicing!(immutable int[]));
static assert(!hasSlicing!string);
static assert( hasSlicing!dstring);

enum rangeFuncs = "@property int front();" ~
                  "void popFront();" ~
                  "@property bool empty();" ~
                  "@property auto save() { return this; }" ~
                  "@property size_t length();";

struct A { mixin(rangeFuncs); int opSlice(size_t, size_t); }
struct B { mixin(rangeFuncs); B opSlice(size_t, size_t); }
struct C { mixin(rangeFuncs); @disable this(); C opSlice(size_t, size_t); }
struct D { mixin(rangeFuncs); int[] opSlice(size_t, size_t); }
static assert(!hasSlicing!(A));
static assert( hasSlicing!(B));
static assert( hasSlicing!(C));
static assert(!hasSlicing!(D));

struct InfOnes
{
    enum empty = false;
    void popFront() {}
    @property int front() { return 1; }
    @property InfOnes save() { return this; }
    auto opSlice(size_t i, size_t j) { return takeExactly(this, j - i); }
    auto opSlice(size_t i, Dollar d) { return this; }

    struct Dollar {}
    Dollar opDollar() const { return Dollar.init; }
}

static assert(hasSlicing!InfOnes);

```
 
  auto **walkLength**(Range)(Range range)  
 Constraints: if (isInputRange!Range && !isInfinite!Range);   
  
auto **walkLength**(Range)(Range range, const size\_t upTo)  
 Constraints: if (isInputRange!Range); 
 
This is a best-effort implementation of `length` for any kind of range. 


If `hasLength!Range`, simply returns `range.length` without checking `upTo` (when specified).   
  
 Otherwise, walks the range through its length and returns the number of elements seen. Performes Ο(`n`) evaluations of `range.empty` and `range.popFront()`, where `n` is the effective length of `range`.   
  
 The `upTo` parameter is useful to "cut the losses" in case the interest is in seeing whether the range has at least some number of elements. If the parameter `upTo` is specified, stops if `upTo` steps have been taken and returns `upTo`.   
  
 Infinite ranges are compatible, provided the parameter `upTo` is specified, in which case the implementation simply returns upTo.

 
Examples:


```
import std.range : iota;

writeln(10.iota.walkLength); // 10
// iota has a length function, and therefore the
// doesn't have to be walked, and the upTo
// parameter is ignored
writeln(10.iota.walkLength(5)); // 10

```
 
  size\_t **popFrontN**(Range)(ref Range r, size\_t n)  
 Constraints: if (isInputRange!Range);   
  
size\_t **popBackN**(Range)(ref Range r, size\_t n)  
 Constraints: if (isBidirectionalRange!Range); 
 
`popFrontN` eagerly advances `r` itself (not a copy) up to `n` times (by calling `r.popFront`). `popFrontN` takes `r` by `ref`, so it mutates the original range. Completes in Ο(`1`) steps for ranges that support slicing and have length. Completes in Ο(`n`) time for all other ranges. 


`popBackN` behaves the same as `popFrontN` but instead removes elements from the back of the (bidirectional) range instead of the front. 

 
Returns:
How much `r` was actually advanced, which may be less than `n` if `r` did not have at least `n` elements. 
 
See Also:

[`std.range.drop`](std_range#drop), [`std.range.dropBack`](std_range#dropBack)

 
Examples:


```
int[] a = [ 1, 2, 3, 4, 5 ];
a.popFrontN(2);
writeln(a); // [3, 4, 5]
a.popFrontN(7);
writeln(a); // []

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
auto LL = iota(1L, 7L);
auto r = popFrontN(LL, 2);
assert(equal(LL, [3L, 4L, 5L, 6L]));
writeln(r); // 2

```
 
 
Examples:


```
int[] a = [ 1, 2, 3, 4, 5 ];
a.popBackN(2);
writeln(a); // [1, 2, 3]
a.popBackN(7);
writeln(a); // []

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;
auto LL = iota(1L, 7L);
auto r = popBackN(LL, 2);
assert(equal(LL, [1L, 2L, 3L, 4L]));
writeln(r); // 2

```
 
  void **popFrontExactly**(Range)(ref Range r, size\_t n)  
 Constraints: if (isInputRange!Range);   
  
void **popBackExactly**(Range)(ref Range r, size\_t n)  
 Constraints: if (isBidirectionalRange!Range); 
 
Eagerly advances `r` itself (not a copy) exactly `n` times (by calling `r.popFront`). `popFrontExactly` takes `r` by `ref`, so it mutates the original range. Completes in Ο(`1`) steps for ranges that support slicing, and have either length or are infinite. Completes in Ο(`n`) time for all other ranges. 



Note
 Unlike [`popFrontN`](#popFrontN), `popFrontExactly` will assume that the range holds at least `n` elements. This makes `popFrontExactly` faster than `popFrontN`, but it also means that if `range` does not contain at least `n` elements, it will attempt to call `popFront` on an empty range, which is undefined behavior. So, only use `popFrontExactly` when it is guaranteed that `range` holds at least `n` elements. 
 `popBackExactly` will behave the same but instead removes elements from the back of the (bidirectional) range instead of the front. 
See Also:

[`std.range.dropExactly`](std_range#dropExactly), [`std.range.dropBackExactly`](std_range#dropBackExactly)

 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filterBidirectional;

auto a = [1, 2, 3];
a.popFrontExactly(1);
writeln(a); // [2, 3]
a.popBackExactly(1);
writeln(a); // [2]

string s = "日本語";
s.popFrontExactly(1);
writeln(s); // "本語"
s.popBackExactly(1);
writeln(s); // "本"

auto bd = filterBidirectional!"true"([1, 2, 3]);
bd.popFrontExactly(1);
assert(bd.equal([2, 3]));
bd.popBackExactly(1);
assert(bd.equal([2]));

```
 
  ElementType!R **moveFront**(R)(R r);  
Moves the front of `r` out and returns it. Leaves `r.front` in a destroyable state that does not allocate any resources (usually equal to its `.init` value).



Examples:


```
auto a = [ 1, 2, 3 ];
writeln(moveFront(a)); // 1
writeln(a.length); // 3

// define a perfunctory input range
struct InputRange
{
    enum bool empty = false;
    enum int front = 7;
    void popFront() {}
    int moveFront() { return 43; }
}
InputRange r;
// calls r.moveFront
writeln(moveFront(r)); // 43

```
 
  ElementType!R **moveBack**(R)(R r);  
Moves the back of `r` out and returns it. Leaves `r.back` in a destroyable state that does not allocate any resources (usually equal to its `.init` value).



Examples:


```
struct TestRange
{
    int payload = 5;
    @property bool empty() { return false; }
    @property TestRange save() { return this; }
    @property ref int front() return { return payload; }
    @property ref int back() return { return payload; }
    void popFront() { }
    void popBack() { }
}
static assert(isBidirectionalRange!TestRange);
TestRange r;
auto x = moveBack(r);
writeln(x); // 5

```
 
  ElementType!R **moveAt**(R)(R r, size\_t i);  
Moves element at index `i` of `r` out and returns it. Leaves  `r[i]` in a destroyable state that does not allocate any resources (usually equal to its `.init` value).



Examples:


```
auto a = [1,2,3,4];
foreach (idx, it; a)
{
    writeln(it); // moveAt(a, idx)
}

```
 
  @property bool **empty**(T)(auto ref scope T a)  
 Constraints: if (is(typeof(a.length) : size\_t)); 
 
Implements the range interface primitive `empty` for types that obey [`hasLength`](#hasLength) property and for narrow strings. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `a.empty` is equivalent to `empty(a)`.



Examples:


```
auto a = [ 1, 2, 3 ];
assert(!a.empty);
assert(a[3 .. $].empty);

int[string] b;
assert(b.empty);
b["zero"] = 0;
assert(!b.empty);

```
 
  pure nothrow @nogc @property @safe inout(T)[] **save**(T)(return scope inout(T)[] a);  
Implements the range interface primitive `save` for built-in arrays. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `array.save` is equivalent to `save(array)`. The function does not duplicate the content of the array, it simply returns its argument.



Examples:


```
auto a = [ 1, 2, 3 ];
auto b = a.save;
assert(b is a);

```
 
  pure nothrow @nogc @safe void **popFront**(T)(ref scope inout(T)[] a)  
 Constraints: if (!isAutodecodableString!(T[]) && !is(T[] == void[]));   
  
pure nothrow @trusted void **popFront**(C)(ref scope inout(C)[] str)  
 Constraints: if (isAutodecodableString!(C[])); 
 
Implements the range interface primitive `popFront` for built-in arrays. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `array.popFront` is equivalent to `popFront(array)`. For [narrow strings](http://dlang.org/glossary.html#narrow%20strings), `popFront` automatically advances to the next [code point](#).



Examples:


```
auto a = [ 1, 2, 3 ];
a.popFront();
writeln(a); // [2, 3]

```
 
  pure nothrow @nogc @safe void **popBack**(T)(ref scope inout(T)[] a)  
 Constraints: if (!isAutodecodableString!(T[]) && !is(T[] == void[]));   
  
pure @safe void **popBack**(T)(ref scope inout(T)[] a)  
 Constraints: if (isAutodecodableString!(T[])); 
 
Implements the range interface primitive `popBack` for built-in arrays. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `array.popBack` is equivalent to `popBack(array)`. For [narrow strings](http://dlang.org/glossary.html#narrow%20strings), `popFront` automatically eliminates the last [code point](http://dlang.org/glossary.html#code%20point).



Examples:


```
auto a = [ 1, 2, 3 ];
a.popBack();
writeln(a); // [1, 2]

```
 
  enum bool **autodecodeStrings**;  

EXPERIMENTAL
 to try out removing autodecoding, set the version `NoAutodecodeStrings`. Most things are expected to fail with this version currently.
  pure nothrow @nogc @property ref @safe inout(T) **front**(T)(return scope inout(T)[] a)  
 Constraints: if (!isAutodecodableString!(T[]) && !is(T[] == void[]));   
  
pure @property @safe dchar **front**(T)(scope const(T)[] a)  
 Constraints: if (isAutodecodableString!(T[])); 
 
Implements the range interface primitive `front` for built-in arrays. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `array.front` is equivalent to `front(array)`. For [narrow strings](http://dlang.org/glossary.html#narrow%20strings), `front` automatically returns the first [code point](http://dlang.org/glossary.html#code%20point) as a `dchar`.



Examples:


```
int[] a = [ 1, 2, 3 ];
writeln(a.front); // 1

```
 
  pure nothrow @nogc @property ref @safe inout(T) **back**(T)(return scope inout(T)[] a)  
 Constraints: if (!isAutodecodableString!(T[]) && !is(T[] == void[]));   
  
pure @property @safe dchar **back**(T)(scope const(T)[] a)  
 Constraints: if (isAutodecodableString!(T[])); 
 
Implements the range interface primitive `back` for built-in arrays. Due to the fact that nonmember functions can be called with the first argument using the dot notation, `array.back` is equivalent to `back(array)`. For [narrow strings](http://dlang.org/glossary.html#narrow%20strings), `back` automatically returns the last [code point](http://dlang.org/glossary.html#code%20point) as a `dchar`.



Examples:


```
int[] a = [ 1, 2, 3 ];
writeln(a.back); // 3
a.back += 4;
writeln(a.back); // 7

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_range_primitives.html>

std.uri
=======

 Encode and decode Uniform Resource Identifiers (URIs). URIs are used in internet transfer protocols. Valid URI characters consist of letters, digits, and the characters **;/?:@&=+$,-.!~\*'()** Reserved URI characters are **;/?:@&=+$,** Escape sequences consist of **%** followed by two hex digits. 



See Also:

[RFC 3986](https://www.ietf.org/rfc/rfc3986.txt)  
 [Wikipedia](http://en.wikipedia.org/wiki/Uniform_resource_identifier) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/uri.d](https://github.com/dlang/phobos/blob/master/std/uri.d)

 
class **URIException**: object.Exception;  
This Exception is thrown if something goes wrong when encoding or decoding a URI.



Examples:


```
import std.exception : assertThrown;
assertThrown!URIException("%ab".decode);

```
 
  string **decode**(Char)(scope const(Char)[] encodedURI)  
 Constraints: if (isSomeChar!Char); 
 
Decodes the URI string encodedURI into a UTF-8 string and returns it. Escape sequences that resolve to reserved URI characters are not replaced. Escape sequences that resolve to the '#' character are not replaced.



Examples:


```
writeln("foo%20bar".decode); // "foo bar"
writeln("%3C%3E.@.%E2%84%A2".decode); // "<>.@.™"
writeln("foo&/".decode); // "foo&/"
writeln("!@#&dollar;&*(".decode); // "!@#&dollar;&*("

```
 
  string **decodeComponent**(Char)(scope const(Char)[] encodedURIComponent)  
 Constraints: if (isSomeChar!Char); 
 
Decodes the URI string encodedURI into a UTF-8 string and returns it. All escape sequences are decoded.



Examples:


```
writeln("foo%2F%26".decodeComponent); // "foo/&"
writeln("dl%C3%A4ng%20r%C3%B6cks".decodeComponent); // "dläng röcks"
writeln("!%40%23%24%25%5E%26*(".decodeComponent); // "!@#&dollar;%^&*("

```
 
  string **encode**(Char)(scope const(Char)[] uri)  
 Constraints: if (isSomeChar!Char); 
 
Encodes the UTF-8 string uri into a URI and returns that URI. Any character not a valid URI character is escaped. The '#' character is not escaped.



Examples:


```
writeln("foo bar".encode); // "foo%20bar"
writeln("<>.@.™".encode); // "%3C%3E.@.%E2%84%A2"
writeln("foo/#?a=1&b=2".encode); // "foo/#?a=1&b=2"
writeln("dlang+rocks!".encode); // "dlang+rocks!"
writeln("!@#&dollar;%^&*(".encode); // "!@#&dollar;%25%5E&*("

```
 
  string **encodeComponent**(Char)(scope const(Char)[] uriComponent)  
 Constraints: if (isSomeChar!Char); 
 
Encodes the UTF-8 string uriComponent into a URI and returns that URI. Any character not a letter, digit, or one of -.!~\*'() is escaped.



Examples:


```
writeln("!@#&dollar;%^&*(".encodeComponent); // "!%40%23%24%25%5E%26*("
writeln("<>.@.™".encodeComponent); // "%3C%3E.%40.%E2%84%A2"
writeln("foo/&".encodeComponent); // "foo%2F%26"
writeln("dläng röcks".encodeComponent); // "dl%C3%A4ng%20r%C3%B6cks"
writeln("dlang+rocks!".encodeComponent); // "dlang%2Brocks!"

```
 
  ptrdiff\_t **uriLength**(Char)(scope const(Char)[] s)  
 Constraints: if (isSomeChar!Char); 
 
Does string s[] start with a URL? 



Returns:
-1 it does not len it does, and s[0 .. len] is the slice of s[] that is that URL
 
Examples:


```
string s1 = "http://www.digitalmars.com/~fred/fredsRX.html#foo end!";
writeln(uriLength(s1)); // 49
string s2 = "no uri here";
writeln(uriLength(s2)); // -1
assert(uriLength("issue 14924") < 0);

```
 
  ptrdiff\_t **emailLength**(Char)(scope const(Char)[] s)  
 Constraints: if (isSomeChar!Char); 
 
Does string s[] start with an email address? 



Returns:
-1 it does not len it does, and s[0 .. i] is the slice of s[] that is that email address 
 
References
 RFC2822
 
Examples:


```
string s1 = "my.e-mail@www.example-domain.com with garbage added";
writeln(emailLength(s1)); // 32
string s2 = "no email address here";
writeln(emailLength(s2)); // -1
assert(emailLength("issue 14924") < 0);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_uri.html>

std.socket
==========

 Socket primitives. 



Example
 See [/dmd/samples/d/listener.d](https://github.com/dlang/dmd/blob/master/samples/listener.d) and [/dmd/samples/d/htmlget.d](https://github.com/dlang/dmd/blob/master/samples/htmlget.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Christopher E. Miller, [David Nadlinger](http://klickverbot.at), [Vladimir Panteleev](http://thecybershadow.net) 
 
Source
 [std/socket.d](https://github.com/dlang/phobos/blob/master/std/socket.d)

 
class **SocketException**: object.Exception;  
Base exception thrown by `std.socket`.

  @property @safe string **lastSocketError**();  
Retrieve the error message for the most recently encountered network error.

  class **SocketOSException**: std.socket.SocketException;  
Socket exceptions representing network errors reported by the operating system.

 
int **errorCode**;  
Platform-specific error code.

  @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null, int err = \_lasterr(), string function(int) @trusted errorFormatter = &formatSocketError);  @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, int err = \_lasterr(), string function(int) @trusted errorFormatter = &formatSocketError);  @safe this(string msg, int err, string function(int) @trusted errorFormatter = &formatSocketError, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);    class **SocketParameterException**: std.socket.SocketException;  
Socket exceptions representing invalid parameters specified by user code.

  class **SocketFeatureException**: std.socket.SocketException;  
Socket exceptions representing attempts to use network capabilities not available on the current system.

  nothrow @nogc @safe bool **wouldHaveBlocked**();  

Returns:

`true` if the last socket operation failed because the socket was in non-blocking mode and the operation would have blocked, or if the socket is in blocking mode and set a SNDTIMEO or RCVTIMEO, and the operation timed out.
  enum **AddressFamily**: ushort;  
The communication domain used to resolve an address.

 
**UNSPEC** 
Unspecified address family

  **UNIX** 
Local communication

  **INET** 
Internet Protocol version 4

  **IPX** 
Novell IPX

  **APPLETALK** 
AppleTalk

  **INET6** 
Internet Protocol version 6

    enum **SocketType**: int;  
Communication semantics

 
**STREAM** 
Sequenced, reliable, two-way communication-based byte streams

  **DGRAM** 
Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order

  **RAW** 
Raw protocol access

  **RDM** 
Reliably-delivered message datagrams

  **SEQPACKET** 
Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length

    enum **ProtocolType**: int;  
Protocol

 
**IP** 
Internet Protocol version 4

  **ICMP** 
Internet Control Message Protocol

  **IGMP** 
Internet Group Management Protocol

  **GGP** 
Gateway to Gateway Protocol

  **TCP** 
Transmission Control Protocol

  **PUP** 
PARC Universal Packet Protocol

  **UDP** 
User Datagram Protocol

  **IDP** 
Xerox NS protocol

  **RAW** 
Raw IP packets

  **IPV6** 
Internet Protocol version 6

    class **Protocol**;  
`Protocol` is a class for retrieving protocol information. 



Example


```
auto proto = new Protocol;
writeln("About protocol TCP:");
if (proto.getProtocolByType(ProtocolType.TCP))
{
    writefln("  Name: %s", proto.name);
    foreach (string s; proto.aliases)
         writefln("  Alias: %s", s);
}
else
    writeln("  No information found");

```
 
ProtocolType **type**;   
  
string **name**;   
  
string[] **aliases**;  
These members are populated when one of the following functions are called successfully:

  nothrow @trusted bool **getProtocolByName**(scope const(char)[] name);  

Returns:
false on failure
  nothrow @trusted bool **getProtocolByType**(ProtocolType type);  

Returns:
false on failure
    class **Service**;  
`Service` is a class for retrieving service information. 



Example


```
auto serv = new Service;
writeln("About service epmap:");
if (serv.getServiceByName("epmap", "tcp"))
{
    writefln("  Service: %s", serv.name);
    writefln("  Port: %d", serv.port);
    writefln("  Protocol: %s", serv.protocolName);
    foreach (string s; serv.aliases)
         writefln("  Alias: %s", s);
}
else
    writefln("  No service for epmap.");

```
 
string **name**;   
  
string[] **aliases**;   
  
ushort **port**;   
  
string **protocolName**;  
These members are populated when one of the following functions are called successfully:

  nothrow @trusted bool **getServiceByName**(scope const(char)[] name, scope const(char)[] protocolName = null);   
  
nothrow @trusted bool **getServiceByPort**(ushort port, scope const(char)[] protocolName = null);  
If a protocol name is omitted, any protocol will be matched. 



Returns:
false on failure.
    class **HostException**: std.socket.SocketOSException;  
Class for exceptions thrown from an `InternetHost`.

  class **InternetHost**;  
`InternetHost` is a class for resolving IPv4 addresses. 


Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly.

 
Examples:


```
InternetHost ih = new InternetHost;

ih.getHostByAddr(0x7F_00_00_01);
writeln(ih.addrList[0]); // 0x7F_00_00_01
ih.getHostByAddr("127.0.0.1");
writeln(ih.addrList[0]); // 0x7F_00_00_01

if (!ih.getHostByName("www.digitalmars.com"))
    return;             // don't fail if not connected to internet

assert(ih.addrList.length);
InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY);
assert(ih.name == "www.digitalmars.com" || ih.name == "digitalmars.com",
        ih.name);

assert(ih.getHostByAddr(ih.addrList[0]));
string getHostNameFromInt = ih.name.dup;

assert(ih.getHostByAddr(ia.toAddrString()));
string getHostNameFromStr = ih.name.dup;

writeln(getHostNameFromInt); // getHostNameFromStr

```
 
 
string **name**;   
  
string[] **aliases**;   
  
uint[] **addrList**;  
These members are populated when one of the following functions are called successfully:

  @trusted bool **getHostByName**(scope const(char)[] name);  
Resolve host name. 



Returns:
false if unable to resolve.
  @trusted bool **getHostByAddr**(uint addr);  
Resolve IPv4 address number. 



Parameters:


|  |  |
| --- | --- |
| uint `addr` | The IPv4 address to resolve, in host byte order. |


 
Returns:
false if unable to resolve.
  @trusted bool **getHostByAddr**(scope const(char)[] addr);  
Same as previous, but addr is an IPv4 address string in the dotted-decimal form *a.b.c.d*. 



Returns:
false if unable to resolve.
    struct **AddressInfo**;  
Holds information about a socket address retrieved by `getAddressInfo`.

 
AddressFamily **family**;  
Address family

  SocketType **type**;  
Socket type

  ProtocolType **protocol**;  
Protocol

  Address **address**;  
Socket address

  string **canonicalName**;  
Canonical name, when `AddressInfoFlags.CANONNAME` is used.

    enum **AddressInfoFlags**: int;  
A subset of flags supported on all platforms with getaddrinfo. Specifies option flags for `getAddressInfo`.

 
**PASSIVE** 
The resulting addresses will be used in a call to `Socket.bind`.

  **CANONNAME** 
The canonical name is returned in `canonicalName` member in the first `AddressInfo`.

  **NUMERICHOST** 
The `node` parameter passed to `getAddressInfo` must be a numeric string. This will suppress any potentially lengthy network host address lookups.

    AddressInfo[] **getAddressInfo**(T...)(scope const(char)[] node, scope T options);  
Provides protocol-independent translation from host names to socket addresses. If advanced functionality is not required, consider using `getAddress` for compatibility with older systems. 



Returns:
Array with one `AddressInfo` per socket address. 
 
Throws:

`SocketOSException` on failure, or `SocketFeatureException` if this functionality is not available on the current system. 
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `node` | string containing host name or numeric address |
| T `options` | optional additional parameters, identified by type: * `string` - service name or port number
* `AddressInfoFlags` - option flags
* `AddressFamily` - address family to filter by
* `SocketType` - socket type to filter by
* `ProtocolType` - protocol to filter by
 |


 
Example


```
// Roundtrip DNS resolution
auto results = getAddressInfo("www.digitalmars.com");
assert(results[0].address.toHostNameString() ==
    "digitalmars.com");

// Canonical name
results = getAddressInfo("www.digitalmars.com",
    AddressInfoFlags.CANONNAME);
assert(results[0].canonicalName == "digitalmars.com");

// IPv6 resolution
results = getAddressInfo("ipv6.google.com");
assert(results[0].family == AddressFamily.INET6);

// Multihomed resolution
results = getAddressInfo("google.com");
assert(results.length > 1);

// Parsing IPv4
results = getAddressInfo("127.0.0.1",
    AddressInfoFlags.NUMERICHOST);
assert(results.length && results[0].family ==
    AddressFamily.INET);

// Parsing IPv6
results = getAddressInfo("::1",
    AddressInfoFlags.NUMERICHOST);
assert(results.length && results[0].family ==
    AddressFamily.INET6);

```
  @safe Address[] **getAddress**(scope const(char)[] hostname, scope const(char)[] service = null);   
  
@safe Address[] **getAddress**(scope const(char)[] hostname, ushort port);  
Provides protocol-independent translation from host names to socket addresses. Uses `getAddressInfo` if the current system supports it, and `InternetHost` otherwise. 



Returns:
Array with one `Address` instance per socket address. 
 
Throws:

`SocketOSException` on failure. 
 
Example


```
writeln("Resolving www.digitalmars.com:");
try
{
    auto addresses = getAddress("www.digitalmars.com");
    foreach (address; addresses)
        writefln("  IP: %s", address.toAddrString());
}
catch (SocketException e)
    writefln("  Lookup failed: %s", e.msg);

```
  @safe Address **parseAddress**(scope const(char)[] hostaddr, scope const(char)[] service = null);   
  
@safe Address **parseAddress**(scope const(char)[] hostaddr, ushort port);  
Provides protocol-independent parsing of network addresses. Does not attempt name resolution. Uses `getAddressInfo` with `AddressInfoFlags.NUMERICHOST` if the current system supports it, and `InternetAddress` otherwise. 



Returns:
An `Address` instance representing specified address. 
 
Throws:

`SocketException` on failure. 
 
Example


```
writeln("Enter IP address:");
string ip = readln().chomp();
try
{
    Address address = parseAddress(ip);
    writefln("Looking up reverse of %s:",
        address.toAddrString());
    try
    {
        string reverse = address.toHostNameString();
        if (reverse)
            writefln("  Reverse name: %s", reverse);
        else
            writeln("  Reverse hostname not found.");
    }
    catch (SocketException e)
        writefln("  Lookup error: %s", e.msg);
}
catch (SocketException e)
{
    writefln("  %s is not a valid IP address: %s",
        ip, e.msg);
}

```
  class **AddressException**: std.socket.SocketOSException;  
Class for exceptions thrown from an `Address`.

  abstract class **Address**;  
`Address` is an abstract class for representing a socket addresses. 



Example


```
writeln("About www.google.com port 80:");
try
{
    Address[] addresses = getAddress("www.google.com", 80);
    writefln("  %d addresses found.", addresses.length);
    foreach (int i, Address a; addresses)
    {
        writefln("  Address %d:", i+1);
        writefln("    IP address: %s", a.toAddrString());
        writefln("    Hostname: %s", a.toHostNameString());
        writefln("    Port: %s", a.toPortString());
        writefln("    Service name: %s",
            a.toServiceNameString());
    }
}
catch (SocketException e)
    writefln("  Lookup error: %s", e.msg);

```
 
abstract pure nothrow @nogc @property @safe sockaddr\* **name**();   
  
abstract const pure nothrow @nogc @property @safe const(sockaddr)\* **name**();  
Returns pointer to underlying `sockaddr` structure.

  abstract const pure nothrow @nogc @property @safe socklen\_t **nameLen**();  
Returns actual size of underlying `sockaddr` structure.

  const pure nothrow @nogc @property @safe AddressFamily **addressFamily**();  
Family of this address.

  const @safe string **toAddrString**();  
Attempts to retrieve the host address as a human-readable string. 



Throws:

`AddressException` on failure, or `SocketFeatureException` if address retrieval for this address family is not available on the current system.
  const @safe string **toHostNameString**();  
Attempts to retrieve the host name as a fully qualified domain name. 



Returns:
The FQDN corresponding to this `Address`, or `null` if the host name did not resolve. 
 
Throws:

`AddressException` on error, or `SocketFeatureException` if host name lookup for this address family is not available on the current system.
  const @safe string **toPortString**();  
Attempts to retrieve the numeric port number as a string. 



Throws:

`AddressException` on failure, or `SocketFeatureException` if port number retrieval for this address family is not available on the current system.
  const @safe string **toServiceNameString**();  
Attempts to retrieve the service name as a string. 



Throws:

`AddressException` on failure, or `SocketFeatureException` if service name lookup for this address family is not available on the current system.
  const @safe string **toString**();  
Human readable string representing this address.

    class **UnknownAddress**: std.socket.Address;  
`UnknownAddress` encapsulates an unknown socket address.

  class **UnknownAddressReference**: std.socket.Address;  
`UnknownAddressReference` encapsulates a reference to an arbitrary socket address.

 
pure nothrow @nogc @safe this(sockaddr\* sa, socklen\_t len);  
Constructs an `Address` with a reference to the specified `sockaddr`.

  pure nothrow @system this(const(sockaddr)\* sa, socklen\_t len);  
Constructs an `Address` with a copy of the specified `sockaddr`.

    class **InternetAddress**: std.socket.Address;  
`InternetAddress` encapsulates an IPv4 (Internet Protocol version 4) socket address. 


Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly.

 
enum uint **ADDR\_ANY**;  
Any IPv4 host address.

  enum uint **ADDR\_NONE**;  
An invalid IPv4 host address.

  enum ushort **PORT\_ANY**;  
Any IPv4 port number.

  const pure nothrow @nogc @property @safe ushort **port**();  
Returns the IPv4 port number (in host byte order).

  const pure nothrow @nogc @property @safe uint **addr**();  
Returns the IPv4 address number (in host byte order).

  @safe this(scope const(char)[] addr, ushort port);  
Construct a new `InternetAddress`. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `addr` | an IPv4 address string in the dotted-decimal form a.b.c.d, or a host name which will be resolved using an `InternetHost` object. |
| ushort `port` | port number, may be `PORT_ANY`. |


  pure nothrow @nogc @safe this(uint addr, ushort port);   
  
pure nothrow @nogc @safe this(ushort port);  
Construct a new `InternetAddress`. 



Parameters:


|  |  |
| --- | --- |
| uint `addr` | (optional) an IPv4 address in host byte order, may be `ADDR_ANY`. |
| ushort `port` | port number, may be `PORT_ANY`. |


  pure nothrow @nogc @safe this(sockaddr\_in addr);  
Construct a new `InternetAddress`. 



Parameters:


|  |  |
| --- | --- |
| sockaddr\_in `addr` | A sockaddr\_in as obtained from lower-level API calls such as getifaddrs. |


  const @trusted string **toAddrString**();  
Human readable string representing the IPv4 address in dotted-decimal form.

  const @safe string **toPortString**();  
Human readable string representing the IPv4 port.

  const @safe string **toHostNameString**();  
Attempts to retrieve the host name as a fully qualified domain name. 



Returns:
The FQDN corresponding to this `InternetAddress`, or `null` if the host name did not resolve. 
 
Throws:

`AddressException` on error.
  const @safe bool **opEquals**(Object o);  
Compares with another InternetAddress of same type for equality 



Returns:
true if the InternetAddresses share the same address and port number.
 
Examples:


```
auto addr1 = new InternetAddress("127.0.0.1", 80);
auto addr2 = new InternetAddress("127.0.0.2", 80);

writeln(addr1); // addr1
assert(addr1 != addr2);

```
 
  static nothrow @trusted uint **parse**(scope const(char)[] addr);  
Parse an IPv4 address string in the dotted-decimal form *a.b.c.d* and return the number. 



Returns:
If the string is not a legitimate IPv4 address, `ADDR_NONE` is returned.
  static nothrow @trusted string **addrToString**(uint addr);  
Convert an IPv4 address number in host byte order to a human readable string representing the IPv4 address in dotted-decimal form.

    class **Internet6Address**: std.socket.Address;  
`Internet6Address` encapsulates an IPv6 (Internet Protocol version 6) socket address. 


Consider using `getAddress`, `parseAddress` and `Address` methods instead of using this class directly.

 
static pure nothrow @nogc @property ref @safe const(ubyte)[16] **ADDR\_ANY**();  
Any IPv6 host address.

  enum ushort **PORT\_ANY**;  
Any IPv6 port number.

  const pure nothrow @nogc @property @safe ushort **port**();  
Returns the IPv6 port number.

  const pure nothrow @nogc @property @safe ubyte[16] **addr**();  
Returns the IPv6 address.

  @trusted this(scope const(char)[] addr, scope const(char)[] service = null);  
Construct a new `Internet6Address`. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `addr` | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. |
| const(char)[] `service` | (optional) service name. |


  @safe this(scope const(char)[] addr, ushort port);  
Construct a new `Internet6Address`. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `addr` | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. |
| ushort `port` | port number, may be `PORT_ANY`. |


  pure nothrow @nogc @safe this(ubyte[16] addr, ushort port);   
  
pure nothrow @nogc @safe this(ushort port);  
Construct a new `Internet6Address`. 



Parameters:


|  |  |
| --- | --- |
| ubyte[16] `addr` | (optional) an IPv6 host address in host byte order, or `ADDR_ANY`. |
| ushort `port` | port number, may be `PORT_ANY`. |


  pure nothrow @nogc @safe this(sockaddr\_in6 addr);  
Construct a new `Internet6Address`. 



Parameters:


|  |  |
| --- | --- |
| sockaddr\_in6 `addr` | A sockaddr\_in6 as obtained from lower-level API calls such as getifaddrs. |


  static @trusted ubyte[16] **parse**(scope const(char)[] addr);  
Parse an IPv6 host address string as described in RFC 2373, and return the address. 



Throws:

`SocketException` on error.
    class **UnixAddress**: std.socket.Address;  
`UnixAddress` encapsulates an address for a Unix domain socket (`AF_UNIX`), i.e. a socket bound to a path name in the file system. Available only on supported systems. 


Linux also supports an abstract address namespace, in which addresses are independent of the file system. A socket address is abstract iff `path` starts with a null byte (`'\0'`). Null bytes in other positions of an abstract address are allowed and have no special meaning. 

 
Example


```
auto addr = new UnixAddress("/var/run/dbus/system_bus_socket");
auto abstractAddr = new UnixAddress("\0/tmp/dbus-OtHLWmCLPR");

```
 
See Also:
[UNIX(7)](http://http//man7.org/linux/man-pages/man7/unix.7.html)
 
@safe this(scope const(char)[] path);  
Construct a new `UnixAddress` from the specified path.

  pure nothrow @nogc @safe this(sockaddr\_un addr);  
Construct a new `UnixAddress`. 



Parameters:


|  |  |
| --- | --- |
| sockaddr\_un `addr` | A sockaddr\_un as obtained from lower-level API calls. |


  const @property @safe string **path**();   
  
const @safe string **toString**();  
Get the underlying path.

    class **SocketAcceptException**: std.socket.SocketOSException;  
Class for exceptions thrown by `Socket.accept`.

  enum **SocketShutdown**: int;  
How a socket is shutdown:

 
**RECEIVE** 
socket receives are disallowed

  **SEND** 
socket sends are disallowed

  **BOTH** 
both RECEIVE and SEND

    enum **SocketFlags**: int;  
Flags may be OR'ed together:

 
**NONE** 
no flags specified

  **OOB** 
out-of-band stream data

  **PEEK** 
peek at incoming data without removing it from the queue, only for receiving

  **DONTROUTE** 
data should not be subject to routing; this flag may be ignored. Only for sending

    struct **TimeVal**;  
Duration timeout value.

 
tv\_sec\_t **seconds**;  
Number of seconds.

  tv\_usec\_t **microseconds**;  
Number of additional microseconds.

    class **SocketSet**;  
A collection of sockets for use with `Socket.select`. 


`SocketSet` wraps the platform `fd_set` type. However, unlike `fd_set`, `SocketSet` is not statically limited to `FD_SETSIZE` or any other limit, and grows as needed.

 
pure nothrow @safe this(size\_t size = FD\_SETSIZE);  
Create a SocketSet with a specific initial capacity (defaults to `FD_SETSIZE`, the system's default capacity).

  pure nothrow @nogc @safe void **reset**();  
Reset the `SocketSet` so that there are 0 `Socket`s in the collection.

  pure nothrow @safe void **add**(Socket s);  
Add a `Socket` to the collection. The socket must not already be in the collection.

  pure nothrow @safe void **remove**(Socket s);  
Remove this `Socket` from the collection. Does nothing if the socket is not in the collection already.

  const pure nothrow @nogc @safe int **isSet**(Socket s);  
Return nonzero if this `Socket` is in the collection.

  const pure nothrow @nogc @property @safe uint **max**();  

Returns:
The current capacity of this `SocketSet`. The exact meaning of the return value varies from platform to platform. 
 
Note
 Since D 2.065, this value does not indicate a restriction, and `SocketSet` will grow its capacity as needed automatically.
    enum **SocketOptionLevel**: int;  
The level at which a socket option is defined:

 
**SOCKET** 
Socket level

  **IP** 
Internet Protocol version 4 level

  **ICMP** 
Internet Control Message Protocol level

  **IGMP** 
Internet Group Management Protocol level

  **GGP** 
Gateway to Gateway Protocol level

  **TCP** 
Transmission Control Protocol level

  **PUP** 
PARC Universal Packet Protocol level

  **UDP** 
User Datagram Protocol level

  **IDP** 
Xerox NS protocol level

  **RAW** 
Raw IP packet level

  **IPV6** 
Internet Protocol version 6 level

    struct **Linger**;  
Linger information for use with SocketOption.LINGER.

 
l\_onoff\_t **on**;  
Nonzero for on.

  l\_linger\_t **time**;  
Linger time.

    enum **SocketOption**: int;  
Specifies a socket option:

 
**DEBUG** 
Record debugging information

  **BROADCAST** 
Allow transmission of broadcast messages

  **REUSEADDR** 
Allow local reuse of address

  **LINGER** 
Linger on close if unsent data is present

  **OOBINLINE** 
Receive out-of-band data in band

  **SNDBUF** 
Send buffer size

  **RCVBUF** 
Receive buffer size

  **DONTROUTE** 
Do not route

  **SNDTIMEO** 
Send timeout

  **RCVTIMEO** 
Receive timeout

  **ERROR** 
Retrieve and clear error status

  **KEEPALIVE** 
Enable keep-alive packets

  **ACCEPTCONN** 
Listen

  **RCVLOWAT** 
Minimum number of input bytes to process

  **SNDLOWAT** 
Minimum number of output bytes to process

  **TYPE** 
Socket type

  **TCP\_NODELAY** 
Disable the Nagle algorithm for send coalescing

  **IPV6\_UNICAST\_HOPS** 
IP unicast hop limit

  **IPV6\_MULTICAST\_IF** 
IP multicast interface

  **IPV6\_MULTICAST\_LOOP** 
IP multicast loopback

  **IPV6\_MULTICAST\_HOPS** 
IP multicast hops

  **IPV6\_JOIN\_GROUP** 
Add an IP group membership

  **IPV6\_LEAVE\_GROUP** 
Drop an IP group membership

  **IPV6\_V6ONLY** 
Treat wildcard bind as AF\_INET6-only

    class **Socket**;  
`Socket` is a class that creates a network communication endpoint using the Berkeley sockets interface.

 
@trusted this(AddressFamily af, SocketType type, ProtocolType protocol);   
  
@safe this(AddressFamily af, SocketType type);   
  
@trusted this(AddressFamily af, SocketType type, scope const(char)[] protocolName);  
Create a blocking socket. If a single protocol type exists to support this socket type within the address family, the `ProtocolType` may be omitted.

  @safe this(scope const AddressInfo info);  
Create a blocking socket using the parameters from the specified `AddressInfo` structure.

  pure nothrow @nogc @safe this(socket\_t sock, AddressFamily af);  
Use an existing socket handle.

  const pure nothrow @nogc @property @safe socket\_t **handle**();  
Get underlying socket handle.

  const nothrow @nogc @property @trusted bool **blocking**();   
  
@property @trusted void **blocking**(bool byes);  
Get/set socket's blocking flag. 


When a socket is blocking, calls to receive(), accept(), and send() will block and wait for data/action. A non-blocking socket will immediately return instead of blocking.

  @property @safe AddressFamily **addressFamily**();  
Get the socket's address family.

  const @property @trusted bool **isAlive**();  
Property that indicates if this is a valid, alive socket.

  @trusted void **bind**(Address addr);  
Associate a local address with this socket. 



Parameters:


|  |  |
| --- | --- |
| Address `addr` | The [`Address`](#Address) to associate this socket with. |


 
Throws:

[`SocketOSException`](#SocketOSException) when unable to bind the socket.
  @trusted void **connect**(Address to);  
Establish a connection. If the socket is blocking, connect waits for the connection to be made. If the socket is nonblocking, connect returns immediately and the connection attempt is still in progress.

  @trusted void **listen**(int backlog);  
Listen for an incoming connection. `bind` must be called before you can `listen`. The `backlog` is a request of how many pending incoming connections are queued until `accept`ed.

  protected pure nothrow @safe Socket **accepting**();  
Called by `accept` when a new `Socket` must be created for a new connection. To use a derived class, override this method and return an instance of your class. The returned `Socket`'s handle must not be set; `Socket` has a protected constructor `this()` to use in this situation. 


Override to use a derived class. The returned socket's handle must not be set.

  @trusted Socket **accept**();  
Accept an incoming connection. If the socket is blocking, `accept` waits for a connection request. Throws `SocketAcceptException` if unable to accept. See `accepting` for use with derived classes.

  nothrow @nogc @trusted void **shutdown**(SocketShutdown how);  
Disables sends and/or receives.

  nothrow @nogc @trusted void **close**();  
Immediately drop any connections and release socket resources. The `Socket` object is no longer usable after `close`. Calling `shutdown` before `close` is recommended for connection-oriented sockets.

  static @property @trusted string **hostName**();  

Returns:
the local machine's host name
  @property @trusted Address **remoteAddress**();  
Remote endpoint `Address`.

  @property @trusted Address **localAddress**();  
Local endpoint `Address`.

  enum int **ERROR**;  
Send or receive error code. See `wouldHaveBlocked`, `lastSocketError` and `Socket.getErrorText` for obtaining more information about the error.

  @trusted ptrdiff\_t **send**(const(void)[] buf, SocketFlags flags);   
  
@safe ptrdiff\_t **send**(const(void)[] buf);  
Send data on the connection. If the socket is blocking and there is no buffer space left, `send` waits. 



Returns:
The number of bytes actually sent, or `Socket.ERROR` on failure.
  @trusted ptrdiff\_t **sendTo**(const(void)[] buf, SocketFlags flags, Address to);   
  
@safe ptrdiff\_t **sendTo**(const(void)[] buf, Address to);   
  
@trusted ptrdiff\_t **sendTo**(const(void)[] buf, SocketFlags flags);   
  
@safe ptrdiff\_t **sendTo**(const(void)[] buf);  
Send data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer space left, `sendTo` waits. 



Returns:
The number of bytes actually sent, or `Socket.ERROR` on failure.
  @trusted ptrdiff\_t **receive**(void[] buf, SocketFlags flags);   
  
@safe ptrdiff\_t **receive**(void[] buf);  
Receive data on the connection. If the socket is blocking, `receive` waits until there is data to be received. 



Returns:
The number of bytes actually received, `0` if the remote side has closed the connection, or `Socket.ERROR` on failure.
  @trusted ptrdiff\_t **receiveFrom**(void[] buf, SocketFlags flags, ref Address from);   
  
@safe ptrdiff\_t **receiveFrom**(void[] buf, ref Address from);   
  
@trusted ptrdiff\_t **receiveFrom**(void[] buf, SocketFlags flags);   
  
@safe ptrdiff\_t **receiveFrom**(void[] buf);  
Receive data and get the remote endpoint `Address`. If the socket is blocking, `receiveFrom` waits until there is data to be received. 



Returns:
The number of bytes actually received, `0` if the remote side has closed the connection, or `Socket.ERROR` on failure.
  @trusted int **getOption**(SocketOptionLevel level, SocketOption option, void[] result);  
Get a socket option. 



Returns:
The number of bytes written to `result`. The length, in bytes, of the actual result - very different from getsockopt()
  @trusted int **getOption**(SocketOptionLevel level, SocketOption option, out int32\_t result);  
Common case of getting integer and boolean options.

  @trusted int **getOption**(SocketOptionLevel level, SocketOption option, out Linger result);  
Get the linger option.

  @trusted void **getOption**(SocketOptionLevel level, SocketOption option, out Duration result);  
Get a timeout (duration) option.

  @trusted void **setOption**(SocketOptionLevel level, SocketOption option, void[] value);  
Set a socket option.

  @trusted void **setOption**(SocketOptionLevel level, SocketOption option, int32\_t value);  
Common case for setting integer and boolean options.

  @trusted void **setOption**(SocketOptionLevel level, SocketOption option, Linger value);  
Set the linger option.

  @trusted void **setOption**(SocketOptionLevel level, SocketOption option, Duration value);  
Sets a timeout (duration) option, i.e. `SocketOption.SNDTIMEO` or `RCVTIMEO`. Zero indicates no timeout. 


In a typical application, you might also want to consider using a non-blocking socket instead of setting a timeout on a blocking one. 

 
Note
 While the receive timeout setting is generally quite accurate on \*nix systems even for smaller durations, there are two issues to be aware of on Windows: First, although undocumented, the effective timeout duration seems to be the one set on the socket plus half a second. `setOption()` tries to compensate for that, but still, timeouts under 500ms are not possible on Windows. Second, be aware that the actual amount of time spent until a blocking call returns randomly varies on the order of 10ms. 
 
Parameters:


|  |  |
| --- | --- |
| SocketOptionLevel `level` | The level at which a socket option is defined. |
| SocketOption `option` | Either `SocketOption.SNDTIMEO` or `SocketOption.RCVTIMEO`. |
| Duration `value` | The timeout duration to set. Must not be negative. |


 
Throws:

`SocketException` if setting the options fails. 
 
Example


```
import std.datetime;
import std.typecons;
auto pair = socketPair();
scope(exit) foreach (s; pair) s.close();

// Set a receive timeout, and then wait at one end of
// the socket pair, knowing that no data will arrive.
pair[0].setOption(SocketOptionLevel.SOCKET,
    SocketOption.RCVTIMEO, dur!"seconds"(1));

auto sw = StopWatch(Yes.autoStart);
ubyte[1] buffer;
pair[0].receive(buffer);
writefln("Waited %s ms until the socket timed out.",
    sw.peek.msecs);

```
  @safe string **getErrorText**();  
Get a text description of this socket's error status, and clear the socket's error status.

  @trusted void **setKeepAlive**(int time, int interval);  
Enables TCP keep-alive with the specified parameters. 



Parameters:


|  |  |
| --- | --- |
| int `time` | Number of seconds with no activity until the first keep-alive packet is sent. |
| int `interval` | Number of seconds between when successive keep-alive packets are sent if no acknowledgement is received. |


 
Throws:

`SocketOSException` if setting the options fails, or `SocketFeatureException` if setting keep-alive parameters is unsupported on the current platform.
  static @trusted int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, Duration timeout);   
  
static @safe int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError);   
  
static @trusted int **select**(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, TimeVal\* timeout);  
Wait for a socket to change status. A wait timeout of [`core.time.Duration`](core_time#Duration) or `TimeVal`, may be specified; if a timeout is not specified or the `TimeVal` is `null`, the maximum timeout is used. The `TimeVal` timeout has an unspecified value when `select` returns. 



Returns:
The number of sockets with status changes, `0` on timeout, or `-1` on interruption. If the return value is greater than `0`, the `SocketSets` are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept. `SocketSet`'s updated to include only those sockets which an event occured. For a `connect()`ing socket, writeability means connected. For a `listen()`ing socket, readability means listening `Winsock`; possibly internally limited to 64 sockets per set. 
 
Returns:
the number of events, 0 on timeout, or -1 on interruption
  protected pure nothrow @safe Address **createAddress**();  
Can be overridden to support other addresses. 



Returns:
a new `Address` object for the current address family.
    class **TcpSocket**: std.socket.Socket;  
`TcpSocket` is a shortcut class for a TCP Socket.

 
@safe this(AddressFamily family);  
Constructs a blocking TCP Socket.

  @safe this();  
Constructs a blocking IPv4 TCP Socket.

  @safe this(Address connectTo);  
Constructs a blocking TCP Socket and connects to an `Address`.

    class **UdpSocket**: std.socket.Socket;  
`UdpSocket` is a shortcut class for a UDP Socket.

 
@safe this(AddressFamily family);  
Constructs a blocking UDP Socket.

  @safe this();  
Constructs a blocking IPv4 UDP Socket.

    @trusted Socket[2] **socketPair**();  
Creates a pair of connected sockets. 


The two sockets are indistinguishable. 

 
Throws:

`SocketException` if creation of the sockets fails.
 
Examples:


```
immutable ubyte[] data = [1, 2, 3, 4];
auto pair = socketPair();
scope(exit) foreach (s; pair) s.close();

pair[0].send(data);

auto buf = new ubyte[data.length];
pair[1].receive(buf);
writeln(buf); // data

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_socket.html>

std.stdio
=========

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



Source
 [std/stdio.d](https://github.com/dlang/phobos/blob/master/std/stdio.d) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), Alex Rønne Petersen
 
alias **KeepTerminator** = std.typecons.Flag!"keepTerminator".Flag;  
If flag `KeepTerminator` is set to `KeepTerminator.yes`, then the delimiter is included in the strings returned.

  struct **File**;  
Encapsulates a `FILE*`. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulating `FILE*` values directly is unsafe and error-prone in many ways. The `File` type ensures safe manipulation, automatic file closing, and a lot of convenience. 


The underlying `FILE*` handle is maintained in a reference-counted manner, such that as soon as the last `File` variable bound to a given `FILE*` goes out of scope, the underlying `FILE*` is automatically closed. 

 
Example


```
// test.d
import std.stdio;

void main(string[] args)
{
    auto f = File("test.txt", "w"); // open for writing
    f.write("Hello");
    if (args.length > 1)
    {
        auto g = f; // now g and f write to the same file
                    // internal reference count is 2
        g.write(", ", args[1]);
        // g exits scope, reference count decreases to 1
    }
    f.writeln("!");
    // f exits scope, reference count falls to zero,
    // underlying `FILE*` is closed.
}

```
 
```
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _

```
 
@safe this(string name, scope const(char)[] stdioOpenmode = "rb");   
  
this(R1, R2)(R1 name)  
 Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1));   
  
this(R1, R2)(R1 name, R2 mode)  
 Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) && isInputRange!R2 && isSomeChar!(ElementEncodingType!R2)); 
 
Constructor taking the name of the file to open and the open mode. 


Copying one `File` object to another results in the two `File` objects referring to the same underlying file.   
  
 The destructor automatically closes the file as soon as no `File` object refers to it anymore. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | range or string representing the file name |
| const(char)[] `stdioOpenmode` | range or string represting the open mode (with the same semantics as in the C standard library [fopen](http://cplusplus.com/reference/clibrary/cstdio/fopen.html) function) |


 
Throws:

`ErrnoException` if the file could not be opened.
  ref @safe File **opAssign**(File rhs) return;  
Assigns a file to another. The target of the assignment gets detached from whatever file it was attached to, and attaches itself to the new file.

  @trusted void **open**(string name, scope const(char)[] stdioOpenmode = "rb");  
Detaches from the current file (throwing on failure), and then attempts to open file `name` with mode `stdioOpenmode`. The mode has the same semantics as in the C standard library [fopen](http://cplusplus.com/reference/clibrary/cstdio/fopen.html) function. 



Throws:

`ErrnoException` in case of error.
  @trusted void **reopen**(string name, scope const(char)[] stdioOpenmode = "rb");  
Reuses the `File` object to either open a different file, or change the file mode. If `name` is `null`, the mode of the currently open file is changed; otherwise, a new file is opened, reusing the C `FILE*`. The function has the same semantics as in the C standard library [freopen](http://cplusplus.com/reference/cstdio/freopen/) function. 



Note
 Calling `reopen` with a `null` `name` is not implemented in all C runtimes. 
 
Throws:

`ErrnoException` in case of error.
  @safe void **popen**(string command, scope const(char)[] stdioOpenmode = "r");  
Detaches from the current file (throwing on failure), and then runs a command by calling the C standard library function [popen](http://opengroup.org/onlinepubs/007908799/xsh/popen.html). 



Throws:

`ErrnoException` in case of error.
  @safe void **fdopen**(int fd, scope const(char)[] stdioOpenmode = "rb");  
First calls `detach` (throwing on failure), then attempts to associate the given file descriptor with the `File`, and sets the file's name to `null`. 


The mode must be compatible with the mode of the file descriptor. 

 
Throws:

`ErrnoException` in case of error. 
 
Parameters:


|  |  |
| --- | --- |
| int `fd` | File descriptor to associate with this `File`. |
| const(char)[] `stdioOpenmode` | Mode to associate with this File. The mode has the same semantics semantics as in the C standard library [fdopen](http://cplusplus.com/reference/cstdio/fopen/) function, and must be compatible with `fd`. |


  void **windowsHandleOpen**(HANDLE handle, scope const(char)[] stdioOpenmode);  
First calls `detach` (throwing on failure), and then attempts to associate the given Windows `HANDLE` with the `File`. The mode must be compatible with the access attributes of the handle. Windows only. 



Throws:

`ErrnoException` in case of error.
  const pure nothrow @property @safe bool **isOpen**();  
Returns `true` if the file is opened.

  const pure @property @trusted bool **eof**();  
Returns `true` if the file is at end (see [feof](http://cplusplus.com/reference/clibrary/cstdio/feof.html)). 



Throws:

`Exception` if the file is not opened.
  const pure nothrow @property @safe string **name**();  
Returns the name last used to initialize this `File`, if any. 


Some functions that create or initialize the `File` set the name field to `null`. Examples include [`tmpfile`](#tmpfile), [`wrapFile`](#wrapFile), and [`fdopen`](#fdopen). See the documentation of those functions for details. 

 
Returns:
The name last used to initialize this this file, or `null` otherwise.
  const pure nothrow @property @trusted bool **error**();  
If the file is not opened, returns `true`. Otherwise, returns [ferror](http://cplusplus.com/reference/clibrary/cstdio/ferror.html) for the file handle.

  @trusted void **detach**();  
Detaches from the underlying file. If the sole owner, calls `close`. 



Throws:

`ErrnoException` on failure if closing the file.
  @trusted void **close**();  
If the file was unopened, succeeds vacuously. Otherwise closes the file (by calling [fclose](http://cplusplus.com/reference/clibrary/cstdio/fclose.html)), throwing on error. Even if an exception is thrown, afterwards the `File` object is empty. This is different from `detach` in that it always closes the file; consequently, all other `File` objects referring to the same handle will see a closed file henceforth. 



Throws:

`ErrnoException` on error.
  pure nothrow @safe void **clearerr**();  
If the file is not opened, succeeds vacuously. Otherwise, returns [clearerr](http://cplusplus.com/reference/clibrary/cstdio/clearerr.html) for the file handle.

  @trusted void **flush**();  
Flushes the C `FILE` buffers. 


Calls [fflush](http://cplusplus.com/reference/clibrary/cstdio/fflush.html) for the file handle. 

 
Throws:

`Exception` if the file is not opened or if the call to `fflush` fails.
  @trusted void **sync**();  
Forces any data buffered by the OS to be written to disk. Call [`flush`](#flush) before calling this function to flush the C `FILE` buffers first. 


This function calls [`FlushFileBuffers`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364439%28v=vs.85%29.aspx) on Windows and [`fsync`](http://pubs.opengroup.org/onlinepubs/7908799/xsh/fsync.html) on POSIX for the file handle. 

 
Throws:

`Exception` if the file is not opened or if the OS call fails.
  T[] **rawRead**(T)(T[] buffer);  
Calls [fread](http://cplusplus.com/reference/clibrary/cstdio/fread.html) for the file handle. The number of items to read and the size of each item is inferred from the size and type of the input array, respectively. 



Returns:
The slice of `buffer` containing the data that was actually read. This will be shorter than `buffer` if EOF was reached before the buffer could be filled. 
 
Throws:

`Exception` if `buffer` is empty. `ErrnoException` if the file is not opened or the call to `fread` fails. `rawRead` always reads in binary mode on Windows.
 
Examples:


```
static import std.file;

auto testFile = std.file.deleteme();
std.file.write(testFile, "\r\n\n\r\n");
scope(exit) std.file.remove(testFile);

auto f = File(testFile, "r");
auto buf = f.rawRead(new char[5]);
f.close();
writeln(buf); // "\r\n\n\r\n"

```
 
  void **rawWrite**(T)(in T[] buffer);  
Calls [fwrite](http://cplusplus.com/reference/clibrary/cstdio/fwrite.html) for the file handle. The number of items to write and the size of each item is inferred from the size and type of the input array, respectively. An error is thrown if the buffer could not be written in its entirety. 


`rawWrite` always writes in binary mode on Windows. 

 
Throws:

`ErrnoException` if the file is not opened or if the call to `fwrite` fails.
 
Examples:


```
static import std.file;

auto testFile = std.file.deleteme();
auto f = File(testFile, "w");
scope(exit) std.file.remove(testFile);

f.rawWrite("\r\n\n\r\n");
f.close();
writeln(std.file.read(testFile)); // "\r\n\n\r\n"

```
 
  @trusted void **seek**(long offset, int origin = SEEK\_SET);  
Calls [fseek](http://cplusplus.com/reference/clibrary/cstdio/fseek.html) for the file handle to move its position indicator. 



Parameters:


|  |  |
| --- | --- |
| long `offset` | Binary files: Number of bytes to offset from origin. Text files: Either zero, or a value returned by [`tell`](#tell). |
| int `origin` | Binary files: Position used as reference for the offset, must be one of [SEEK\_SET](core_stdc_stdio#SEEK_SET), [SEEK\_CUR](core_stdc_stdio#SEEK_CUR) or [SEEK\_END](core_stdc_stdio#SEEK_END). Text files: Shall necessarily be [SEEK\_SET](core_stdc_stdio#SEEK_SET). |


 
Throws:

`Exception` if the file is not opened. `ErrnoException` if the call to `fseek` fails.
  const @property @trusted ulong **tell**();  
Calls [ftell](http://cplusplus.com/reference/clibrary/cstdio/ftell.html) for the managed file handle. 



Throws:

`Exception` if the file is not opened. `ErrnoException` if the call to `ftell` fails.
 
Examples:


```
import std.conv : text;
static import std.file;

auto testFile = std.file.deleteme();
std.file.write(testFile, "abcdefghijklmnopqrstuvwqxyz");
scope(exit) { std.file.remove(testFile); }

auto f = File(testFile);
auto a = new ubyte[4];
f.rawRead(a);
writeln(f.tell); // 4

```
 
  @safe void **rewind**();  
Calls [rewind](http://cplusplus.com/reference/clibrary/cstdio/rewind.html) for the file handle. 



Throws:

`Exception` if the file is not opened.
  @trusted void **setvbuf**(size\_t size, int mode = \_IOFBF);  
Calls [setvbuf](http://cplusplus.com/reference/clibrary/cstdio/setvbuf.html) for the file handle. 



Throws:

`Exception` if the file is not opened. `ErrnoException` if the call to `setvbuf` fails.
  @trusted void **setvbuf**(void[] buf, int mode = \_IOFBF);  
Calls [setvbuf](http://cplusplus.com/reference/clibrary/cstdio/setvbuf.html) for the file handle. 



Throws:

`Exception` if the file is not opened. `ErrnoException` if the call to `setvbuf` fails.
  void **lock**(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0);  
Locks the specified file segment. If the file segment is already locked by another process, waits until the existing lock is released. If both `start` and `length` are zero, the entire file is locked. 


Locks created using `lock` and `tryLock` have the following properties: * All locks are automatically released when the process terminates.
* Locks are not inherited by child processes.
* Closing a file will release all locks associated with the file. On POSIX, even locks acquired via a different `File` will be released as well.
* Not all NFS implementations correctly implement file locking.


  bool **tryLock**(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0);  
Attempts to lock the specified file segment. If both `start` and `length` are zero, the entire file is locked. 



Returns:

`true` if the lock was successful, and `false` if the specified file segment was already locked.
  void **unlock**(ulong start = 0, ulong length = 0);  
Removes the lock over the specified file segment.

  void **write**(S...)(S args);  
Writes its arguments in text format to the file. 



Throws:

`Exception` if the file is not opened. `ErrnoException` on an error writing to the file.
  void **writeln**(S...)(S args);  
Writes its arguments in text format to the file, followed by a newline. 



Throws:

`Exception` if the file is not opened. `ErrnoException` on an error writing to the file.
  void **writef**(alias fmt, A...)(A args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
void **writef**(Char, A...)(in Char[] fmt, A args);  
Writes its arguments in text format to the file, according to the format string fmt. 



Parameters:


|  |  |
| --- | --- |
| Char[] `fmt` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
| A `args` | Items to write. |


 
Throws:

`Exception` if the file is not opened. `ErrnoException` on an error writing to the file.
  void **writefln**(alias fmt, A...)(A args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
void **writefln**(Char, A...)(in Char[] fmt, A args);  
Equivalent to `file.writef(fmt, args, '\n')`.

  S **readln**(S = string)(dchar terminator = '\x0a')  
 Constraints: if (isSomeString!S); 
 
Read line from the file handle and return it as a specified type. 


This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the `File.readln(buf)` version, which may offer better performance as it can reuse its read buffer. 

 
Parameters:


|  |  |
| --- | --- |
| S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`. |
| dchar `terminator` | Line terminator (by default, `'\n'`). |


 
Note
 String terminators are not supported due to ambiguity with readln(buf) below. 
 
Returns:
The line that was read, including the line terminator character. 
 
Throws:

`StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. 
 
Example


```
// Reads `stdin` and writes it to `stdout`.
import std.stdio;

void main()
{
    string line;
    while ((line = stdin.readln()) !is null)
        write(line);
}

```
  size\_t **readln**(C)(ref C[] buf, dchar terminator = '\x0a')  
 Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));   
  
size\_t **readln**(C, R)(ref C[] buf, R terminator)  
 Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); 
 
Read line from the file handle and write it to `buf[]`, including terminating character. 


This can be faster than `line = File.readln()` because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them. 

 
Parameters:


|  |  |
| --- | --- |
| C[] `buf` | Buffer used to store the resulting line data. buf is enlarged if necessary, then set to the slice exactly containing the line. |
| dchar `terminator` | Line terminator (by default, `'\n'`). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). |


 
Returns:
0 for end of file, otherwise number of characters read. The return value will always be equal to `buf.length`. 
 
Throws:

`StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. 
 
Example


```
// Read lines from `stdin` into a string
// Ignore lines starting with '#'
// Write the string to `stdout`
import std.stdio;

void main()
{
    string output;
    char[] buf;

    while (stdin.readln(buf))
    {
        if (buf[0] == '#')
            continue;

        output ~= buf;
    }

    write(output);
}

```
 This method can be more efficient than the one in the previous example because `stdin.readln(buf)` reuses (if possible) memory allocated for `buf`, whereas `line = stdin.readln()` makes a new memory allocation for every line. For even better performance you can help `readln` by passing in a large buffer to avoid memory reallocations. This can be done by reusing the largest buffer returned by `readln`: 
Example


```
// Read lines from `stdin` and count words
import std.array, std.stdio;

void main()
{
    char[] buf;
    size_t words = 0;

    while (!stdin.eof)
    {
        char[] line = buf;
        stdin.readln(line);
        if (line.length > buf.length)
            buf = line;

        words += line.split.length;
    }

    writeln(words);
}

```
 This is actually what [`byLine`](#byLine) does internally, so its usage is recommended if you want to process a complete file.  uint **readf**(alias format, Data...)(auto ref Data data)  
 Constraints: if (isSomeString!(typeof(format)));   
  
uint **readf**(Data...)(scope const(char)[] format, auto ref Data data);  
Reads formatted data from the file using [`std.format.formattedRead`](std_format#formattedRead). 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `format` | The [format string](std%20format_#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
| Data `data` | Items to be read. |


 
Example


```
// test.d
void main()
{
    import std.stdio;
    auto f = File("input");
    foreach (_; 0 .. 3)
    {
        int a;
        f.readf!" %d"(a);
        writeln(++a);
    }
}

```
 
```
% echo "1 2 3" > input
% rdmd test.d
2
3
4

```
 
Examples:


```
static import std.file;

auto deleteme = std.file.deleteme();
std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n");
scope(exit) std.file.remove(deleteme);
string s;
auto f = File(deleteme);
f.readf!"%s\n"(s);
writeln(s); // "hello"
f.readf("%s\n", s);
writeln(s); // "world"

bool b1, b2;
f.readf("%s\n%s\n", b1, b2);
assert(b1 == true && b2 == false);

```
 
  static @safe File **tmpfile**();  
Returns a temporary file by calling [tmpfile](http://cplusplus.com/reference/clibrary/cstdio/tmpfile.html). Note that the created file has no [`name`](#name).

  static @safe File **wrapFile**(FILE\* f);  
Unsafe function that wraps an existing `FILE*`. The resulting `File` never takes the initiative in closing the file. Note that the created file has no [`name`](#name)

  pure @safe FILE\* **getFP**();  
Returns the `FILE*` corresponding to this object.

  const @property @trusted int **fileno**();  
Returns the file number corresponding to this object.

  @property HANDLE **windowsHandle**();  
Returns the underlying operating system `HANDLE` (Windows only).

  auto **byLine**(Terminator = char, Char = char)(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a')  
 Constraints: if (isScalarType!Terminator);   
  
auto **byLine**(Terminator, Char = char)(KeepTerminator keepTerminator, Terminator terminator)  
 Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); 
 
Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle one line at a time. 


The element type for the range will be `Char[]`. Range primitives may throw `StdioException` on I/O error. 

 
Note
 Each `front` will not persist after `popFront` is called, so the caller must copy its contents (e.g. by calling `to!string`) when retention is needed. If the caller needs to retain a copy of every line, use the [`byLineCopy`](#byLineCopy) function instead. 
 
Parameters:


|  |  |
| --- | --- |
| Char | Character type for each line, defaulting to `char`. |
| KeepTerminator `keepTerminator` | Use `Yes.keepTerminator` to include the terminator at the end of each line. |
| Terminator `terminator` | Line separator (`'\n'` by default). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). |


 
Example


```
import std.algorithm, std.stdio, std.string;
// Count words in a file using ranges.
void main()
{
    auto file = File("file.txt"); // Open for reading
    const wordCount = file.byLine()            // Read lines
                          .map!split           // Split into words
                          .map!(a => a.length) // Count words per line
                          .sum();              // Total word count
    writeln(wordCount);
}

```
 
Example


```
import std.range, std.stdio;
// Read lines using foreach.
void main()
{
    auto file = File("file.txt"); // Open for reading
    auto range = file.byLine();
    // Print first three lines
    foreach (line; range.take(3))
        writeln(line);
    // Print remaining lines beginning with '#'
    foreach (line; range)
    {
        if (!line.empty && line[0] == '#')
            writeln(line);
    }
}

```
 Notice that neither example accesses the line data returned by `front` after the corresponding `popFront` call is made (because the contents may well have changed).  auto **byLineCopy**(Terminator = char, Char = immutable(char))(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a')  
 Constraints: if (isScalarType!Terminator);   
  
auto **byLineCopy**(Terminator, Char = immutable(char))(KeepTerminator keepTerminator, Terminator terminator)  
 Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); 
 
Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle one line at a time. Each line will be newly allocated. `front` will cache its value to allow repeated calls without unnecessary allocations. 



Note
 Due to caching byLineCopy can be more memory-efficient than `File.byLine.map!idup`. 
 The element type for the range will be `Char[]`. Range primitives may throw `StdioException` on I/O error. 
Parameters:


|  |  |
| --- | --- |
| Char | Character type for each line, defaulting to `immutable char`. |
| KeepTerminator `keepTerminator` | Use `Yes.keepTerminator` to include the terminator at the end of each line. |
| Terminator `terminator` | Line separator (`'\n'` by default). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). |


 
Example


```
import std.algorithm, std.array, std.stdio;
// Print sorted lines of a file.
void main()
{
    auto sortedLines = File("file.txt")   // Open for reading
                       .byLineCopy()      // Read persistent lines
                       .array()           // into an array
                       .sort();           // then sort them
    foreach (line; sortedLines)
        writeln(line);
}

```
 
See Also:
[`std.file.readText`](std_file#readText)
  auto **byRecord**(Fields...)(string format);  
Creates an [input range](std_range_primitives#isInputRange) set up to parse one line at a time from the file into a tuple. 


Range primitives may throw `StdioException` on I/O error. 

 
Parameters:


|  |  |
| --- | --- |
| string `format` | tuple record [format](std_format#formattedRead) |


 
Returns:
The input range set up to parse one line at a time into a record tuple. 
 
See Also:
It is similar to [`byLine`](#byLine) and uses [format](std_format#formattedRead) under the hood.
 
Examples:


```
static import std.file;
import std.typecons : tuple;

// prepare test file
auto testFile = std.file.deleteme();
scope(failure) printf("Failed test at line %d\n", __LINE__);
std.file.write(testFile, "1 2\n4 1\n5 100");
scope(exit) std.file.remove(testFile);

File f = File(testFile);
scope(exit) f.close();

auto expected = [tuple(1, 2), tuple(4, 1), tuple(5, 100)];
uint i;
foreach (e; f.byRecord!(int, int)("%s %s"))
{
    writeln(e); // expected[i++]
}

```
 
  auto **byChunk**(size\_t chunkSize);   
  
auto **byChunk**(ubyte[] buffer);  
Returns an [input range](std_range_primitives#isInputRange) set up to read from the file handle a chunk at a time. 


The element type for the range will be `ubyte[]`. Range primitives may throw `StdioException` on I/O error. 

 
Example


```
void main()
{
    // Read standard input 4KB at a time
    foreach (ubyte[] buffer; stdin.byChunk(4096))
    {
        ... use buffer ...
    }
}

```
 The parameter may be a number (as shown in the example above) dictating the size of each chunk. Alternatively, `byChunk` accepts a user-provided buffer that it uses directly. 
Example


```
void main()
{
    // Read standard input 4KB at a time
    foreach (ubyte[] buffer; stdin.byChunk(new ubyte[4096]))
    {
        ... use buffer ...
    }
}

```
 In either case, the content of the buffer is reused across calls. That means `front` will not persist after `popFront` is called, so if retention is needed, the caller must copy its contents (e.g. by calling `buffer.dup`). In the example above, `buffer.length` is 4096 for all iterations, except for the last one, in which case `buffer.length` may be less than 4096 (but always greater than zero). With the mentioned limitations, `byChunk` works with any algorithm compatible with input ranges. 
Example


```
// Efficient file copy, 1MB at a time.
import std.algorithm, std.stdio;
void main()
{
    stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter());
}

```
 [`std.algorithm.iteration.joiner`](std_algorithm_iteration#joiner) can be used to join chunks together into a single range lazily. 
Example


```
import std.algorithm, std.stdio;
void main()
{
    //Range of ranges
    static assert(is(typeof(stdin.byChunk(4096).front) == ubyte[]));
    //Range of elements
    static assert(is(typeof(stdin.byChunk(4096).joiner.front) == ubyte));
}

```
 
Returns:
A call to `byChunk` returns a range initialized with the `File` object and the appropriate buffer. 
 
Throws:
If the user-provided size is zero or the user-provided buffer is empty, throws an `Exception`. In case of an I/O error throws `StdioException`.
  @safe auto **lockingTextWriter**();  
Output range which locks the file when created, and unlocks the file when it goes out of scope. 



Returns:
An [output range](std_range_primitives#isOutputRange) which accepts string types, `ubyte[]`, individual character types, and individual `ubyte`s. 
 
Note
 Writing either arrays of `char`s or `ubyte`s is faster than writing each character individually from a range. For large amounts of data, writing the contents in chunks using an intermediary array can result in a speed increase. 
 
Throws:

[`std.utf.UTFException`](std_utf#UTFException) if the data given is a `char` range and it contains malformed UTF data. 
 
See Also:

[`byChunk`](#byChunk) for an example.
  auto **lockingBinaryWriter**();  
Returns an output range that locks the file and allows fast writing to it. 



Example
 Produce a grayscale image of the [Mandelbrot set](https://en.wikipedia.org/wiki/Mandelbrot_set) in binary [Netpbm format](https://en.wikipedia.org/wiki/Netpbm_format) to standard output. 


```
import std.algorithm, std.complex, std.range, std.stdio;

void main()
{
    enum size = 500;
    writef("P5\n%d %d %d\n", size, size, ubyte.max);

    iota(-1, 3, 2.0/size).map!(y =>
        iota(-1.5, 0.5, 2.0/size).map!(x =>
            cast(ubyte)(1+
                recurrence!((a, n) => x + y * complex(0, 1) + a[n-1]^^2)(complex(0))
                .take(ubyte.max)
                .countUntil!(z => z.re^^2 + z.im^^2 > 4))
        )
    )
    .copy(stdout.lockingBinaryWriter);
}

```
  @property @safe ulong **size**();  
Returns the size of the file in bytes, ulong.max if file is not searchable or throws if the operation fails. 



Example


```
import std.stdio, std.file;

void main()
{
    string deleteme = "delete.me";
    auto file_handle = File(deleteme, "w");
    file_handle.write("abc"); //create temporary file
    scope(exit) deleteme.remove; //remove temporary file at scope exit

    assert(file_handle.size() == 3); //check if file size is 3 bytes
}

```
    enum **LockType**: int;  
Used to specify the lock type for `File.lock` and `File.tryLock`.

 
**read** 
Specifies a read (shared) lock. A read lock denies all processes write access to the specified region of the file, including the process that first locks the region. All processes can read the locked region. Multiple simultaneous read locks are allowed, as long as there are no exclusive locks.

  **readWrite** 
Specifies a read/write (exclusive) lock. A read/write lock denies all other processes both read and write access to the locked file region. If a segment has an exclusive lock, it may not have any shared locks or other exclusive locks.

    enum auto **isFileHandle**(T);  
Indicates whether `T` is a file handle, i.e. the type is implicitly convertable to [`File`](#File) or a pointer to a [`core.stdc.stdio.FILE`](core_stdc_stdio#FILE). 



Returns:

`true` if `T` is a file handle, `false` otherwise.
 
Examples:


```
static assert(isFileHandle!(FILE*));
static assert(isFileHandle!(File));

```
 
  void **write**(T...)(T args)  
 Constraints: if (!is(T[0] : File)); 
 
Writes its arguments in text format to standard output (without a trailing newline). 



Parameters:


|  |  |
| --- | --- |
| T `args` | the items to write to `stdout` |


 
Throws:
In case of an I/O error, throws an `StdioException`. 
 
Example
 Reads `stdin` and writes it to `stdout` with an argument counter. 


```
import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         write("Input ", count, ": ", line, "\n");
    }
}

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



Parameters:


|  |  |
| --- | --- |
| T `args` | the items to write to `stdout` |


 
Throws:
In case of an I/O error, throws an [`StdioException`](#StdioException). 
 
Example
 Reads `stdin` and writes it to `stdout` with an argument counter. 


```
import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}

```
  void **writef**(alias fmt, A...)(A args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
void **writef**(Char, A...)(in Char[] fmt, A args);  
Writes formatted data to standard output (without a trailing newline). 



Parameters:


|  |  |
| --- | --- |
| Char[] `fmt` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
| A `args` | Items to write. |


 
Note
 In older versions of Phobos, it used to be possible to write: 
 
```
writef(stderr, "%s", "message");

```
 to print a message to `stderr`. This syntax is no longer supported, and has been superceded by: 
```
stderr.writef("%s", "message");

```
  void **writefln**(alias fmt, A...)(A args)  
 Constraints: if (isSomeString!(typeof(fmt)));   
  
void **writefln**(Char, A...)(in Char[] fmt, A args);  
Equivalent to `writef(fmt, args, '\n')`.

  uint **readf**(alias format, A...)(auto ref A args)  
 Constraints: if (isSomeString!(typeof(format)));   
  
uint **readf**(A...)(scope const(char)[] format, auto ref A args);  
Reads formatted data from `stdin` using [`std.format.formattedRead`](std_format#formattedRead). 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `format` | The [format string](std_format#formattedWrite). When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
| A `args` | Items to be read. |


 
Example


```
// test.d
void main()
{
    import std.stdio;
    foreach (_; 0 .. 3)
    {
        int a;
        readf!" %d"(a);
        writeln(++a);
    }
}

```
 
```
% echo "1 2 3" | rdmd test.d
2
3
4

```
  S **readln**(S = string)(dchar terminator = '\x0a')  
 Constraints: if (isSomeString!S); 
 
Read line from `stdin`. 


This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the `readln(buf)` version, which may offer better performance as it can reuse its read buffer. 

 
Returns:
The line that was read, including the line terminator character. 
 
Parameters:


|  |  |
| --- | --- |
| S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`. |
| dchar `terminator` | Line terminator (by default, `'\n'`). |


 
Note
 String terminators are not supported due to ambiguity with readln(buf) below. 
 
Throws:

`StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. 
 
Example
 Reads `stdin` and writes it to `stdout`. 


```
import std.stdio;

void main()
{
    string line;
    while ((line = readln()) !is null)
        write(line);
}

```
  size\_t **readln**(C)(ref C[] buf, dchar terminator = '\x0a')  
 Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));   
  
size\_t **readln**(C, R)(ref C[] buf, R terminator)  
 Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); 
 
Read line from `stdin` and write it to buf[], including terminating character. 


This can be faster than `line = readln()` because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them. 

 
Returns:

`size_t` 0 for end of file, otherwise number of characters read 
 
Parameters:


|  |  |
| --- | --- |
| C[] `buf` | Buffer used to store the resulting line data. buf is resized as necessary. |
| dchar `terminator` | Line terminator (by default, `'\n'`). Use [`std.ascii.newline`](std_ascii#newline) for portability (unless the file was opened in text mode). |


 
Throws:

`StdioException` on I/O error, or `UnicodeException` on Unicode conversion error. 
 
Example
 Reads `stdin` and writes it to `stdout`. 


```
import std.stdio;

void main()
{
    char[] buf;
    while (readln(buf))
        write(buf);
}

```
  nothrow @nogc @trusted FILE\* **\_popen**(R1, R2)(R1 name, R2 mode = "r")  
 Constraints: if ((isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) || isSomeString!R1) && (isInputRange!R2 && isSomeChar!(ElementEncodingType!R2) || isSomeString!R2)); 
 
Convenience function that forwards to `core.sys.posix.stdio.popen` with appropriately-constructed C-style strings.

  struct **lines**;  
Iterates through the lines of a file by using `foreach`. 



Example


```
void main()
{
  foreach (string line; lines(stdin))
  {
    ... use line ...
  }
}

```
 The line terminator (`'\n'` by default) is part of the string read (it could be missing in the last line of the file). Several types are supported for `line`, and the behavior of `lines` changes accordingly: 1. If `line` has type `string`, `wstring`, or `dstring`, a new string of the respective type is allocated every read.
2. If `line` has type `char[]`, `wchar[]`, `dchar[]`, the line's content will be reused (overwritten) across reads.
3. If `line` has type `immutable(ubyte)[]`, the behavior is similar to case (1), except that no UTF checking is attempted upon input.
4. If `line` has type `ubyte[]`, the behavior is similar to case (2), except that no UTF checking is attempted upon input.

 In all cases, a two-symbols versions is also accepted, in which case the first symbol (of integral type, e.g. `ulong` or `uint`) tracks the zero-based number of the current line. 
Example


```
  foreach (ulong i, string line; lines(stdin))
  {
    ... use line ...
  }

```
 In case of an I/O error, an `StdioException` is thrown. 
See Also:
[`byLine`](#byLine)
 
this(File f, dchar terminator = '\x0a');  
Constructor. 



Parameters:


|  |  |
| --- | --- |
| File `f` | File to read lines from. |
| dchar `terminator` | Line separator (`'\n'` by default). |


    auto **chunks**(File f, size\_t size);  
Iterates through a file a chunk at a time by using `foreach`. 



Example


```
void main()
{
    foreach (ubyte[] buffer; chunks(stdin, 4096))
    {
        ... use buffer ...
    }
}

```
 The content of `buffer` is reused across calls. In the example above, `buffer.length` is 4096 for all iterations, except for the last one, in which case `buffer.length` may be less than 4096 (but always greater than zero). In case of an I/O error, an `StdioException` is thrown.  void **toFile**(T)(T data, string fileName)  
 Constraints: if (is(typeof(copy(data, stdout.lockingBinaryWriter)))); 
 
Writes an array or range to a file. Shorthand for `data.copy(File(fileName, "wb").lockingBinaryWriter)`. Similar to [`std.file.write`](std_file#write), strings are written as-is, rather than encoded according to the `File`'s [orientation](http://en.cppreference.com/w/c/io#Narrow_and_wide_orientation).

  class **StdioException**: object.Exception;  
Thrown if I/O errors happen.

 
uint **errno**;  
Operating system error code.

  @trusted this(string message, uint e = core.stdc.errno.errno);  
Initialize with a message and an error code.

  static void **opCall**(string msg);   
  
static void **opCall**();  
Convenience functions that throw an `StdioException`.

    alias **stdin** = makeGlobal!"core.stdc.stdio.**stdin**".makeGlobal;  
The standard input stream. 



Returns:
stdin as a [`File`](#File). 
 
Note
 The returned [`File`](#File) wraps [`core.stdc.stdio.stdin`](core_stdc_stdio#stdin), and is therefore thread global. Reassigning `stdin` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. 
 All reading from `stdin` automatically locks the file globally, and will cause all other threads calling `read` to wait until the lock is released. 
Examples:


```
// Read stdin, sort lines, write to stdout
import std.algorithm.mutation : copy;
import std.algorithm.sorting : sort;
import std.array : array;
import std.typecons : Yes;

void main()
{
    stdin                       // read from stdin
    .byLineCopy(Yes.keepTerminator) // copying each line
    .array()                    // convert to array of lines
    .sort()                     // sort the lines
    .copy(                      // copy output of .sort to an OutputRange
        stdout.lockingTextWriter()); // the OutputRange
}

```
 
  alias **stdout** = makeGlobal!"core.stdc.stdio.**stdout**".makeGlobal;  
The standard output stream. 



Returns:
stdout as a [`File`](#File). 
 
Note
 The returned [`File`](#File) wraps [`core.stdc.stdio.stdout`](core_stdc_stdio#stdout), and is therefore thread global. Reassigning `stdout` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. 
 All writing to `stdout` automatically locks the file globally, and will cause all other threads calling `write` to wait until the lock is released. 
Examples:


```
void main()
{
    stdout.writeln("Write a message to stdout.");
}

```
 
 
Examples:


```
void main()
{
    import std.algorithm.iteration : filter, map, sum;
    import std.format : format;
    import std.range : iota, tee;

    int len;
    const r = 6.iota
              .filter!(a => a % 2) // 1 3 5
              .map!(a => a * 2) // 2 6 10
              .tee!(_ => stdout.writefln("len: %d", len++))
              .sum;

    writeln(r); // 18
}

```
 
 
Examples:


```
void main()
{
    import std.algorithm.mutation : copy;
    import std.algorithm.iteration : map;
    import std.format : format;
    import std.range : iota;

    10.iota
    .map!(e => "N: %d".format(e))
    .copy(stdout.lockingTextWriter()); // the OutputRange
}

```
 
  alias **stderr** = makeGlobal!"core.stdc.stdio.**stderr**".makeGlobal;  
The standard error stream. 



Returns:
stderr as a [`File`](#File). 
 
Note
 The returned [`File`](#File) wraps [`core.stdc.stdio.stderr`](core_stdc_stdio#stderr), and is therefore thread global. Reassigning `stderr` to a different `File` must be done in a single-threaded or locked context in order to avoid race conditions. 
 All writing to `stderr` automatically locks the file globally, and will cause all other threads calling `write` to wait until the lock is released. 
Examples:


```
void main()
{
    stderr.writeln("Write a message to stderr.");
}

```
 
  File **openNetwork**(string host, ushort port);  
Experimental network access via the File interface 


Opens a TCP connection to the given host and port, then returns a File struct with read and write access through the same interface as any other file (meaning writef and the byLine ranges work!). 

 
Authors:
Adam D. Ruppe 
 
Bugs:
Only works on Linux
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_stdio.html>

std.windows.charset
===================

 Support UTF-8 on Windows 95, 98 and ME systems. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
[Walter Bright](http://digitalmars.com)
 
const(char)\* **toMBSz**(scope const(char)[] s, uint codePage = 0);  
Converts the UTF-8 string s into a null-terminated string in a Windows 8-bit character set. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `s` | UTF-8 string to convert. |
| uint `codePage` | is the number of the target codepage, or 0 - ANSI, 1 - OEM, 2 - Mac |


 
Authors:
yaneurao, Walter Bright, Stewart Gordon
  string **fromMBSz**(immutable(char)\* s, int codePage = 0);  
Converts the null-terminated string s from a Windows 8-bit character set into a UTF-8 char array. 



Parameters:


|  |  |
| --- | --- |
| immutable(char)\* `s` | UTF-8 string to convert. |
| int `codePage` | is the number of the source codepage, or 0 - ANSI, 1 - OEM, 2 - Mac |


 
Authors:
Stewart Gordon, Walter Bright
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_windows_charset.html>

std.windows.syserror
====================

 Convert Win32 error code to string. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Credits
 Based on code written by Regan Heath
 
@trusted string **sysErrorString**(DWORD errCode, int langId = LANG\_NEUTRAL, int subLangId = SUBLANG\_DEFAULT);  
Query the text for a Windows error code, as returned by  [`GetLastError`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360.aspx), as a D string.

  class **WindowsException**: object.Exception;  
Thrown if errors that set  [`GetLastError`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360.aspx) occur.

 
final @property DWORD **code**();  
`GetLastError`'s return value.

    @safe T **wenforce**(T, S)(T value, lazy S msg = null, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_)  
 Constraints: if (isSomeString!S); 
 
If `!!value` is true, `value` is returned. Otherwise, `new WindowsException(GetLastError(), msg)` is thrown. `WindowsException` assumes that the last operation set `GetLastError()` appropriately. 



Example


```
wenforce(DeleteFileA("junk.tmp"), "DeleteFile failed");

```
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_windows_syserror.html>

std.uuid
========

 A [UUID](http://en.wikipedia.org/wiki/Universally_unique_identifier), or [Universally unique identifier](http://en.wikipedia.org/wiki/Universally_unique_identifier), is intended to uniquely identify information in a distributed environment without significant central coordination. It can be used to tag objects with very short lifetimes, or to reliably identify very persistent objects across a network. 




| Category | Functions |
| --- | --- |
| Parsing UUIDs | [*parseUUID*](#parseUUID) [*UUID*](#UUID) [*UUIDParsingException*](#UUIDParsingException) [*uuidRegex*](#uuidRegex) |
| Generating UUIDs | [*sha1UUID*](#sha1UUID) [*randomUUID*](#randomUUID) [*md5UUID*](#md5UUID) |
| Using UUIDs | [*UUID.uuidVersion*](#uuidVersion) [*UUID.variant*](#variant) [*UUID.toString*](#toString) [*UUID.data*](#data) [*UUID.swap*](#swap) [*UUID.opEquals*](#opEquals) [*UUID.opCmp*](#opCmp) [*UUID.toHash*](#toHash) |
| UUID namespaces | [*dnsNamespace*](#dnsNamespace) [*urlNamespace*](#urlNamespace) [*oidNamespace*](#oidNamespace) [*x500Namespace*](#x500Namespace) |

  UUIDs have many applications. Some examples follow: Databases may use UUIDs to identify rows or records in order to ensure that they are unique across different databases, or for publication/subscription services. Network messages may be identified with a UUID to ensure that different parts of a message are put back together again. Distributed computing may use UUIDs to identify a remote procedure call. Transactions and classes involved in serialization may be identified by UUIDs. Microsoft's component object model (COM) uses UUIDs to distinguish different software component interfaces. UUIDs are inserted into documents from Microsoft Office programs. UUIDs identify audio or video streams in the Advanced Systems Format (ASF). UUIDs are also a basis for OIDs (object identifiers), and URNs (uniform resource name).   
  
 An attractive feature of UUIDs when compared to alternatives is their relative small size, of 128 bits, or 16 bytes. Another is that the creation of UUIDs does not require a centralized authority.   
  
 When UUIDs are generated by one of the defined mechanisms, they are either guaranteed to be unique, different from all other generated UUIDs (that is, it has never been generated before and it will never be generated again), or it is extremely likely to be unique (depending on the mechanism).   
  
 For efficiency, UUID is implemented as a struct. UUIDs are therefore empty if not explicitly initialized. An UUID is empty if [`UUID.empty`](#empty) is true. Empty UUIDs are equal to `UUID.init`, which is a UUID with all 16 bytes set to 0. Use UUID's constructors or the UUID generator functions to get an initialized UUID.   
  
 This is a port of  [boost.uuid](http://www.boost.org/doc/libs/1_42_0/libs/uuid/uuid.html) from the Boost project with some minor additions and API changes for a more D-like API. 

 
Standards:

[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt) 
 
See Also:

<http://en.wikipedia.org/wiki/Universally_unique_identifier> 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Johannes Pfau 
 
Source
 [std/uuid.d](https://github.com/dlang/phobos/blob/master/std/uuid.d) 
 
Examples:


```
import std.uuid;

UUID[] ids;
ids ~= randomUUID();
ids ~= md5UUID("test.name.123");
ids ~= sha1UUID("test.name.123");

foreach (entry; ids)
{
    writeln(entry.variant); // UUID.Variant.rfc4122
}
writeln(ids[0].uuidVersion); // UUID.Version.randomNumberBased
writeln(ids[1].toString()); // "22390768-cced-325f-8f0f-cfeaa19d0ccd"
assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207,
    234, 161, 157, 12, 205]);
UUID id;
assert(id.empty);

```
 
 
struct **UUID**;  

Examples:


```
UUID id;
assert(id.empty);

id = randomUUID;
assert(!id.empty);

id = UUID(cast(ubyte[16]) [138, 179, 6, 14, 44, 186, 79,
    35, 183, 76, 181, 45, 179, 189, 251, 70]);
writeln(id.toString()); // "8ab3060e-2cba-4f23-b74c-b52db3bdfb46"

```
 
 
enum **Variant**: int;  
RFC 4122 defines different internal data layouts for UUIDs. These are the UUID formats supported by this module. It's possible to read, compare and use all these Variants, but UUIDs generated by this module will always be in rfc4122 format. 



Note
 Do not confuse this with [`std.variant.Variant`](std_variant#Variant).
 
**ncs** 
NCS backward compatibility

  **rfc4122** 
Defined in RFC 4122 document

  **microsoft** 
Microsoft Corporation backward compatibility

  **future** 
Reserved for future use

    enum **Version**: int;  
RFC 4122 defines different UUID versions. The version shows how a UUID was generated, e.g. a version 4 UUID was generated from a random number, a version 3 UUID from an MD5 hash of a name. 



Note
 All of these UUID versions can be read and processed by `std.uuid`, but only version 3, 4 and 5 UUIDs can be generated.
 
**unknown** 
Unknown version

  **timeBased** 
Version 1

  **dceSecurity** 
Version 2

  **nameBasedMD5** 
Version 3 (Name based + MD5)

  **randomNumberBased** 
Version 4 (Random)

  **nameBasedSHA1** 
Version 5 (Name based + SHA-1)

    ubyte[16] **data**;  
It is sometimes useful to get or set the 16 bytes of a UUID directly. 



Note
 UUID uses a 16-ubyte representation for the UUID data. RFC 4122 defines a UUID as a special structure in big-endian format. These 16-ubytes always equal the big-endian structure defined in RFC 4122. 
 
Example


```
auto rawData = uuid.data; //get data
rawData[0] = 1; //modify
uuid.data = rawData; //set data
uuid.data[1] = 2; //modify directly

```
  pure nothrow @nogc @safe this(ref scope const ubyte[16] uuidData);   
  
pure nothrow @nogc @safe this(const ubyte[16] uuidData);  
Construct a UUID struct from the 16 byte representation of a UUID.



Examples:


```
enum ubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
auto uuid = UUID(data);
enum ctfe = UUID(data);
writeln(uuid.data); // data
writeln(ctfe.data); // data

```
 
  pure @safe this(T...)(T uuidData)  
 Constraints: if (uuidData.length == 16 && allSatisfy!(isIntegral, T)); 
 
Construct a UUID struct from the 16 byte representation of a UUID. Variadic constructor to allow a simpler syntax, see examples. You need to pass exactly 16 ubytes.



Examples:


```
auto tmp = UUID(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
assert(tmp.data == cast(ubyte[16])[0,1,2,3,4,5,6,7,8,9,10,11,
    12,13,14,15]);

```
 
  this(T)(in T[] uuid)  
 Constraints: if (isSomeChar!(Unqual!T)); 
 
 Parse a UUID from its canonical string form. An UUID in its canonical form looks like this: 8ab3060e-2cba-4f23-b74c-b52db3bdfb46 



Throws:

[`UUIDParsingException`](#UUIDParsingException) if the input is invalid 
 
CTFE
 This function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time. 
 
Note
 This is a strict parser. It only accepts the pattern above. It doesn't support any leading or trailing characters. It only accepts characters used for hex numbers and the string must have hyphens exactly like above. 
 For a less strict parser, see [`parseUUID`](#parseUUID) 
Examples:


```
auto id = UUID("8AB3060E-2cba-4f23-b74c-b52db3bdfb46");
assert(id.data == [138, 179, 6, 14, 44, 186, 79, 35, 183, 76,
   181, 45, 179, 189, 251, 70]);
writeln(id.toString()); // "8ab3060e-2cba-4f23-b74c-b52db3bdfb46"

//Can also be used in CTFE, for example as UUID literals:
enum ctfeID = UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46");
//here parsing is done at compile time, no runtime overhead!

```
 
  const pure nothrow @nogc @property @trusted bool **empty**();  
Returns true if and only if the UUID is equal to {00000000-0000-0000-0000-000000000000}



Examples:


```
UUID id;
assert(id.empty);
id = UUID("00000000-0000-0000-0000-000000000001");
assert(!id.empty);

```
 
  const pure nothrow @nogc @property @safe Variant **variant**();  
RFC 4122 defines different internal data layouts for UUIDs. Returns the format used by this UUID. 



Note
 Do not confuse this with [`std.variant.Variant`](std_variant#Variant). The type of this property is [`std.uuid.UUID.Variant`](#Variant). 
 
See Also:
[`UUID.Variant`](#Variant)
 
Examples:


```
assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").variant
   == UUID.Variant.rfc4122);

```
 
  const pure nothrow @nogc @property @safe Version **uuidVersion**();  
RFC 4122 defines different UUID versions. The version shows how a UUID was generated, e.g. a version 4 UUID was generated from a random number, a version 3 UUID from an MD5 hash of a name. Returns the version used by this UUID. 



See Also:
[`UUID.Version`](#Version)
 
Examples:


```
assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").uuidVersion
    == UUID.Version.randomNumberBased);

```
 
  pure nothrow @nogc @safe void **swap**(ref UUID rhs);  
Swap the data of this UUID with the data of rhs.



Examples:


```
immutable ubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
UUID u1;
UUID u2 = UUID(data);
u1.swap(u2);

writeln(u1); // UUID(data)
writeln(u2); // UUID.init

```
 
  const pure nothrow @nogc @safe bool **opEquals**(const UUID s);   
  
const pure nothrow @nogc @safe bool **opEquals**(ref scope const UUID s);   
  
const pure nothrow @nogc @safe int **opCmp**(const UUID s);   
  
const pure nothrow @nogc @safe int **opCmp**(ref scope const UUID s);   
  
pure nothrow @nogc @safe UUID **opAssign**(const UUID s);   
  
pure nothrow @nogc @safe UUID **opAssign**(ref scope const UUID s);   
  
const pure nothrow @nogc @safe size\_t **toHash**();  
All of the standard numeric operators are defined for the UUID struct.



Examples:


```
//compare UUIDs
writeln(UUID("00000000-0000-0000-0000-000000000000")); // UUID.init

//UUIDs in associative arrays:
int[UUID] test = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0") : 1,
    UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a") : 2,
    UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1") : 3];

writeln(test[UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")]); // 3

//UUIDS can be sorted:
import std.algorithm;
UUID[] ids = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0"),
              UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a"),
              UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")];
sort(ids);

```
 
  const void **toString**(Writer)(scope Writer sink);  
Write the UUID into `sink` as an ASCII string in the canonical form, which is 36 characters in the form "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" 



Parameters:


|  |  |
| --- | --- |
| Writer `sink` | OutputRange or writeable array at least 36 entries long |


  const pure nothrow @trusted string **toString**();  
Return the UUID as a string in the canonical form.



Examples:


```
immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46";
auto id = UUID(str);
writeln(id.toString()); // str

```
 
    pure nothrow @nogc @safe UUID **md5UUID**(const(char[]) name, const UUID namespace = UUID.init);   
  
pure nothrow @nogc @safe UUID **md5UUID**(const(ubyte[]) data, const UUID namespace = UUID.init);  
This function generates a name based (Version 3) UUID from a namespace UUID and a name. If no namespace UUID was passed, the empty UUID `UUID.init` is used. 



Note
 The default namespaces ([`dnsNamespace`](#dnsNamespace), ...) defined by this module should be used when appropriate. 
 RFC 4122 recommends to use Version 5 UUIDs (SHA-1) instead of Version 3 UUIDs (MD5) for new applications. 
CTFE
 CTFE is not supported. 
 
Note
 RFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used by `std.uuid` is compatible with Boost's implementation. `std.uuid` guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter). 
 
Note
 This function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!).
 
Examples:


```
//Use default UUID.init namespace
auto simpleID = md5UUID("test.uuid.any.string");

//use a name-based id as namespace
auto namespace = md5UUID("my.app");
auto id = md5UUID("some-description", namespace);

```
 
  pure nothrow @nogc @safe UUID **sha1UUID**(scope const(char)[] name, scope const UUID namespace = UUID.init);   
  
pure nothrow @nogc @safe UUID **sha1UUID**(scope const(ubyte)[] data, scope const UUID namespace = UUID.init);  
This function generates a name based (Version 5) UUID from a namespace UUID and a name. If no namespace UUID was passed, the empty UUID `UUID.init` is used. 



Note
 The default namespaces ([`dnsNamespace`](#dnsNamespace), ...) defined by this module should be used when appropriate. 
 
CTFE
 CTFE is not supported. 
 
Note
 RFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used by `std.uuid` is compatible with Boost's implementation. `std.uuid` guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter). 
 
Note
 This function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!).
 
Examples:


```
//Use default UUID.init namespace
auto simpleID = sha1UUID("test.uuid.any.string");

//use a name-based id as namespace
auto namespace = sha1UUID("my.app");
auto id = sha1UUID("some-description", namespace);

```
 
  @safe UUID **randomUUID**();   
  
UUID **randomUUID**(RNG)(ref RNG randomGen)  
 Constraints: if (isInputRange!RNG && isIntegral!(ElementType!RNG)); 
 
This function generates a random number based UUID from a random number generator. 


This function is not supported at compile time. 

 
Parameters:


|  |  |
| --- | --- |
| RNG `randomGen` | uniform RNG |


 
See Also:
[`std.random.isUniformRNG`](std_random#isUniformRNG)
 
Examples:


```
import std.random : Xorshift192, unpredictableSeed;

//simple call
auto uuid = randomUUID();

//provide a custom RNG. Must be seeded manually.
Xorshift192 gen;

gen.seed(unpredictableSeed);
auto uuid3 = randomUUID(gen);

```
 
  UUID **parseUUID**(T)(T uuidString)  
 Constraints: if (isSomeString!T);   
  
UUID **parseUUID**(Range)(ref Range uuidRange)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementType!Range)); 
 
This is a less strict parser compared to the parser used in the UUID constructor. It enforces the following rules: 


* hex numbers are always two hexdigits([0-9a-fA-F])
* there must be exactly 16 such pairs in the input, not less, not more
* there can be exactly one dash between two hex-pairs, but not more
* there can be multiple characters enclosing the 16 hex pairs, as long as these characters do not contain [0-9a-fA-F]

 

 
Note
 Like most parsers, it consumes its argument. This means: 


```
string s = "8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46";
parseUUID(s);
assert(s == "");

```
 
Throws:

[`UUIDParsingException`](#UUIDParsingException) if the input is invalid 
 
CTFE
 This function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time.
 
Examples:


```
auto id = parseUUID("8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46");
//no dashes
id = parseUUID("8ab3060e2cba4f23b74cb52db3bdfb46");
//dashes at different positions
id = parseUUID("8a-b3-06-0e2cba4f23b74c-b52db3bdfb-46");
//leading / trailing characters
id = parseUUID("{8ab3060e-2cba-4f23-b74c-b52db3bdfb46}");
//unicode
id = parseUUID("ü8ab3060e2cba4f23b74cb52db3bdfb46ü");
//multiple trailing/leading characters
id = parseUUID("///8ab3060e2cba4f23b74cb52db3bdfb46||");

//Can also be used in CTFE, for example as UUID literals:
enum ctfeID = parseUUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46");
//here parsing is done at compile time, no runtime overhead!

```
 
  enum UUID **dnsNamespace**;  
Default namespace from RFC 4122 


Name string is a fully-qualified domain name

  enum UUID **urlNamespace**;  
Default namespace from RFC 4122 


Name string is a URL

  enum UUID **oidNamespace**;  
Default namespace from RFC 4122 


Name string is an ISO OID

  enum UUID **x500Namespace**;  
Default namespace from RFC 4122 


Name string is an X.500 DN (in DER or a text output format)

  enum string **uuidRegex**;  
Regex string to extract UUIDs from text.



Examples:


```
import std.algorithm;
import std.regex;

string test = "Lorem ipsum dolor sit amet, consetetur "~
"6ba7b814-9dad-11d1-80b4-00c04fd430c8 sadipscing \n"~
"elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore \r\n"~
"magna aliquyam erat, sed diam voluptua. "~
"8ab3060e-2cba-4f23-b74c-b52db3bdfb46 At vero eos et accusam et "~
"justo duo dolores et ea rebum.";

auto r = regex(uuidRegex, "g");
UUID[] found;
foreach (c; match(test, r))
{
    found ~= UUID(c.hit);
}
assert(found == [
    UUID("6ba7b814-9dad-11d1-80b4-00c04fd430c8"),
    UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46"),
]);

```
 
  class **UUIDParsingException**: object.Exception;  
This exception is thrown if an error occurs when parsing a UUID from a string.



Examples:


```
import std.exception : collectException;

const inputUUID = "this-is-an-invalid-uuid";
auto ex = collectException!UUIDParsingException(UUID(inputUUID));
assert(ex !is null); // check that exception was thrown
writeln(ex.input); // inputUUID
writeln(ex.position); // 0
writeln(ex.reason); // UUIDParsingException.Reason.tooLittle

```
 
 
enum **Reason**: int;   
  
Reason **reason**;  
The reason why parsing the UUID string failed (if known)

 
**unknown** **tooLittle** 
The passed in input was correct, but more input was expected.

  **tooMuch** 
The input data is too long (There's no guarantee the first part of the data is valid)

  **invalidChar** 
Encountered an invalid character

    string **input**;  
The original input string which should have been parsed.

  size\_t **position**;  
The position in the input string where the error occurred.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_uuid.html>

std.variant
===========

 This module implements a [discriminated union](http://erdani.org/publications/cuj-04-2002.php.html) type (a.k.a. [tagged union](http://en.wikipedia.org/wiki/Tagged_union), [algebraic type](http://en.wikipedia.org/wiki/Algebraic_data_type)). Such types are useful for type-uniform binary interfaces, interfacing with scripting languages, and comfortable exploratory programming. 


A [`Variant`](#Variant) object can hold a value of any type, with very few restrictions (such as `shared` types and noncopyable types). Setting the value is as immediate as assigning to the `Variant` object. To read back the value of the appropriate type `T`, use the [`get`](#get) method. To query whether a `Variant` currently holds a value of type `T`, use [`peek`](#peek). To fetch the exact type currently held, call [`type`](#type), which returns the `TypeInfo` of the current value.   
  
 In addition to [`Variant`](#Variant), this module also defines the [`Algebraic`](#Algebraic) type constructor. Unlike `Variant`, `Algebraic` only allows a finite set of types, which are specified in the instantiation (e.g. `Algebraic!(int, string)` may only hold an `int` or a `string`). 

 
Credits
 Reviewed by Brad Roberts. Daniel Keep provided a detailed code review prompting the following improvements: (1) better support for arrays; (2) support for associative arrays; (3) friendlier behavior towards the garbage collector. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.org) 
 
Source
 [std/variant.d](https://github.com/dlang/phobos/blob/master/std/variant.d)

 
Examples:


```
Variant a; // Must assign before use, otherwise exception ensues
// Initialize with an integer; make the type int
Variant b = 42;
writeln(b.type); // typeid (int)
// Peek at the value
assert(b.peek!(int) !is null && *b.peek!(int) == 42);
// Automatically convert per language rules
auto x = b.get!(real);

// Assign any other type, including other variants
a = b;
a = 3.14;
writeln(a.type); // typeid (double)
// Implicit conversions work just as with built-in types
assert(a < b);
// Check for convertibility
assert(!a.convertsTo!(int)); // double not convertible to int
// Strings and all other arrays are supported
a = "now I'm a string";
writeln(a); // "now I'm a string"

// can also assign arrays
a = new int[42];
writeln(a.length); // 42
a[5] = 7;
writeln(a[5]); // 7

// Can also assign class values
class Foo {}
auto foo = new Foo;
a = foo;
assert(*a.peek!(Foo) == foo); // and full type information is preserved

```
 
 
template **maxSize**(T...) 
Gives the `sizeof` the largest type given.



Examples:


```
static assert(maxSize!(int, long) == 8);
static assert(maxSize!(bool, byte) == 1);

struct Cat { int a, b, c; }
static assert(maxSize!(bool, Cat) == 12);

```
 
  struct **VariantN**(size\_t maxDataSize, AllowedTypesParam...);  
Back-end type seldom used directly by user code. Two commonly-used types using `VariantN` are: 


1. [`Algebraic`](#Algebraic): A closed discriminated union with a limited type universe (e.g., `Algebraic!(int, double, string)` only accepts these three types and rejects anything else).
2. [`Variant`](#Variant): An open discriminated union allowing an unbounded set of types. If any of the types in the `Variant` are larger than the largest built-in type, they will automatically be boxed. This means that even large types will only be the size of a pointer within the `Variant`, but this also implies some overhead. `Variant` can accommodate all primitive types and all user-defined types.

   
  
 Both `Algebraic` and `Variant` share  `VariantN`'s interface. (See their respective documentations below.)   
  
 `VariantN` is a discriminated union type parameterized with the largest size of the types stored (`maxDataSize`) and with the list of allowed types (`AllowedTypes`). If the list is empty, then any type up of size up to  `maxDataSize` (rounded up for alignment) can be stored in a `VariantN` object without being boxed (types larger than this will be boxed).

 
Examples:


```
alias Var = VariantN!(maxSize!(int, double, string));

Var a; // Must assign before use, otherwise exception ensues
// Initialize with an integer; make the type int
Var b = 42;
writeln(b.type); // typeid (int)
// Peek at the value
assert(b.peek!(int) !is null && *b.peek!(int) == 42);
// Automatically convert per language rules
auto x = b.get!(real);

// Assign any other type, including other variants
a = b;
a = 3.14;
writeln(a.type); // typeid (double)
// Implicit conversions work just as with built-in types
assert(a < b);
// Check for convertibility
assert(!a.convertsTo!(int)); // double not convertible to int
// Strings and all other arrays are supported
a = "now I'm a string";
writeln(a); // "now I'm a string"

```
 
 
Examples:
can also assign arrays 
```
alias Var = VariantN!(maxSize!(int[]));

Var a = new int[42];
writeln(a.length); // 42
a[5] = 7;
writeln(a[5]); // 7

```
 
 
Examples:
Can also assign class values 
```
alias Var = VariantN!(maxSize!(int*)); // classes are pointers
Var a;

class Foo {}
auto foo = new Foo;
a = foo;
assert(*a.peek!(Foo) == foo); // and full type information is preserved

```
 
 
alias **AllowedTypes** = This2Variant!(VariantN, AllowedTypesParam);  
The list of allowed types. If empty, any type is allowed.

  enum bool **allowed**(T);  
Tells whether a type `T` is statically allowed for storage inside a `VariantN` object by looking `T` up in `AllowedTypes`.

  this(T)(T value);  
Constructs a `VariantN` value given an argument of a generic type. Statically rejects disallowed types.

  this(T : VariantN!(tsize, Types), size\_t tsize, Types...)(T value)  
 Constraints: if (!is(T : VariantN) && (Types.length > 0) && allSatisfy!(allowed, Types)); 
 
Allows assignment from a subset algebraic type

  VariantN **opAssign**(T)(T rhs);  
Assigns a `VariantN` from a generic argument. Statically rejects disallowed types.

  const pure nothrow @property bool **hasValue**();  
Returns true if and only if the `VariantN` object holds a valid value (has been initialized with, or assigned from, a valid value).



Examples:


```
Variant a;
assert(!a.hasValue);
Variant b;
a = b;
assert(!a.hasValue); // still no value
a = 5;
assert(a.hasValue);

```
 
  inout @property inout(T)\* **peek**(T)();  
If the `VariantN` object holds a value of the *exact* type `T`, returns a pointer to that value. Otherwise, returns `null`. In cases where `T` is statically disallowed,  `peek` will not compile.



Examples:


```
Variant a = 5;
auto b = a.peek!(int);
assert(b !is null);
*b = 6;
writeln(a); // 6

```
 
  const nothrow @property @trusted TypeInfo **type**();  
Returns the `typeid` of the currently held value.

  const @property bool **convertsTo**(T)();  
Returns `true` if and only if the `VariantN` object holds an object implicitly convertible to type `T`. Implicit convertibility is defined as per [ImplicitConversionTargets](std_traits#ImplicitConversionTargets).

  inout @property inout(T) **get**(T)();   
  
inout @property auto **get**(uint index)()  
 Constraints: if (index < AllowedTypes.length); 
 
Returns the value stored in the `VariantN` object, either by specifying the needed type or the index in the list of allowed types. The latter overload only applies to bounded variants (e.g. [`Algebraic`](#Algebraic)). 



Parameters:


|  |  |
| --- | --- |
| T | The requested type. The currently stored value must implicitly convert to the requested type, in fact `DecayStaticToDynamicArray!T`. If an implicit conversion is not possible, throws a `VariantException`. |
| index | The index of the type among `AllowedTypesParam`, zero-based. |


  @property T **coerce**(T)();  
Returns the value stored in the `VariantN` object, explicitly converted (coerced) to the requested type  `T`. If `T` is a string type, the value is formatted as a string. If the `VariantN` object is a string, a parse of the string to type `T` is attempted. If a conversion is not possible, throws a  `VariantException`.

  string **toString**();  
Formats the stored value as a string.

  const bool **opEquals**(T)(auto ref T rhs)  
 Constraints: if (allowed!T || is(immutable(T) == immutable(VariantN))); 
 
Comparison for equality used by the "==" and "!=" operators.

  int **opCmp**(T)(T rhs)  
 Constraints: if (allowed!T); 
 
Ordering comparison used by the "<", "<=", ">", and ">=" operators. In case comparison is not sensible between the held value and `rhs`, an exception is thrown.

  const nothrow @safe size\_t **toHash**();  
Computes the hash of the held value.

  VariantN **opBinary**(string op, T)(T rhs)  
 Constraints: if ((op == "+" || op == "-" || op == "\*" || op == "/" || op == "^^" || op == "%") && is(typeof(opArithmetic!(T, op)(rhs))));   
  
VariantN **opBinary**(string op, T)(T rhs)  
 Constraints: if ((op == "&" || op == "|" || op == "^" || op == ">>" || op == "<<" || op == ">>>") && is(typeof(opLogic!(T, op)(rhs))));   
  
VariantN **opBinaryRight**(string op, T)(T lhs)  
 Constraints: if ((op == "+" || op == "\*") && is(typeof(opArithmetic!(T, op)(lhs))));   
  
VariantN **opBinaryRight**(string op, T)(T lhs)  
 Constraints: if ((op == "&" || op == "|" || op == "^") && is(typeof(opLogic!(T, op)(lhs))));   
  
VariantN **opBinary**(string op, T)(T rhs)  
 Constraints: if (op == "~");   
  
VariantN **opOpAssign**(string op, T)(T rhs);  
Arithmetic between `VariantN` objects and numeric values. All arithmetic operations return a `VariantN` object typed depending on the types of both values involved. The conversion rules mimic D's built-in rules for arithmetic conversions.

  inout inout(Variant) **opIndex**(K)(K i);   
  
Variant **opIndexAssign**(T, N)(T value, N i);   
  
Variant **opIndexOpAssign**(string op, T, N)(T value, N i);  
Array and associative array operations. If a  `VariantN` contains an (associative) array, it can be indexed into. Otherwise, an exception is thrown.



Examples:


```
Variant a = new int[10];
a[5] = 42;
writeln(a[5]); // 42
a[5] += 8;
writeln(a[5]); // 50

int[int] hash = [ 42:24 ];
a = hash;
writeln(a[42]); // 24
a[42] /= 2;
writeln(a[42]); // 12

```
 
  @property size\_t **length**();  
If the `VariantN` contains an (associative) array, returns the length of that array. Otherwise, throws an exception.

  int **opApply**(Delegate)(scope Delegate dg)  
 Constraints: if (is(Delegate == delegate)); 
 
If the `VariantN` contains an array, applies `dg` to each element of the array in turn. Otherwise, throws an exception.

    template **Algebraic**(T...) 
Algebraic data type restricted to a closed set of possible types. It's an alias for [`VariantN`](#VariantN) with an appropriately-constructed maximum size. `Algebraic` is useful when it is desirable to restrict what a discriminated type could hold to the end of defining simpler and more efficient manipulation. 



Examples:


```
auto v = Algebraic!(int, double, string)(5);
assert(v.peek!(int));
v = 3.14;
assert(v.peek!(double));
// auto x = v.peek!(long); // won't compile, type long not allowed
// v = '1'; // won't compile, type char not allowed

```
 
 
Examples:

#### Self-Referential Types

 A useful and popular use of algebraic data structures is for defining [self-referential data structures](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=self-referential%20data%20structures), i.e. structures that embed references to values of their own type within. This is achieved with `Algebraic` by using `This` as a placeholder whenever a reference to the type being defined is needed. The `Algebraic` instantiation will perform [alpha renaming](https://en.wikipedia.org/wiki/Name_resolution_(programming_languages)#Alpha_renaming_to_make_name_resolution_trivial) on its constituent types, replacing `This` with the self-referenced type. The structure of the type involving `This` may be arbitrarily complex. 
```
import std.typecons : Tuple, tuple;

// A tree is either a leaf or a branch of two other trees
alias Tree(Leaf) = Algebraic!(Leaf, Tuple!(This*, This*));
Tree!int tree = tuple(new Tree!int(42), new Tree!int(43));
Tree!int* right = tree.get!1[1];
writeln(*right); // 43

// An object is a double, a string, or a hash of objects
alias Obj = Algebraic!(double, string, This[string]);
Obj obj = "hello";
writeln(obj.get!1); // "hello"
obj = 42.0;
writeln(obj.get!0); // 42
obj = ["customer": Obj("John"), "paid": Obj(23.95)];
writeln(obj.get!2["customer"]); // "John"

```
 
  alias **Variant** = VariantN!32LU.VariantN;  
Alias for [`VariantN`](#VariantN) instantiated with the largest size of `creal`, `char[]`, and `void delegate()`. This ensures that `Variant` is large enough to hold all of D's predefined types unboxed, including all numeric types, pointers, delegates, and class references. You may want to use `VariantN` directly with a different maximum size either for storing larger types unboxed, or for saving memory.



Examples:


```
Variant a; // Must assign before use, otherwise exception ensues
// Initialize with an integer; make the type int
Variant b = 42;
writeln(b.type); // typeid (int)
// Peek at the value
assert(b.peek!(int) !is null && *b.peek!(int) == 42);
// Automatically convert per language rules
auto x = b.get!(real);

// Assign any other type, including other variants
a = b;
a = 3.14;
writeln(a.type); // typeid (double)
// Implicit conversions work just as with built-in types
assert(a < b);
// Check for convertibility
assert(!a.convertsTo!(int)); // double not convertible to int
// Strings and all other arrays are supported
a = "now I'm a string";
writeln(a); // "now I'm a string"

```
 
 
Examples:
can also assign arrays 
```
Variant a = new int[42];
writeln(a.length); // 42
a[5] = 7;
writeln(a[5]); // 7

```
 
 
Examples:
Can also assign class values 
```
Variant a;

class Foo {}
auto foo = new Foo;
a = foo;
assert(*a.peek!(Foo) == foo); // and full type information is preserved

```
 
  Variant[] **variantArray**(T...)(T args);  
Returns an array of variants constructed from `args`. 


This is by design. During construction the `Variant` needs static type information about the type being held, so as to store a pointer to function for fast retrieval.

 
Examples:


```
auto a = variantArray(1, 3.14, "Hi!");
writeln(a[1]); // 3.14
auto b = Variant(a); // variant array as variant
writeln(b[1]); // 3.14

```
 
  class **VariantException**: object.Exception;  
Thrown in three cases: 


1. An uninitialized `Variant` is used in any way except assignment and `hasValue`;
2. A `get` or `coerce` is attempted with an incompatible target type;
3. A comparison between `Variant` objects of incompatible types is attempted.


 
Examples:


```
import std.exception : assertThrown;

Variant v;

// uninitialized use
assertThrown!VariantException(v + 1);
assertThrown!VariantException(v.length);

// .get with an incompatible target type
assertThrown!VariantException(Variant("a").get!int);

// comparison between incompatible types
assertThrown!VariantException(Variant(3) < Variant("a"));

```
 
 
TypeInfo **source**;  
The source type in the conversion or comparison

  TypeInfo **target**;  
The target type in the conversion or comparison

    template **visit**(Handlers...) if (Handlers.length > 0) 
Applies a delegate or function to the given [`Algebraic`](#Algebraic) depending on the held type, ensuring that all types are handled by the visiting functions. 


The delegate or function having the currently held value as parameter is called with `variant`'s current value. Visiting handlers are passed in the template parameter list. It is statically ensured that all held types of `variant` are handled across all handlers. `visit` allows delegates and static functions to be passed as parameters.   
  
 If a function with an untyped parameter is specified, this function is called when the variant contains a type that does not match any other function. This can be used to apply the same function across multiple possible types. Exactly one generic function is allowed.   
  
 If a function without parameters is specified, this function is called when `variant` doesn't hold a value. Exactly one parameter-less function is allowed.   
  
 Duplicate overloads matching the same type in one of the visitors are disallowed. 

 
Returns:
The return type of visit is deduced from the visiting functions and must be the same across all overloads. 
 
Throws:

[`VariantException`](#VariantException) if `variant` doesn't hold a value and no parameter-less fallback function is specified.
 
Examples:


```
Algebraic!(int, string) variant;

variant = 10;
assert(variant.visit!((string s) => cast(int) s.length,
                      (int i)    => i)()
                      == 10);
variant = "string";
assert(variant.visit!((int i) => i,
                      (string s) => cast(int) s.length)()
                      == 6);

// Error function usage
Algebraic!(int, string) emptyVar;
auto rslt = emptyVar.visit!((string s) => cast(int) s.length,
                      (int i)    => i,
                      () => -1)();
writeln(rslt); // -1

// Generic function usage
Algebraic!(int, float, real) number = 2;
writeln(number.visit!(x => x += 1)); // 3

// Generic function for int/float with separate behavior for string
Algebraic!(int, float, string) something = 2;
assert(something.visit!((string s) => s.length, x => x) == 2); // generic
something = "asdf";
assert(something.visit!((string s) => s.length, x => x) == 4); // string

// Generic handler and empty handler
Algebraic!(int, float, real) empty2;
writeln(empty2.visit!(x => x + 1, () => -1)); // -1

```
 
 
auto **visit**(VariantType)(VariantType variant)  
 Constraints: if (isAlgebraic!VariantType); 
   template **tryVisit**(Handlers...) if (Handlers.length > 0) 
Behaves as [`visit`](#visit) but doesn't enforce that all types are handled by the visiting functions. 


If a parameter-less function is specified it is called when either `variant` doesn't hold a value or holds a type which isn't handled by the visiting functions. 

 
Returns:
The return type of tryVisit is deduced from the visiting functions and must be the same across all overloads. 
 
Throws:

[`VariantException`](#VariantException) if `variant` doesn't hold a value or `variant` holds a value which isn't handled by the visiting functions, when no parameter-less fallback function is specified.
 
Examples:


```
Algebraic!(int, string) variant;

variant = 10;
auto which = -1;
variant.tryVisit!((int i) { which = 0; })();
writeln(which); // 0

// Error function usage
variant = "test";
variant.tryVisit!((int i) { which = 0; },
                  ()      { which = -100; })();
writeln(which); // -100

```
 
 
auto **tryVisit**(VariantType)(VariantType variant)  
 Constraints: if (isAlgebraic!VariantType); 
   

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_variant.html>

std.utf
=======

 Encode and decode UTF-8, UTF-16 and UTF-32 strings. 


UTF character support is restricted to `'\u0000' <= character <= '\U0010FFFF'`.   
  
 

| Category | Functions |
| --- | --- |
| Decode | [`decode`](#decode) [`decodeFront`](#decodeFront) |
| Lazy decode | [`byCodeUnit`](#byCodeUnit) [`byChar`](#byChar) [`byWchar`](#byWchar) [`byDchar`](#byDchar) [`byUTF`](#byUTF) |
| Encode | [`encode`](#encode) [`toUTF8`](#toUTF8) [`toUTF16`](#toUTF16) [`toUTF32`](#toUTF32) [`toUTFz`](#toUTFz) [`toUTF16z`](#toUTF16z) |
| Length | [`codeLength`](#codeLength) [`count`](#count) [`stride`](#stride) [`strideBack`](#strideBack) |
| Index | [`toUCSindex`](#toUCSindex) [`toUTFindex`](#toUTFindex) |
| Validation | [`isValidDchar`](#isValidDchar) [`validate`](#validate) |
| Miscellaneous | [`replacementDchar`](#replacementDchar) [`UseReplacementDchar`](#UseReplacementDchar) [`UTFException`](#UTFException) |

 

 
See Also:

[Wikipedia](http://en.wikipedia.org/wiki/Unicode)  
 <http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8>  
 <http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335> 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [std/utf.d](https://github.com/dlang/phobos/blob/master/std/utf.d)

 
class **UTFException**: core.exception.UnicodeException;  
Exception thrown on errors in std.utf functions.



Examples:


```
import std.exception : assertThrown;

char[4] buf;
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDBFF));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDC00));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDFFF));
assertThrown!UTFException(encode(buf, cast(dchar) 0x110000));

```
 
 
pure nothrow @nogc @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);   
  
pure nothrow @safe this(string msg, size\_t index, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  
Standard exception constructors.

  const string **toString**();  

Returns:
A `string` detailing the invalid UTF sequence.
    pure nothrow @nogc @safe bool **isValidDchar**(dchar c);  
Check whether the given Unicode code point is valid. 



Parameters:


|  |  |
| --- | --- |
| dchar `c` | code point to check |


 
Returns:

`true` if and only if `c` is a valid Unicode code point 
 
Note
 `'\uFFFE'` and `'\uFFFF'` are considered valid by `isValidDchar`, as they are permitted for internal use by an application, but they are not allowed for interchange by the Unicode standard.
 
Examples:


```
assert( isValidDchar(cast(dchar) 0x41));
assert( isValidDchar(cast(dchar) 0x00));
assert(!isValidDchar(cast(dchar) 0xD800));
assert(!isValidDchar(cast(dchar) 0x11FFFF));

```
 
  uint **stride**(S)(auto ref S str, size\_t index)  
 Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(char)));   
  
uint **stride**(S)(auto ref S str)  
 Constraints: if (is(S : const(char[])) || isInputRange!S && is(immutable(ElementType!S) == immutable(char)));   
  
uint **stride**(S)(auto ref S str, size\_t index)  
 Constraints: if (is(S : const(wchar[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(wchar)));   
  
pure @safe uint **stride**(S)(auto ref S str)  
 Constraints: if (is(S : const(wchar[])));   
  
uint **stride**(S)(auto ref S str)  
 Constraints: if (isInputRange!S && is(immutable(ElementType!S) == immutable(wchar)) && !is(S : const(wchar[])));   
  
uint **stride**(S)(auto ref S str, size\_t index = 0)  
 Constraints: if (is(S : const(dchar[])) || isInputRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar))); 
 
Calculate the length of the UTF sequence starting at `index` in `str`. 



Parameters:


|  |  |
| --- | --- |
| S `str` | [input range](std_range_primitives#isInputRange) of UTF code units. Must be random access if `index` is passed |
| size\_t `index` | starting index of UTF sequence (default: `0`) |


 
Returns:
The number of code units in the UTF sequence. For UTF-8, this is a value between 1 and 4 (as per [RFC 3629, section 3](http://tools.ietf.org/html/rfc3629#section-3)). For UTF-16, it is either 1 or 2. For UTF-32, it is always 1. 
 
Throws:
May throw a `UTFException` if `str[index]` is not the start of a valid UTF sequence. 
 
Note
 `stride` will only analyze the first `str[index]` element. It will not fully verify the validity of the UTF sequence, nor even verify the presence of the sequence: it will not actually guarantee that `index + stride(str, index) <= str.length`.
 
Examples:


```
writeln("a".stride); // 1
writeln("λ".stride); // 2
writeln("aλ".stride); // 1
writeln("aλ".stride(1)); // 2
writeln("𐐷".stride); // 4

```
 
  uint **strideBack**(S)(auto ref S str, size\_t index)  
 Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(char)));   
  
uint **strideBack**(S)(auto ref S str)  
 Constraints: if (is(S : const(char[])) || isRandomAccessRange!S && hasLength!S && is(immutable(ElementType!S) == immutable(char)));   
  
uint **strideBack**(S)(auto ref S str)  
 Constraints: if (isBidirectionalRange!S && is(immutable(ElementType!S) == immutable(char)) && !isRandomAccessRange!S);   
  
uint **strideBack**(S)(auto ref S str, size\_t index)  
 Constraints: if (is(S : const(wchar[])) || isRandomAccessRange!S && is(immutable(ElementType!S) == immutable(wchar)));   
  
uint **strideBack**(S)(auto ref S str)  
 Constraints: if (is(S : const(wchar[])) || isBidirectionalRange!S && is(immutable(ElementType!S) == immutable(wchar)));   
  
uint **strideBack**(S)(auto ref S str, size\_t index)  
 Constraints: if (isRandomAccessRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar)));   
  
uint **strideBack**(S)(auto ref S str)  
 Constraints: if (isBidirectionalRange!S && is(immutable(ElementEncodingType!S) == immutable(dchar))); 
 
Calculate the length of the UTF sequence ending one code unit before `index` in `str`. 



Parameters:


|  |  |
| --- | --- |
| S `str` | bidirectional range of UTF code units. Must be random access if `index` is passed |
| size\_t `index` | index one past end of UTF sequence (default: `str.length`) |


 
Returns:
The number of code units in the UTF sequence. For UTF-8, this is a value between 1 and 4 (as per [RFC 3629, section 3](http://tools.ietf.org/html/rfc3629#section-3)). For UTF-16, it is either 1 or 2. For UTF-32, it is always 1. 
 
Throws:
May throw a `UTFException` if `str[index]` is not one past the end of a valid UTF sequence. 
 
Note
 `strideBack` will only analyze the element at `str[index - 1]` element. It will not fully verify the validity of the UTF sequence, nor even verify the presence of the sequence: it will not actually guarantee that `strideBack(str, index) <= index`.
 
Examples:


```
writeln("a".strideBack); // 1
writeln("λ".strideBack); // 2
writeln("aλ".strideBack); // 2
writeln("aλ".strideBack(1)); // 1
writeln("𐐷".strideBack); // 4

```
 
  pure @safe size\_t **toUCSindex**(C)(const(C)[] str, size\_t index)  
 Constraints: if (isSomeChar!C); 
 
Given `index` into `str` and assuming that `index` is at the start of a UTF sequence, `toUCSindex` determines the number of UCS characters up to `index`. So, `index` is the index of a code unit at the beginning of a code point, and the return value is how many code points into the string that that code point is.



Examples:


```
writeln(toUCSindex(`hello world`, 7)); // 7
writeln(toUCSindex(`hello world`w, 7)); // 7
writeln(toUCSindex(`hello world`d, 7)); // 7

writeln(toUCSindex(`Ma Chérie`, 7)); // 6
writeln(toUCSindex(`Ma Chérie`w, 7)); // 7
writeln(toUCSindex(`Ma Chérie`d, 7)); // 7

writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`, 9)); // 3
writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`w, 9)); // 9
writeln(toUCSindex(`さいごの果実 / ミツバチと科学者`d, 9)); // 9

```
 
  pure @safe size\_t **toUTFindex**(C)(const(C)[] str, size\_t n)  
 Constraints: if (isSomeChar!C); 
 
Given a UCS index `n` into `str`, returns the UTF index. So, `n` is how many code points into the string the code point is, and the array index of the code unit is returned.



Examples:


```
writeln(toUTFindex(`hello world`, 7)); // 7
writeln(toUTFindex(`hello world`w, 7)); // 7
writeln(toUTFindex(`hello world`d, 7)); // 7

writeln(toUTFindex(`Ma Chérie`, 6)); // 7
writeln(toUTFindex(`Ma Chérie`w, 7)); // 7
writeln(toUTFindex(`Ma Chérie`d, 7)); // 7

writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`, 3)); // 9
writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`w, 9)); // 9
writeln(toUTFindex(`さいごの果実 / ミツバチと科学者`d, 9)); // 9

```
 
  alias **UseReplacementDchar** = std.typecons.Flag!"useReplacementDchar".Flag;  
Whether or not to replace invalid UTF with [`replacementDchar`](#replacementDchar)

  dchar **decode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(auto ref S str, ref size\_t index)  
 Constraints: if (!isSomeString!S && isRandomAccessRange!S && hasSlicing!S && hasLength!S && isSomeChar!(ElementType!S));   
  
pure @trusted dchar **decode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(auto ref S str, ref size\_t index)  
 Constraints: if (isSomeString!S); 
 
Decodes and returns the code point starting at `str[index]`. `index` is advanced to one past the decoded code point. If the code point is not well-formed, then a `UTFException` is thrown and `index` remains unchanged. 


decode will only work with strings and random access ranges of code units with length and slicing, whereas [`decodeFront`](#decodeFront) will work with any input range of code units. 

 
Parameters:


|  |  |
| --- | --- |
| useReplacementDchar | if invalid UTF, return replacementDchar rather than throwing |
| S `str` | input string or indexable Range |
| size\_t `index` | starting index into s[]; incremented by number of code units processed |


 
Returns:
decoded character 
 
Throws:

[`UTFException`](#UTFException) if `str[index]` is not the start of a valid UTF sequence and useReplacementDchar is `No.useReplacementDchar`

 
Examples:


```
size_t i;

assert("a".decode(i) == 'a' && i == 1);
i = 0;
assert("å".decode(i) == 'å' && i == 2);
i = 1;
assert("aå".decode(i) == 'å' && i == 3);
i = 0;
assert("å"w.decode(i) == 'å' && i == 1);

// ë as a multi-code point grapheme
i = 0;
assert("e\u0308".decode(i) == 'e' && i == 1);
// ë as a single code point grapheme
i = 0;
assert("ë".decode(i) == 'ë' && i == 2);
i = 0;
assert("ë"w.decode(i) == 'ë' && i == 1);

```
 
  dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits)  
 Constraints: if (!isSomeString!S && isInputRange!S && isSomeChar!(ElementType!S));   
  
pure @trusted dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits)  
 Constraints: if (isSomeString!S);   
  
dchar **decodeFront**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str)  
 Constraints: if (isInputRange!S && isSomeChar!(ElementType!S)); 
 
`decodeFront` is a variant of [`decode`](#decode) which specifically decodes the first code point. Unlike [`decode`](#decode), `decodeFront` accepts any [input range](std_range_primitives#isInputRange) of code units (rather than just a string or random access range). It also takes the range by `ref` and pops off the elements as it decodes them. If `numCodeUnits` is passed in, it gets set to the number of code units which were in the code point which was decoded. 



Parameters:


|  |  |
| --- | --- |
| useReplacementDchar | if invalid UTF, return replacementDchar rather than throwing |
| S `str` | input string or indexable Range |
| size\_t `numCodeUnits` | set to number of code units processed |


 
Returns:
decoded character 
 
Throws:

[`UTFException`](#UTFException) if `str.front` is not the start of a valid UTF sequence. If an exception is thrown, then there is no guarantee as to the number of code units which were popped off, as it depends on the type of range being used and how many code units had to be popped off before the code point was determined to be invalid.
 
Examples:


```
import std.range.primitives;
string str = "Hello, World!";

assert(str.decodeFront == 'H' && str == "ello, World!");
str = "å";
assert(str.decodeFront == 'å' && str.empty);
str = "å";
size_t i;
assert(str.decodeFront(i) == 'å' && i == 2 && str.empty);

```
 
  dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits)  
 Constraints: if (isSomeString!S);   
  
dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str, out size\_t numCodeUnits)  
 Constraints: if (!isSomeString!S && isSomeChar!(ElementType!S) && isBidirectionalRange!S && (isRandomAccessRange!S && hasLength!S || !isRandomAccessRange!S));   
  
dchar **decodeBack**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar, S)(ref S str)  
 Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && isSomeChar!(ElementType!S) || !isRandomAccessRange!S && isBidirectionalRange!S && isSomeChar!(ElementType!S)); 
 
`decodeBack` is a variant of [`decode`](#decode) which specifically decodes the last code point. Unlike [`decode`](#decode), `decodeBack` accepts any bidirectional range of code units (rather than just a string or random access range). It also takes the range by `ref` and pops off the elements as it decodes them. If `numCodeUnits` is passed in, it gets set to the number of code units which were in the code point which was decoded. 



Parameters:


|  |  |
| --- | --- |
| useReplacementDchar | if invalid UTF, return `replacementDchar` rather than throwing |
| S `str` | input string or bidirectional Range |
| size\_t `numCodeUnits` | gives the number of code units processed |


 
Returns:
A decoded UTF character. 
 
Throws:

[`UTFException`](#UTFException) if `str.back` is not the end of a valid UTF sequence. If an exception is thrown, the `str` itself remains unchanged, but there is no guarantee as to the value of `numCodeUnits` (when passed).
 
Examples:


```
import std.range.primitives;
string str = "Hello, World!";

assert(str.decodeBack == '!' && str == "Hello, World");
str = "å";
assert(str.decodeBack == 'å' && str.empty);
str = "å";
size_t i;
assert(str.decodeBack(i) == 'å' && i == 2 && str.empty);

```
 
  pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out char[4] buf, dchar c);   
  
pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out wchar[2] buf, dchar c);   
  
pure @safe size\_t **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(out dchar[1] buf, dchar c);  
Encodes `c` into the static array, `buf`, and returns the actual length of the encoded character (a number between `1` and `4` for `char[4]` buffers and a number between `1` and `2` for `wchar[2]` buffers). 



Throws:

`UTFException` if `c` is not a valid UTF code point.
 
Examples:


```
import std.exception : assertThrown;
import std.typecons : Yes;

char[4] buf;

assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000");
assert(encode(buf, '\u007F') == 1 && buf[0 .. 1] == "\u007F");
assert(encode(buf, '\u0080') == 2 && buf[0 .. 2] == "\u0080");
assert(encode(buf, '\uE000') == 3 && buf[0 .. 3] == "\uE000");
assert(encode(buf, 0xFFFE) == 3 && buf[0 .. 3] == "\xEF\xBF\xBE");
assertThrown!UTFException(encode(buf, cast(dchar) 0x110000));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
auto slice = buf[];
writeln(slice.decodeFront); // replacementDchar

```
 
 
Examples:


```
import std.exception : assertThrown;
import std.typecons : Yes;

wchar[2] buf;

assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000");
assert(encode(buf, '\uD7FF') == 1 && buf[0 .. 1] == "\uD7FF");
assert(encode(buf, '\uE000') == 1 && buf[0 .. 1] == "\uE000");
assert(encode(buf, '\U00010000') == 2 && buf[0 .. 2] == "\U00010000");
assert(encode(buf, '\U0010FFFF') == 2 && buf[0 .. 2] == "\U0010FFFF");
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
auto slice = buf[];
writeln(slice.decodeFront); // replacementDchar

```
 
 
Examples:


```
import std.exception : assertThrown;
import std.typecons : Yes;

dchar[1] buf;

assert(encode(buf, '\u0000') == 1 && buf[0] == '\u0000');
assert(encode(buf, '\uD7FF') == 1 && buf[0] == '\uD7FF');
assert(encode(buf, '\uE000') == 1 && buf[0] == '\uE000');
assert(encode(buf, '\U0010FFFF') == 1 && buf[0] == '\U0010FFFF');
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
writeln(buf[0]); // replacementDchar

```
 
  pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref char[] str, dchar c);   
  
pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref wchar[] str, dchar c);   
  
pure @safe void **encode**(UseReplacementDchar useReplacementDchar = No.useReplacementDchar)(ref dchar[] str, dchar c);  
Encodes `c` in `str`'s encoding and appends it to `str`. 



Throws:

`UTFException` if `c` is not a valid UTF code point.
 
Examples:


```
char[] s = "abcd".dup;
dchar d1 = 'a';
dchar d2 = 'ø';

encode(s, d1);
writeln(s.length); // 5
writeln(s); // "abcda"
encode(s, d2);
writeln(s.length); // 7
writeln(s); // "abcdaø"

```
 
  pure nothrow @nogc @safe ubyte **codeLength**(C)(dchar c)  
 Constraints: if (isSomeChar!C); 
 
Returns the number of code units that are required to encode the code point `c` when `C` is the character type used to encode it.



Examples:


```
writeln(codeLength!char('a')); // 1
writeln(codeLength!wchar('a')); // 1
writeln(codeLength!dchar('a')); // 1

writeln(codeLength!char('\U0010FFFF')); // 4
writeln(codeLength!wchar('\U0010FFFF')); // 2
writeln(codeLength!dchar('\U0010FFFF')); // 1

```
 
  size\_t **codeLength**(C, InputRange)(InputRange input)  
 Constraints: if (isInputRange!InputRange && !isInfinite!InputRange && isSomeChar!(ElementType!InputRange)); 
 
Returns the number of code units that are required to encode `str` in a string whose character type is `C`. This is particularly useful when slicing one string with the length of another and the two string types use different character types. 



Parameters:


|  |  |
| --- | --- |
| C | the character type to get the encoding length for |
| InputRange `input` | the [input range](std_range_primitives#isInputRange) to calculate the encoding length from |


 
Returns:
The number of code units in `input` when encoded to `C`

 
Examples:


```
assert(codeLength!char("hello world") ==
       "hello world".length);
assert(codeLength!wchar("hello world") ==
       "hello world"w.length);
assert(codeLength!dchar("hello world") ==
       "hello world"d.length);

assert(codeLength!char(`プログラミング`) ==
       `プログラミング`.length);
assert(codeLength!wchar(`プログラミング`) ==
       `プログラミング`w.length);
assert(codeLength!dchar(`プログラミング`) ==
       `プログラミング`d.length);

string haystack = `Être sans la verité, ça, ce ne serait pas bien.`;
wstring needle = `Être sans la verité`;
assert(haystack[codeLength!char(needle) .. $] ==
       `, ça, ce ne serait pas bien.`);

```
 
  pure @safe void **validate**(S)(in S str)  
 Constraints: if (isSomeString!S); 
 
Checks to see if `str` is well-formed unicode or not. 



Throws:

`UTFException` if `str` is not well-formed.
 
Examples:


```
import std.exception : assertThrown;
char[] a = [167, 133, 175];
assertThrown!UTFException(validate(a));

```
 
  string **toUTF8**(S)(S s)  
 Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); 
 
Encodes the elements of `s` to UTF-8 and returns a newly allocated string of the elements. 



Parameters:


|  |  |
| --- | --- |
| S `s` | the string to encode |


 
Returns:
A UTF-8 string 
 
See Also:
For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF).
 
Examples:


```
import std.algorithm.comparison : equal;

// The ö is represented by two UTF-8 code units
assert("Hellø"w.toUTF8.equal(['H', 'e', 'l', 'l', 0xC3, 0xB8]));

// 𐐷 is four code units in UTF-8
assert("𐐷"d.toUTF8.equal([0xF0, 0x90, 0x90, 0xB7]));

```
 
  wstring **toUTF16**(S)(S s)  
 Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); 
 
Encodes the elements of `s` to UTF-16 and returns a newly GC allocated `wstring` of the elements. 



Parameters:


|  |  |
| --- | --- |
| S `s` | the range to encode |


 
Returns:
A UTF-16 string 
 
See Also:
For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF).
 
Examples:


```
import std.algorithm.comparison : equal;

// these graphemes are two code units in UTF-16 and one in UTF-32
writeln("𤭢"d.length); // 1
writeln("𐐷"d.length); // 1

assert("𤭢"d.toUTF16.equal([0xD852, 0xDF62]));
assert("𐐷"d.toUTF16.equal([0xD801, 0xDC37]));

```
 
  dstring **toUTF32**(S)(S s)  
 Constraints: if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)); 
 
Encodes the elements of `s` to UTF-32 and returns a newly GC allocated `dstring` of the elements. 



Parameters:


|  |  |
| --- | --- |
| S `s` | the range to encode |


 
Returns:
A UTF-32 string 
 
See Also:
For a lazy, non-allocating version of these functions, see [`byUTF`](#byUTF).
 
Examples:


```
import std.algorithm.comparison : equal;

// these graphemes are two code units in UTF-16 and one in UTF-32
writeln("𤭢"w.length); // 2
writeln("𐐷"w.length); // 2

assert("𤭢"w.toUTF32.equal([0x00024B62]));
assert("𐐷"w.toUTF32.equal([0x00010437]));

```
 
  template **toUTFz**(P) if (isPointer!P && isSomeChar!(typeof(\*P.init))) 
Returns a C-style zero-terminated string equivalent to `str`. `str` 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 `str.empty` is `true`, then a string containing only `'\0'` is returned. 


`toUTFz` accepts any type of string and is templated on the type of character pointer that you wish to convert to. It will avoid allocating a new string if it can, but there's a decent chance that it will end up having to allocate a new string - particularly when dealing with character types other than `char`.   
  
 Warning 1: If the result of `toUTFz` equals `str.ptr`, then if anything alters the character one past the end of `str` (which is the `'\0'` character terminating the string), then the string won't be zero-terminated anymore. The most likely scenarios for that are if you append to `str` and no reallocation takes place or when `str` is a slice of a larger array, and you alter the character in the larger array which is one character past the end of `str`. Another case where it could occur would be if you had a mutable character array immediately after `str` in memory (for example, if they're member variables in a user-defined type with one declared right after the other) and that character array happened to start with `'\0'`. Such scenarios will never occur if you immediately use the zero-terminated string after calling `toUTFz` and the C function using it doesn't keep a reference to it. Also, they are unlikely to occur even if you save the zero-terminated string (the cases above would be among the few examples of where it could happen). However, if you save the zero-terminate string and want to be absolutely certain that the string stays zero-terminated, then simply append a `'\0'` to the string and use its `ptr` property rather than calling `toUTFz`.   
  
 Warning 2: When passing a character pointer 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 go away during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

 
Examples:


```
auto p1 = toUTFz!(char*)("hello world");
auto p2 = toUTFz!(const(char)*)("hello world");
auto p3 = toUTFz!(immutable(char)*)("hello world");
auto p4 = toUTFz!(char*)("hello world"d);
auto p5 = toUTFz!(const(wchar)*)("hello world");
auto p6 = toUTFz!(immutable(dchar)*)("hello world"w);

```
 
  pure @safe const(wchar)\* **toUTF16z**(C)(const(C)[] str)  
 Constraints: if (isSomeChar!C); 
 
`toUTF16z` is a convenience function for `toUTFz!(const(wchar)*)`. 


Encodes string `s` into UTF-16 and returns the encoded string. `toUTF16z` is suitable for calling the 'W' functions in the Win32 API that take an `LPCWSTR` argument.

 
Examples:


```
string str = "Hello, World!";
const(wchar)* p = str.toUTF16z;
writeln(p[str.length]); // '\0'

```
 
  pure nothrow @nogc @safe size\_t **count**(C)(const(C)[] str)  
 Constraints: if (isSomeChar!C); 
 
Returns the total number of code points encoded in `str`. 



Supercedes
 This function supercedes [`toUCSindex`](#toUCSindex). 
 
Standards:
Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 
 
Throws:

`UTFException` if `str` is not well-formed.
 
Examples:


```
writeln(count("")); // 0
writeln(count("a")); // 1
writeln(count("abc")); // 3
writeln(count("\u20AC100")); // 4

```
 
  enum dchar **replacementDchar**;  
Inserted in place of invalid UTF sequences. 



References
 <http://en.wikipedia.org/wiki/Replacement_character#Replacement_character>

  auto **byCodeUnit**(R)(R r)  
 Constraints: if (isConvertibleToString!R && !isStaticArray!R || isInputRange!R && isSomeChar!(ElementEncodingType!R)); 
 
Iterate a range of char, wchar, or dchars by code unit. 


The purpose is to bypass the special case decoding that [`std.range.primitives.front`](std_range_primitives#front) does to character arrays. As a result, using ranges with `byCodeUnit` can be `nothrow` while [`std.range.primitives.front`](std_range_primitives#front) throws when it encounters invalid Unicode sequences.   
  
 A code unit is a building block of the UTF encodings. Generally, an individual code unit does not represent what's perceived as a full character (a.k.a. a grapheme cluster in Unicode terminology). Many characters are encoded with multiple code units. For example, the UTF-8 code units for `ø` are `0xC3 0xB8`. That means, an individual element of `byCodeUnit` often does not form a character on its own. Attempting to treat it as one while iterating over the resulting range will give nonsensical results. 

 
Parameters:


|  |  |
| --- | --- |
| R `r` | an [input range](std_range_primitives#isInputRange) of characters (including strings) or a type that implicitly converts to a string type. |


 
Returns:
If `r` is not an auto-decodable string (i.e. a narrow string or a user-defined type that implicits converts to a string type), then `r` is returned. Otherwise, `r` is converted to its corresponding string type (if it's not already a string) and wrapped in a random-access range where the element encoding type of the string (its code unit) is the element type of the range, and that range returned. The range has slicing. If `r` is quirky enough to be a struct or class which is an input range of characters on its own (i.e. it has the input range API as member functions), *and* it's implicitly convertible to a string type, then `r` is returned, and no implicit conversion takes place. If `r` is wrapped in a new range, then that range has a `source` property for returning the string that's currently contained within that range. 
 
See Also:
Refer to the [`std.uni`](std_uni) docs for a reference on Unicode terminology. For a range that iterates by grapheme cluster (written character) see [`std.uni.byGrapheme`](std_uni#byGrapheme).
 
Examples:


```
import std.range.primitives;
import std.traits : isAutodecodableString;

auto r = "Hello, World!".byCodeUnit();
static assert(hasLength!(typeof(r)));
static assert(hasSlicing!(typeof(r)));
static assert(isRandomAccessRange!(typeof(r)));
static assert(is(ElementType!(typeof(r)) == immutable char));

// contrast with the range capabilities of standard strings (with or
// without autodecoding enabled).
auto s = "Hello, World!";
static assert(isBidirectionalRange!(typeof(r)));
static if (isAutodecodableString!(typeof(s)))
{
    // with autodecoding enabled, strings are non-random-access ranges of
    // dchar.
    static assert(is(ElementType!(typeof(s)) == dchar));
    static assert(!isRandomAccessRange!(typeof(s)));
    static assert(!hasSlicing!(typeof(s)));
    static assert(!hasLength!(typeof(s)));
}
else
{
    // without autodecoding, strings are normal arrays.
    static assert(is(ElementType!(typeof(s)) == immutable char));
    static assert(isRandomAccessRange!(typeof(s)));
    static assert(hasSlicing!(typeof(s)));
    static assert(hasLength!(typeof(s)));
}

```
 
 
Examples:

`byCodeUnit` does no Unicode decoding 
```
string noel1 = "noe\u0308l"; // noël using e + combining diaeresis
assert(noel1.byCodeUnit[2] != 'ë');
writeln(noel1.byCodeUnit[2]); // 'e'

string noel2 = "no\u00EBl"; // noël using a precomposed ë character
// Because string is UTF-8, the code unit at index 2 is just
// the first of a sequence that encodes 'ë'
assert(noel2.byCodeUnit[2] != 'ë');

```
 
 
Examples:

`byCodeUnit` exposes a `source` property when wrapping narrow strings. 
```
import std.algorithm.comparison : equal;
import std.range : popFrontN;
import std.traits : isAutodecodableString;
{
    auto range = byCodeUnit("hello world");
    range.popFrontN(3);
    assert(equal(range.save, "lo world"));
    static if (isAutodecodableString!string) // only enabled with autodecoding
    {
        string str = range.source;
        writeln(str); // "lo world"
    }
}
// source only exists if the range was wrapped
{
    auto range = byCodeUnit("hello world"d);
    static assert(!__traits(compiles, range.source));
}

```
 
  alias **byChar** = byUTF!(char, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R));   
  
alias **byWchar** = byUTF!(wchar, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R));   
  
alias **byDchar** = byUTF!(dchar, Flag.yes).byUTF(R)(R r) if (isAutodecodableString!R && isInputRange!R && isSomeChar!(ElementEncodingType!R));  
Iterate an [input range](std_range_primitives#isInputRange) of characters by char, wchar, or dchar. These aliases simply forward to [`byUTF`](#byUTF) with the corresponding C argument. 



Parameters:


|  |  |
| --- | --- |
| R r | input range of characters, or array of characters |


  template **byUTF**(C, UseReplacementDchar useReplacementDchar = Yes.useReplacementDchar) if (isSomeChar!C) 
Iterate an [input range](std_range_primitives#isInputRange) of characters by char type `C` by encoding the elements of the range. 


UTF sequences that cannot be converted to the specified encoding are either replaced by U+FFFD per "5.22 Best Practice for U+FFFD Substitution" of the Unicode Standard 6.2 or result in a thrown UTFException. Hence byUTF is not symmetric. This algorithm is lazy, and does not allocate memory. `@nogc`, `pure`-ity, `nothrow`, and `@safe`-ty are inferred from the `r` parameter. 

 
Parameters:


|  |  |
| --- | --- |
| C | `char`, `wchar`, or `dchar` |
| useReplacementDchar | UseReplacementDchar.yes means replace invalid UTF with `replacementDchar`, UseReplacementDchar.no means throw `UTFException` for invalid UTF |


 
Throws:

`UTFException` if invalid UTF sequence and `useReplacementDchar` is set to `UseReplacementDchar.yes` 
 
GC
 Does not use GC if `useReplacementDchar` is set to `UseReplacementDchar.no` 
 
Returns:
A forward range if `R` is a range and not auto-decodable, as defined by [`std.traits.isAutodecodableString`](std_traits#isAutodecodableString), and if the base range is also a forward range. Or, if `R` is a range and it is auto-decodable and `is(ElementEncodingType!typeof(r) == C)`, then the range is passed to [`byCodeUnit`](#byCodeUnit). Otherwise, an input range of characters.
 
Examples:


```
import std.algorithm.comparison : equal;

// hellö as a range of `char`s, which are UTF-8
assert("hell\u00F6".byUTF!char().equal(['h', 'e', 'l', 'l', 0xC3, 0xB6]));

// `wchar`s are able to hold the ö in a single element (UTF-16 code unit)
assert("hell\u00F6".byUTF!wchar().equal(['h', 'e', 'l', 'l', 'ö']));

// 𐐷 is four code units in UTF-8, two in UTF-16, and one in UTF-32
assert("𐐷".byUTF!char().equal([0xF0, 0x90, 0x90, 0xB7]));
assert("𐐷".byUTF!wchar().equal([0xD801, 0xDC37]));
assert("𐐷".byUTF!dchar().equal([0x00010437]));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;
import std.exception : assertThrown;

assert("hello\xF0betty".byChar.byUTF!(dchar, UseReplacementDchar.yes).equal("hello\uFFFDetty"));
assertThrown!UTFException("hello\xF0betty".byChar.byUTF!(dchar, UseReplacementDchar.no).equal("hello betty"));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_utf.html>

std.zlib
========

 Compress/decompress data using the [zlib library](http://www.zlib.net). 



Examples:
 If you have a small buffer you can use [`compress`](#compress) and [`uncompress`](#uncompress) directly. 
```
import std.zlib;

auto src =
"the quick brown fox jumps over the lazy dog\r
 the quick brown fox jumps over the lazy dog\r";

ubyte[] dst;
ubyte[] result;

dst = compress(src);
result = cast(ubyte[]) uncompress(dst);
assert(result == src);

```
 When the data to be compressed doesn't fit in one buffer, use [`Compress`](#Compress) and [`UnCompress`](#UnCompress). 
```
import std.zlib;
import std.stdio;
import std.conv : to;
import std.algorithm.iteration : map;

UnCompress decmp = new UnCompress;
foreach (chunk; stdin.byChunk(4096).map!(x => decmp.uncompress(x)))
{
    chunk.to!string.write;
}


```
 
 
References
 [Wikipedia](http://en.wikipedia.org/wiki/Zlib) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/zlib.d](https://github.com/dlang/phobos/blob/master/std/zlib.d)

 
class **ZlibException**: object.Exception;  
Errors throw a ZlibException.

  uint **adler32**(uint adler, const(void)[] buf);  
Compute the Adler-32 checksum of a buffer's worth of data.

 
Parameters:


|  |  |
| --- | --- |
| uint `adler` | the starting checksum for the computation. Use 1 for a new checksum. Use the output of this function for a cumulative checksum. |
| const(void)[] `buf` | buffer containing input data |


 
Returns:
A `uint` checksum for the provided input data and starting checksum 
 
See Also:
<http://en.wikipedia.org/wiki/Adler-32>
 
Examples:


```
static ubyte[] data = [1,2,3,4,5,6,7,8,9,10];

uint adler = adler32(0u, data);
writeln(adler); // 0xdc0037

```
 
  uint **crc32**(uint crc, const(void)[] buf);  
Compute the CRC32 checksum of a buffer's worth of data.

 
Parameters:


|  |  |
| --- | --- |
| uint `crc` | the starting checksum for the computation. Use 0 for a new checksum. Use the output of this function for a cumulative checksum. |
| const(void)[] `buf` | buffer containing input data |


 
Returns:
A `uint` checksum for the provided input data and starting checksum 
 
See Also:
<http://en.wikipedia.org/wiki/Cyclic_redundancy_check>
  ubyte[] **compress**(const(void)[] srcbuf, int level);   
  
ubyte[] **compress**(const(void)[] srcbuf);  
Compress data

 
Parameters:


|  |  |
| --- | --- |
| const(void)[] `srcbuf` | buffer containing the data to compress |
| int `level` | compression level. Legal values are -1 .. 9, with -1 indicating the default level (6), 0 indicating no compression, 1 being the least compression and 9 being the most. |


 
Returns:
the compressed data
  void[] **uncompress**(const(void)[] srcbuf, size\_t destlen = 0u, int winbits = 15);  
Decompresses the data in srcbuf[]. 



Parameters:


|  |  |
| --- | --- |
| const(void)[] `srcbuf` | buffer containing the compressed data. |
| size\_t `destlen` | size of the uncompressed data. It need not be accurate, but the decompression will be faster if the exact size is supplied. |
| int `winbits` | the base two logarithm of the maximum window size. |


 
Returns:
the decompressed data.
  enum **HeaderFormat**: int;  
the header format the compressed stream is wrapped in

 
**deflate** 
a standard zlib header

  **gzip** 
a gzip file format header

  **determineFromData** 
used when decompressing. Try to automatically detect the stream format by looking at the data

    class **Compress**;  
Used when the data to be compressed is not all in one buffer.

 
this(int level, HeaderFormat header = HeaderFormat.deflate);   
  
this(HeaderFormat header = HeaderFormat.deflate);  
Constructor. 



Parameters:


|  |  |
| --- | --- |
| int `level` | compression level. Legal values are 1 .. 9, with 1 being the least compression and 9 being the most. The default value is 6. |
| HeaderFormat `header` | sets the compression type to one of the options available in [`HeaderFormat`](#HeaderFormat). Defaults to HeaderFormat.deflate. |


 
See Also:

[`compress`](#compress), [`HeaderFormat`](#HeaderFormat)

  const(void)[] **compress**(const(void)[] buf);  
Compress the data in buf and return the compressed data. 



Parameters:


|  |  |
| --- | --- |
| const(void)[] `buf` | data to compress |


 
Returns:
the compressed data. The buffers returned from successive calls to this should be concatenated together.
  void[] **flush**(int mode = Z\_FINISH);  
Compress and return any remaining data. The returned data should be appended to that returned by compress(). 



Parameters:


|  |  |
| --- | --- |
| int `mode` | one of the following:  Z\_SYNC\_FLUSH  Syncs up flushing to the next byte boundary. Used when more data is to be compressed later on. Z\_FULL\_FLUSH  Syncs up flushing to the next byte boundary. Used when more data is to be compressed later on, and the decompressor needs to be restartable at this point. Z\_FINISH (default) Used when finished compressing the data.   |


    class **UnCompress**;  
Used when the data to be decompressed is not all in one buffer.

 
this(uint destbufsize);   
  
this(HeaderFormat format = HeaderFormat.determineFromData);  
Construct. destbufsize is the same as for D.zlib.uncompress().

  const(void)[] **uncompress**(const(void)[] buf);  
Decompress the data in buf and return the decompressed data. The buffers returned from successive calls to this should be concatenated together.

  void[] **flush**();  
Decompress and return any remaining data. The returned data should be appended to that returned by uncompress(). The UnCompress object cannot be used further.

  const @property bool **empty**();  
Returns true if all input data has been decompressed and no further data can be decompressed (inflate() returned Z\_STREAM\_END)



Examples:


```
// some random data
ubyte[1024] originalData = void;

// append garbage data (or don't, this works in both cases)
auto compressedData = cast(ubyte[]) compress(originalData) ~ cast(ubyte[]) "whatever";

auto decompressor = new UnCompress();
auto uncompressedData = decompressor.uncompress(compressedData);

assert(uncompressedData[] == originalData[],
        "The uncompressed and the original data differ");
assert(decompressor.empty, "The UnCompressor reports not being done");

```
 
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_zlib.html>

etc.c.odbc.sqltypes
===================

 Declarations for interfacing with the ODBC library. 


Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;1@digitaldaemon.com)).   
  
 `etc.c.odbc.sqlext.d` corresponds to the `sqlext.h` C header file. 

 
See Also:
 [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference)


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_odbc_sqltypes.html>

std.string
==========

 String handling functions. 




| Category | Functions |
| --- | --- |
| Searching | [*column*](#column) [*indexOf*](#indexOf) [*indexOfAny*](#indexOfAny) [*indexOfNeither*](#indexOfNeither) [*lastIndexOf*](#lastIndexOf) [*lastIndexOfAny*](#lastIndexOfAny) [*lastIndexOfNeither*](#lastIndexOfNeither) |
| Comparison | [*isNumeric*](#isNumeric) |
| Mutation | [*capitalize*](#capitalize) |
| Pruning and Filling | [*center*](#center) [*chomp*](#chomp) [*chompPrefix*](#chompPrefix) [*chop*](#chop) [*detabber*](#detabber) [*detab*](#detab) [*entab*](#entab) [*entabber*](#entabber) [*leftJustify*](#leftJustify) [*outdent*](#outdent) [*rightJustify*](#rightJustify) [*strip*](#strip) [*stripLeft*](#stripLeft) [*stripRight*](#stripRight) [*wrap*](#wrap) |
| Substitution | [*abbrev*](#abbrev) [*soundex*](#soundex) [*soundexer*](#soundexer) [*succ*](#succ) [*tr*](#tr) [*translate*](#translate) |
| Miscellaneous | [*assumeUTF*](#assumeUTF) [*fromStringz*](#fromStringz) [*lineSplitter*](#lineSplitter) [*representation*](#representation) [*splitLines*](#splitLines) [*toStringz*](#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#cmp) [`count`](std_algorithm_searching#count) [`endsWith`](std_algorithm_searching#endsWith) [`startsWith`](std_algorithm_searching#startsWith) |
| std.array | [`join`](std_array#join) [`replace`](std_array#replace) [`replaceInPlace`](std_array#replaceInPlace) [`split`](std_array#split) [`empty`](std_array#empty) |
| std.format | [`format`](std_format#format) [`sformat`](std_format#sformat) |
| std.uni | [`icmp`](std_uni#icmp) [`toLower`](std_uni#toLower) [`toLowerInPlace`](std_uni#toLowerInPlace) [`toUpper`](std_uni#toUpper) [`toUpperInPlace`](std_uni#toUpperInPlace) |

   
  
 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`](std_uni) and [`std.ascii`](std_ascii), respectively. Other functions that have a wider generality than just strings can be found in [`std.algorithm`](std_algorithm) and [`std.range`](std_range). 

 
See Also:

* [`std.algorithm`](std_algorithm) and [`std.range`](std_range) for generic range algorithms
* [`std.ascii`](std_ascii) for functions that work with ASCII strings
* [`std.uni`](std_uni) for functions that work with unicode strings

 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), [Andrei Alexandrescu](http://erdani.org), [Jonathan M Davis](http://jmdavisprog.com), and David L. 'SpottedTiger' Davis 
 
Source
 [std/string.d](https://github.com/dlang/phobos/blob/master/std/string.d)

 
class **StringException**: object.Exception;  
Exception thrown on errors in std.string functions.



Examples:


```
import std.exception : assertThrown;
auto bad = "      a\n\tb\n   c";
assertThrown!StringException(bad.outdent);

```
 
  pure nothrow @nogc @system inout(Char)[] **fromStringz**(Char)(return scope inout(Char)\* cString)  
 Constraints: if (isSomeChar!Char); 
 

Parameters:


|  |  |
| --- | --- |
| inout(Char)\* `cString` | A null-terminated c-style string. |


 
Returns:
A D-style array of `char`, `wchar` or `dchar` referencing the same string. The returned array will retain the same type qualifiers as the input. Important Note: The returned array is a slice of the original buffer. The original data is not changed and not copied.
 
Examples:


```
writeln(fromStringz("foo\0"c.ptr)); // "foo"c
writeln(fromStringz("foo\0"w.ptr)); // "foo"w
writeln(fromStringz("foo\0"d.ptr)); // "foo"d

writeln(fromStringz("福\0"c.ptr)); // "福"c
writeln(fromStringz("福\0"w.ptr)); // "福"w
writeln(fromStringz("福\0"d.ptr)); // "福"d

```
 
  pure nothrow @trusted immutable(char)\* **toStringz**(scope const(char)[] s);   
  
pure nothrow @trusted immutable(char)\* **toStringz**(return scope string s);  

Parameters:


|  |  |
| --- | --- |
| const(char)[] `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. 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.
 
Examples:


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

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

string test = "";
p = toStringz(test);
writeln(*p); // 0

test = "\0";
p = toStringz(test);
writeln(*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);
writeln(*p); // 0

```
 
  alias **CaseSensitive** = std.typecons.Flag!"caseSensitive".Flag;  
Flag indicating whether a search is case-sensitive.

  ptrdiff\_t **indexOf**(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);   
  
ptrdiff\_t **indexOf**(C)(scope const(C)[] s, dchar c, CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!C);   
  
ptrdiff\_t **indexOf**(Range)(Range s, dchar c, size\_t startIdx, CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);   
  
ptrdiff\_t **indexOf**(C)(scope const(C)[] s, dchar c, size\_t startIdx, CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!C); 
 
Searches for character in range. 



Parameters:


|  |  |
| --- | --- |
| Range `s` | string or InputRange of characters to search in correct UTF format |
| dchar `c` | character to search for |
| size\_t `startIdx` | starting index to a well-formed code point |
| CaseSensitive `cs` | `Yes.caseSensitive` or `No.caseSensitive` |


 
Returns:
the index of the first occurrence of `c` in `s` with respect to the start index `startIdx`. If `c` is not found, then `-1` is returned. If `c` is found the value of the returned index is at least `startIdx`. If the parameters are not valid UTF, the result will still be in the range [-1 .. s.length], but will not be reliable otherwise. 
 
Throws:
If the sequence starting at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. 
 
See Also:
[`std.algorithm.searching.countUntil`](std_algorithm_searching#countUntil)
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(indexOf(s, 'W')); // 6
writeln(indexOf(s, 'Z')); // -1
writeln(indexOf(s, 'w', No.caseSensitive)); // 6

```
 
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(indexOf(s, 'W', 4)); // 6
writeln(indexOf(s, 'Z', 100)); // -1
writeln(indexOf(s, 'w', 3, No.caseSensitive)); // 6

```
 
  ptrdiff\_t **indexOf**(Range, Char)(Range s, const(Char)[] sub)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && isSomeChar!Char);   
  
ptrdiff\_t **indexOf**(Range, Char)(Range s, const(Char)[] sub, in CaseSensitive cs)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && isSomeChar!Char);   
  
@safe ptrdiff\_t **indexOf**(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, in size\_t startIdx)  
 Constraints: if (isSomeChar!Char1 && isSomeChar!Char2);   
  
@safe ptrdiff\_t **indexOf**(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, in size\_t startIdx, in CaseSensitive cs)  
 Constraints: if (isSomeChar!Char1 && isSomeChar!Char2); 
 
Searches for substring in `s`. 



Parameters:


|  |  |
| --- | --- |
| Range `s` | string or ForwardRange of characters to search in correct UTF format |
| const(Char)[] `sub` | substring to search for |
| size\_t `startIdx` | the index into s to start searching from |
| CaseSensitive `cs` | `Yes.caseSensitive` (default) or `No.caseSensitive` |


 
Returns:
the index of the first occurrence of `sub` in `s` with respect to the start index `startIdx`. If `sub` is not found, then `-1` is returned. If the arguments are not valid UTF, the result will still be in the range [-1 .. s.length], but will not be reliable otherwise. If `sub` is found the value of the returned index is at least `startIdx`. 
 
Throws:
If the sequence starting at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. 
 
Bugs:
Does not work with case insensitive strings where the mapping of tolower and toupper is not 1:1.
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(indexOf(s, "Wo", 4)); // 6
writeln(indexOf(s, "Zo", 100)); // -1
writeln(indexOf(s, "wo", 3, No.caseSensitive)); // 6

```
 
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(indexOf(s, "Wo")); // 6
writeln(indexOf(s, "Zo")); // -1
writeln(indexOf(s, "wO", No.caseSensitive)); // 6

```
 
  pure @safe ptrdiff\_t **lastIndexOf**(Char)(const(Char)[] s, in dchar c, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char);   
  
pure @safe ptrdiff\_t **lastIndexOf**(Char)(const(Char)[] s, in dchar c, in size\_t startIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char); 
 

Parameters:


|  |  |
| --- | --- |
| const(Char)[] `s` | string to search |
| dchar `c` | character to search for |
| size\_t `startIdx` | the index into s to start searching from |
| CaseSensitive `cs` | `Yes.caseSensitive` or `No.caseSensitive` |


 
Returns:
The index of the last occurrence of `c` in `s`. If `c` is not found, then `-1` is returned. The `startIdx` slices `s` in the following way `s[0 .. startIdx]`. `startIdx` represents a codeunit index in `s`. 
 
Throws:
If the sequence ending at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. `cs` indicates whether the comparisons are case sensitive.
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(lastIndexOf(s, 'l')); // 9
writeln(lastIndexOf(s, 'Z')); // -1
writeln(lastIndexOf(s, 'L', No.caseSensitive)); // 9

```
 
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(lastIndexOf(s, 'l', 4)); // 3
writeln(lastIndexOf(s, 'Z', 1337)); // -1
writeln(lastIndexOf(s, 'L', 7, No.caseSensitive)); // 3

```
 
  pure @safe ptrdiff\_t **lastIndexOf**(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char1 && isSomeChar!Char2);   
  
pure @safe ptrdiff\_t **lastIndexOf**(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, in size\_t startIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char1 && isSomeChar!Char2); 
 

Parameters:


|  |  |
| --- | --- |
| const(Char1)[] `s` | string to search |
| const(Char2)[] `sub` | substring to search for |
| size\_t `startIdx` | the index into s to start searching from |
| CaseSensitive `cs` | `Yes.caseSensitive` or `No.caseSensitive` |


 
Returns:
the index of the last occurrence of `sub` in `s`. If `sub` is not found, then `-1` is returned. The `startIdx` slices `s` in the following way `s[0 .. startIdx]`. `startIdx` represents a codeunit index in `s`. 
 
Throws:
If the sequence ending at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. `cs` indicates whether the comparisons are case sensitive.
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(lastIndexOf(s, "ll")); // 2
writeln(lastIndexOf(s, "Zo")); // -1
writeln(lastIndexOf(s, "lL", No.caseSensitive)); // 2

```
 
 
Examples:


```
import std.typecons : No;

string s = "Hello World";
writeln(lastIndexOf(s, "ll", 4)); // 2
writeln(lastIndexOf(s, "Zo", 128)); // -1
writeln(lastIndexOf(s, "lL", 3, No.caseSensitive)); // -1

```
 
  pure @safe ptrdiff\_t **indexOfAny**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2);   
  
pure @safe ptrdiff\_t **indexOfAny**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in size\_t startIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2); 
 
Returns the index of the first occurrence of any of the elements in  `needles` in `haystack`. If no element of `needles` is found, then `-1` is returned. The `startIdx` slices `haystack` in the following way `haystack[startIdx .. $]`. `startIdx` represents a codeunit index in `haystack`. If the sequence ending at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `haystack` | String to search for needles in. |
| const(Char2)[] `needles` | Strings to search for in haystack. |
| size\_t `startIdx` | slices haystack like this `haystack[startIdx .. $]`. If the startIdx is greater equal the length of haystack the functions returns `-1`. |
| CaseSensitive `cs` | Indicates whether the comparisons are case sensitive. |


 
Examples:


```
import std.conv : to;

ptrdiff_t i = "helloWorld".indexOfAny("Wr");
writeln(i); // 5
i = "öällo world".indexOfAny("lo ");
writeln(i); // 4

```
 
 
Examples:


```
import std.conv : to;

ptrdiff_t i = "helloWorld".indexOfAny("Wr", 4);
writeln(i); // 5

i = "Foo öällo world".indexOfAny("lh", 3);
writeln(i); // 8

```
 
  pure @safe ptrdiff\_t **lastIndexOfAny**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2);   
  
pure @safe ptrdiff\_t **lastIndexOfAny**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in size\_t stopIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2); 
 
Returns the index of the last occurrence of any of the elements in  `needles` in `haystack`. If no element of `needles` is found, then `-1` is returned. The `stopIdx` slices `haystack` in the following way `s[0 .. stopIdx]`. `stopIdx` represents a codeunit index in `haystack`. If the sequence ending at `startIdx` does not represent a well formed codepoint, then a [`std.utf.UTFException`](std_utf#UTFException) may be thrown. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `haystack` | String to search for needles in. |
| const(Char2)[] `needles` | Strings to search for in haystack. |
| size\_t `stopIdx` | slices haystack like this `haystack[0 .. stopIdx]`. If the stopIdx is greater equal the length of haystack the functions returns `-1`. |
| CaseSensitive `cs` | Indicates whether the comparisons are case sensitive. |


 
Examples:


```
ptrdiff_t i = "helloWorld".lastIndexOfAny("Wlo");
writeln(i); // 8

i = "Foo öäöllo world".lastIndexOfAny("öF");
writeln(i); // 8

```
 
 
Examples:


```
import std.conv : to;

ptrdiff_t i = "helloWorld".lastIndexOfAny("Wlo", 4);
writeln(i); // 3

i = "Foo öäöllo world".lastIndexOfAny("öF", 3);
writeln(i); // 0

```
 
  pure @safe ptrdiff\_t **indexOfNeither**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2);   
  
pure @safe ptrdiff\_t **indexOfNeither**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in size\_t startIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2); 
 
Returns the index of the first occurrence of any character not an elements in `needles` in `haystack`. If all element of `haystack` are element of `needles` `-1` is returned. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `haystack` | String to search for needles in. |
| const(Char2)[] `needles` | Strings to search for in haystack. |
| size\_t `startIdx` | slices haystack like this `haystack[startIdx .. $]`. If the startIdx is greater equal the length of haystack the functions returns `-1`. |
| CaseSensitive `cs` | Indicates whether the comparisons are case sensitive. |


 
Examples:


```
writeln(indexOfNeither("abba", "a", 2)); // 2
writeln(indexOfNeither("def", "de", 1)); // 2
writeln(indexOfNeither("dfefffg", "dfe", 4)); // 6

```
 
 
Examples:


```
writeln(indexOfNeither("def", "a")); // 0
writeln(indexOfNeither("def", "de")); // 2
writeln(indexOfNeither("dfefffg", "dfe")); // 6

```
 
  pure @safe ptrdiff\_t **lastIndexOfNeither**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2);   
  
pure @safe ptrdiff\_t **lastIndexOfNeither**(Char, Char2)(const(Char)[] haystack, const(Char2)[] needles, in size\_t stopIdx, in CaseSensitive cs = Yes.caseSensitive)  
 Constraints: if (isSomeChar!Char && isSomeChar!Char2); 
 
Returns the last index of the first occurence of any character that is not an elements in `needles` in `haystack`. If all element of `haystack` are element of `needles` `-1` is returned. 



Parameters:


|  |  |
| --- | --- |
| const(Char)[] `haystack` | String to search for needles in. |
| const(Char2)[] `needles` | Strings to search for in haystack. |
| size\_t `stopIdx` | slices haystack like this `haystack[0 .. stopIdx]` If the stopIdx is greater equal the length of haystack the functions returns `-1`. |
| CaseSensitive `cs` | Indicates whether the comparisons are case sensitive. |


 
Examples:


```
writeln(lastIndexOfNeither("abba", "a")); // 2
writeln(lastIndexOfNeither("def", "f")); // 1

```
 
 
Examples:


```
writeln(lastIndexOfNeither("def", "rsa", 3)); // -1
writeln(lastIndexOfNeither("abba", "a", 2)); // 1

```
 
  pure nothrow @nogc @safe auto **representation**(Char)(Char[] s)  
 Constraints: if (isSomeChar!Char); 
 
Returns the representation of a string, which has the same type as the string except the character type is replaced by `ubyte`, `ushort`, or `uint` depending on the character width. 



Parameters:


|  |  |
| --- | --- |
| Char[] `s` | The string to return the representation of. |


 
Returns:
The representation of the passed string.
 
Examples:


```
string s = "hello";
static assert(is(typeof(representation(s)) == immutable(ubyte)[]));
assert(representation(s) is cast(immutable(ubyte)[]) s);
writeln(representation(s)); // [0x68, 0x65, 0x6c, 0x6c, 0x6f]

```
 
  pure @trusted S **capitalize**(S)(S input)  
 Constraints: if (isSomeString!S); 
 
Capitalize the first character of `s` and convert the rest of `s` to lowercase. 



Parameters:


|  |  |
| --- | --- |
| S `input` | The string to capitalize. |


 
Returns:
The capitalized string. 
 
See Also:

[`std.uni.asCapitalized`](std_uni#asCapitalized) for a lazy range version that doesn't allocate memory
 
Examples:


```
writeln(capitalize("hello")); // "Hello"
writeln(capitalize("World")); // "World"

```
 
  alias **KeepTerminator** = std.typecons.Flag!"keepTerminator".Flag;   
  
pure @safe C[][] **splitLines**(C)(C[] s, KeepTerminator keepTerm = No.keepTerminator)  
 Constraints: if (isSomeChar!C); 
 
Split `s` into an array of lines according to the unicode standard using `'\r'`, `'\n'`, `"\r\n"`, [`std.uni.lineSep`](std_uni#lineSep), [`std.uni.paraSep`](std_uni#paraSep), `U+0085` (NEL), `'\v'` and `'\f'` as delimiters. If `keepTerm` is set to `KeepTerminator.yes`, then the delimiter is included in the strings returned. 


Does not throw on invalid UTF; such is simply passed unchanged to the output.   
  
 Allocates memory; use [`lineSplitter`](#lineSplitter) for an alternative that does not.   
  
 Adheres to [Unicode 7.0](http://www.unicode.org/versions/Unicode7.0.0/ch05.pdf). 

 
Parameters:


|  |  |
| --- | --- |
| C[] `s` | a string of `chars`, `wchars`, or `dchars`, or any custom type that casts to a `string` type |
| `KeepTerminator` `keepTerm` | whether delimiter is included or not in the results |


 
Returns:
array of strings, each element is a line that is a slice of `s` 
 
See Also:

[`lineSplitter`](#lineSplitter) [`std.algorithm.splitter`](std_algorithm#splitter) [`std.regex.splitter`](std_regex#splitter)

 
Examples:


```
string s = "Hello\nmy\rname\nis";
writeln(splitLines(s)); // ["Hello", "my", "name", "is"]

```
 
  auto **lineSplitter**(KeepTerminator keepTerm = No.keepTerminator, Range)(Range r)  
 Constraints: if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);   
  
auto **lineSplitter**(KeepTerminator keepTerm = No.keepTerminator, C)(C[] r)  
 Constraints: if (isSomeChar!C); 
 
Split an array or slicable range of characters into a range of lines using `'\r'`, `'\n'`, `'\v'`, `'\f'`, `"\r\n"`, [`std.uni.lineSep`](std_uni#lineSep), [`std.uni.paraSep`](std_uni#paraSep) and `'\u0085'` (NEL) as delimiters. If `keepTerm` is set to `Yes.keepTerminator`, then the delimiter is included in the slices returned. 


Does not throw on invalid UTF; such is simply passed unchanged to the output.   
  
 Adheres to [Unicode 7.0](http://www.unicode.org/versions/Unicode7.0.0/ch05.pdf).   
  
 Does not allocate memory. 

 
Parameters:


|  |  |
| --- | --- |
| Range `r` | array of `chars`, `wchars`, or `dchars` or a slicable range |
| keepTerm | whether delimiter is included or not in the results |


 
Returns:
range of slices of the input range `r` 
 
See Also:

[`splitLines`](#splitLines) [`std.algorithm.splitter`](std_algorithm#splitter) [`std.regex.splitter`](std_regex#splitter)

 
Examples:


```
import std.array : array;

string s = "Hello\nmy\rname\nis";

/* notice the call to 'array' to turn the lazy range created by
lineSplitter comparable to the string[] created by splitLines.
*/
writeln(lineSplitter(s).array); // splitLines(s)

```
 
 
Examples:


```
auto s = "\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";
auto lines = s.lineSplitter();
static immutable witness = ["", "peter", "", "paul", "jerry", "ice", "cream", "", "sunday", "mon\u2030day"];
uint i;
foreach (line; lines)
{
    writeln(line); // witness[i++]
}
writeln(i); // witness.length

```
 
  auto **stripLeft**(Range)(Range input)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isInfinite!Range && !isConvertibleToString!Range);   
  
auto **stripLeft**(Range, Char)(Range input, const(Char)[] chars)  
 Constraints: if ((isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char); 
 
Strips leading whitespace (as defined by [`std.uni.isWhite`](std_uni#isWhite)) or as specified in the second argument. 



Parameters:


|  |  |
| --- | --- |
| Range `input` | string or [forward range](std_range_primitives#isForwardRange) of characters |
| const(Char)[] `chars` | string of characters to be stripped |


 
Returns:

`input` stripped of leading whitespace or characters specified in the second argument. 
 
Postconditions
 `input` and the returned value will share the same tail (see [`std.array.sameTail`](std_array#sameTail)). 
 
See Also:
Generic stripping on ranges: [`std.algorithm.mutation.stripLeft`](std_algorithm_mutation#stripLeft)

 
Examples:


```
import std.uni : lineSep, paraSep;
assert(stripLeft("     hello world     ") ==
       "hello world     ");
assert(stripLeft("\n\t\v\rhello world\n\t\v\r") ==
       "hello world\n\t\v\r");
assert(stripLeft(" \u2028hello world") ==
       "hello world");
assert(stripLeft("hello world") ==
       "hello world");
assert(stripLeft([lineSep] ~ "hello world" ~ lineSep) ==
       "hello world" ~ [lineSep]);
assert(stripLeft([paraSep] ~ "hello world" ~ paraSep) ==
       "hello world" ~ [paraSep]);

import std.array : array;
import std.utf : byChar;
assert(stripLeft("     hello world     "w.byChar).array ==
       "hello world     ");
assert(stripLeft("     \u2022hello world     ".byChar).array ==
       "\u2022hello world     ");

```
 
 
Examples:


```
assert(stripLeft("     hello world     ", " ") ==
       "hello world     ");
assert(stripLeft("xxxxxhello world     ", "x") ==
       "hello world     ");
assert(stripLeft("xxxyy    hello world     ", "xy ") ==
       "hello world     ");

```
 
 
Examples:


```
import std.array : array;
import std.utf : byChar, byWchar, byDchar;

assert(stripLeft("  xxxyy hello world     "w.byChar, "xy ").array ==
       "hello world     ");

assert(stripLeft("\u2028\u2020hello world\u2028"w.byWchar,
                 "\u2028").array == "\u2020hello world\u2028");
assert(stripLeft("\U00010001hello world"w.byWchar, " ").array ==
       "\U00010001hello world"w);
assert(stripLeft("\U00010001 xyhello world"d.byDchar,
                 "\U00010001 xy").array == "hello world"d);

writeln(stripLeft("\u2020hello"w, "\u2020"w)); // "hello"w
writeln(stripLeft("\U00010001hello"d, "\U00010001"d)); // "hello"d
writeln(stripLeft(" hello ", "")); // " hello "

```
 
  auto **stripRight**(Range)(Range str)  
 Constraints: if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range));   
  
auto **stripRight**(Range, Char)(Range str, const(Char)[] chars)  
 Constraints: if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char); 
 
Strips trailing whitespace (as defined by [`std.uni.isWhite`](std_uni#isWhite)) or as specified in the second argument. 



Parameters:


|  |  |
| --- | --- |
| Range `str` | string or random access range of characters |
| const(Char)[] `chars` | string of characters to be stripped |


 
Returns:
slice of `str` stripped of trailing whitespace or characters specified in the second argument. 
 
See Also:
Generic stripping on ranges: [`std.algorithm.mutation.stripRight`](std_algorithm_mutation#stripRight)

 
Examples:


```
import std.uni : lineSep, paraSep;
assert(stripRight("     hello world     ") ==
       "     hello world");
assert(stripRight("\n\t\v\rhello world\n\t\v\r") ==
       "\n\t\v\rhello world");
assert(stripRight("hello world") ==
       "hello world");
assert(stripRight([lineSep] ~ "hello world" ~ lineSep) ==
       [lineSep] ~ "hello world");
assert(stripRight([paraSep] ~ "hello world" ~ paraSep) ==
       [paraSep] ~ "hello world");

```
 
 
Examples:


```
assert(stripRight("     hello world     ", "x") ==
       "     hello world     ");
assert(stripRight("     hello world     ", " ") ==
       "     hello world");
assert(stripRight("     hello worldxy     ", "xy ") ==
       "     hello world");

```
 
  auto **strip**(Range)(Range str)  
 Constraints: if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range));   
  
auto **strip**(Range, Char)(Range str, const(Char)[] chars)  
 Constraints: if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char);   
  
auto **strip**(Range, Char)(Range str, const(Char)[] leftChars, const(Char)[] rightChars)  
 Constraints: if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char); 
 
Strips both leading and trailing whitespace (as defined by [`std.uni.isWhite`](std_uni#isWhite)) or as specified in the second argument. 



Parameters:


|  |  |
| --- | --- |
| Range `str` | string or random access range of characters |
| const(Char)[] `chars` | string of characters to be stripped |
| const(Char)[] `leftChars` | string of leading characters to be stripped |
| const(Char)[] `rightChars` | string of trailing characters to be stripped |


 
Returns:
slice of `str` stripped of leading and trailing whitespace or characters as specified in the second argument. 
 
See Also:
Generic stripping on ranges: [`std.algorithm.mutation.strip`](std_algorithm_mutation#strip)

 
Examples:


```
import std.uni : lineSep, paraSep;
assert(strip("     hello world     ") ==
       "hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
       "hello world");
assert(strip("hello world") ==
       "hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
       "hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
       "hello world");

```
 
 
Examples:


```
assert(strip("     hello world     ", "x") ==
       "     hello world     ");
assert(strip("     hello world     ", " ") ==
       "hello world");
assert(strip("   xyxyhello worldxyxy     ", "xy ") ==
       "hello world");
writeln(strip("\u2020hello\u2020"w, "\u2020"w)); // "hello"w
writeln(strip("\U00010001hello\U00010001"d, "\U00010001"d)); // "hello"d
writeln(strip(" hello ", "")); // " hello "

```
 
 
Examples:


```
writeln(strip("xxhelloyy", "x", "y")); // "hello"
assert(strip("   xyxyhello worldxyxyzz    ", "xy ", "xyz ") ==
       "hello world");
writeln(strip("\u2020hello\u2028"w, "\u2020"w, "\u2028"w)); // "hello"w
assert(strip("\U00010001hello\U00010002"d, "\U00010001"d, "\U00010002"d) ==
       "hello"d);
writeln(strip(" hello ", "", "")); // " hello "

```
 
  Range **chomp**(Range)(Range str)  
 Constraints: if ((isRandomAccessRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range);   
  
Range **chomp**(Range, C2)(Range str, const(C2)[] delimiter)  
 Constraints: if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range && isSomeChar!C2); 
 
If `str` ends with `delimiter`, then `str` is returned without `delimiter` on its end. If it `str` does *not* end with `delimiter`, then it is returned unchanged. 


If no `delimiter` is given, then one trailing `'\r'`, `'\n'`, `"\r\n"`, `'\f'`, `'\v'`, [`std.uni.lineSep`](std_uni#lineSep), [`std.uni.paraSep`](std_uni#paraSep), or [`std.uni.nelSep`](std_uni#nelSep) is removed from the end of `str`. If `str` does not end with any of those characters, then it is returned unchanged. 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | string or indexable range of characters |
| const(C2)[] `delimiter` | string of characters to be sliced off end of str[] |


 
Returns:
slice of str
 
Examples:


```
import std.uni : lineSep, paraSep, nelSep;
import std.utf : decode;
writeln(chomp(" hello world  \n\r")); // " hello world  \n"
writeln(chomp(" hello world  \r\n")); // " hello world  "
writeln(chomp(" hello world  \f")); // " hello world  "
writeln(chomp(" hello world  \v")); // " hello world  "
writeln(chomp(" hello world  \n\n")); // " hello world  \n"
writeln(chomp(" hello world  \n\n ")); // " hello world  \n\n "
writeln(chomp(" hello world  \n\n" ~ [lineSep])); // " hello world  \n\n"
writeln(chomp(" hello world  \n\n" ~ [paraSep])); // " hello world  \n\n"
writeln(chomp(" hello world  \n\n" ~ [nelSep])); // " hello world  \n\n"
writeln(chomp(" hello world")); // " hello world"
writeln(chomp("")); // ""

writeln(chomp(" hello world", "orld")); // " hello w"
writeln(chomp(" hello world", " he")); // " hello world"
writeln(chomp("", "hello")); // ""

// Don't decode pointlessly
writeln(chomp("hello\xFE", "\r")); // "hello\xFE"

```
 
  Range **chompPrefix**(Range, C2)(Range str, const(C2)[] delimiter)  
 Constraints: if ((isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range && isSomeChar!C2); 
 
If `str` starts with `delimiter`, then the part of `str` following `delimiter` is returned. If `str` does *not* start with 


`delimiter`, then it is returned unchanged. 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | string or [forward range](std_range_primitives#isForwardRange) of characters |
| const(C2)[] `delimiter` | string of characters to be sliced off front of str[] |


 
Returns:
slice of str
 
Examples:


```
writeln(chompPrefix("hello world", "he")); // "llo world"
writeln(chompPrefix("hello world", "hello w")); // "orld"
writeln(chompPrefix("hello world", " world")); // "hello world"
writeln(chompPrefix("", "hello")); // ""

```
 
  Range **chop**(Range)(Range str)  
 Constraints: if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range); 
 
Returns `str` without its last character, if there is one. If `str` ends with `"\r\n"`, then both are removed. If `str` is empty, then it is returned unchanged. 



Parameters:


|  |  |
| --- | --- |
| Range `str` | string (must be valid UTF) |


 
Returns:
slice of str
 
Examples:


```
writeln(chop("hello world")); // "hello worl"
writeln(chop("hello world\n")); // "hello world"
writeln(chop("hello world\r")); // "hello world"
writeln(chop("hello world\n\r")); // "hello world\n"
writeln(chop("hello world\r\n")); // "hello world"
writeln(chop("Walter Bright")); // "Walter Brigh"
writeln(chop("")); // ""

```
 
  S **leftJustify**(S)(S s, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isSomeString!S); 
 
Left justify `s` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `s` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| S `s` | string |
| size\_t `width` | minimum field width |
| dchar `fillChar` | used to pad end up to `width` characters |


 
Returns:
GC allocated string 
 
See Also:

[`leftJustifier`](#leftJustifier), which does not allocate
 
Examples:


```
writeln(leftJustify("hello", 7, 'X')); // "helloXX"
writeln(leftJustify("hello", 2, 'X')); // "hello"
writeln(leftJustify("hello", 9, 'X')); // "helloXXXX"

```
 
  auto **leftJustifier**(Range)(Range r, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Left justify `s` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `s` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | string or range of characters |
| size\_t `width` | minimum field width |
| dchar `fillChar` | used to pad end up to `width` characters |


 
Returns:
a lazy range of the left justified result 
 
See Also:
[`rightJustifier`](#rightJustifier)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.utf : byChar;
assert(leftJustifier("hello", 2).equal("hello".byChar));
assert(leftJustifier("hello", 7).equal("hello  ".byChar));
assert(leftJustifier("hello", 7, 'x').equal("helloxx".byChar));

```
 
  S **rightJustify**(S)(S s, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isSomeString!S); 
 
Right justify `s` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `s` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| S `s` | string |
| size\_t `width` | minimum field width |
| dchar `fillChar` | used to pad end up to `width` characters |


 
Returns:
GC allocated string 
 
See Also:

[`rightJustifier`](#rightJustifier), which does not allocate
 
Examples:


```
writeln(rightJustify("hello", 7, 'X')); // "XXhello"
writeln(rightJustify("hello", 2, 'X')); // "hello"
writeln(rightJustify("hello", 9, 'X')); // "XXXXhello"

```
 
  auto **rightJustifier**(Range)(Range r, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Right justify `s` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `s` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | string or [forward range](std_range_primitives#isForwardRange) of characters |
| size\_t `width` | minimum field width |
| dchar `fillChar` | used to pad end up to `width` characters |


 
Returns:
a lazy range of the right justified result 
 
See Also:
[`leftJustifier`](#leftJustifier)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.utf : byChar;
assert(rightJustifier("hello", 2).equal("hello".byChar));
assert(rightJustifier("hello", 7).equal("  hello".byChar));
assert(rightJustifier("hello", 7, 'x').equal("xxhello".byChar));

```
 
  S **center**(S)(S s, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isSomeString!S); 
 
Center `s` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `s` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| S `s` | The string to center |
| size\_t `width` | Width of the field to center `s` in |
| dchar `fillChar` | The character to use for filling excess space in the field |


 
Returns:
The resulting center-justified string. The returned string is GC-allocated. To avoid GC allocation, use [`centerJustifier`](#centerJustifier) instead.
 
Examples:


```
writeln(center("hello", 7, 'X')); // "XhelloX"
writeln(center("hello", 2, 'X')); // "hello"
writeln(center("hello", 9, 'X')); // "XXhelloXX"

```
 
  auto **centerJustifier**(Range)(Range r, size\_t width, dchar fillChar = ' ')  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Center justify `r` in a field `width` characters wide. `fillChar` is the character that will be used to fill up the space in the field that `r` doesn't fill. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | string or [forward range](std_range_primitives#isForwardRange) of characters |
| size\_t `width` | minimum field width |
| dchar `fillChar` | used to pad end up to `width` characters |


 
Returns:
a lazy range of the center justified result 
 
See Also:

[`leftJustifier`](#leftJustifier) [`rightJustifier`](#rightJustifier)

 
Examples:


```
import std.algorithm.comparison : equal;
import std.utf : byChar;
assert(centerJustifier("hello", 2).equal("hello".byChar));
assert(centerJustifier("hello", 8).equal(" hello  ".byChar));
assert(centerJustifier("hello", 7, 'x').equal("xhellox".byChar));

```
 
  pure auto **detab**(Range)(auto ref Range s, size\_t tabSize = 8)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || \_\_traits(compiles, StringTypeOf!Range)); 
 
Replace each tab character in `s` with the number of spaces necessary to align the following character at the next tab stop. 



Parameters:


|  |  |
| --- | --- |
| Range `s` | string |
| size\_t `tabSize` | distance between tab stops |


 
Returns:
GC allocated string with tabs replaced with spaces
 
Examples:


```
writeln(detab(" \n\tx", 9)); // " \n         x"

```
 
  auto **detabber**(Range)(Range r, size\_t tabSize = 8)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Replace each tab character in `r` with the number of spaces necessary to align the following character at the next tab stop. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | string or [forward range](std_range_primitives#isForwardRange) |
| size\_t `tabSize` | distance between tab stops |


 
Returns:
lazy forward range with tabs replaced with spaces
 
Examples:


```
import std.array : array;

writeln(detabber(" \n\tx", 9).array); // " \n         x"

```
 
  auto **entab**(Range)(Range s, size\_t tabSize = 8)  
 Constraints: if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range)); 
 
Replaces spaces in `s` with the optimal number of tabs. All spaces and tabs at the end of a line are removed. 



Parameters:


|  |  |
| --- | --- |
| Range `s` | String to convert. |
| size\_t `tabSize` | Tab columns are `tabSize` spaces apart. |


 
Returns:
GC allocated string with spaces replaced with tabs; use [`entabber`](#entabber) to not allocate. 
 
See Also:
[`entabber`](#entabber)
 
Examples:


```
writeln(entab("        x \n")); // "\tx\n"

```
 
  auto **entabber**(Range)(Range r, size\_t tabSize = 8)  
 Constraints: if (isForwardRange!Range && !isConvertibleToString!Range); 
 
Replaces spaces in range `r` with the optimal number of tabs. All spaces and tabs at the end of a line are removed. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | string or [forward range](std_range_primitives#isForwardRange) |
| size\_t `tabSize` | distance between tab stops |


 
Returns:
lazy forward range with spaces replaced with tabs 
 
See Also:
[`entab`](#entab)
 
Examples:


```
import std.array : array;
writeln(entabber("        x \n").array); // "\tx\n"

```
 
  pure @safe C1[] **translate**(C1, C2 = immutable(char))(C1[] str, in dchar[dchar] transTable, const(C2)[] toRemove = null)  
 Constraints: if (isSomeChar!C1 && isSomeChar!C2);   
  
pure @safe C1[] **translate**(C1, S, C2 = immutable(char))(C1[] str, in S[dchar] transTable, const(C2)[] toRemove = null)  
 Constraints: if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2); 
 
Replaces the characters in `str` which are keys in `transTable` with their corresponding values in `transTable`. `transTable` is an AA where its keys are `dchar` and its values are either `dchar` or some type of string. Also, if `toRemove` is given, the characters in it are removed from `str` prior to translation. `str` itself is unaltered. A copy with the changes is returned. 



See Also:

[`tr`](#tr), [`std.array.replace`](std_array#replace), [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) 
 
Parameters:


|  |  |
| --- | --- |
| C1[] `str` | The original string. |
| dchar[dchar] `transTable` | The AA indicating which characters to replace and what to replace them with. |
| const(C2)[] `toRemove` | The characters to remove from the string. |


 
Examples:


```
dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];
writeln(translate("hello world", transTable1)); // "h5ll7 w7rld"

writeln(translate("hello world", transTable1, "low")); // "h5 rd"

string[dchar] transTable2 = ['e' : "5", 'o' : "orange"];
writeln(translate("hello world", transTable2)); // "h5llorange worangerld"

```
 
  void **translate**(C1, C2 = immutable(char), Buffer)(const(C1)[] str, in dchar[dchar] transTable, const(C2)[] toRemove, Buffer buffer)  
 Constraints: if (isSomeChar!C1 && isSomeChar!C2 && isOutputRange!(Buffer, C1));   
  
void **translate**(C1, S, C2 = immutable(char), Buffer)(C1[] str, in S[dchar] transTable, const(C2)[] toRemove, Buffer buffer)  
 Constraints: if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2 && isOutputRange!(Buffer, S)); 
 
This is an overload of `translate` which takes an existing buffer to write the contents to. 



Parameters:


|  |  |
| --- | --- |
| const(C1)[] `str` | The original string. |
| dchar[dchar] `transTable` | The AA indicating which characters to replace and what to replace them with. |
| const(C2)[] `toRemove` | The characters to remove from the string. |
| Buffer `buffer` | An output range to write the contents to. |


 
Examples:


```
import std.array : appender;
dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];
auto buffer = appender!(dchar[])();
translate("hello world", transTable1, null, buffer);
writeln(buffer.data); // "h5ll7 w7rld"

buffer.clear();
translate("hello world", transTable1, "low", buffer);
writeln(buffer.data); // "h5 rd"

buffer.clear();
string[dchar] transTable2 = ['e' : "5", 'o' : "orange"];
translate("hello world", transTable2, null, buffer);
writeln(buffer.data); // "h5llorange worangerld"

```
 
  pure nothrow @trusted C[] **translate**(C = immutable(char))(scope const(char)[] str, scope const(char)[] transTable, scope const(char)[] toRemove = null)  
 Constraints: if (is(immutable(C) == immutable(char))); 
 
This is an *ASCII-only* overload of [`translate`](#translate). It will *not* work with Unicode. It exists as an optimization for the cases where Unicode processing is not necessary. 


Unlike the other overloads of [`translate`](#translate), this one does not take an AA. Rather, it takes a `string` generated by [`makeTransTable`](#makeTransTable).   
  
 The array generated by `makeTransTable` is `256` elements long such that the index is equal to the ASCII character being replaced and the value is equal to the character that it's being replaced with. Note that translate does not decode any of the characters, so you can actually pass it Extended ASCII characters if you want to (ASCII only actually uses `128` characters), but be warned that Extended ASCII characters are not valid Unicode and therefore will result in a `UTFException` being thrown from most other Phobos functions.   
  
 Also, because no decoding occurs, it is possible to use this overload to translate ASCII characters within a proper UTF-8 string without altering the other, non-ASCII characters. It's replacing any code unit greater than `127` with another code unit or replacing any code unit with another code unit greater than `127` which will cause UTF validation issues. 

 
See Also:

[`tr`](#tr), [`std.array.replace`](std_array#replace), [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute) 
 
Parameters:


|  |  |
| --- | --- |
| const(char)[] `str` | The original string. |
| const(char)[] `transTable` | The string indicating which characters to replace and what to replace them with. It is generated by [`makeTransTable`](#makeTransTable). |
| const(char)[] `toRemove` | The characters to remove from the string. |


 
Examples:


```
auto transTable1 = makeTrans("eo5", "57q");
writeln(translate("hello world", transTable1)); // "h5ll7 w7rld"

writeln(translate("hello world", transTable1, "low")); // "h5 rd"

```
 
  pure nothrow @trusted string **makeTrans**(scope const(char)[] from, scope const(char)[] to);  
Do same thing as [`makeTransTable`](#makeTransTable) but allocate the translation table on the GC heap. 


Use [`makeTransTable`](#makeTransTable) instead.

 
Examples:


```
auto transTable1 = makeTrans("eo5", "57q");
writeln(translate("hello world", transTable1)); // "h5ll7 w7rld"

writeln(translate("hello world", transTable1, "low")); // "h5 rd"

```
 
  pure nothrow @nogc @safe char[256] **makeTransTable**(scope const(char)[] from, scope const(char)[] to);  
Construct 256 character translation table, where characters in from[] are replaced by corresponding characters in to[]. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `from` | array of chars, less than or equal to 256 in length |
| const(char)[] `to` | corresponding array of chars to translate to |


 
Returns:
translation array
 
Examples:


```
writeln(translate("hello world", makeTransTable("hl", "q5"))); // "qe55o wor5d"
writeln(translate("hello world", makeTransTable("12345", "67890"))); // "hello world"

```
 
  pure @trusted void **translate**(C = immutable(char), Buffer)(scope const(char)[] str, scope const(char)[] transTable, scope const(char)[] toRemove, Buffer buffer)  
 Constraints: if (is(immutable(C) == immutable(char)) && isOutputRange!(Buffer, char)); 
 
This is an *ASCII-only* overload of `translate` which takes an existing buffer to write the contents to. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `str` | The original string. |
| const(char)[] `transTable` | The string indicating which characters to replace and what to replace them with. It is generated by [`makeTransTable`](#makeTransTable). |
| const(char)[] `toRemove` | The characters to remove from the string. |
| Buffer `buffer` | An output range to write the contents to. |


 
Examples:


```
import std.array : appender;
auto buffer = appender!(char[])();
auto transTable1 = makeTransTable("eo5", "57q");
translate("hello world", transTable1, null, buffer);
writeln(buffer.data); // "h5ll7 w7rld"

buffer.clear();
translate("hello world", transTable1, "low", buffer);
writeln(buffer.data); // "h5 rd"

```
 
  pure @safe S **succ**(S)(S s)  
 Constraints: if (isSomeString!S); 
 
Return string that is the 'successor' to s[]. If the rightmost character is a-zA-Z0-9, it is incremented within its case or digits. If it generates a carry, the process is repeated with the one to its immediate left.



Examples:


```
writeln(succ("1")); // "2"
writeln(succ("9")); // "10"
writeln(succ("999")); // "1000"
writeln(succ("zz99")); // "aaa00"

```
 
  C1[] **tr**(C1, C2, C3, C4 = immutable(char))(C1[] str, const(C2)[] from, const(C3)[] to, const(C4)[] modifiers = null);  
Replaces the characters in `str` which are in `from` with the the corresponding characters in `to` and returns the resulting string. 


`tr` is based on [Posix's tr](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tr.html), though it doesn't do everything that the Posix utility does. 

 
Parameters:


|  |  |
| --- | --- |
| C1[] `str` | The original string. |
| const(C2)[] `from` | The characters to replace. |
| const(C3)[] `to` | The characters to replace with. |
| const(C4)[] `modifiers` | String containing modifiers. |


 
Modifiers



|  |  |
| --- | --- |
| Modifier | Description |
| `'c'` | Complement the list of characters in `from` |
| `'d'` | Removes matching characters with no corresponding replacement in `to` |
| `'s'` | Removes adjacent duplicates in the replaced characters |

 If the modifier `'d'` is present, then the number of characters in `to` may be only `0` or `1`. If the modifier `'d'` is *not* present, and `to` is empty, then `to` is taken to be the same as `from`. If the modifier `'d'` is *not* present, and `to` is shorter than `from`, then `to` is extended by replicating the last character in `to`. Both `from` and `to` may contain ranges using the `'-'` character (e.g. `"a-d"` is synonymous with `"abcd"`.) Neither accept a leading `'^'` as meaning the complement of the string (use the `'c'` modifier for that). 
See Also:

[`translate`](#translate), [`std.array.replace`](std_array#replace), [`std.algorithm.iteration.substitute`](std_algorithm_iteration#substitute)

 
Examples:


```
writeln(tr("abcdef", "cd", "CD")); // "abCDef"
writeln(tr("1st March, 2018", "March", "MAR", "s")); // "1st MAR, 2018"
writeln(tr("abcdef", "ef", "", "d")); // "abcd"
writeln(tr("14-Jul-87", "a-zA-Z", " ", "cs")); // " Jul "

```
 
  bool **isNumeric**(S)(S s, bool bAllowSep = false)  
 Constraints: if (isSomeString!S || isRandomAccessRange!S && hasSlicing!S && isSomeChar!(ElementType!S) && !isInfinite!S); 
 
Takes a string `s` and determines if it represents a number. This function also takes an optional parameter, `bAllowSep`, which will accept the separator characters `','` and `'__'` within the string. But these characters should be stripped from the string before using any of the conversion functions like `to!int()`, `to!float()`, and etc else an error will occur. 


Also please note, that no spaces are allowed within the string anywhere whether it's a leading, trailing, or embedded space(s), thus they too must be stripped from the string before using this function, or any of the conversion functions. 

 
Parameters:


|  |  |
| --- | --- |
| S `s` | the string or random access range to check |
| bool `bAllowSep` | accept separator characters or not |


 
Returns:
`bool`
 
Examples:
Integer Whole Number: (byte, ubyte, short, ushort, int, uint, long, and ulong) ['+'|'-']digit(s)[U|L|UL] 
```
assert(isNumeric("123"));
assert(isNumeric("123UL"));
assert(isNumeric("123L"));
assert(isNumeric("+123U"));
assert(isNumeric("-123L"));

```
 
 
Examples:
Floating-Point Number: (float, double, real, ifloat, idouble, and ireal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|inf|-inf] 
```
assert(isNumeric("+123"));
assert(isNumeric("-123.01"));
assert(isNumeric("123.3e-10f"));
assert(isNumeric("123.3e-10fi"));
assert(isNumeric("123.3e-10L"));

assert(isNumeric("nan"));
assert(isNumeric("nani"));
assert(isNumeric("-inf"));

```
 
 
Examples:
Floating-Point Number: (cfloat, cdouble, and creal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][+] [digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|nan+nani|inf|-inf] 
```
assert(isNumeric("-123e-1+456.9e-10Li"));
assert(isNumeric("+123e+10+456i"));
assert(isNumeric("123+456"));

```
 
 
Examples:
isNumeric works with CTFE 
```
enum a = isNumeric("123.00E-5+1234.45E-12Li");
enum b = isNumeric("12345xxxx890");

static assert( a);
static assert(!b);

```
 
  char[4] **soundexer**(Range)(Range str)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);   
  
char[4] **soundexer**(Range)(auto ref Range str)  
 Constraints: if (isConvertibleToString!Range); 
 
Soundex algorithm. 


The Soundex algorithm converts a word into 4 characters based on how the word sounds phonetically. The idea is that two spellings that sound alike will have the same Soundex value, which means that Soundex can be used for fuzzy matching of names. 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | String or InputRange to convert to Soundex representation. |


 
Returns:
The four character array with the Soundex result in it. The array has zero's in it if there is no Soundex representation for the string. 
 
See Also:

[Wikipedia](http://en.wikipedia.org/wiki/Soundex), [The Soundex Indexing System](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=The%20Soundex%20Indexing%20System) [`soundex`](#soundex) 
 
Note
 Only works well with English names.
 
Examples:


```
writeln(soundexer("Gauss")); // "G200"
writeln(soundexer("Ghosh")); // "G200"

writeln(soundexer("Robert")); // "R163"
writeln(soundexer("Rupert")); // "R163"

writeln(soundexer("0123^&^^**&^")); // ['\0', '\0', '\0', '\0']

```
 
  pure nothrow @safe char[] **soundex**(scope const(char)[] str, char[] buffer = null);  
Like [`soundexer`](#soundexer), but with different parameters and return value. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `str` | String to convert to Soundex representation. |
| char[] `buffer` | Optional 4 char array to put the resulting Soundex characters into. If null, the return value buffer will be allocated on the heap. |


 
Returns:
The four character array with the Soundex result in it. Returns null if there is no Soundex representation for the string. 
 
See Also:
[`soundexer`](#soundexer)
 
Examples:


```
writeln(soundex("Gauss")); // "G200"
writeln(soundex("Ghosh")); // "G200"

writeln(soundex("Robert")); // "R163"
writeln(soundex("Rupert")); // "R163"

writeln(soundex("0123^&^^**&^")); // null

```
 
  pure @safe string[string] **abbrev**(string[] values);  
Construct an associative array consisting of all abbreviations that uniquely map to the strings in values. 


This is useful in cases where the user is expected to type in one of a known set of strings, and the program will helpfully auto-complete the string once sufficient characters have been entered that uniquely identify it.

 
Examples:


```
import std.string;

static string[] list = [ "food", "foxy" ];
auto abbrevs = abbrev(list);
assert(abbrevs == ["fox": "foxy", "food": "food",
                   "foxy": "foxy", "foo": "food"]);

```
 
  size\_t **column**(Range)(Range str, in size\_t tabsize = 8)  
 Constraints: if ((isInputRange!Range && isSomeChar!(Unqual!(ElementEncodingType!Range)) || isNarrowString!Range) && !isConvertibleToString!Range); 
 
Compute column number at the end of the printed form of the string, assuming the string starts in the leftmost column, which is numbered starting from 0. 


Tab characters are expanded into enough spaces to bring the column number to the next multiple of tabsize. If there are multiple lines in the string, the column number of the last line is returned. 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | string or InputRange to be analyzed |
| size\_t `tabsize` | number of columns a tab character represents |


 
Returns:
column number
 
Examples:


```
import std.utf : byChar, byWchar, byDchar;

writeln(column("1234 ")); // 5
writeln(column("1234 "w)); // 5
writeln(column("1234 "d)); // 5

writeln(column("1234 ".byChar())); // 5
writeln(column("1234 "w.byWchar())); // 5
writeln(column("1234 "d.byDchar())); // 5

// Tab stops are set at 8 spaces by default; tab characters insert enough
// spaces to bring the column position to the next multiple of 8.
writeln(column("\t")); // 8
writeln(column("1\t")); // 8
writeln(column("\t1")); // 9
writeln(column("123\t")); // 8

// Other tab widths are possible by specifying it explicitly:
writeln(column("\t", 4)); // 4
writeln(column("1\t", 4)); // 4
writeln(column("\t1", 4)); // 5
writeln(column("123\t", 4)); // 4

// New lines reset the column number.
writeln(column("abc\n")); // 0
writeln(column("abc\n1")); // 1
writeln(column("abcdefg\r1234")); // 4
writeln(column("abc\u20281")); // 1
writeln(column("abc\u20291")); // 1
writeln(column("abc\u00851")); // 1
writeln(column("abc\u00861")); // 5

```
 
  S **wrap**(S)(S s, in size\_t columns = 80, S firstindent = null, S indent = null, in size\_t tabsize = 8)  
 Constraints: if (isSomeString!S); 
 
Wrap text into a paragraph. 


The input text string s is formed into a paragraph by breaking it up into a sequence of lines, delineated by \n, such that the number of columns is not exceeded on each line. The last line is terminated with a \n. 

 
Parameters:


|  |  |
| --- | --- |
| S `s` | text string to be wrapped |
| size\_t `columns` | maximum number of columns in the paragraph |
| S `firstindent` | string used to indent first line of the paragraph |
| S `indent` | string to use to indent following lines of the paragraph |
| size\_t `tabsize` | column spacing of tabs in firstindent[] and indent[] |


 
Returns:
resulting paragraph as an allocated string
 
Examples:


```
writeln(wrap("a short string", 7)); // "a short\nstring\n"

// wrap will not break inside of a word, but at the next space
writeln(wrap("a short string", 4)); // "a\nshort\nstring\n"

writeln(wrap("a short string", 7, "\t")); // "\ta\nshort\nstring\n"
writeln(wrap("a short string", 7, "\t", "    ")); // "\ta\n    short\n    string\n"

```
 
  pure @safe S **outdent**(S)(S str)  
 Constraints: if (isSomeString!S); 
 
Removes one level of indentation from a multi-line string. 


This uniformly outdents the text as much as possible. Whitespace-only lines are always converted to blank lines.   
  
 Does not allocate memory if it does not throw. 

 
Parameters:


|  |  |
| --- | --- |
| S `str` | multi-line string |


 
Returns:
outdented string 
 
Throws:
StringException if indentation is done with different sequences of whitespace characters.
 
Examples:


```
enum pretty = q{
   import std.stdio;
   void main() {
       writeln("Hello");
   }
}.outdent();

enum ugly = q{
import std.stdio;
void main() {
writeln("Hello");
}
};

writeln(pretty); // ugly

```
 
  pure @safe S[] **outdent**(S)(S[] lines)  
 Constraints: if (isSomeString!S); 
 
Removes one level of indentation from an array of single-line strings. 


This uniformly outdents the text as much as possible. Whitespace-only lines are always converted to blank lines. 

 
Parameters:


|  |  |
| --- | --- |
| S[] `lines` | array of single-line strings |


 
Returns:
lines[] is rewritten in place with outdented lines 
 
Throws:
StringException if indentation is done with different sequences of whitespace characters.
 
Examples:


```
auto str1 = [
    "    void main()\n",
    "    {\n",
    "        test();\n",
    "    }\n"
];
auto str1Expected = [
    "void main()\n",
    "{\n",
    "    test();\n",
    "}\n"
];
writeln(str1.outdent); // str1Expected

auto str2 = [
    "void main()\n",
    "    {\n",
    "            test();\n",
    "    }\n"
];
writeln(str2.outdent); // str2

```
 
  auto **assumeUTF**(T)(T[] arr)  
 Constraints: if (staticIndexOf!(immutable(T), immutable(ubyte), immutable(ushort), immutable(uint)) != -1); 
 
Assume the given array of integers `arr` is a well-formed UTF string and return it typed as a UTF string. 


`ubyte` becomes `char`, `ushort` becomes `wchar` and `uint` becomes `dchar`. Type qualifiers are preserved.   
  
 When compiled with debug mode, this function performs an extra check to make sure the return value is a valid Unicode string. 

 
Parameters:


|  |  |
| --- | --- |
| T[] `arr` | array of bytes, ubytes, shorts, ushorts, ints, or uints |


 
Returns:
arr retyped as an array of chars, wchars, or dchars 
 
Throws:
In debug mode `AssertError`, when the result is not a well-formed UTF string. 
 
See Also:
[`representation`](#representation)
 
Examples:


```
string a = "Hölo World";
immutable(ubyte)[] b = a.representation;
string c = b.assumeUTF;

writeln(c); // "Hölo World"

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_string.html>

std.zip
=======

 Read and write data in the [zip archive](https://en.wikipedia.org/wiki/Zip_%28file_format%29) format. 



Standards:
The current implementation mostly conforms to [ISO/IEC 21320-1:2015](https://www.iso.org/standard/60101.html), which means, * that files can only be stored uncompressed or using the deflate mechanism,
* that encryption features are not used,
* that digital signature features are not used,
* that patched data features are not used, and
* that archives may not span multiple volumes.

 Additionally, archives are checked for malware attacks and rejected if detected. This includes * [zip bombs](https://news.ycombinator.com/item?id=20352439) which generate gigantic amounts of unpacked data
* zip archives that contain overlapping records
* chameleon zip archives which generate different unpacked data, depending on the implementation of the unpack algorithm

 The current implementation makes use of the zlib compression library. 
 
Usage
 There are two main ways of usage: Extracting files from a zip archive and storing files into a zip archive. These can be mixed though (e.g. read an archive, remove some files, add others and write the new archive). 
 
Examples:
Example for reading an existing zip archive: 
```
import std.stdio : writeln, writefln;
import std.file : read;
import std.zip;

void main(string[] args)
{
    // read a zip file into memory
    auto zip = new ZipArchive(read(args[1]));

    // iterate over all zip members
    writefln("%-10s  %-8s  Name", "Length", "CRC-32");
    foreach (name, am; zip.directory)
    {
        // print some data about each member
        writefln("%10s  %08x  %s", am.expandedSize, am.crc32, name);
        assert(am.expandedData.length == 0);

        // decompress the archive member
        zip.expand(am);
        assert(am.expandedData.length == am.expandedSize);
    }
}

```
 Example for writing files into a zip archive: 
```
import std.file : write;
import std.string : representation;
import std.zip;

void main()
{
    // Create an ArchiveMembers for each file.
    ArchiveMember file1 = new ArchiveMember();
    file1.name = "test1.txt";
    file1.expandedData("Test data.\n".dup.representation);
    file1.compressionMethod = CompressionMethod.none; // don't compress

    ArchiveMember file2 = new ArchiveMember();
    file2.name = "test2.txt";
    file2.expandedData("More test data.\n".dup.representation);
    file2.compressionMethod = CompressionMethod.deflate; // compress

    // Create an archive and add the member.
    ZipArchive zip = new ZipArchive();

    // add ArchiveMembers
    zip.addMember(file1);
    zip.addMember(file2);

    // Build the archive
    void[] compressed_data = zip.build();

    // Write to a file
    write("test.zip", compressed_data);
}

```
 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [std/zip.d](https://github.com/dlang/phobos/blob/master/std/zip.d)

 
class **ZipException**: object.Exception;  
Thrown on error.

  enum **CompressionMethod**: ushort;  
Compression method used by `ArchiveMember`.

 
**none** 
No compression, just archiving.

  **deflate** 
Deflate algorithm. Use zlib library to compress.

    class **ArchiveMember**;  
A single file or directory inside the archive.

 
string **name**;  
The name of the archive member; it is used to index the archive directory for the member. Each member must have a unique name. Do not change without removing member from the directory first.

  ubyte[] **extra**;  
The content of the extra data field for this member. See  [original documentation](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) for a description of the general format of this data. May contain undocumented 3rd-party data.

  string **comment**;  
Comment associated with this member.

  ushort **flags**;  
Contains some information on how to extract this archive. See  [original documentation](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) for details.

  ushort **internalAttributes**;  
Internal attributes. Bit 1 is set, if the member is apparently in binary format and bit 2 is set, if each record is preceded by the length of the record.

  const pure nothrow @nogc @property @safe ushort **extractVersion**();  
The zip file format version needed to extract this member. 



Returns:
Format version needed to extract this member.
  const pure nothrow @nogc @property @safe uint **crc32**();  
Cyclic redundancy check (CRC) value. 



Returns:
CRC32 value.
  const pure nothrow @nogc @property @safe uint **compressedSize**();  
Size of data of member in compressed form. 



Returns:
Size of the compressed archive.
  const pure nothrow @nogc @property @safe uint **expandedSize**();  
Size of data of member in uncompressed form. 



Returns:
Size of uncompressed archive.
  deprecated const pure nothrow @nogc @property @safe ushort **diskNumber**();  
Should be 0. 



Returns:
The number of the disk where this member can be found.
  pure nothrow @nogc @property @safe ubyte[] **compressedData**();  
Data of member in compressed form. 



Returns:
The file data in compressed form.
  pure nothrow @nogc @property @safe ubyte[] **expandedData**();   
  
@property @safe void **expandedData**(ubyte[] ed);  
Get or set data of member in uncompressed form. When an existing archive is read `ZipArchive.expand` needs to be called before this can be accessed. 



Parameters:


|  |  |
| --- | --- |
| ubyte[] `ed` | Expanded Data. |


 
Returns:
The file data.
  @property @safe void **fileAttributes**(uint attr);   
  
const nothrow @nogc @property uint **fileAttributes**();  
Get or set the OS specific file attributes for this archive member. 



Parameters:


|  |  |
| --- | --- |
| uint `attr` | Attributes as obtained by [`std.file.getAttributes`](std_file#getAttributes) or [`std.file.DirEntry.attributes`](std_file#DirEntry.attributes). |


 
Returns:
The file attributes or 0 if the file attributes were encoded for an incompatible OS (Windows vs. POSIX).
  const pure nothrow @nogc @property @safe DosFileTime **time**();   
  
@property void **time**(SysTime **time**);   
  
pure nothrow @nogc @property @safe void **time**(DosFileTime **time**);  
Get or set the last modification time for this member. 



Parameters:


|  |  |
| --- | --- |
| SysTime `time` | Time to set (will be saved as DosFileTime, which is less accurate). |


 
Returns:
The last modification time in DosFileFormat.
  const pure nothrow @nogc @property @safe CompressionMethod **compressionMethod**();   
  
pure @property @safe void **compressionMethod**(CompressionMethod cm);  
Get or set compression method used for this member. 



Parameters:


|  |  |
| --- | --- |
| CompressionMethod `cm` | Compression method. |


 
Returns:
Compression method. 
 
See Also:
[`CompressionMethod`](#CompressionMethod)
  pure nothrow @nogc @property @safe uint **index**(uint value);   
  
const pure nothrow @nogc @property @safe uint **index**();  
The index of this archive member within the archive. Set this to a different value for reordering the members of an archive. 



Parameters:


|  |  |
| --- | --- |
| uint `value` | Index value to set. |


 
Returns:
The index.
    class **ZipArchive**;  
Object representing the entire archive. ZipArchives are collections of ArchiveMembers.

 
string **comment**;  
The archive comment. Must be less than 65536 bytes in length.

  pure nothrow @nogc @property @safe ubyte[] **data**();  
Array representing the entire contents of the archive. 



Returns:
Data of the entire contents of the archive.
  deprecated const pure nothrow @nogc @property @safe uint **diskNumber**();  
0 since multi-disk zip archives are not supported. 



Returns:
Number of this disk.
  deprecated const pure nothrow @nogc @property @safe uint **diskStartDir**();  
0 since multi-disk zip archives are not supported. 



Returns:
Number of the disk, where the central directory starts.
  deprecated const pure nothrow @nogc @property @safe uint **numEntries**();   
  
const pure nothrow @nogc @property @safe uint **totalEntries**();  
Number of ArchiveMembers in the directory. 



Returns:
The number of files in this archive.
  const pure nothrow @nogc @property @safe bool **isZip64**();   
  
pure nothrow @nogc @property @safe void **isZip64**(bool value);  
True when the archive is in Zip64 format. Set this to true to force building a Zip64 archive. 



Parameters:


|  |  |
| --- | --- |
| bool `value` | True, when the archive is forced to be build in Zip64 format. |


 
Returns:
True, when the archive is in Zip64 format.
  pure nothrow @nogc @property @safe ArchiveMember[string] **directory**();  
Associative array indexed by the name of each member of the archive. 


All the members of the archive can be accessed with a foreach loop: 

 
Example


```
ZipArchive archive = new ZipArchive(data);
foreach (ArchiveMember am; archive.directory)
{
    writefln("member name is '%s'", am.name);
}

```
 
Returns:
Associative array with all archive members.
  pure nothrow @nogc @safe this();  
Constructor to use when creating a new archive.

  @safe void **addMember**(ArchiveMember de);  
Add a member to the archive. The file is compressed on the fly. 



Parameters:


|  |  |
| --- | --- |
| ArchiveMember `de` | Member to be added. |


 
Throws:
ZipException when an unsupported compression method is used or when compression failed.
  @safe void **deleteMember**(ArchiveMember de);  
Delete member `de` from the archive. Uses the name of the member to detect which element to delete. 



Parameters:


|  |  |
| --- | --- |
| ArchiveMember `de` | Member to be deleted. |


  pure @safe void[] **build**();  
Construct the entire contents of the current members of the archive. 


Fills in the properties data[], totalEntries, and directory[]. For each ArchiveMember, fills in properties crc32, compressedSize, compressedData[]. 

 
Returns:
Array representing the entire archive. 
 
Throws:
ZipException when the archive could not be build.
  this(void[] buffer);  
Constructor to use when reading an existing archive. 


Fills in the properties data[], totalEntries, comment[], and directory[]. For each ArchiveMember, fills in properties madeVersion, extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, compressedData[], internalAttributes, externalAttributes, name[], extra[], comment[]. Use expand() to get the expanded data for each ArchiveMember. 

 
Parameters:


|  |  |
| --- | --- |
| void[] `buffer` | The entire contents of the archive. |


 
Throws:
ZipException when the archive was invalid or when malware was detected.
  ubyte[] **expand**(ArchiveMember de);  
Decompress the contents of a member. 


Fills in properties extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, expandedData[], name[], extra[]. 

 
Parameters:


|  |  |
| --- | --- |
| ArchiveMember `de` | Member to be decompressed. |


 
Returns:
The expanded data. 
 
Throws:
ZipException when the entry is invalid or the compression method is not supported.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_zip.html>

etc.c.odbc.sql
==============

 Declarations for interfacing with the ODBC library. 


Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;1@digitaldaemon.com)).   
  
 `etc.c.odbc.sql` is the the main include for ODBC v3.0+ Core functions, corresponding to the `sql.h` C header file. It `import`s `public`ly `etc.c.odbc.sqltypes` for conformity with the C header. 

 
Note
 The ODBC library itself not a part of the `dmd` distribution (and typically not a part of the distribution packages of other compilers such as `gdc` and `ldc`). To use ODBC, install it per the vendor- and platform-specific instructions and then use the appropriate command-line flags (e.g. for dmd, `-L-lodbc` on Posix and `-Lodbc32.lib` on Windows) to link with the ODBC library. On Windows, using `pragma(lib, "odbc32")` in D code at top level is also appropriate. 
 
See Also:
 [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference)


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_odbc_sql.html>

std.range
=========

 This module defines the notion of a range. Ranges generalize the concept of arrays, lists, or anything that involves sequential access. This abstraction enables the same set of algorithms (see [`std.algorithm`](std_algorithm)) to be used with a vast variety of different concrete types. For example, a linear search algorithm such as [`std.algorithm.searching.find`](std_algorithm_searching#find) works not just for arrays, but for linked-lists, input files, incoming network data, etc. 



Guides
 There are many articles available that can bolster understanding ranges: 
 * Ali Çehreli's [tutorial on ranges](http://ddili.org/ders/d.en/ranges.html) for the basics of working with and creating range-based code.
* Jonathan M. Davis [*Introduction to Ranges*](http://dconf.org/2015/talks/davis.html) talk at DConf 2015 a vivid introduction from its core constructs to practical advice.
* The DLang Tour's [chapter on ranges](http://tour.dlang.org/tour/en/basics/ranges) for an interactive introduction.
* H. S. Teoh's [tutorial on component programming with ranges](http://wiki.dlang.org/Component_programming_with_ranges) for a real-world showcase of the influence of range-based programming on complex algorithms.
* Andrei Alexandrescu's article  [*On Iteration*](http://www.informit.com/articles/printerfriendly.aspx?p=1407357&rll=1) for conceptual aspect of ranges and the motivation

 
Submodules
 This module has two submodules: 
 The [`std.range.primitives`](std_range_primitives) submodule provides basic range functionality. It defines several templates for testing whether a given object is a range, what kind of range it is, and provides some common range operations. The [`std.range.interfaces`](std_range_interfaces) submodule provides object-based interfaces for working with ranges via runtime polymorphism. The remainder of this module provides a rich set of range creation and composition templates that let you construct new ranges out of existing ranges: 

|  |  |
| --- | --- |
| [`chain`](#chain) | Concatenates several ranges into a single range.  |
| [`choose`](#choose) | Chooses one of two ranges at runtime based on a boolean condition.  |
| [`chooseAmong`](#chooseAmong) | Chooses one of several ranges at runtime based on an index.  |
| [`chunks`](#chunks) | Creates a range that returns fixed-size chunks of the original range.  |
| [`cycle`](#cycle) | Creates an infinite range that repeats the given forward range indefinitely. Good for implementing circular buffers.  |
| [`drop`](#drop) | Creates the range that results from discarding the first *n* elements from the given range.  |
| [`dropBack`](#dropBack) | Creates the range that results from discarding the last *n* elements from the given range.  |
| [`dropExactly`](#dropExactly) | Creates the range that results from discarding exactly *n* of the first elements from the given range.  |
| [`dropBackExactly`](#dropBackExactly) | Creates the range that results from discarding exactly *n* of the last elements from the given range.  |
| [`dropOne`](#dropOne) | Creates the range that results from discarding the first element from the given range.  |
| `[dropBackOne](#dropBackOne)` | Creates the range that results from discarding the last element from the given range.  |
| [`enumerate`](#enumerate) | Iterates a range with an attached index variable.  |
| [`evenChunks`](#evenChunks) | Creates a range that returns a number of chunks of approximately equal length from the original range.  |
| [`frontTransversal`](#frontTransversal) | Creates a range that iterates over the first elements of the given ranges.  |
| [`generate`](#generate) | Creates a range by successive calls to a given function. This allows to create ranges as a single delegate.  |
| [`indexed`](#indexed) | Creates a range that offers a view of a given range as though its elements were reordered according to a given range of indices.  |
| [`iota`](#iota) | Creates a range consisting of numbers between a starting point and ending point, spaced apart by a given interval.  |
| [`lockstep`](#lockstep) | Iterates *n* ranges in lockstep, for use in a `foreach` loop. Similar to `zip`, except that `lockstep` is designed especially for `foreach` loops.  |
| [`nullSink`](#nullSink) | An output range that discards the data it receives.  |
| [`only`](#only) | Creates a range that iterates over the given arguments.  |
| [`padLeft`](#padLeft) | Pads a range to a specified length by adding a given element to the front of the range. Is lazy if the range has a known length.  |
| [`padRight`](#padRight) | Lazily pads a range to a specified length by adding a given element to the back of the range.  |
| [`radial`](#radial) | Given a random-access range and a starting point, creates a range that alternately returns the next left and next right element to the starting point.  |
| [`recurrence`](#recurrence) | Creates a forward range whose values are defined by a mathematical recurrence relation.  |
| [`refRange`](#refRange) | Pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other.  |
| [`repeat`](#repeat) | Creates a range that consists of a single element repeated *n* times, or an infinite range repeating that element indefinitely.  |
| [`retro`](#retro) | Iterates a bidirectional range backwards.  |
| [`roundRobin`](#roundRobin) | Given *n* ranges, creates a new range that return the *n* first elements of each range, in turn, then the second element of each range, and so on, in a round-robin fashion.  |
| [`sequence`](#sequence) | Similar to `recurrence`, except that a random-access range is created.  |
| `[slide](#slide)` | Creates a range that returns a fixed-size sliding window over the original range. Unlike chunks, it advances a configurable number of items at a time, not one chunk at a time.  |
| [`stride`](#stride) | Iterates a range with stride *n*.  |
| [`tail`](#tail) | Return a range advanced to within `n` elements of the end of the given range.  |
| [`take`](#take) | Creates a sub-range consisting of only up to the first *n* elements of the given range.  |
| [`takeExactly`](#takeExactly) | Like `take`, but assumes the given range actually has *n* elements, and therefore also defines the `length` property.  |
| [`takeNone`](#takeNone) | Creates a random-access range consisting of zero elements of the given range.  |
| [`takeOne`](#takeOne) | Creates a random-access range consisting of exactly the first element of the given range.  |
| [`tee`](#tee) | Creates a range that wraps a given range, forwarding along its elements while also calling a provided function with each element.  |
| [`transposed`](#transposed) | Transposes a range of ranges.  |
| [`transversal`](#transversal) | Creates a range that iterates over the *n*'th elements of the given random-access ranges.  |
| [`zip`](#zip) | Given *n* ranges, creates a range that successively returns a tuple of all the first elements, a tuple of all the second elements, etc.  |

 
Sortedness
 Ranges whose elements are sorted afford better efficiency with certain operations. For this, the [`assumeSorted`](#assumeSorted) function can be used to construct a [`SortedRange`](#SortedRange) from a pre-sorted range. The [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort) function also conveniently returns a [`SortedRange`](#SortedRange). [`SortedRange`](#SortedRange) objects provide some additional range operations that take advantage of the fact that the range is sorted. 
 
Source
 [std/range/package.d](https://github.com/dlang/phobos/blob/master/std/range/package.d) 
 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Andrei Alexandrescu](http://erdani.com), David Simcha, [Jonathan M Davis](http://jmdavisprog.com), and Jack Stouffer. Credit for some of the ideas in building this module goes to [Leonardo Maffi](http://fantascienza.net/leonardo/so/).
 
auto **retro**(Range)(Range r)  
 Constraints: if (isBidirectionalRange!(Unqual!Range)); 
 
Iterates a bidirectional range backwards. The original range can be accessed by using the `source` property. Applying retro twice to the same range yields the original range. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | the bidirectional range to iterate backwards |


 
Returns:
A bidirectional range with length if `r` also provides a length. Or, if `r` is a random access range, then the return value will be random access as well. 
 
See Also:

[`std.algorithm.mutation.reverse`](std_algorithm_mutation#reverse) for mutating the source range directly.
 
Examples:


```
import std.algorithm.comparison : equal;
int[5] a = [ 1, 2, 3, 4, 5 ];
int[5] b = [ 5, 4, 3, 2, 1 ];
assert(equal(retro(a[]), b[]));
assert(retro(a[]).source is a[]);
assert(retro(retro(a[])) is a[]);

```
 
  auto **stride**(Range)(Range r, size\_t n)  
 Constraints: if (isInputRange!(Unqual!Range)); 
 
Iterates range `r` with stride `n`. If the range is a random-access range, moves by indexing into the range; otherwise, moves by successive calls to `popFront`. Applying stride twice to the same range results in a stride with a step that is the product of the two applications. It is an error for `n` to be 0. 



Parameters:


|  |  |
| --- | --- |
| Range `r` | the [input range](std_range_primitives#isInputRange) to stride over |
| size\_t `n` | the number of elements to skip over |


 
Returns:
At minimum, an input range. The resulting range will adopt the range primitives of the underlying range as long as [`std.range.primitives.hasLength`](std_range_primitives#hasLength) is `true`.
 
Examples:


```
import std.algorithm.comparison : equal;

int[] a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ];
assert(equal(stride(a, 3), [ 1, 4, 7, 10 ][]));
writeln(stride(stride(a, 2), 3)); // stride(a, 6)

```
 
  auto **chain**(Ranges...)(Ranges rs)  
 Constraints: if (Ranges.length > 0 && allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) && !is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Ranges))) == void)); 
 
Spans multiple ranges in sequence. The function `chain` takes any number of ranges and returns a `Chain!(R1, R2,...)` object. The ranges may be different, but they must have the same element type. The result is a range that offers the `front`, `popFront`, and `empty` primitives. If all input ranges offer random access and `length`, `Chain` offers them as well. 


If only one range is offered to `Chain` or `chain`, the `Chain` type exits the picture by aliasing itself directly to that range's type. 

 
Parameters:


|  |  |
| --- | --- |
| Ranges `rs` | the [input ranges](std_range_primitives#isInputRange) to chain together |


 
Returns:
An input range at minimum. If all of the ranges in `rs` provide a range primitive, the returned range will also provide that range primitive. 
 
See Also:

[`only`](#only) to chain values to a range
 
Examples:


```
import std.algorithm.comparison : equal;

int[] arr1 = [ 1, 2, 3, 4 ];
int[] arr2 = [ 5, 6 ];
int[] arr3 = [ 7 ];
auto s = chain(arr1, arr2, arr3);
writeln(s.length); // 7
writeln(s[5]); // 6
assert(equal(s, [1, 2, 3, 4, 5, 6, 7][]));

```
 
 
Examples:
Range primitives are carried over to the returned range if all of the ranges provide them 
```
import std.algorithm.comparison : equal;
import std.algorithm.sorting : sort;

int[] arr1 = [5, 2, 8];
int[] arr2 = [3, 7, 9];
int[] arr3 = [1, 4, 6];

// in-place sorting across all of the arrays
auto s = arr1.chain(arr2, arr3).sort;

assert(s.equal([1, 2, 3, 4, 5, 6, 7, 8, 9]));
assert(arr1.equal([1, 2, 3]));
assert(arr2.equal([4, 5, 6]));
assert(arr3.equal([7, 8, 9]));

```
 
 
Examples:
Due to safe type promotion in D, chaining together different character ranges results in a `uint` range. Use [byChar](std_utf#byChar), [byWchar](std_utf#byWchar), and [byDchar](std_utf#byDchar) on the ranges to get the type you need. 
```
import std.utf : byChar, byCodeUnit;

auto s1 = "string one";
auto s2 = "string two";
// s1 and s2 front is dchar because of auto-decoding
static assert(is(typeof(s1.front) == dchar) && is(typeof(s2.front) == dchar));

auto r1 = s1.chain(s2);
// chains of ranges of the same character type give that same type
static assert(is(typeof(r1.front) == dchar));

auto s3 = "string three".byCodeUnit;
static assert(is(typeof(s3.front) == immutable char));
auto r2 = s1.chain(s3);
// chaining ranges of mixed character types gives `dchar`
static assert(is(typeof(r2.front) == dchar));

// use byChar on character ranges to correctly convert them to UTF-8
auto r3 = s1.byChar.chain(s3);
static assert(is(typeof(r3.front) == immutable char));

```
 
  auto **choose**(R1, R2)(bool condition, return scope R1 r1, return scope R2 r2)  
 Constraints: if (isInputRange!(Unqual!R1) && isInputRange!(Unqual!R2) && !is(CommonType!(ElementType!(Unqual!R1), ElementType!(Unqual!R2)) == void)); 
 
Choose one of two ranges at runtime depending on a Boolean condition. 


The ranges may be different, but they must have compatible element types (i.e. `CommonType` must exist for the two element types). The result is a range that offers the weakest capabilities of the two (e.g. `ForwardRange` if `R1` is a random-access range and `R2` is a forward range). 

 
Parameters:


|  |  |
| --- | --- |
| bool `condition` | which range to choose: `r1` if `true`, `r2` otherwise |
| R1 `r1` | the "true" range |
| R2 `r2` | the "false" range |


 
Returns:
A range type dependent on `R1` and `R2`.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter, map;

auto data1 = only(1, 2, 3, 4).filter!(a => a != 3);
auto data2 = only(5, 6, 7, 8).map!(a => a + 1);

// choose() is primarily useful when you need to select one of two ranges
// with different types at runtime.
static assert(!is(typeof(data1) == typeof(data2)));

auto chooseRange(bool pickFirst)
{
    // The returned range is a common wrapper type that can be used for
    // returning or storing either range without running into a type error.
    return choose(pickFirst, data1, data2);

    // Simply returning the chosen range without using choose() does not
    // work, because map() and filter() return different types.
    //return pickFirst ? data1 : data2; // does not compile
}

auto result = chooseRange(true);
assert(result.equal(only(1, 2, 4)));

result = chooseRange(false);
assert(result.equal(only(6, 7, 8, 9)));

```
 
  auto **chooseAmong**(Ranges...)(size\_t index, return scope Ranges rs)  
 Constraints: if (Ranges.length >= 2 && allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) && !is(CommonType!(staticMap!(ElementType, Ranges)) == void)); 
 
Choose one of multiple ranges at runtime. 


The ranges may be different, but they must have compatible element types. The result is a range that offers the weakest capabilities of all `Ranges`. 

 
Parameters:


|  |  |
| --- | --- |
| size\_t `index` | which range to choose, must be less than the number of ranges |
| Ranges `rs` | two or more ranges |


 
Returns:
The indexed range. If rs consists of only one range, the return type is an alias of that range's type.
 
Examples:


```
auto test()
{
    import std.algorithm.comparison : equal;

    int[4] sarr1 = [1, 2, 3, 4];
    int[2] sarr2 = [5, 6];
    int[1] sarr3 = [7];
    auto arr1 = sarr1[];
    auto arr2 = sarr2[];
    auto arr3 = sarr3[];

    {
        auto s = chooseAmong(0, arr1, arr2, arr3);
        auto t = s.save;
        writeln(s.length); // 4
        writeln(s[2]); // 3
        s.popFront();
        assert(equal(t, only(1, 2, 3, 4)));
    }
    {
        auto s = chooseAmong(1, arr1, arr2, arr3);
        writeln(s.length); // 2
        s.front = 8;
        assert(equal(s, only(8, 6)));
    }
    {
        auto s = chooseAmong(1, arr1, arr2, arr3);
        writeln(s.length); // 2
        s[1] = 9;
        assert(equal(s, only(8, 9)));
    }
    {
        auto s = chooseAmong(1, arr2, arr1, arr3)[1 .. 3];
        writeln(s.length); // 2
        assert(equal(s, only(2, 3)));
    }
    {
        auto s = chooseAmong(0, arr1, arr2, arr3);
        writeln(s.length); // 4
        writeln(s.back); // 4
        s.popBack();
        s.back = 5;
        assert(equal(s, only(1, 2, 5)));
        s.back = 3;
        assert(equal(s, only(1, 2, 3)));
    }
    {
        uint[5] foo = [1, 2, 3, 4, 5];
        uint[5] bar = [6, 7, 8, 9, 10];
        auto c = chooseAmong(1, foo[], bar[]);
        writeln(c[3]); // 9
        c[3] = 42;
        writeln(c[3]); // 42
        writeln(c.moveFront()); // 6
        writeln(c.moveBack()); // 10
        writeln(c.moveAt(4)); // 10
    }
    {
        import std.range : cycle;
        auto s = chooseAmong(0, cycle(arr2), cycle(arr3));
        assert(isInfinite!(typeof(s)));
        assert(!s.empty);
        writeln(s[100]); // 8
        writeln(s[101]); // 9
        assert(s[0 .. 3].equal(only(8, 9, 8)));
    }
    return 0;
}
// works at runtime
auto a = test();
// and at compile time
static b = test();

```
 
  auto **roundRobin**(Rs...)(Rs rs)  
 Constraints: if (Rs.length > 1 && allSatisfy!(isInputRange, staticMap!(Unqual, Rs))); 
 
`roundRobin(r1, r2, r3)` yields `r1.front`, then `r2.front`, then `r3.front`, after which it pops off one element from each and continues again from `r1`. For example, if two ranges are involved, it alternately yields elements off the two ranges. `roundRobin` stops after it has consumed all ranges (skipping over the ones that finish early).



Examples:


```
import std.algorithm.comparison : equal;

int[] a = [ 1, 2, 3 ];
int[] b = [ 10, 20, 30, 40 ];
auto r = roundRobin(a, b);
assert(equal(r, [ 1, 10, 2, 20, 3, 30, 40 ]));

```
 
 
Examples:
roundRobin can be used to create "interleave" functionality which inserts an element between each element in a range. 
```
import std.algorithm.comparison : equal;

auto interleave(R, E)(R range, E element)
if ((isInputRange!R && hasLength!R) || isForwardRange!R)
{
    static if (hasLength!R)
        immutable len = range.length;
    else
        immutable len = range.save.walkLength;

    return roundRobin(
        range,
        element.repeat(len - 1)
    );
}

assert(interleave([1, 2, 3], 0).equal([1, 0, 2, 0, 3]));

```
 
  auto **radial**(Range, I)(Range r, I startingIndex)  
 Constraints: if (isRandomAccessRange!(Unqual!Range) && hasLength!(Unqual!Range) && hasSlicing!(Unqual!Range) && isIntegral!I);   
  
auto **radial**(R)(R r)  
 Constraints: if (isRandomAccessRange!(Unqual!R) && hasLength!(Unqual!R) && hasSlicing!(Unqual!R)); 
 
Iterates a random-access range starting from a given point and progressively extending left and right from that point. If no initial point is given, iteration starts from the middle of the range. Iteration spans the entire range. 


When `startingIndex` is 0 the range will be fully iterated in order and in reverse order when `r.length` is given. 

 
Parameters:


|  |  |
| --- | --- |
| Range `r` | a random access range with length and slicing |
| I `startingIndex` | the index to begin iteration from |


 
Returns:
A forward range with length
 
Examples:


```
import std.algorithm.comparison : equal;
int[] a = [ 1, 2, 3, 4, 5 ];
assert(equal(radial(a), [ 3, 4, 2, 5, 1 ]));
a = [ 1, 2, 3, 4 ];
assert(equal(radial(a), [ 2, 3, 1, 4 ]));

// If the left end is reached first, the remaining elements on the right
// are concatenated in order:
a = [ 0, 1, 2, 3, 4, 5 ];
assert(equal(radial(a, 1), [ 1, 2, 0, 3, 4, 5 ]));

// If the right end is reached first, the remaining elements on the left
// are concatenated in reverse order:
assert(equal(radial(a, 4), [ 4, 5, 3, 2, 1, 0 ]));

```
 
  Take!R **take**(R)(R input, size\_t n)  
 Constraints: if (isInputRange!(Unqual!R));   
  
struct **Take**(Range) if (isInputRange!(Unqual!Range) && !(!isInfinite!(Unqual!Range) && hasSlicing!(Unqual!Range) || is(Range T == **Take**!T)));   
  
template **Take**(R) if (isInputRange!(Unqual!R) && (!isInfinite!(Unqual!R) && hasSlicing!(Unqual!R) || is(R T == **Take**!T))) 
Lazily takes only up to `n` elements of a range. This is particularly useful when using with infinite ranges. 


Unlike [`takeExactly`](#takeExactly), `take` does not require that there are `n` or more elements in `input`. As a consequence, length information is not applied to the result unless `input` also has length information. 

 
Parameters:


|  |  |
| --- | --- |
| R `input` | an [input range](std_range_primitives#isInputRange) to iterate over up to `n` times |
| size\_t `n` | the number of elements to take |


 
Returns:
At minimum, an input range. If the range offers random access and `length`, `take` offers them as well.
 
Examples:


```
import std.algorithm.comparison : equal;

int[] arr1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
auto s = take(arr1, 5);
writeln(s.length); // 5
writeln(s[4]); // 5
assert(equal(s, [ 1, 2, 3, 4, 5 ][]));

```
 
 
Examples:
If the range runs out before `n` elements, `take` simply returns the entire range (unlike [`takeExactly`](#takeExactly), which will cause an assertion failure if the range ends prematurely): 
```
import std.algorithm.comparison : equal;

int[] arr2 = [ 1, 2, 3 ];
auto t = take(arr2, 5);
writeln(t.length); // 3
assert(equal(t, [ 1, 2, 3 ]));

```
 
  auto **takeExactly**(R)(R range, size\_t n)  
 Constraints: if (isInputRange!R); 
 
Similar to [`take`](#take), but assumes that `range` has at least `n` elements. Consequently, the result of `takeExactly(range, n)` always defines the `length` property (and initializes it to `n`) even when `range` itself does not define `length`. 


The result of `takeExactly` is identical to that of [`take`](#take) in cases where the original range defines `length` or is infinite.   
  
 Unlike [`take`](#take), however, it is illegal to pass a range with less than `n` elements to `takeExactly`; this will cause an assertion failure.

 
Examples:


```
import std.algorithm.comparison : equal;

auto a = [ 1, 2, 3, 4, 5 ];

auto b = takeExactly(a, 3);
assert(equal(b, [1, 2, 3]));
static assert(is(typeof(b.length) == size_t));
writeln(b.length); // 3
writeln(b.front); // 1
writeln(b.back); // 3

```
 
  auto **takeOne**(R)(R source)  
 Constraints: if (isInputRange!R); 
 
Returns a range with at most one element; for example, `takeOne([42, 43, 44])` returns a range consisting of the integer `42`. Calling `popFront()` off that range renders it empty. 


In effect `takeOne(r)` is somewhat equivalent to `take(r, 1)` but in certain interfaces it is important to know statically that the range may only have at most one element.   
  
 The type returned by `takeOne` is a random-access range with length regardless of `R`'s capabilities, as long as it is a forward range. (another feature that distinguishes `takeOne` from `take`). If (D R) is an input range but not a forward range, return type is an input range with all random-access capabilities except save.

 
Examples:


```
auto s = takeOne([42, 43, 44]);
static assert(isRandomAccessRange!(typeof(s)));
writeln(s.length); // 1
assert(!s.empty);
writeln(s.front); // 42
s.front = 43;
writeln(s.front); // 43
writeln(s.back); // 43
writeln(s[0]); // 43
s.popFront();
writeln(s.length); // 0
assert(s.empty);

```
 
  auto **takeNone**(R)()  
 Constraints: if (isInputRange!R); 
 
Returns an empty range which is statically known to be empty and is guaranteed to have `length` and be random access regardless of `R`'s capabilities.



Examples:


```
auto range = takeNone!(int[])();
writeln(range.length); // 0
assert(range.empty);

```
 
  auto **takeNone**(R)(R range)  
 Constraints: if (isInputRange!R); 
 
Creates an empty range from the given range in Ο(`1`). If it can, it will return the same range type. If not, it will return `takeExactly(range, 0)`.



Examples:


```
import std.algorithm.iteration : filter;
assert(takeNone([42, 27, 19]).empty);
assert(takeNone("dlang.org").empty);
assert(takeNone(filter!"true"([42, 27, 19])).empty);

```
 
  auto **tail**(Range)(Range range, size\_t n)  
 Constraints: if (isInputRange!Range && !isInfinite!Range && (hasLength!Range || isForwardRange!Range)); 
 
Return a range advanced to within `_n` elements of the end of `range`. 


Intended as the range equivalent of the Unix [tail](http://en.wikipedia.org/wiki/Tail_%28Unix%29) utility. When the length of `range` is less than or equal to `_n`, `range` is returned as-is.   
  
 Completes in Ο(`1`) steps for ranges that support slicing and have length. Completes in Ο(`range.length`) time for all other ranges. 

 
Parameters:


|  |  |
| --- | --- |
| Range `range` | range to get tail of |
| size\_t `n` | maximum number of elements to include in tail |


 
Returns:
Returns the tail of `range` augmented with length information
 
Examples:


```
// tail -c n
writeln([1, 2, 3].tail(1)); // [3]
writeln([1, 2, 3].tail(2)); // [2, 3]
writeln([1, 2, 3].tail(3)); // [1, 2, 3]
writeln([1, 2, 3].tail(4)); // [1, 2, 3]
writeln([1, 2, 3].tail(0).length); // 0

// tail --lines=n
import std.algorithm.comparison : equal;
import std.algorithm.iteration : joiner;
import std.exception : assumeWontThrow;
import std.string : lineSplitter;
assert("one\ntwo\nthree"
    .lineSplitter
    .tail(2)
    .joiner("\n")
    .equal("two\nthree")
    .assumeWontThrow);

```
 
  R **drop**(R)(R range, size\_t n)  
 Constraints: if (isInputRange!R);   
  
R **dropBack**(R)(R range, size\_t n)  
 Constraints: if (isBidirectionalRange!R); 
 
Convenience function which calls [`std.range.primitives.popFrontN`](std_range_primitives#popFrontN)`(range, n)` and returns `range`. `drop` makes it easier to pop elements from a range and then pass it to another function within a single expression, whereas `popFrontN` would require multiple statements. 


`dropBack` provides the same functionality but instead calls [`std.range.primitives.popBackN`](std_range_primitives#popBackN)`(range, n)` 

 
Note
 `drop` and `dropBack` will only pop *up to* `n` elements but will stop if the range is empty first. In other languages this is sometimes called `skip`. 
 
Parameters:


|  |  |
| --- | --- |
| R `range` | the [input range](std_range_primitives#isInputRange) to drop from |
| size\_t `n` | the number of elements to drop |


 
Returns:

`range` with up to `n` elements dropped 
 
See Also:

[`std.range.primitives.popFront`](std_range_primitives#popFront), [`std.range.primitives.popBackN`](std_range_primitives#popBackN)

 
Examples:


```
import std.algorithm.comparison : equal;

writeln([0, 2, 1, 5, 0, 3].drop(3)); // [5, 0, 3]
writeln("hello world".drop(6)); // "world"
assert("hello world".drop(50).empty);
assert("hello world".take(6).drop(3).equal("lo "));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;

writeln([0, 2, 1, 5, 0, 3].dropBack(3)); // [0, 2, 1]
writeln("hello world".dropBack(6)); // "hello"
assert("hello world".dropBack(50).empty);
assert("hello world".drop(4).dropBack(4).equal("o w"));

```
 
  R **dropExactly**(R)(R range, size\_t n)  
 Constraints: if (isInputRange!R);   
  
R **dropBackExactly**(R)(R range, size\_t n)  
 Constraints: if (isBidirectionalRange!R); 
 
Similar to [`drop`](#drop) and `dropBack` but they call `range.[popFrontExactly](#popFrontExactly)(n)` and `range.popBackExactly(n)` instead. 



Note
 Unlike `drop`, `dropExactly` will assume that the range holds at least `n` elements. This makes `dropExactly` faster than `drop`, but it also means that if `range` does not contain at least `n` elements, it will attempt to call `popFront` on an empty range, which is undefined behavior. So, only use `popFrontExactly` when it is guaranteed that `range` holds at least `n` elements. 
 
Parameters:


|  |  |
| --- | --- |
| R `range` | the [input range](std_range_primitives#isInputRange) to drop from |
| size\_t `n` | the number of elements to drop |


 
Returns:

`range` with `n` elements dropped 
 
See Also:

[`std.range.primitives.popFrontExcatly`](std_range_primitives#popFrontExcatly), [`std.range.primitives.popBackExcatly`](std_range_primitives#popBackExcatly)

 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filterBidirectional;

auto a = [1, 2, 3];
writeln(a.dropExactly(2)); // [3]
writeln(a.dropBackExactly(2)); // [1]

string s = "日本語";
writeln(s.dropExactly(2)); // "語"
writeln(s.dropBackExactly(2)); // "日"

auto bd = filterBidirectional!"true"([1, 2, 3]);
assert(bd.dropExactly(2).equal([3]));
assert(bd.dropBackExactly(2).equal([1]));

```
 
  R **dropOne**(R)(R range)  
 Constraints: if (isInputRange!R);   
  
R **dropBackOne**(R)(R range)  
 Constraints: if (isBidirectionalRange!R); 
 
Convenience function which calls `range.popFront()` and returns `range`. `dropOne` makes it easier to pop an element from a range and then pass it to another function within a single expression, whereas `popFront` would require multiple statements. 


`dropBackOne` provides the same functionality but instead calls `range.popBack()`.

 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filterBidirectional;
import std.container.dlist : DList;

auto dl = DList!int(9, 1, 2, 3, 9);
assert(dl[].dropOne().dropBackOne().equal([1, 2, 3]));

auto a = [1, 2, 3];
writeln(a.dropOne()); // [2, 3]
writeln(a.dropBackOne()); // [1, 2]

string s = "日本語";
import std.exception : assumeWontThrow;
assert(assumeWontThrow(s.dropOne() == "本語"));
assert(assumeWontThrow(s.dropBackOne() == "日本"));

auto bd = filterBidirectional!"true"([1, 2, 3]);
assert(bd.dropOne().equal([2, 3]));
assert(bd.dropBackOne().equal([1, 2]));

```
 
  struct **Repeat**(T);   
  
Repeat!T **repeat**(T)(T value);   
  
Take!(Repeat!T) **repeat**(T)(T value, size\_t n);  
Create a range which repeats one value. 



Parameters:


|  |  |
| --- | --- |
| T `value` | the value to repeat |
| size\_t `n` | the number of times to repeat `value` |


 
Returns:
If `n` is not defined, an infinite random access range with slicing. If `n` is defined, a random access range with slicing.
 
Examples:


```
import std.algorithm.comparison : equal;

assert(5.repeat().take(4).equal([5, 5, 5, 5]));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;

assert(5.repeat(4).equal([5, 5, 5, 5]));

```
 
 
inout @property inout(T) **front**();   
  
inout @property inout(T) **back**();   
  
enum bool **empty**;   
  
void **popFront**();   
  
void **popBack**();   
  
inout @property auto **save**();   
  
inout inout(T) **opIndex**(size\_t);   
  
auto **opSlice**(size\_t i, size\_t j);   
  
enum auto **opDollar**;   
  
inout auto **opSlice**(size\_t, DollarToken);  
Range primitives

    auto **generate**(Fun)(Fun fun)  
 Constraints: if (isCallable!fun);   
  
auto **generate**(alias fun)()  
 Constraints: if (isCallable!fun); 
 
Given callable ([`std.traits.isCallable`](std_traits#isCallable)) `fun`, create as a range whose front is defined by successive calls to `fun()`. This is especially useful to call function with global side effects (random functions), or to create ranges expressed as a single delegate, rather than an entire `front`/`popFront`/`empty` structure. `fun` maybe be passed either a template alias parameter (existing function, delegate, struct type defining `static opCall`) or a run-time value argument (delegate, function object). The result range models an InputRange ([`std.range.primitives.isInputRange`](std_range_primitives#isInputRange)). The resulting range will call `fun()` on construction, and every call to `popFront`, and the cached value will be returned when `front` is called. 



Returns:
an `inputRange` where each element represents another call to fun.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;

int i = 1;
auto powersOfTwo = generate!(() => i *= 2)().take(10);
assert(equal(powersOfTwo, iota(1, 11).map!"2^^a"()));

```
 
 
Examples:


```
import std.algorithm.comparison : equal;

//Returns a run-time delegate
auto infiniteIota(T)(T low, T high)
{
    T i = high;
    return (){if (i == high) i = low; return i++;};
}
//adapted as a range.
assert(equal(generate(infiniteIota(1, 4)).take(10), [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]));

```
 
 
Examples:


```
import std.format : format;
import std.random : uniform;

auto r = generate!(() => uniform(0, 6)).take(10);
format("%(%s %)", r);

```
 
  struct **Cycle**(R) if (isForwardRange!R && !isInfinite!R);   
  
template **Cycle**(R) if (isInfinite!R)  
  
struct **Cycle**(R) if (isStaticArray!R);   
  
auto **cycle**(R)(R input)  
 Constraints: if (isInputRange!R);   
  
Cycle!R **cycle**(R)(R input, size\_t index = 0)  
 Constraints: if (isRandomAccessRange!R && !isInfinite!R);   
  
@system Cycle!R **cycle**(R)(ref R input, size\_t index = 0)  
 Constraints: if (isStaticArray!R); 
 
Repeats the given forward range ad infinitum. If the original range is infinite (fact that would make `Cycle` the identity application), `Cycle` detects that and aliases itself to the range type itself. That works for non-forward ranges too. If the original range has random access, `Cycle` offers random access and also offers a constructor taking an initial position `index`. `Cycle` works with static arrays in addition to ranges, mostly for performance reasons. 



Note
 The input range must not be empty. 
 
Tip
 This is a great way to implement simple circular buffers.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range : cycle, take;

// Here we create an infinitive cyclic sequence from [1, 2]
// (i.e. get here [1, 2, 1, 2, 1, 2 and so on]) then
// take 5 elements of this sequence (so we have [1, 2, 1, 2, 1])
// and compare them with the expected values for equality.
assert(cycle([1, 2]).take(5).equal([ 1, 2, 1, 2, 1 ]));

```
 
 
this(R input, size\_t index = 0);   
  
@property ref auto **front**();   
  
const @property ref auto **front**();   
  
@property void **front**(ElementType!R val);   
  
enum bool **empty**;   
  
void **popFront**();   
  
ref auto **opIndex**(size\_t n);   
  
const ref auto **opIndex**(size\_t n);   
  
void **opIndexAssign**(ElementType!R val, size\_t n);   
  
@property Cycle **save**();   
  
enum auto **opDollar**;   
  
auto **opSlice**(size\_t i, size\_t j);   
  
auto **opSlice**(size\_t i, DollarToken);  
Range primitives

    struct **Zip**(Ranges...) if (Ranges.length && allSatisfy!(isInputRange, Ranges));   
  
auto **zip**(Ranges...)(Ranges ranges)  
 Constraints: if (Ranges.length && allSatisfy!(isInputRange, Ranges));   
  
auto **zip**(Ranges...)(StoppingPolicy sp, Ranges ranges)  
 Constraints: if (Ranges.length && allSatisfy!(isInputRange, Ranges)); 
 
Iterate several ranges in lockstep. The element type is a proxy tuple that allows accessing the current element in the `n`th range by using `e[n]`. 


`zip` is similar to [`lockstep`](#lockstep), but `lockstep` doesn't bundle its elements and uses the `opApply` protocol. `lockstep` allows reference access to the elements in `foreach` iterations. 

 
Parameters:


|  |  |
| --- | --- |
| StoppingPolicy `sp` | controls what `zip` will do if the ranges are different lengths |
| Ranges `ranges` | the ranges to zip together |


 
Returns:
At minimum, an input range. `Zip` offers the lowest range facilities of all components, e.g. it offers random access iff all ranges offer random access, and also offers mutation and swapping if all ranges offer it. Due to this, `Zip` is extremely powerful because it allows manipulating several ranges in lockstep. 
 
Throws:
An `Exception` if all of the ranges are not the same length and `sp` is set to `StoppingPolicy.requireSameLength`. 
 
Limitations
 The `@nogc` and `nothrow` attributes cannot be inferred for the `Zip` struct because [`StoppingPolicy`](#StoppingPolicy) can vary at runtime. This limitation is not shared by the anonymous range returned by the `zip` function when not given an explicit `StoppingPolicy` as an argument.
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;

// pairwise sum
auto arr = only(0, 1, 2);
auto part1 = zip(arr, arr.dropOne).map!"a[0] + a[1]";
assert(part1.equal(only(1, 3)));

```
 
 
Examples:


```
import std.conv : to;

int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "b", "c" ];
string[] result;

foreach (tup; zip(a, b))
{
    result ~= tup[0].to!string ~ tup[1];
}

writeln(result); // ["1a", "2b", "3c"]

size_t idx = 0;
// unpacking tuple elements with foreach
foreach (e1, e2; zip(a, b))
{
    writeln(e1); // a[idx]
    writeln(e2); // b[idx]
    ++idx;
}

```
 
 
Examples:

`zip` is powerful - the following code sorts two arrays in parallel: 
```
import std.algorithm.sorting : sort;

int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "c", "b" ];
zip(a, b).sort!((t1, t2) => t1[0] > t2[0]);

writeln(a); // [3, 2, 1]
// b is sorted according to a's sorting
writeln(b); // ["b", "c", "a"]

```
 
 
this(R rs, StoppingPolicy s = StoppingPolicy.shortest);  
Builds an object. Usually this is invoked indirectly by using the [`zip`](#zip) function.

  enum bool **empty**;  
Returns `true` if the range is at end. The test depends on the stopping policy.

  @property Zip **save**();  @property ElementType **front**();  
Returns the current iterated element.

  @property void **front**(ElementType v);  
Sets the front of all iterated ranges.

  ElementType **moveFront**();  
Moves out the front.

  @property ElementType **back**();  
Returns the rightmost element.

  ElementType **moveBack**();  
Moves out the back. 


Returns the rightmost element.

  @property void **back**(ElementType v);  
Returns the current iterated element. 


Returns the rightmost element.

  void **popFront**();  
Advances to the next element in all controlled ranges.

  void **popBack**();  
Calls `popBack` for all controlled ranges.

  @property auto **length**();  
Returns the length of this range. Defined only if all ranges define `length`.

  alias **opDollar** = length;  
Returns the length of this range. Defined only if all ranges define `length`.

  auto **opSlice**(size\_t from, size\_t to);  
Returns a slice of the range. Defined only if all range define slicing.

  ElementType **opIndex**(size\_t n);  
Returns the `n`th element in the composite range. Defined if all ranges offer random access.

  void **opIndexAssign**(ElementType v, size\_t n);  
Assigns to the `n`th element in the composite range. Defined if all ranges offer random access. 


Returns the `n`th element in the composite range. Defined if all ranges offer random access.

  ElementType **moveAt**(size\_t n);  
Destructively reads the `n`th element in the composite range. Defined if all ranges offer random access. 


Returns the `n`th element in the composite range. Defined if all ranges offer random access.

    enum **StoppingPolicy**: int;  
Dictates how iteration in a [`zip`](#zip) and [`lockstep`](#lockstep) should stop. By default stop at the end of the shortest of all ranges.



Examples:


```
import std.algorithm.comparison : equal;
import std.exception : assertThrown;
import std.range.primitives;
import std.typecons : tuple;

auto a = [1, 2, 3];
auto b = [4, 5, 6, 7];

auto shortest = zip(StoppingPolicy.shortest, a, b);
assert(shortest.equal([
    tuple(1, 4),
    tuple(2, 5),
    tuple(3, 6)
]));

auto longest = zip(StoppingPolicy.longest, a, b);
assert(longest.equal([
    tuple(1, 4),
    tuple(2, 5),
    tuple(3, 6),
    tuple(0, 7)
]));

auto same = zip(StoppingPolicy.requireSameLength, a, b);
same.popFrontN(3);
assertThrown!Exception(same.popFront);

```
 
 
**shortest** 
Stop when the shortest range is exhausted

  **longest** 
Stop when the longest range is exhausted

  **requireSameLength** 
Require that all ranges are equal

    struct **Lockstep**(Ranges...) if (Ranges.length > 1 && allSatisfy!(isInputRange, Ranges));   
  
Lockstep!Ranges **lockstep**(Ranges...)(Ranges ranges)  
 Constraints: if (allSatisfy!(isInputRange, Ranges));   
  
Lockstep!Ranges **lockstep**(Ranges...)(Ranges ranges, StoppingPolicy s)  
 Constraints: if (allSatisfy!(isInputRange, Ranges)); 
 
Iterate multiple ranges in lockstep using a `foreach` loop. In contrast to [`zip`](#zip) it allows reference access to its elements. If only a single range is passed in, the `Lockstep` aliases itself away. If the ranges are of different lengths and `s` == `StoppingPolicy.shortest` stop after the shortest range is empty. If the ranges are of different lengths and `s` == `StoppingPolicy.requireSameLength`, throw an exception. `s` may not be `StoppingPolicy.longest`, and passing this will throw an exception. 


Iterating over `Lockstep` in reverse and with an index is only possible when `s` == `StoppingPolicy.requireSameLength`, in order to preserve indexes. If an attempt is made at iterating in reverse when `s` == `StoppingPolicy.shortest`, an exception will be thrown.   
  
 By default `StoppingPolicy` is set to `StoppingPolicy.shortest`. 

 
Limitations
 The `pure`, `@safe`, `@nogc`, or `nothrow` attributes cannot be inferred for `lockstep` iteration. [`zip`](#zip) can infer the first two due to a different implementation. 
 
See Also:

[`zip`](#zip) `lockstep` is similar to [`zip`](#zip), but `zip` bundles its elements and returns a range. `lockstep` also supports reference access. Use `zip` if you want to pass the result to a range function.
 
Examples:


```
auto arr1 = [1,2,3,4,5,100];
auto arr2 = [6,7,8,9,10];

foreach (ref a, b; lockstep(arr1, arr2))
{
    a += b;
}

writeln(arr1); // [7, 9, 11, 13, 15, 100]

/// Lockstep also supports iterating with an index variable:
foreach (index, a, b; lockstep(arr1, arr2))
{
    writeln(arr1[index]); // a
    writeln(arr2[index]); // b
}

```
 
 
this(R ranges, StoppingPolicy sp = StoppingPolicy.shortest);    struct **Recurrence**(alias fun, StateType, size\_t stateSize);   
  
Recurrence!(fun, CommonType!State, State.length) **recurrence**(alias fun, State...)(State initial);  
Creates a mathematical sequence given the initial values and a recurrence function that computes the next value from the existing values. The sequence comes in the form of an infinite forward range. The type `Recurrence` itself is seldom used directly; most often, recurrences are obtained by calling the function `recurrence`. 


When calling `recurrence`, the function that computes the next value is specified as a template argument, and the initial values in the recurrence are passed as regular arguments. For example, in a Fibonacci sequence, there are two initial values (and therefore a state size of 2) because computing the next Fibonacci value needs the past two values.   
  
 The signature of this function should be: 
```
auto fun(R)(R state, size_t n)

```
 where `n` will be the index of the current value, and `state` will be an opaque state vector that can be indexed with array-indexing notation `state[i]`, where valid values of `i` range from `(n - 1)` to `(n - State.length)`.   
  
 If the function is passed in string form, the state has name `"a"` and the zero-based index in the recurrence has name `"n"`. The given string must return the desired value for `a[n]` given `a[n - 1]`, `a[n - 2]`, `a[n - 3]`,..., `a[n - stateSize]`. The state size is dictated by the number of arguments passed to the call to `recurrence`. The `Recurrence` struct itself takes care of managing the recurrence's state and shifting it appropriately.

 
Examples:


```
import std.algorithm.comparison : equal;

// The Fibonacci numbers, using function in string form:
// a[0] = 1, a[1] = 1, and compute a[n+1] = a[n-1] + a[n]
auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);
assert(fib.take(10).equal([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));

// The factorials, using function in lambda form:
auto fac = recurrence!((a,n) => a[n-1] * n)(1);
assert(take(fac, 10).equal([
    1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880
]));

// The triangular numbers, using function in explicit form:
static size_t genTriangular(R)(R state, size_t n)
{
    return state[n-1] + n;
}
auto tri = recurrence!genTriangular(0);
assert(take(tri, 10).equal([0, 1, 3, 6, 10, 15, 21, 28, 36, 45]));

```
 
  struct **Sequence**(alias fun, State);   
  
auto **sequence**(alias fun, State...)(State args);  
`Sequence` is similar to `Recurrence` except that iteration is presented in the so-called  [closed form](http://en.wikipedia.org/wiki/Closed_form). This means that the `n`th element in the series is computable directly from the initial values and `n` itself. This implies that the interface offered by `Sequence` is a random-access range, as opposed to the regular `Recurrence`, which only offers forward iteration. 


The state of the sequence is stored as a `Tuple` so it can be heterogeneous.

 
Examples:
Odd numbers, using function in string form: 
```
auto odds = sequence!("a[0] + n * a[1]")(1, 2);
writeln(odds.front); // 1
odds.popFront();
writeln(odds.front); // 3
odds.popFront();
writeln(odds.front); // 5

```
 
 
Examples:
Triangular numbers, using function in lambda form: 
```
auto tri = sequence!((a,n) => n*(n+1)/2)();

// Note random access
writeln(tri[0]); // 0
writeln(tri[3]); // 6
writeln(tri[1]); // 1
writeln(tri[4]); // 10
writeln(tri[2]); // 3

```
 
 
Examples:
Fibonacci numbers, using function in explicit form: 
```
import std.math : pow, round, sqrt;
static ulong computeFib(S)(S state, size_t n)
{
    // Binet's formula
    return cast(ulong)(round((pow(state[0], n+1) - pow(state[1], n+1)) /
                             state[2]));
}
auto fib = sequence!computeFib(
    (1.0 + sqrt(5.0)) / 2.0,    // Golden Ratio
    (1.0 - sqrt(5.0)) / 2.0,    // Conjugate of Golden Ratio
    sqrt(5.0));

// Note random access with [] operator
writeln(fib[1]); // 1
writeln(fib[4]); // 5
writeln(fib[3]); // 3
writeln(fib[2]); // 2
writeln(fib[9]); // 55

```
 
  auto **iota**(B, E, S)(B begin, E end, S step)  
 Constraints: if ((isIntegral!(CommonType!(B, E)) || isPointer!(CommonType!(B, E))) && isIntegral!S);   
  
auto **iota**(B, E)(B begin, E end)  
 Constraints: if (isFloatingPoint!(CommonType!(B, E)));   
  
auto **iota**(B, E)(B begin, E end)  
 Constraints: if (isIntegral!(CommonType!(B, E)) || isPointer!(CommonType!(B, E)));   
  
auto **iota**(E)(E end)  
 Constraints: if (is(typeof(iota(E(0), end))));   
  
auto **iota**(B, E, S)(B begin, E end, S step)  
 Constraints: if (isFloatingPoint!(CommonType!(B, E, S)));   
  
auto **iota**(B, E)(B begin, E end)  
 Constraints: if (!isIntegral!(CommonType!(B, E)) && !isFloatingPoint!(CommonType!(B, E)) && !isPointer!(CommonType!(B, E)) && is(typeof((ref B b) { ++b; } )) && (is(typeof(B.init < E.init)) || is(typeof(B.init == E.init)))); 
 
Creates a range of values that span the given starting and stopping values. 



Parameters:


|  |  |
| --- | --- |
| B `begin` | The starting value. |
| E `end` | The value that serves as the stopping criterion. This value is not included in the range. |
| S `step` | The value to add to the current value at each iteration. |


 
Returns:
A range that goes through the numbers `begin`, `begin + step`, `begin + 2 * step`, `...`, up to and excluding `end`. The two-argument overloads have `step = 1`. If `begin < end && step < 0` or `begin > end && step > 0` or `begin == end`, then an empty range is returned. If `step == 0` then `begin == end` is an error. For built-in types, the range returned is a random access range. For user-defined types that support `++`, the range is an input range. An integral iota also supports `in` operator from the right. It takes the stepping into account, the integral won't be considered contained if it falls between two consecutive values of the range. `contains` does the same as in, but from lefthand side. 
 
Example


```
void main()
{
    import std.stdio;

    // The following groups all produce the same output of:
    // 0 1 2 3 4

    foreach (i; 0 .. 5)
        writef("%s ", i);
    writeln();

    import std.range : iota;
    foreach (i; iota(0, 5))
        writef("%s ", i);
    writeln();

    writefln("%(%s %|%)", iota(0, 5));

    import std.algorithm.iteration : map;
    import std.algorithm.mutation : copy;
    import std.format;
    iota(0, 5).map!(i => format("%s ", i)).copy(stdout.lockingTextWriter());
    writeln();
}

```
 
Examples:


```
import std.algorithm.comparison : equal;
import std.math : approxEqual;

auto r = iota(0, 10, 1);
assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
assert(3 in r);
assert(r.contains(3)); //Same as above
assert(!(10 in r));
assert(!(-8 in r));
r = iota(0, 11, 3);
assert(equal(r, [0, 3, 6, 9]));
writeln(r[2]); // 6
assert(!(2 in r));
auto rf = iota(0.0, 0.5, 0.1);
assert(approxEqual(rf, [0.0, 0.1, 0.2, 0.3, 0.4]));

```
 
  enum **TransverseOptions**: int;  
Options for the [`FrontTransversal`](#FrontTransversal) and [`Transversal`](#Transversal) ranges (below).



Examples:


```
import std.algorithm.comparison : equal;
import std.exception : assertThrown;

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

auto r1 = arr.frontTransversal!(TransverseOptions.assumeJagged);
assert(r1.equal([1, 3]));

// throws on construction
assertThrown!Exception(arr.frontTransversal!(TransverseOptions.enforceNotJagged));

auto r2 = arr.frontTransversal!(TransverseOptions.assumeNotJagged);
assert(r2.equal([1, 3]));

// either assuming or checking for equal lengths makes
// the result a random access range
writeln(r2[0]); // 1
static assert(!__traits(compiles, r1[0]));

```
 
 
**assumeJagged** 
When transversed, the elements of a range of ranges are assumed to have different lengths (e.g. a jagged array).

  **enforceNotJagged** 
The transversal enforces that the elements of a range of ranges have all the same length (e.g. an array of arrays, all having the same length). Checking is done once upon construction of the transversal range.

  **assumeNotJagged** 
The transversal assumes, without verifying, that the elements of a range of ranges have all the same length. This option is useful if checking was already done from the outside of the range.

    struct **FrontTransversal**(Ror, TransverseOptions opt = TransverseOptions.assumeJagged);   
  
FrontTransversal!(RangeOfRanges, opt) **frontTransversal**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr);  
Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges.



Examples:


```
import std.algorithm.comparison : equal;
int[][] x = new int[][2];
x[0] = [1, 2];
x[1] = [3, 4];
auto ror = frontTransversal(x);
assert(equal(ror, [ 1, 3 ][]));

```
 
 
this(RangeOfRanges input);  
Construction from an input.

  enum bool **empty**;   
  
@property ref auto **front**();   
  
ElementType **moveFront**();   
  
void **popFront**();  
Forward range primitives.

  @property FrontTransversal **save**();  
Duplicates this `frontTransversal`. Note that only the encapsulating range of range will be duplicated. Underlying ranges will not be duplicated.

  @property ref auto **back**();   
  
void **popBack**();   
  
ElementType **moveBack**();  
Bidirectional primitives. They are offered if  `isBidirectionalRange!RangeOfRanges`.

  ref auto **opIndex**(size\_t n);   
  
ElementType **moveAt**(size\_t n);   
  
void **opIndexAssign**(ElementType val, size\_t n);  
Random-access primitive. It is offered if  `isRandomAccessRange!RangeOfRanges && (opt == TransverseOptions.assumeNotJagged || opt == TransverseOptions.enforceNotJagged)`.

  typeof(this) **opSlice**(size\_t lower, size\_t upper);  
Slicing if offered if `RangeOfRanges` supports slicing and all the conditions for supporting indexing are met.

    struct **Transversal**(Ror, TransverseOptions opt = TransverseOptions.assumeJagged);   
  
Transversal!(RangeOfRanges, opt) **transversal**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr, size\_t n);  
Given a range of ranges, iterate transversally through the `n`th element of each of the enclosed ranges. This function is similar to `unzip` in other languages. 



Parameters:


|  |  |
| --- | --- |
| opt | Controls the assumptions the function makes about the lengths of the ranges |
| RangeOfRanges `rr` | An input range of random access ranges |


 
Returns:
At minimum, an input range. Range primitives such as bidirectionality and random access are given if the element type of `rr` provides them.
 
Examples:


```
import std.algorithm.comparison : equal;
int[][] x = new int[][2];
x[0] = [1, 2];
x[1] = [3, 4];
auto ror = transversal(x, 1);
assert(equal(ror, [ 2, 4 ]));

```
 
 
Examples:
The following code does a full unzip 
```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
int[][] y = [[1, 2, 3], [4, 5, 6]];
auto z = y.front.walkLength.iota.map!(i => transversal(y, i));
assert(equal!equal(z, [[1, 4], [2, 5], [3, 6]]));

```
 
 
this(RangeOfRanges input, size\_t n);  
Construction from an input and an index.

  enum bool **empty**;   
  
@property ref auto **front**();   
  
E **moveFront**();   
  
@property void **front**(E val);   
  
void **popFront**();   
  
@property typeof(this) **save**();  
Forward range primitives.

  @property ref auto **back**();   
  
void **popBack**();   
  
E **moveBack**();   
  
@property void **back**(E val);  
Bidirectional primitives. They are offered if  `isBidirectionalRange!RangeOfRanges`.

  ref auto **opIndex**(size\_t n);   
  
E **moveAt**(size\_t n);   
  
void **opIndexAssign**(E val, size\_t n);  
Random-access primitive. It is offered if  `isRandomAccessRange!RangeOfRanges && (opt == TransverseOptions.assumeNotJagged || opt == TransverseOptions.enforceNotJagged)`.

  typeof(this) **opSlice**(size\_t lower, size\_t upper);  
Slicing if offered if `RangeOfRanges` supports slicing and all the conditions for supporting indexing are met.

    Transposed!(RangeOfRanges, opt) **transposed**(TransverseOptions opt = TransverseOptions.assumeJagged, RangeOfRanges)(RangeOfRanges rr)  
 Constraints: if (isForwardRange!RangeOfRanges && isInputRange!(ElementType!RangeOfRanges) && hasAssignableElements!RangeOfRanges); 
 
Given a range of ranges, returns a range of ranges where the *i*'th subrange contains the *i*'th elements of the original subranges. 


`Transposed` currently defines `save`, but does not work as a forward range. Consuming a copy made with `save` will consume all copies, even the original sub-ranges fed into `Transposed`. 

 
Parameters:


|  |  |
| --- | --- |
| opt | Controls the assumptions the function makes about the lengths of the ranges (i.e. jagged or not) |
| RangeOfRanges `rr` | Range of ranges |


 
Examples:


```
import std.algorithm.comparison : equal;
int[][] ror = [
    [1, 2, 3],
    [4, 5, 6]
];
auto xp = transposed(ror);
assert(equal!"a.equal(b)"(xp, [
    [1, 4],
    [2, 5],
    [3, 6]
]));

```
 
 
Examples:


```
int[][] x = new int[][2];
x[0] = [1, 2];
x[1] = [3, 4];
auto tr = transposed(x);
int[][] witness = [ [ 1, 3 ], [ 2, 4 ] ];
uint i;

foreach (e; tr)
{
    writeln(array(e)); // witness[i++]
}

```
 
  struct **Indexed**(Source, Indices) if (isRandomAccessRange!Source && isInputRange!Indices && is(typeof(Source.init[ElementType!Indices.init])));   
  
Indexed!(Source, Indices) **indexed**(Source, Indices)(Source source, Indices indices);  
This struct takes two ranges, `source` and `indices`, and creates a view of `source` as if its elements were reordered according to `indices`. `indices` may include only a subset of the elements of `source` and may also repeat elements. 


`Source` must be a random access range. The returned range will be bidirectional or random-access if `Indices` is bidirectional or random-access, respectively.

 
Examples:


```
import std.algorithm.comparison : equal;
auto source = [1, 2, 3, 4, 5];
auto indices = [4, 3, 1, 2, 0, 4];
auto ind = indexed(source, indices);
assert(equal(ind, [5, 4, 2, 3, 1, 5]));
assert(equal(retro(ind), [5, 1, 3, 2, 4, 5]));

```
 
 
@property ref auto **front**();   
  
void **popFront**();   
  
@property typeof(this) **save**();   
  
@property ref auto **front**(ElementType!Source newVal);   
  
auto **moveFront**();   
  
@property ref auto **back**();   
  
void **popBack**();   
  
@property ref auto **back**(ElementType!Source newVal);   
  
auto **moveBack**();   
  
ref auto **opIndex**(size\_t index);   
  
typeof(this) **opSlice**(size\_t a, size\_t b);   
  
auto **opIndexAssign**(ElementType!Source newVal, size\_t index);   
  
auto **moveAt**(size\_t index);  
Range primitives

  @property Source **source**();  
Returns the source range.

  @property Indices **indices**();  
Returns the indices range.

  size\_t **physicalIndex**(size\_t logicalIndex);  
Returns the physical index into the source range corresponding to a given logical index. This is useful, for example, when indexing an `Indexed` without adding another layer of indirection.



Examples:


```
auto ind = indexed([1, 2, 3, 4, 5], [1, 3, 4]);
writeln(ind.physicalIndex(0)); // 1

```
 
    struct **Chunks**(Source) if (isInputRange!Source);   
  
Chunks!Source **chunks**(Source)(Source source, size\_t chunkSize)  
 Constraints: if (isInputRange!Source); 
 
This range iterates over fixed-sized chunks of size `chunkSize` of a `source` range. `Source` must be an [input range](std_range_primitives#isInputRange). `chunkSize` must be greater than zero. 


If `!isInfinite!Source` and `source.walkLength` is not evenly divisible by `chunkSize`, the back element of this range will contain fewer than `chunkSize` elements.   
  
 If `Source` is a forward range, the resulting range will be forward ranges as well. Otherwise, the resulting chunks will be input ranges consuming the same input: iterating over `front` will shrink the chunk such that subsequent invocations of `front` will no longer return the full chunk, and calling `popFront` on the outer range will invalidate any lingering references to previous values of `front`. 

 
Parameters:


|  |  |
| --- | --- |
| Source `source` | Range from which the chunks will be selected |
| size\_t `chunkSize` | Chunk size |


 
See Also:

[`slide`](#slide) 
 
Returns:
Range of chunks.
 
Examples:


```
import std.algorithm.comparison : equal;
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = chunks(source, 4);
writeln(chunks[0]); // [1, 2, 3, 4]
writeln(chunks[1]); // [5, 6, 7, 8]
writeln(chunks[2]); // [9, 10]
writeln(chunks.back); // chunks[2]
writeln(chunks.front); // chunks[0]
writeln(chunks.length); // 3
assert(equal(retro(array(chunks)), array(retro(chunks))));

```
 
 
Examples:
Non-forward input ranges are supported, but with limited semantics. 
```
import std.algorithm.comparison : equal;

int i;

// The generator doesn't save state, so it cannot be a forward range.
auto inputRange = generate!(() => ++i).take(10);

// We can still process it in chunks, but it will be single-pass only.
auto chunked = inputRange.chunks(2);

assert(chunked.front.equal([1, 2]));
assert(chunked.front.empty); // Iterating the chunk has consumed it
chunked.popFront;
assert(chunked.front.equal([3, 4]));

```
 
 
this(Source source, size\_t chunkSize);  
Standard constructor

  @property auto **front**();   
  
void **popFront**();   
  
@property bool **empty**();  
Input range primitives. Always present.

  @property typeof(this) **save**();  
Forward range primitives. Only present if `Source` is a forward range.

  @property size\_t **length**();  
Length. Only if `hasLength!Source` is `true`

  auto **opIndex**(size\_t index);   
  
typeof(this) **opSlice**(size\_t lower, size\_t upper);  
Indexing and slicing operations. Provided only if `hasSlicing!Source` is `true`.

  @property auto **back**();   
  
void **popBack**();  
Bidirectional range primitives. Provided only if both `hasSlicing!Source` and `hasLength!Source` are `true`.

    struct **EvenChunks**(Source) if (isForwardRange!Source && hasLength!Source);   
  
EvenChunks!Source **evenChunks**(Source)(Source source, size\_t chunkCount)  
 Constraints: if (isForwardRange!Source && hasLength!Source); 
 
This range splits a `source` range into `chunkCount` chunks of approximately equal length. `Source` must be a forward range with known length. 


Unlike [`chunks`](#chunks), `evenChunks` takes a chunk count (not size). The returned range will contain zero or more `source.length / chunkCount + 1` elements followed by `source.length / chunkCount` elements. If `source.length < chunkCount`, some chunks will be empty.   
  
 `chunkCount` must not be zero, unless `source` is also empty.

 
Examples:


```
import std.algorithm.comparison : equal;
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = evenChunks(source, 3);
writeln(chunks[0]); // [1, 2, 3, 4]
writeln(chunks[1]); // [5, 6, 7]
writeln(chunks[2]); // [8, 9, 10]

```
 
 
this(Source source, size\_t chunkCount);  
Standard constructor

  @property auto **front**();   
  
void **popFront**();   
  
@property bool **empty**();   
  
@property typeof(this) **save**();  
Forward range primitives. Always present.

  const @property size\_t **length**();  
Length

  auto **opIndex**(size\_t index);   
  
typeof(this) **opSlice**(size\_t lower, size\_t upper);   
  
@property auto **back**();   
  
void **popBack**();  
Indexing, slicing and bidirectional operations and range primitives. Provided only if `hasSlicing!Source` is `true`.

    auto **slide**(Flag!"withPartial" f = Yes.withPartial, Source)(Source source, size\_t windowSize, size\_t stepSize = 1)  
 Constraints: if (isForwardRange!Source); 
 
A fixed-sized sliding window iteration of size `windowSize` over a `source` range by a custom `stepSize`. 


The `Source` range must be at least a [ForwardRange](std_range_primitives#isForwardRange) and the `windowSize` must be greater than zero.   
  
 For `windowSize = 1` it splits the range into single element groups (aka `unflatten`) For `windowSize = 2` it is similar to `zip(source, source.save.dropOne)`. 

 
Parameters:


|  |  |
| --- | --- |
| f | Whether the last element has fewer elements than `windowSize` it should be be ignored (`No.withPartial`) or added (`Yes.withPartial`) |
| Source `source` | Range from which the slide will be selected |
| size\_t `windowSize` | Sliding window size |
| size\_t `stepSize` | Steps between the windows (by default 1) |


 
Returns:
Range of all sliding windows with propagated bi-directionality, forwarding, random access, and slicing. 
 
Note
 To avoid performance overhead, [bi-directionality](std_range_primitives#isBidirectionalRange) is only available when [`std.range.primitives.hasSlicing`](std_range_primitives#hasSlicing) and [`std.range.primitives.hasLength`](std_range_primitives#hasLength) are true. 
 
See Also:
[`chunks`](#chunks)
 
Examples:
Iterate over ranges with windows 
```
import std.algorithm.comparison : equal;

assert([0, 1, 2, 3].slide(2).equal!equal(
    [[0, 1], [1, 2], [2, 3]]
));

assert(5.iota.slide(3).equal!equal(
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
));

```
 
 
Examples:
set a custom stepsize (default 1) 
```
import std.algorithm.comparison : equal;

assert(6.iota.slide(1, 2).equal!equal(
    [[0], [2], [4]]
));

assert(6.iota.slide(2, 4).equal!equal(
    [[0, 1], [4, 5]]
));

assert(iota(7).slide(2, 2).equal!equal(
    [[0, 1], [2, 3], [4, 5], [6]]
));

assert(iota(12).slide(2, 4).equal!equal(
    [[0, 1], [4, 5], [8, 9]]
));

```
 
 
Examples:
Allow the last slide to have fewer elements than windowSize 
```
import std.algorithm.comparison : equal;

assert(3.iota.slide!(No.withPartial)(4).empty);
assert(3.iota.slide!(Yes.withPartial)(4).equal!equal(
    [[0, 1, 2]]
));

```
 
 
Examples:
Count all the possible substrings of length 2 
```
import std.algorithm.iteration : each;

int[dstring] d;
"AGAGA"d.slide!(Yes.withPartial)(2).each!(a => d[a]++);
writeln(d); // ["AG"d:2, "GA"d:2]

```
 
 
Examples:
withPartial only has an effect if last element in the range doesn't have the full size 
```
import std.algorithm.comparison : equal;

assert(5.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4]]));
assert(6.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5]]));
assert(7.iota.slide!(Yes.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5, 6]]));

assert(5.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2]]));
assert(6.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2]]));
assert(7.iota.slide!(No.withPartial)(3, 4).equal!equal([[0, 1, 2], [4, 5, 6]]));

```
 
  auto **only**(Values...)(return scope Values values)  
 Constraints: if (!is(CommonType!Values == void) || Values.length == 0); 
 
Assemble `values` into a range that carries all its elements in-situ. 


Useful when a single value or multiple disconnected values must be passed to an algorithm expecting a range, without having to perform dynamic memory allocation.   
  
 As copying the range means copying all elements, it can be safely returned from functions. For the same reason, copying the returned range may be expensive for a large number of arguments. 

 
Parameters:


|  |  |
| --- | --- |
| Values `values` | the values to assemble together |


 
Returns:
A `RandomAccessRange` of the assembled values. 
 
See Also:

[`chain`](#chain) to chain ranges
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter, joiner, map;
import std.algorithm.searching : findSplitBefore;
import std.uni : isUpper;

assert(equal(only('♡'), "♡"));
writeln([1, 2, 3, 4].findSplitBefore(only(3))[0]); // [1, 2]

assert(only("one", "two", "three").joiner(" ").equal("one two three"));

string title = "The D Programming Language";
assert(title
    .filter!isUpper // take the upper case letters
    .map!only       // make each letter its own range
    .joiner(".")    // join the ranges together lazily
    .equal("T.D.P.L"));

```
 
  auto **enumerate**(Enumerator = size\_t, Range)(Range range, Enumerator start = 0)  
 Constraints: if (isIntegral!Enumerator && isInputRange!Range); 
 
Iterate over `range` with an attached index variable. 


Each element is a [`std.typecons.Tuple`](std_typecons#Tuple) containing the index and the element, in that order, where the index member is named `index` and the element member is named `value`.   
  
 The index starts at `start` and is incremented by one on every iteration. 

 
Overflow
 If `range` has length, then it is an error to pass a value for `start` so that `start + range.length` is bigger than `Enumerator.max`, thus it is ensured that overflow cannot happen. 
 If `range` does not have length, and `popFront` is called when `front.index == Enumerator.max`, the index will overflow and continue from `Enumerator.min`. 
Parameters:


|  |  |
| --- | --- |
| Range `range` | the [input range](std_range_primitives#isInputRange) to attach indexes to |
| Enumerator `start` | the number to start the index counter from |


 
Returns:
At minimum, an input range. All other range primitives are given in the resulting range if `range` has them. The exceptions are the bidirectional primitives, which are propagated only if `range` has length. 
 
Example
 Useful for using `foreach` with an index loop variable: 


```
    import std.stdio : stdin, stdout;
    import std.range : enumerate;

    foreach (lineNum, line; stdin.byLine().enumerate(1))
        stdout.writefln("line #%s: %s", lineNum, line);

```
 
Examples:
Can start enumeration from a negative position: 
```
import std.array : assocArray;
import std.range : enumerate;

bool[int] aa = true.repeat(3).enumerate(-1).assocArray();
assert(aa[-1]);
assert(aa[0]);
assert(aa[1]);

```
 
  enum auto **isTwoWayCompatible**(alias fn, T1, T2);  
 Returns true if `fn` accepts variables of type T1 and T2 in any order. The following code should compile: 
```
(ref T1 a, ref T2 b)
{
  fn(a, b);
  fn(b, a);
}

```
 



Examples:


```
void func1(int a, int b);
void func2(int a, float b);

static assert(isTwoWayCompatible!(func1, int, int));
static assert(isTwoWayCompatible!(func1, short, int));
static assert(!isTwoWayCompatible!(func2, int, float));

void func3(ref int a, ref int b);
static assert( isTwoWayCompatible!(func3, int, int));
static assert(!isTwoWayCompatible!(func3, short, int));

```
 
  enum **SearchPolicy**: int;  
Policy used with the searching primitives `lowerBound`,  `upperBound`, and `equalRange` of [`SortedRange`](#SortedRange) below.



Examples:


```
import std.algorithm.comparison : equal;

auto a = assumeSorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
auto p1 = a.upperBound!(SearchPolicy.binarySearch)(3);
assert(p1.equal([4, 5, 6, 7, 8, 9]));

auto p2 = a.lowerBound!(SearchPolicy.gallop)(4);
assert(p2.equal([0, 1, 2, 3]));

```
 
 
**linear** 
Searches in a linear fashion.

  **trot** 
Searches with a step that is grows linearly (1, 2, 3,...) leading to a quadratic search schedule (indexes tried are 0, 1, 3, 6, 10, 15, 21, 28,...) Once the search overshoots its target, the remaining interval is searched using binary search. The search is completed in Ο(`sqrt(n)`) time. Use it when you are reasonably confident that the value is around the beginning of the range.

  **gallop** 
Performs a  [galloping search algorithm](https://en.wikipedia.org/wiki/Exponential_search), i.e. searches with a step that doubles every time, (1, 2, 4, 8, ...) leading to an exponential search schedule (indexes tried are 0, 1, 3, 7, 15, 31, 63,...) Once the search overshoots its target, the remaining interval is searched using binary search. A value is found in Ο(`log(n)`) time.

  **binarySearch** 
Searches using a classic interval halving policy. The search starts in the middle of the range, and each search step cuts the range in half. This policy finds a value in Ο(`log(n)`) time but is less cache friendly than `gallop` for large ranges. The `binarySearch` policy is used as the last step of `trot`, `gallop`, `trotBackwards`, and  `gallopBackwards` strategies.

  **trotBackwards** 
Similar to `trot` but starts backwards. Use it when confident that the value is around the end of the range.

  **gallopBackwards** 
Similar to `gallop` but starts backwards. Use it when confident that the value is around the end of the range.

    enum **SortedRangeOptions**: int;  
Options for [`SortedRange`](#SortedRange) ranges (below).



Examples:


```
// create a SortedRange, that's checked strictly
SortedRange!(int[],"a < b", SortedRangeOptions.checkStrictly)([ 1, 3, 5, 7, 9 ]);

```
 
 
**assumeSorted** 
Assume, that the range is sorted without checking.

  **checkStrictly** 
All elements of the range are checked to be sorted. The check is performed in O(n) time.

  **checkRoughly** 
Some elements of the range are checked to be sorted. For ranges with random order, this will almost surely detect, that it is not sorted. For almost sorted ranges it's more likely to fail. The checked elements are choosen in a deterministic manner, which makes this check reproducable. The check is performed in O(log(n)) time.

    struct **SortedRange**(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted) if (isInputRange!Range && !isInstanceOf!(**SortedRange**, Range));   
  
template **SortedRange**(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted) if (isInstanceOf!(**SortedRange**, Range)) 
Represents a sorted range. In addition to the regular range primitives, supports additional operations that take advantage of the ordering, such as merge and binary search. To obtain a  `SortedRange` from an unsorted range `r`, use [`std.algorithm.sorting.sort`](std_algorithm_sorting#sort) which sorts `r` in place and returns the corresponding `SortedRange`. To construct a `SortedRange` from a range `r` that is known to be already sorted, use [`assumeSorted`](#assumeSorted). 



Parameters:
 
Examples:


```
import std.algorithm.sorting : sort;
auto a = [ 1, 2, 3, 42, 52, 64 ];
auto r = assumeSorted(a);
assert(r.contains(3));
assert(!(32 in r));
auto r1 = sort!"a > b"(a);
assert(3 in r1);
assert(!r1.contains(32));
writeln(r1.release()); // [64, 52, 42, 3, 2, 1]

```
 
 
Examples:

`SortedRange` could accept ranges weaker than random-access, but it is unable to provide interesting functionality for them. Therefore, `SortedRange` is currently restricted to random-access ranges. No copy of the original range is ever made. If the underlying range is changed concurrently with its corresponding `SortedRange` in ways that break its sorted-ness, `SortedRange` will work erratically. 
```
import std.algorithm.mutation : swap;
auto a = [ 1, 2, 3, 42, 52, 64 ];
auto r = assumeSorted(a);
assert(r.contains(42));
swap(a[3], a[5]);         // illegal to break sortedness of original range
assert(!r.contains(42));  // passes although it shouldn't

```
 
 
@property bool **empty**();   
  
@property auto **save**();   
  
@property ref auto **front**();   
  
void **popFront**();   
  
@property ref auto **back**();   
  
void **popBack**();   
  
ref auto **opIndex**(size\_t i);   
  
scope auto **opSlice**(size\_t a, size\_t b) return;  
Range primitives.

  auto **release**();  
Releases the controlled range and returns it.

  auto **lowerBound**(SearchPolicy sp = SearchPolicy.binarySearch, V)(V value)  
 Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && hasSlicing!Range); 
 
This function uses a search with policy `sp` to find the largest left subrange on which `pred(x, value)` is `true` for all `x` (e.g., if `pred` is "less than", returns the portion of the range with elements strictly smaller than `value`). The search schedule and its complexity are documented in [`SearchPolicy`](#SearchPolicy).



Examples:


```
import std.algorithm.comparison : equal;
auto a = assumeSorted([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]);
auto p = a.lowerBound(4);
assert(equal(p, [ 0, 1, 2, 3 ]));

```
 
  auto **upperBound**(SearchPolicy sp = SearchPolicy.binarySearch, V)(V value)  
 Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V)); 
 
This function searches with policy `sp` to find the largest right subrange on which `pred(value, x)` is `true` for all `x` (e.g., if `pred` is "less than", returns the portion of the range with elements strictly greater than `value`). The search schedule and its complexity are documented in [`SearchPolicy`](#SearchPolicy). 


For ranges that do not offer random access, `SearchPolicy.linear` is the only policy allowed (and it must be specified explicitly lest it exposes user code to unexpected inefficiencies). For random-access searches, all policies are allowed, and `SearchPolicy.binarySearch` is the default.

 
Examples:


```
import std.algorithm.comparison : equal;
auto a = assumeSorted([ 1, 2, 3, 3, 3, 4, 4, 5, 6 ]);
auto p = a.upperBound(3);
assert(equal(p, [4, 4, 5, 6]));

```
 
  auto **equalRange**(V)(V value)  
 Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && isRandomAccessRange!Range); 
 
Returns the subrange containing all elements `e` for which both  `pred(e, value)` and `pred(value, e)` evaluate to `false` (e.g., if `pred` is "less than", returns the portion of the range with elements equal to `value`). Uses a classic binary search with interval halving until it finds a value that satisfies the condition, then uses `SearchPolicy.gallopBackwards` to find the left boundary and `SearchPolicy.gallop` to find the right boundary. These policies are justified by the fact that the two boundaries are likely to be near the first found value (i.e., equal ranges are relatively small). Completes the entire search in Ο(`log(n)`) time.



Examples:


```
import std.algorithm.comparison : equal;
auto a = [ 1, 2, 3, 3, 3, 4, 4, 5, 6 ];
auto r = a.assumeSorted.equalRange(3);
assert(equal(r, [ 3, 3, 3 ]));

```
 
  auto **trisect**(V)(V value)  
 Constraints: if (isTwoWayCompatible!(predFun, ElementType!Range, V) && isRandomAccessRange!Range && hasLength!Range); 
 
Returns a tuple `r` such that `r[0]` is the same as the result of `lowerBound(value)`, `r[1]` is the same as the result of `equalRange(value)`, and `r[2]` is the same as the result of `upperBound(value)`. The call is faster than computing all three separately. Uses a search schedule similar to `equalRange`. Completes the entire search in Ο(`log(n)`) time.



Examples:


```
import std.algorithm.comparison : equal;
auto a = [ 1, 2, 3, 3, 3, 4, 4, 5, 6 ];
auto r = assumeSorted(a).trisect(3);
assert(equal(r[0], [ 1, 2 ]));
assert(equal(r[1], [ 3, 3, 3 ]));
assert(equal(r[2], [ 4, 4, 5, 6 ]));

```
 
  bool **contains**(V)(V value)  
 Constraints: if (isRandomAccessRange!Range); 
 
Returns `true` if and only if `value` can be found in `range`, which is assumed to be sorted. Performs Ο(`log(r.length)`) evaluations of `pred`.

  bool **opBinaryRight**(string op, V)(V value)  
 Constraints: if (op == "in" && isRandomAccessRange!Range); 
 
Like `contains`, but the value is specified before the range.

  auto **groupBy**()();  
Returns a range of subranges of elements that are equivalent according to the sorting relation.

    auto **assumeSorted**(alias pred = "a < b", R)(R r)  
 Constraints: if (isInputRange!(Unqual!R)); 
 
Assumes `r` is sorted by predicate `pred` and returns the corresponding `SortedRange!(pred, R)` having `r` as support. To check for sorted-ness at cost Ο(`n`), use [`std.algorithm.sorting.isSorted`](std_algorithm_sorting#isSorted).



Examples:


```
import std.algorithm.comparison : equal;

int[] a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
auto p = assumeSorted(a);

assert(equal(p.lowerBound(4), [0, 1, 2, 3]));
assert(equal(p.lowerBound(5), [0, 1, 2, 3, 4]));
assert(equal(p.lowerBound(6), [0, 1, 2, 3, 4, 5]));
assert(equal(p.lowerBound(6.9), [0, 1, 2, 3, 4, 5, 6]));

```
 
  struct **RefRange**(R) if (isInputRange!R);   
  
auto **refRange**(R)(R\* range)  
 Constraints: if (isInputRange!R); 
 
Wrapper which effectively makes it possible to pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. So, for instance, if it's passed to a function which would implicitly copy the original range if it were passed to it, the original range is *not* copied but is consumed as if it were a reference type. 



Note
 `save` works as normal and operates on a new range, so if `save` is ever called on the `RefRange`, then no operations on the saved range will affect the original. 
 
Parameters:


|  |  |
| --- | --- |
| R\* `range` | the range to construct the `RefRange` from |


 
Returns:
A `RefRange`. If the given range is a class type (and thus is already a reference type), then the original range is returned rather than a `RefRange`.
 
Examples:
Basic Example 
```
import std.algorithm.searching : find;
ubyte[] buffer = [1, 9, 45, 12, 22];
auto found1 = find(buffer, 45);
writeln(found1); // [45, 12, 22]
writeln(buffer); // [1, 9, 45, 12, 22]

auto wrapped1 = refRange(&buffer);
auto found2 = find(wrapped1, 45);
writeln(*found2.ptr); // [45, 12, 22]
writeln(buffer); // [45, 12, 22]

auto found3 = find(wrapped1.save, 22);
writeln(*found3.ptr); // [22]
writeln(buffer); // [45, 12, 22]

string str = "hello world";
auto wrappedStr = refRange(&str);
writeln(str.front); // 'h'
str.popFrontN(5);
writeln(str); // " world"
writeln(wrappedStr.front); // ' '
writeln(*wrappedStr.ptr); // " world"

```
 
 
Examples:
opAssign Example. 
```
ubyte[] buffer1 = [1, 2, 3, 4, 5];
ubyte[] buffer2 = [6, 7, 8, 9, 10];
auto wrapped1 = refRange(&buffer1);
auto wrapped2 = refRange(&buffer2);
assert(wrapped1.ptr is &buffer1);
assert(wrapped2.ptr is &buffer2);
assert(wrapped1.ptr !is wrapped2.ptr);
assert(buffer1 != buffer2);

wrapped1 = wrapped2;

//Everything points to the same stuff as before.
assert(wrapped1.ptr is &buffer1);
assert(wrapped2.ptr is &buffer2);
assert(wrapped1.ptr !is wrapped2.ptr);

//But buffer1 has changed due to the assignment.
writeln(buffer1); // [6, 7, 8, 9, 10]
writeln(buffer2); // [6, 7, 8, 9, 10]

buffer2 = [11, 12, 13, 14, 15];

//Everything points to the same stuff as before.
assert(wrapped1.ptr is &buffer1);
assert(wrapped2.ptr is &buffer2);
assert(wrapped1.ptr !is wrapped2.ptr);

//But buffer2 has changed due to the assignment.
writeln(buffer1); // [6, 7, 8, 9, 10]
writeln(buffer2); // [11, 12, 13, 14, 15]

wrapped2 = null;

//The pointer changed for wrapped2 but not wrapped1.
assert(wrapped1.ptr is &buffer1);
assert(wrapped2.ptr is null);
assert(wrapped1.ptr !is wrapped2.ptr);

//buffer2 is not affected by the assignment.
writeln(buffer1); // [6, 7, 8, 9, 10]
writeln(buffer2); // [11, 12, 13, 14, 15]

```
 
 
pure nothrow @safe this(R\* range);  auto **opAssign**(RefRange rhs);  
This does not assign the pointer of `rhs` to this `RefRange`. Rather it assigns the range pointed to by `rhs` to the range pointed to by this `RefRange`. This is because *any* operation on a `RefRange` is the same is if it occurred to the original range. The one exception is when a `RefRange` is assigned `null` either directly or because `rhs` is `null`. In that case, `RefRange` no longer refers to the original range but is `null`.

  void **opAssign**(typeof(null) rhs);  inout pure nothrow @property @safe inout(R\*) **ptr**();  
A pointer to the wrapped range.

  @property auto **front**();   
  
const @property auto **front**();   
  
@property auto **front**(ElementType!R value);  @property bool **empty**();   
  
const @property bool **empty**();  void **popFront**();  @property auto **save**();   
  
const @property auto **save**();   
  
auto **opSlice**();   
  
const auto **opSlice**();  
Only defined if `isForwardRange!R` is `true`.

  @property auto **back**();   
  
const @property auto **back**();   
  
@property auto **back**(ElementType!R value);   
  
void **popBack**();  
Only defined if `isBidirectionalRange!R` is `true`.

  ref auto **opIndex**(IndexType)(IndexType index);   
  
const ref auto **opIndex**(IndexType)(IndexType index);  
Only defined if `isRandomAccesRange!R` is `true`.

  auto **moveFront**();  
Only defined if `hasMobileElements!R` and `isForwardRange!R` are `true`.

  auto **moveBack**();  
Only defined if `hasMobileElements!R` and `isBidirectionalRange!R` are `true`.

  auto **moveAt**(size\_t index);  
Only defined if `hasMobileElements!R` and `isRandomAccessRange!R` are `true`.

  @property size\_t **length**();   
  
const @property size\_t **length**();   
  
alias **opDollar** = length;  
Only defined if `hasLength!R` is `true`.

  auto **opSlice**(IndexType1, IndexType2)(IndexType1 begin, IndexType2 end);   
  
const auto **opSlice**(IndexType1, IndexType2)(IndexType1 begin, IndexType2 end);  
Only defined if `hasSlicing!R` is `true`.

    auto **bitwise**(R)(auto ref R range)  
 Constraints: if (isInputRange!R && isIntegral!(ElementType!R)); 
 
Bitwise adapter over an integral type range. Consumes the range elements bit by bit, from the least significant bit to the most significant bit. 



Parameters:


|  |  |
| --- | --- |
| R | an integral [input range](std_range_primitives#isInputRange) to iterate over |
| R `range` | range to consume bit by by |


 
Returns:
A `Bitwise` input range with propagated forward, bidirectional and random access capabilities
 
Examples:


```
import std.algorithm.comparison : equal;
import std.format : format;

// 00000011 00001001
ubyte[] arr = [3, 9];
auto r = arr.bitwise;

// iterate through it as with any other range
writeln(format("%(%d%)", r)); // "1100000010010000"
assert(format("%(%d%)", r.retro).equal("1100000010010000".retro));

auto r2 = r[5 .. $];
// set a bit
r[2] = 1;
writeln(arr[0]); // 7
writeln(r[5]); // r2[0]

```
 
 
Examples:
You can use bitwise to implement an uniform bool generator 
```
import std.algorithm.comparison : equal;
import std.random : rndGen;

auto rb = rndGen.bitwise;
static assert(isInfinite!(typeof(rb)));

auto rb2 = rndGen.bitwise;
// Don't forget that structs are passed by value
assert(rb.take(10).equal(rb2.take(10)));

```
 
  struct **NullSink**;   
  
ref auto **nullSink**();  
An OutputRange that discards the data it receives.



Examples:


```
import std.algorithm.iteration : map;
import std.algorithm.mutation : copy;
[4, 5, 6].map!(x => x * 2).copy(nullSink); // data is discarded

```
 
 
Examples:


```
import std.csv : csvNextToken;

string line = "a,b,c";

// ignore the first column
line.csvNextToken(nullSink, ',', '"');
line.popFront;

// look at the second column
Appender!string app;
line.csvNextToken(app, ',', '"');
writeln(app.data); // "b"

```
 
  auto **tee**(Flag!"pipeOnPop" pipeOnPop = Yes.pipeOnPop, R1, R2)(R1 inputRange, R2 outputRange)  
 Constraints: if (isInputRange!R1 && isOutputRange!(R2, ElementType!R1));   
  
auto **tee**(alias fun, Flag!"pipeOnPop" pipeOnPop = Yes.pipeOnPop, R1)(R1 inputRange)  
 Constraints: if (is(typeof(fun) == void) || isSomeFunction!fun); 
 
Implements a "tee" style pipe, wrapping an input range so that elements of the range can be passed to a provided function or [`OutputRange`](#OutputRange) as they are iterated over. This is useful for printing out intermediate values in a long chain of range code, performing some operation with side-effects on each call to `front` or `popFront`, or diverting the elements of a range into an auxiliary [`OutputRange`](#OutputRange). 


It is important to note that as the resultant range is evaluated lazily, in the case of the version of `tee` that takes a function, the function will not actually be executed until the range is "walked" using functions that evaluate ranges, such as [`std.array.array`](std_array#array) or [`std.algorithm.iteration.fold`](std_algorithm_iteration#fold). 

 
Parameters:


|  |  |
| --- | --- |
| pipeOnPop | If `Yes.pipeOnPop`, simply iterating the range without ever calling `front` is enough to have `tee` mirror elements to `outputRange` (or, respectively, `fun`). Note that each `popFront()` call will mirror the old `front` value, not the new one. This means that the last value will not be forwarded if the range isn't iterated until empty. If `No.pipeOnPop`, only elements for which `front` does get called will be also sent to `outputRange`/`fun`. If `front` is called twice for the same element, it will still be sent only once. If this caching is undesired, consider using [`std.algorithm.iteration.map`](std_algorithm_iteration#map) instead. |
| R1 `inputRange` | The input range being passed through. |
| R2 `outputRange` | This range will receive elements of `inputRange` progressively as iteration proceeds. |
| fun | This function will be called with elements of `inputRange` progressively as iteration proceeds. |


 
Returns:
An input range that offers the elements of `inputRange`. Regardless of whether `inputRange` is a more powerful range (forward, bidirectional etc), the result is always an input range. Reading this causes `inputRange` to be iterated and returns its elements in turn. In addition, the same elements will be passed to `outputRange` or `fun` as well. 
 
See Also:
[`std.algorithm.iteration.each`](std_algorithm_iteration#each)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter, map;

// Sum values while copying
int[] values = [1, 4, 9, 16, 25];
int sum = 0;
auto newValues = values.tee!(a => sum += a).array;
assert(equal(newValues, values));
writeln(sum); // 1 + 4 + 9 + 16 + 25

// Count values that pass the first filter
int count = 0;
auto newValues4 = values.filter!(a => a < 10)
                        .tee!(a => count++)
                        .map!(a => a + 1)
                        .filter!(a => a < 10);

//Fine, equal also evaluates any lazy ranges passed to it.
//count is not 3 until equal evaluates newValues4
assert(equal(newValues4, [2, 5]));
writeln(count); // 3

```
 
  auto **padLeft**(R, E)(R r, E e, size\_t n)  
 Constraints: if ((isInputRange!R && hasLength!R || isForwardRange!R) && !is(CommonType!(ElementType!R, E) == void)); 
 
Extends the length of the input range `r` by padding out the start of the range with the element `e`. The element `e` must be of a common type with the element type of the range `r` as defined by [`std.traits.CommonType`](std_traits#CommonType). If `n` is less than the length of of `r`, then `r` is returned unmodified. 


If `r` is a string with Unicode characters in it, `padLeft` follows D's rules about length for strings, which is not the number of characters, or graphemes, but instead the number of encoding units. If you want to treat each grapheme as only one encoding unit long, then call [`std.uni.byGrapheme`](std_uni#byGrapheme) before calling this function.   
  
 If `r` has a length, then this is Ο(`1`). Otherwise, it's Ο(`r.length`). 

 
Parameters:


|  |  |
| --- | --- |
| R `r` | an [input range](std_range_primitives#isInputRange) with a length, or a forward range |
| E `e` | element to pad the range with |
| size\_t `n` | the length to pad to |


 
Returns:
A range containing the elements of the original range with the extra padding See Also: [`std.string.leftJustifier`](std_string#leftJustifier)

 
Examples:


```
import std.algorithm.comparison : equal;

assert([1, 2, 3, 4].padLeft(0, 6).equal([0, 0, 1, 2, 3, 4]));
assert([1, 2, 3, 4].padLeft(0, 3).equal([1, 2, 3, 4]));

assert("abc".padLeft('_', 6).equal("___abc"));

```
 
  auto **padRight**(R, E)(R r, E e, size\_t n)  
 Constraints: if (isInputRange!R && !isInfinite!R && !is(CommonType!(ElementType!R, E) == void)); 
 
Extend the length of the input range `r` by padding out the end of the range with the element `e`. The element `e` must be of a common type with the element type of the range `r` as defined by [`std.traits.CommonType`](std_traits#CommonType). If `n` is less than the length of of `r`, then the contents of `r` are returned. 


The range primitives that the resulting range provides depends whether or not `r` provides them. Except the functions `back` and `popBack`, which also require the range to have a length as well as `back` and `popBack` 

 
Parameters:


|  |  |
| --- | --- |
| R `r` | an [input range](std_range_primitives#isInputRange) with a length |
| E `e` | element to pad the range with |
| size\_t `n` | the length to pad to |


 
Returns:
A range containing the elements of the original range with the extra padding See Also: [`std.string.rightJustifier`](std_string#rightJustifier)

 
Examples:


```
import std.algorithm.comparison : equal;

assert([1, 2, 3, 4].padRight(0, 6).equal([1, 2, 3, 4, 0, 0]));
assert([1, 2, 3, 4].padRight(0, 4).equal([1, 2, 3, 4]));

assert("abc".padRight('_', 6).equal("abc___"));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_range.html>

etc.c.odbc.sqlext
=================

 Declarations for interfacing with the ODBC library. 


Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;1@digitaldaemon.com)).   
  
 `etc.c.odbc.sqlext` corresponds to the `sqlext.h` C header file. 

 
See Also:
 [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference)


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_odbc_sqlext.html>

std.uni
=======

 The `std.uni` module provides an implementation of fundamental Unicode algorithms and data structures. This doesn't include UTF encoding and decoding primitives, see [`std.utf.decode`](std_utf#decode) and [`std.utf.encode`](std_utf#encode) in [`std.utf`](std_utf) for this functionality. 

 

| Category | Functions |
| --- | --- |
| Decode | [`byCodePoint`](#byCodePoint) [`byGrapheme`](#byGrapheme) [`decodeGrapheme`](#decodeGrapheme) [`graphemeStride`](#graphemeStride) |
| Comparison | [`icmp`](#icmp) [`sicmp`](#sicmp) |
| Classification | [`isAlpha`](#isAlpha) [`isAlphaNum`](#isAlphaNum) [`isCodepointSet`](#isCodepointSet) [`isControl`](#isControl) [`isFormat`](#isFormat) [`isGraphical`](#isGraphical) [`isIntegralPair`](#isIntegralPair) [`isMark`](#isMark) [`isNonCharacter`](#isNonCharacter) [`isNumber`](#isNumber) [`isPrivateUse`](#isPrivateUse) [`isPunctuation`](#isPunctuation) [`isSpace`](#isSpace) [`isSurrogate`](#isSurrogate) [`isSurrogateHi`](#isSurrogateHi) [`isSurrogateLo`](#isSurrogateLo) [`isSymbol`](#isSymbol) [`isWhite`](#isWhite) |
| Normalization | [`NFC`](#NFC) [`NFD`](#NFD) [`NFKD`](#NFKD) [`NormalizationForm`](#NormalizationForm) [`normalize`](#normalize) |
| Decompose | [`decompose`](#decompose) [`decomposeHangul`](#decomposeHangul) [`UnicodeDecomposition`](#UnicodeDecomposition) |
| Compose | [`compose`](#compose) [`composeJamo`](#composeJamo) |
| Sets | [`CodepointInterval`](#CodepointInterval) [`CodepointSet`](#CodepointSet) [`InversionList`](#InversionList) [`unicode`](#unicode) |
| Trie | [`codepointSetTrie`](#codepointSetTrie) [`CodepointSetTrie`](#CodepointSetTrie) [`codepointTrie`](#codepointTrie) [`CodepointTrie`](#CodepointTrie) [`toTrie`](#toTrie) [`toDelegate`](#toDelegate) |
| Casing | [`asCapitalized`](#asCapitalized) [`asLowerCase`](#asLowerCase) [`asUpperCase`](#asUpperCase) [`isLower`](#isLower) [`isUpper`](#isUpper) [`toLower`](#toLower) [`toLowerInPlace`](#toLowerInPlace) [`toUpper`](#toUpper) [`toUpperInPlace`](#toUpperInPlace) |
| Utf8Matcher | [`isUtfMatcher`](#isUtfMatcher) [`MatcherConcept`](#MatcherConcept) [`utfMatcher`](#utfMatcher) |
| Separators | [`lineSep`](#lineSep) [`nelSep`](#nelSep) [`paraSep`](#paraSep) |
| Building blocks | [`allowedIn`](#allowedIn) [`combiningClass`](#combiningClass) [`Grapheme`](#Grapheme) |

   
  
 All primitives listed operate on Unicode characters and sets of characters. For functions which operate on ASCII characters and ignore Unicode [characters](#Character), see [`std.ascii`](std_ascii). For definitions of Unicode [character](#Character), [code point](#Code%20point) and other terms used throughout this module see the [terminology](#Terminology) section below. 

 The focus of this module is the core needs of developing Unicode-aware applications. To that effect it provides the following optimized primitives: 

 * Character classification by category and common properties: [`isAlpha`](#isAlpha), [`isWhite`](#isWhite) and others.
* Case-insensitive string comparison ([`sicmp`](#sicmp), [`icmp`](#icmp)).
* Converting text to any of the four normalization forms via [`normalize`](#normalize).
* Decoding ([`decodeGrapheme`](#decodeGrapheme)) and iteration ([`byGrapheme`](#byGrapheme), [`graphemeStride`](#graphemeStride)) by user-perceived characters, that is by [`Grapheme`](#Grapheme) clusters.
* Decomposing and composing of individual character(s) according to canonical or compatibility rules, see [`compose`](#compose) and [`decompose`](#decompose), including the specific version for Hangul syllables [`composeJamo`](#composeJamo) and [`decomposeHangul`](#decomposeHangul).

 It's recognized that an application may need further enhancements and extensions, such as less commonly known algorithms, or tailoring existing ones for region specific needs. To help users with building any extra functionality beyond the core primitives, the module provides: 

 * [`CodepointSet`](#CodepointSet), a type for easy manipulation of sets of characters. Besides the typical set algebra it provides an unusual feature: a D source code generator for detection of [code points](#Code%20point) in this set. This is a boon for meta-programming parser frameworks, and is used internally to power classification in small sets like [`isWhite`](#isWhite).
* A way to construct optimal packed multi-stage tables also known as a special case of [Trie](https://en.wikipedia.org/wiki/Trie). The functions [`codepointTrie`](#codepointTrie), [`codepointSetTrie`](#codepointSetTrie) construct custom tries that map dchar to value. The end result is a fast and predictable Ο(`1`) lookup that powers functions like [`isAlpha`](#isAlpha) and [`combiningClass`](#combiningClass), but for user-defined data sets.
* A useful technique for Unicode-aware parsers that perform character classification of encoded [code points](#Code%20point) is to avoid unnecassary decoding at all costs. [`utfMatcher`](#utfMatcher) provides an improvement over the usual workflow of decode-classify-process, combining the decoding and classification steps. By extracting necessary bits directly from encoded [code units](#Code%20unit) matchers achieve significant performance improvements. See [`MatcherConcept`](#MatcherConcept) for the common interface of UTF matchers.
* Generally useful building blocks for customized normalization: [`combiningClass`](#combiningClass) for querying combining class and [`allowedIn`](#allowedIn) for testing the Quick\_Check property of a given normalization form.
* Access to a large selection of commonly used sets of [code points](#Code%20point). [Supported sets](#Unicode%20properties) include Script, Block and General Category. The exact contents of a set can be observed in the CLDR utility, on the [property index](http://www.unicode.org/cldr/utility/properties.jsp) page of the Unicode website. See [`unicode`](#unicode) for easy and (optionally) compile-time checked set queries.

 ### Synopsis

 
```
import std.uni;
void main()
{
    // initialize code point sets using script/block or property name
    // now 'set' contains code points from both scripts.
    auto set = unicode("Cyrillic") | unicode("Armenian");
    // same thing but simpler and checked at compile-time
    auto ascii = unicode.ASCII;
    auto currency = unicode.Currency_Symbol;

    // easy set ops
    auto a = set & ascii;
    assert(a.empty); // as it has no intersection with ascii
    a = set | ascii;
    auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian

    // some properties of code point sets
    assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2
    // testing presence of a code point in a set
    // is just fine, it is O(logN)
    assert(!b['$']);
    assert(!b['\u058F']); // Armenian dram sign
    assert(b['¥']);

    // building fast lookup tables, these guarantee O(1) complexity
    // 1-level Trie lookup table essentially a huge bit-set ~262Kb
    auto oneTrie = toTrie!1(b);
    // 2-level far more compact but typically slightly slower
    auto twoTrie = toTrie!2(b);
    // 3-level even smaller, and a bit slower yet
    auto threeTrie = toTrie!3(b);
    assert(oneTrie['£']);
    assert(twoTrie['£']);
    assert(threeTrie['£']);

    // build the trie with the most sensible trie level
    // and bind it as a functor
    auto cyrillicOrArmenian = toDelegate(set);
    auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!");
    assert(balance == "ընկեր!");
    // compatible with bool delegate(dchar)
    bool delegate(dchar) bindIt = cyrillicOrArmenian;

    // Normalization
    string s = "Plain ascii (and not only), is always normalized!";
    assert(s is normalize(s));// is the same string

    string nonS = "A\u0308ffin"; // A ligature
    auto nS = normalize(nonS); // to NFC, the W3C endorsed standard
    assert(nS == "Äffin");
    assert(nS != nonS);
    string composed = "Äffin";

    assert(normalize!NFD(composed) == "A\u0308ffin");
    // to NFKD, compatibility decomposition useful for fuzzy matching/searching
    assert(normalize!NFKD("2¹⁰") == "210");
}

```
 ### Terminology

 The following is a list of important Unicode notions and definitions. Any conventions used specifically in this module alone are marked as such. The descriptions are based on the formal definition as found in  [chapter three of The Unicode Standard Core Specification.](http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf) 


*Abstract character* A unit of information used for the organization, control, or representation of textual data. Note that: * When representing data, the nature of that data is generally symbolic as opposed to some other kind of data (for example, visual).
* An abstract character has no concrete form and should not be confused with a [glyph](#Glyph).
* An abstract character does not necessarily correspond to what a user thinks of as a “character” and should not be confused with a [`Grapheme`](#Grapheme).
* The abstract characters encoded (see Encoded character) are known as Unicode abstract characters.
* Abstract characters not directly encoded by the Unicode Standard can often be represented by the use of combining character sequences.


*Canonical decomposition* The decomposition of a character or character sequence that results from recursively applying the canonical mappings found in the Unicode Character Database and these described in Conjoining Jamo Behavior (section 12 of [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf)). 
*Canonical composition* The precise definition of the Canonical composition is the algorithm as specified in  [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf) section 11. Informally it's the process that does the reverse of the canonical decomposition with the addition of certain rules that e.g. prevent legacy characters from appearing in the composed result. 
*Canonical equivalent* Two character sequences are said to be canonical equivalents if their full canonical decompositions are identical. 
*Character* Typically differs by context. For the purpose of this documentation the term *character* implies *encoded character*, that is, a code point having an assigned abstract character (a symbolic meaning). 
*Code point* Any value in the Unicode codespace; that is, the range of integers from 0 to 10FFFF (hex). Not all code points are assigned to encoded characters. 
*Code unit* The minimal bit combination that can represent a unit of encoded text for processing or interchange. Depending on the encoding this could be: 8-bit code units in the UTF-8 (`char`), 16-bit code units in the UTF-16 (`wchar`), and 32-bit code units in the UTF-32 (`dchar`). *Note that in UTF-32, a code unit is a code point and is represented by the D `dchar` type.*
*Combining character* A character with the General Category of Combining Mark(M). * All characters with non-zero canonical combining class are combining characters, but the reverse is not the case: there are combining characters with a zero combining class.
* These characters are not normally used in isolation unless they are being described. They include such characters as accents, diacritics, Hebrew points, Arabic vowel signs, and Indic matras.


*Combining class* A numerical value used by the Unicode Canonical Ordering Algorithm to determine which sequences of combining marks are to be considered canonically equivalent and which are not. 
*Compatibility decomposition* The decomposition of a character or character sequence that results from recursively applying both the compatibility mappings and the canonical mappings found in the Unicode Character Database, and those described in Conjoining Jamo Behavior no characters can be further decomposed. 
*Compatibility equivalent* Two character sequences are said to be compatibility equivalents if their full compatibility decompositions are identical. 
*Encoded character* An association (or mapping) between an abstract character and a code point. 
*Glyph* The actual, concrete image of a glyph representation having been rasterized or otherwise imaged onto some display surface. 
*Grapheme base* A character with the property Grapheme\_Base, or any standard Korean syllable block. 
*Grapheme cluster* Defined as the text between grapheme boundaries as specified by Unicode Standard Annex #29, [Unicode text segmentation](http://www.unicode.org/reports/tr29/). Important general properties of a grapheme: * The grapheme cluster represents a horizontally segmentable unit of text, consisting of some grapheme base (which may consist of a Korean syllable) together with any number of nonspacing marks applied to it.
* A grapheme cluster typically starts with a grapheme base and then extends across any subsequent sequence of nonspacing marks. A grapheme cluster is most directly relevant to text rendering and processes such as cursor placement and text selection in editing, but may also be relevant to comparison and searching.
* For many processes, a grapheme cluster behaves as if it was a single character with the same properties as its grapheme base. Effectively, nonspacing marks apply *graphically* to the base, but do not change its properties.

 This module defines a number of primitives that work with graphemes: [`Grapheme`](#Grapheme), [`decodeGrapheme`](#decodeGrapheme) and [`graphemeStride`](#graphemeStride). All of them are using *extended grapheme* boundaries as defined in the aforementioned standard annex. 


*Nonspacing mark* A combining character with the General Category of Nonspacing Mark (Mn) or Enclosing Mark (Me). 
*Spacing mark* A combining character that is not a nonspacing mark. ### Normalization

 The concepts of [canonical equivalent](#Canonical%20equivalent) or [compatibility equivalent](#Compatibility%20equivalent) characters in the Unicode Standard make it necessary to have a full, formal definition of equivalence for Unicode strings. String equivalence is determined by a process called normalization, whereby strings are converted into forms which are compared directly for identity. This is the primary goal of the normalization process, see the function [`normalize`](#normalize) to convert into any of the four defined forms. 

 A very important attribute of the Unicode Normalization Forms is that they must remain stable between versions of the Unicode Standard. A Unicode string normalized to a particular Unicode Normalization Form in one version of the standard is guaranteed to remain in that Normalization Form for implementations of future versions of the standard. 

 The Unicode Standard specifies four normalization forms. Informally, two of these forms are defined by maximal decomposition of equivalent sequences, and two of these forms are defined by maximal *composition* of equivalent sequences. 


* Normalization Form D (NFD): The  [canonical decomposition](#Canonical%20decomposition) of a character sequence.
* Normalization Form KD (NFKD): The  [compatibility decomposition](#Compatibility%20decomposition) of a character sequence.
* Normalization Form C (NFC): The canonical composition of the [canonical decomposition](#Canonical%20decomposition) of a coded character sequence.
* Normalization Form KC (NFKC): The canonical composition of the  [compatibility decomposition](#Compatibility%20decomposition) of a character sequence

 The choice of the normalization form depends on the particular use case. NFC is the best form for general text, since it's more compatible with strings converted from legacy encodings. NFKC is the preferred form for identifiers, especially where there are security concerns. NFD and NFKD are the most useful for internal processing. 

 ### Construction of lookup tables

 The Unicode standard describes a set of algorithms that depend on having the ability to quickly look up various properties of a code point. Given the the codespace of about 1 million [code points](#Code%20point), it is not a trivial task to provide a space-efficient solution for the multitude of properties. 

 Common approaches such as hash-tables or binary search over sorted code point intervals (as in [`InversionList`](#InversionList)) are insufficient. Hash-tables have enormous memory footprint and binary search over intervals is not fast enough for some heavy-duty algorithms. 

 The recommended solution (see Unicode Implementation Guidelines) is using multi-stage tables that are an implementation of the [Trie](http://en.wikipedia.org/wiki/Trie) data structure with integer keys and a fixed number of stages. For the remainder of the section this will be called a fixed trie. The following describes a particular implementation that is aimed for the speed of access at the expense of ideal size savings. 

 Taking a 2-level Trie as an example the principle of operation is as follows. Split the number of bits in a key (code point, 21 bits) into 2 components (e.g. 15 and 8). The first is the number of bits in the index of the trie and the other is number of bits in each page of the trie. The layout of the trie is then an array of size 2^^bits-of-index followed an array of memory chunks of size 2^^bits-of-page/bits-per-element. 

 The number of pages is variable (but not less then 1) unlike the number of entries in the index. The slots of the index all have to contain a number of a page that is present. The lookup is then just a couple of operations - slice the upper bits, lookup an index for these, take a page at this index and use the lower bits as an offset within this page. 


  
  
 Assuming that pages are laid out consequently in one array at `pages`, the pseudo-code is: 
```
auto elemsPerPage = (2 ^^ bits_per_page) / Value.sizeOfInBits;
pages[index[n >> bits_per_page]][n & (elemsPerPage - 1)];

```
 Where if `elemsPerPage` is a power of 2 the whole process is a handful of simple instructions and 2 array reads. Subsequent levels of the trie are introduced by recursing on this notion - the index array is treated as values. The number of bits in index is then again split into 2 parts, with pages over 'current-index' and the new 'upper-index'. 

   
  
 For completeness a level 1 trie is simply an array. The current implementation takes advantage of bit-packing values when the range is known to be limited in advance (such as `bool`). See also [`BitPacked`](#BitPacked) for enforcing it manually. The major size advantage however comes from the fact that multiple **identical pages on every level are merged** by construction. 

 The process of constructing a trie is more involved and is hidden from the user in a form of the convenience functions [`codepointTrie`](#codepointTrie), [`codepointSetTrie`](#codepointSetTrie) and the even more convenient [`toTrie`](#toTrie). In general a set or built-in AA with `dchar` type can be turned into a trie. The trie object in this module is read-only (immutable); it's effectively frozen after construction. 

 ### Unicode properties

 This is a full list of Unicode properties accessible through [`unicode`](#unicode) with specific helpers per category nested within. Consult the [CLDR utility](http://www.unicode.org/cldr/utility/properties.jsp) when in doubt about the contents of a particular set. 

 General category sets listed below are only accessible with the [`unicode`](#unicode) shorthand accessor.

 

**General category** | Abb. | Long form | Abb. | Long form | Abb. | Long form |
| L | Letter | Cn | Unassigned | Po | Other\_Punctuation |
| Ll | Lowercase\_Letter | Co | Private\_Use | Ps | Open\_Punctuation |
| Lm | Modifier\_Letter | Cs | Surrogate | S | Symbol |
| Lo | Other\_Letter | N | Number | Sc | Currency\_Symbol |
| Lt | Titlecase\_Letter | Nd | Decimal\_Number | Sk | Modifier\_Symbol |
| Lu | Uppercase\_Letter | Nl | Letter\_Number | Sm | Math\_Symbol |
| M | Mark | No | Other\_Number | So | Other\_Symbol |
| Mc | Spacing\_Mark | P | Punctuation | Z | Separator |
| Me | Enclosing\_Mark | Pc | Connector\_Punctuation | Zl | Line\_Separator |
| Mn | Nonspacing\_Mark | Pd | Dash\_Punctuation | Zp | Paragraph\_Separator |
| C | Other | Pe | Close\_Punctuation | Zs | Space\_Separator |
| Cc | Control | Pf | Final\_Punctuation | - | Any |
| Cf | Format | Pi | Initial\_Punctuation | - | ASCII |

 Sets for other commonly useful properties that are accessible with [`unicode`](#unicode):

 

**Common binary properties**| Name | Name | Name |
| Alphabetic | Ideographic | Other\_Uppercase |
| ASCII\_Hex\_Digit | IDS\_Binary\_Operator | Pattern\_Syntax |
| Bidi\_Control | ID\_Start | Pattern\_White\_Space |
| Cased | IDS\_Trinary\_Operator | Quotation\_Mark |
| Case\_Ignorable | Join\_Control | Radical |
| Dash | Logical\_Order\_Exception | Soft\_Dotted |
| Default\_Ignorable\_Code\_Point | Lowercase | STerm |
| Deprecated | Math | Terminal\_Punctuation |
| Diacritic | Noncharacter\_Code\_Point | Unified\_Ideograph |
| Extender | Other\_Alphabetic | Uppercase |
| Grapheme\_Base | Other\_Default\_Ignorable\_Code\_Point | Variation\_Selector |
| Grapheme\_Extend | Other\_Grapheme\_Extend | White\_Space |
| Grapheme\_Link | Other\_ID\_Continue | XID\_Continue |
| Hex\_Digit | Other\_ID\_Start | XID\_Start |
| Hyphen | Other\_Lowercase |
| ID\_Continue | Other\_Math |

 Below is the table with block names accepted by [`unicode.block`](#unicode.block). Note that the shorthand version [`unicode`](#unicode) requires "In" to be prepended to the names of blocks so as to disambiguate scripts and blocks. 

 

**Blocks**| Aegean Numbers | Ethiopic Extended | Mongolian |
| Alchemical Symbols | Ethiopic Extended-A | Musical Symbols |
| Alphabetic Presentation Forms | Ethiopic Supplement | Myanmar |
| Ancient Greek Musical Notation | General Punctuation | Myanmar Extended-A |
| Ancient Greek Numbers | Geometric Shapes | New Tai Lue |
| Ancient Symbols | Georgian | NKo |
| Arabic | Georgian Supplement | Number Forms |
| Arabic Extended-A | Glagolitic | Ogham |
| Arabic Mathematical Alphabetic Symbols | Gothic | Ol Chiki |
| Arabic Presentation Forms-A | Greek and Coptic | Old Italic |
| Arabic Presentation Forms-B | Greek Extended | Old Persian |
| Arabic Supplement | Gujarati | Old South Arabian |
| Armenian | Gurmukhi | Old Turkic |
| Arrows | Halfwidth and Fullwidth Forms | Optical Character Recognition |
| Avestan | Hangul Compatibility Jamo | Oriya |
| Balinese | Hangul Jamo | Osmanya |
| Bamum | Hangul Jamo Extended-A | Phags-pa |
| Bamum Supplement | Hangul Jamo Extended-B | Phaistos Disc |
| Basic Latin | Hangul Syllables | Phoenician |
| Batak | Hanunoo | Phonetic Extensions |
| Bengali | Hebrew | Phonetic Extensions Supplement |
| Block Elements | High Private Use Surrogates | Playing Cards |
| Bopomofo | High Surrogates | Private Use Area |
| Bopomofo Extended | Hiragana | Rejang |
| Box Drawing | Ideographic Description Characters | Rumi Numeral Symbols |
| Brahmi | Imperial Aramaic | Runic |
| Braille Patterns | Inscriptional Pahlavi | Samaritan |
| Buginese | Inscriptional Parthian | Saurashtra |
| Buhid | IPA Extensions | Sharada |
| Byzantine Musical Symbols | Javanese | Shavian |
| Carian | Kaithi | Sinhala |
| Chakma | Kana Supplement | Small Form Variants |
| Cham | Kanbun | Sora Sompeng |
| Cherokee | Kangxi Radicals | Spacing Modifier Letters |
| CJK Compatibility | Kannada | Specials |
| CJK Compatibility Forms | Katakana | Sundanese |
| CJK Compatibility Ideographs | Katakana Phonetic Extensions | Sundanese Supplement |
| CJK Compatibility Ideographs Supplement | Kayah Li | Superscripts and Subscripts |
| CJK Radicals Supplement | Kharoshthi | Supplemental Arrows-A |
| CJK Strokes | Khmer | Supplemental Arrows-B |
| CJK Symbols and Punctuation | Khmer Symbols | Supplemental Mathematical Operators |
| CJK Unified Ideographs | Lao | Supplemental Punctuation |
| CJK Unified Ideographs Extension A | Latin-1 Supplement | Supplementary Private Use Area-A |
| CJK Unified Ideographs Extension B | Latin Extended-A | Supplementary Private Use Area-B |
| CJK Unified Ideographs Extension C | Latin Extended Additional | Syloti Nagri |
| CJK Unified Ideographs Extension D | Latin Extended-B | Syriac |
| Combining Diacritical Marks | Latin Extended-C | Tagalog |
| Combining Diacritical Marks for Symbols | Latin Extended-D | Tagbanwa |
| Combining Diacritical Marks Supplement | Lepcha | Tags |
| Combining Half Marks | Letterlike Symbols | Tai Le |
| Common Indic Number Forms | Limbu | Tai Tham |
| Control Pictures | Linear B Ideograms | Tai Viet |
| Coptic | Linear B Syllabary | Tai Xuan Jing Symbols |
| Counting Rod Numerals | Lisu | Takri |
| Cuneiform | Low Surrogates | Tamil |
| Cuneiform Numbers and Punctuation | Lycian | Telugu |
| Currency Symbols | Lydian | Thaana |
| Cypriot Syllabary | Mahjong Tiles | Thai |
| Cyrillic | Malayalam | Tibetan |
| Cyrillic Extended-A | Mandaic | Tifinagh |
| Cyrillic Extended-B | Mathematical Alphanumeric Symbols | Transport And Map Symbols |
| Cyrillic Supplement | Mathematical Operators | Ugaritic |
| Deseret | Meetei Mayek | Unified Canadian Aboriginal Syllabics |
| Devanagari | Meetei Mayek Extensions | Unified Canadian Aboriginal Syllabics Extended |
| Devanagari Extended | Meroitic Cursive | Vai |
| Dingbats | Meroitic Hieroglyphs | Variation Selectors |
| Domino Tiles | Miao | Variation Selectors Supplement |
| Egyptian Hieroglyphs | Miscellaneous Mathematical Symbols-A | Vedic Extensions |
| Emoticons | Miscellaneous Mathematical Symbols-B | Vertical Forms |
| Enclosed Alphanumerics | Miscellaneous Symbols | Yijing Hexagram Symbols |
| Enclosed Alphanumeric Supplement | Miscellaneous Symbols and Arrows | Yi Radicals |
| Enclosed CJK Letters and Months | Miscellaneous Symbols And Pictographs | Yi Syllables |
| Enclosed Ideographic Supplement | Miscellaneous Technical |
| Ethiopic | Modifier Tone Letters |

 Below is the table with script names accepted by [`unicode.script`](#unicode.script) and by the shorthand version [`unicode`](#unicode):

 

**Scripts**| Arabic | Hanunoo | Old\_Italic |
| Armenian | Hebrew | Old\_Persian |
| Avestan | Hiragana | Old\_South\_Arabian |
| Balinese | Imperial\_Aramaic | Old\_Turkic |
| Bamum | Inherited | Oriya |
| Batak | Inscriptional\_Pahlavi | Osmanya |
| Bengali | Inscriptional\_Parthian | Phags\_Pa |
| Bopomofo | Javanese | Phoenician |
| Brahmi | Kaithi | Rejang |
| Braille | Kannada | Runic |
| Buginese | Katakana | Samaritan |
| Buhid | Kayah\_Li | Saurashtra |
| Canadian\_Aboriginal | Kharoshthi | Sharada |
| Carian | Khmer | Shavian |
| Chakma | Lao | Sinhala |
| Cham | Latin | Sora\_Sompeng |
| Cherokee | Lepcha | Sundanese |
| Common | Limbu | Syloti\_Nagri |
| Coptic | Linear\_B | Syriac |
| Cuneiform | Lisu | Tagalog |
| Cypriot | Lycian | Tagbanwa |
| Cyrillic | Lydian | Tai\_Le |
| Deseret | Malayalam | Tai\_Tham |
| Devanagari | Mandaic | Tai\_Viet |
| Egyptian\_Hieroglyphs | Meetei\_Mayek | Takri |
| Ethiopic | Meroitic\_Cursive | Tamil |
| Georgian | Meroitic\_Hieroglyphs | Telugu |
| Glagolitic | Miao | Thaana |
| Gothic | Mongolian | Thai |
| Greek | Myanmar | Tibetan |
| Gujarati | New\_Tai\_Lue | Tifinagh |
| Gurmukhi | Nko | Ugaritic |
| Han | Ogham | Vai |
| Hangul | Ol\_Chiki | Yi |

 Below is the table of names accepted by [`unicode.hangulSyllableType`](#unicode.hangulSyllableType).

 

**Hangul syllable type**| Abb. | Long form |
| L | Leading\_Jamo |
| LV | LV\_Syllable |
| LVT | LVT\_Syllable |
| T | Trailing\_Jamo |
| V | Vowel\_Jamo |

 
References
 [ASCII Table](http://www.digitalmars.com/d/ascii-table.html), [Wikipedia](http://en.wikipedia.org/wiki/Unicode), [The Unicode Consortium](http://www.unicode.org), [Unicode normalization forms](http://www.unicode.org/reports/tr15/), [Unicode text segmentation](http://www.unicode.org/reports/tr29/)  [Unicode Implementation Guidelines](http://www.unicode.org/uni2book/ch05.pdf)  [Unicode Conformance](http://www.unicode.org/uni2book/ch03.pdf) 
 
Trademarks
 Unicode(tm) is a trademark of Unicode, Inc. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Dmitry Olshansky 
 
Source
 [std/uni/package.d](https://github.com/dlang/phobos/blob/master/std/uni/package.d) 
 
Standards:

[Unicode v6.2](http://www.unicode.org/versions/Unicode6.2.0/) 
 
enum dchar **lineSep**;  
Constant [code point](#Code%20point) (0x2028) - line separator.

  enum dchar **paraSep**;  
Constant [code point](#Code%20point) (0x2029) - paragraph separator.

  enum dchar **nelSep**;  
Constant [code point](#Code%20point) (0x0085) - next line.

  template **isCodepointSet**(T) 
Tests if T is some kind a set of code points. Intended for template constraints.

  enum auto **isIntegralPair**(T, V = uint);  
 Tests if `T` is a pair of integers that implicitly convert to `V`. The following code must compile for any pair `T`: 
```
(T x){ V a = x[0]; V b = x[1];}

```
 The following must not compile: 
```
(T x){ V c = x[2];}

```
 

  alias **CodepointSet** = InversionList!(GcPolicy).InversionList;  
The recommended default type for set of [code points](#Code%20point). For details, see the current implementation: [`InversionList`](#InversionList).

  struct **CodepointInterval**;  
The recommended type of [`std.typecons.Tuple`](std_typecons#Tuple) to represent [a, b) intervals of [code points](#Code%20point). As used in [`InversionList`](#InversionList). Any interval type should pass [`isIntegralPair`](#isIntegralPair) trait.

  struct **InversionList**(SP = GcPolicy);    `InversionList` is a set of [code points](#Code%20point) represented as an array of open-right [a, b) intervals (see [`CodepointInterval`](#CodepointInterval) above). The name comes from the way the representation reads left to right. For instance a set of all values [10, 50), [80, 90), plus a singular value 60 looks like this: 

 
```
10, 50, 60, 61, 80, 90

```
  The way to read this is: start with negative meaning that all numbers smaller then the next one are not present in this set (and positive - the contrary). Then switch positive/negative after each number passed from left to right. 

 This way negative spans until 10, then positive until 50, then negative until 60, then positive until 61, and so on. As seen this provides a space-efficient storage of highly redundant data that comes in long runs. A description which Unicode [character](#Character) properties fit nicely. The technique itself could be seen as a variation on [RLE encoding](https://en.wikipedia.org/wiki/Run-length_encoding). 

 Sets are value types (just like `int` is) thus they are never aliased. 

 
Example


```
auto a = CodepointSet('a', 'z'+1);
auto b = CodepointSet('A', 'Z'+1);
auto c = a;
a = a | b;
assert(a == CodepointSet('A', 'Z'+1, 'a', 'z'+1));
assert(a != c);

```
 See also [`unicode`](#unicode) for simpler construction of sets from predefined ones. 

 Memory usage is 8 bytes per each contiguous interval in a set. The value semantics are achieved by using the [COW](http://en.wikipedia.org/wiki/Copy-on-write) technique and thus it's not safe to cast this type to shared. 

 
Note

It's not recommended to rely on the template parameters or the exact type of a current [code point](#Code%20point) set in `std.uni`. The type and parameters may change when the standard allocators design is finalized. Use [`isCodepointSet`](#isCodepointSet) with templates or just stick with the default alias [`CodepointSet`](#CodepointSet) throughout the whole code base. 

 
pure this(Set)(Set set)  
 Constraints: if (isCodepointSet!Set); 
 
Construct from another code point set of any type.

  pure this(Range)(Range intervals)  
 Constraints: if (isForwardRange!Range && isIntegralPair!(ElementType!Range)); 
 
Construct a set from a forward range of code point intervals.

  this()(uint[] intervals...);  
Construct a set from plain values of code point intervals.



Examples:


```
import std.algorithm.comparison : equal;

auto set = CodepointSet('a', 'z'+1, 'а', 'я'+1);
foreach (v; 'a'..'z'+1)
    assert(set[v]);
// Cyrillic lowercase interval
foreach (v; 'а'..'я'+1)
    assert(set[v]);
//specific order is not required, intervals may interesect
auto set2 = CodepointSet('а', 'я'+1, 'a', 'd', 'b', 'z'+1);
//the same end result
assert(set2.byInterval.equal(set.byInterval));
// test constructor this(Range)(Range intervals)
auto chessPiecesWhite = CodepointInterval(9812, 9818);
auto chessPiecesBlack = CodepointInterval(9818, 9824);
auto set3 = CodepointSet([chessPiecesWhite, chessPiecesBlack]);
foreach (v; '♔'..'♟'+1)
    assert(set3[v]);

```
 
  @property scope auto **byInterval**();  
Get range that spans all of the [code point](#Code%20point) intervals in this [`InversionList`](#InversionList).

  const bool **opIndex**(uint val);  
Tests the presence of code point `val` in this set.



Examples:


```
auto gothic = unicode.Gothic;
// Gothic letter ahsa
assert(gothic['\U00010330']);
// no ascii in Gothic obviously
assert(!gothic['$']);

```
 
  @property size\_t **length**();  
Number of [code points](#Code%20point) in this set

  This **opBinary**(string op, U)(U rhs)  
 Constraints: if (isCodepointSet!U || is(U : dchar)); 
 
Sets support natural syntax for set algebra, namely: 

 

| Operator | Math notation | Description |
| --- | --- | --- |
| & | a ∩ b | intersection |
| | | a ∪ b | union |
| - | a ∖ b | subtraction |
| ~ | a ~ b | symmetric set difference i.e. (a ∪ b) \ (a ∩ b) |



Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;

auto lower = unicode.LowerCase;
auto upper = unicode.UpperCase;
auto ascii = unicode.ASCII;

assert((lower & upper).empty); // no intersection
auto lowerASCII = lower & ascii;
assert(lowerASCII.byCodepoint.equal(iota('a', 'z'+1)));
// throw away all of the lowercase ASCII
writeln((ascii - lower).length); // 128 - 26

auto onlyOneOf = lower ~ ascii;
assert(!onlyOneOf['Δ']); // not ASCII and not lowercase
assert(onlyOneOf['$']); // ASCII and not lowercase
assert(!onlyOneOf['a']); // ASCII and lowercase
assert(onlyOneOf['я']); // not ASCII but lowercase

// throw away all cased letters from ASCII
auto noLetters = ascii - (lower | upper);
writeln(noLetters.length); // 128 - 26 * 2

```
 
  ref This **opOpAssign**(string op, U)(U rhs)  
 Constraints: if (isCodepointSet!U || is(U : dchar)); 
 
The 'op=' versions of the above overloaded operators.

  const bool **opBinaryRight**(string op : "in", U)(U ch)  
 Constraints: if (is(U : dchar)); 
 
Tests the presence of codepoint `ch` in this set, the same as [`opIndex`](#opIndex).



Examples:


```
assert('я' in unicode.Cyrillic);
assert(!('z' in unicode.Cyrillic));

```
 
  auto **opUnary**(string op : "!")();  
Obtains a set that is the inversion of this set. 



See Also:
[`inverted`](#inverted)
  @property auto **byCodepoint**();  
A range that spans each [code point](#Code%20point) in this set.



Examples:


```
import std.algorithm.comparison : equal;
import std.range : iota;

auto set = unicode.ASCII;
set.byCodepoint.equal(iota(0, 0x80));

```
 
  void **toString**(Writer)(scope Writer sink, ref scope const FormatSpec!char fmt);  
Obtain a textual representation of this InversionList in form of open-right intervals. 


The formatting flag is applied individually to each value, for example: - **%s** and **%d** format the intervals as a [low .. high) range of integrals
 - **%x** formats the intervals as a [low .. high) range of lowercase hex characters
 - **%X** formats the intervals as a [low .. high) range of uppercase hex characters


 
Examples:


```
import std.conv : to;
import std.format : format;
import std.uni : unicode;

assert(unicode.Cyrillic.to!string ==
    "[1024..1157) [1159..1320) [7467..7468) [7544..7545) [11744..11776) [42560..42648) [42655..42656)");

// The specs '%s' and '%d' are equivalent to the to!string call above.
writeln(format("%d", unicode.Cyrillic)); // unicode.Cyrillic.to!string

assert(format("%#x", unicode.Cyrillic) ==
    "[0x400..0x485) [0x487..0x528) [0x1d2b..0x1d2c) [0x1d78..0x1d79) [0x2de0..0x2e00) "
    ~"[0xa640..0xa698) [0xa69f..0xa6a0)");

assert(format("%#X", unicode.Cyrillic) ==
    "[0X400..0X485) [0X487..0X528) [0X1D2B..0X1D2C) [0X1D78..0X1D79) [0X2DE0..0X2E00) "
    ~"[0XA640..0XA698) [0XA69F..0XA6A0)");

```
 
  ref auto **add**()(uint a, uint b);  
Add an interval [a, b) to this set.



Examples:


```
CodepointSet someSet;
someSet.add('0', '5').add('A','Z'+1);
someSet.add('5', '9'+1);
assert(someSet['0']);
assert(someSet['5']);
assert(someSet['9']);
assert(someSet['Z']);

```
 
  @property auto **inverted**();  
Obtains a set that is the inversion of this set. 


See the '!' [`opUnary`](#opUnary) for the same but using operators.

 
Examples:


```
auto set = unicode.ASCII;
// union with the inverse gets all of the code points in the Unicode
writeln((set | set.inverted).length); // 0x110000
// no intersection with the inverse
assert((set & set.inverted).empty);

```
 
  string **toSourceCode**(string funcName = "");  
Generates string with D source code of unary function with name of `funcName` taking a single `dchar` argument. If `funcName` is empty the code is adjusted to be a lambda function. 


The function generated tests if the [code point](#Code%20point) passed belongs to this set or not. The result is to be used with string mixin. The intended usage area is aggressive optimization via meta programming in parser generators and the like. 

 
Note
 Use with care for relatively small or regular sets. It could end up being slower then just using multi-staged tables. 
 
Example


```
import std.stdio;

// construct set directly from [a, b&dollar;RPAREN intervals
auto set = CodepointSet(10, 12, 45, 65, 100, 200);
writeln(set);
writeln(set.toSourceCode("func"));

```
 The above outputs something along the lines of: 
```
bool func(dchar ch)  @safe pure nothrow @nogc
{
    if (ch < 45)
    {
        if (ch == 10 || ch == 11) return true;
        return false;
    }
    else if (ch < 65) return true;
    else
    {
        if (ch < 100) return false;
        if (ch < 200) return true;
        return false;
    }
}

```
  const @property bool **empty**();  
True if this set doesn't contain any [code points](#Code%20point).



Examples:


```
CodepointSet emptySet;
writeln(emptySet.length); // 0
assert(emptySet.empty);

```
 
    template **codepointSetTrie**(sizes...) if (sumOfIntegerTuple!sizes == 21) 
A shorthand for creating a custom multi-level fixed Trie from a `CodepointSet`. `sizes` are numbers of bits per level, with the most significant bits used first. 



Note
 The sum of `sizes` must be equal 21. 
 
See Also:

[`toTrie`](#toTrie), which is even simpler. 
 
Example


```
{
    import std.stdio;
    auto set = unicode("Number");
    auto trie = codepointSetTrie!(8, 5, 8)(set);
    writeln("Input code points to test:");
    foreach (line; stdin.byLine)
    {
        int count=0;
        foreach (dchar ch; line)
            if (trie[ch])// is number
                count++;
        writefln("Contains %d number code points.", count);
    }
}

```
  template **CodepointSetTrie**(sizes...) if (sumOfIntegerTuple!sizes == 21) 
Type of Trie generated by codepointSetTrie function.

  template **codepointTrie**(T, sizes...) if (sumOfIntegerTuple!sizes == 21)  
  
template **CodepointTrie**(T, sizes...) if (sumOfIntegerTuple!sizes == 21) 
A slightly more general tool for building fixed `Trie` for the Unicode data. 


Specifically unlike `codepointSetTrie` it's allows creating mappings of `dchar` to an arbitrary type `T`. 

 
Note
 Overload taking `CodepointSet`s will naturally convert only to bool mapping `Trie`s. 
 CodepointTrie is the type of Trie as generated by codepointTrie function. 
auto **codepointTrie**()(T[dchar] map, T defValue = T.init);  auto **codepointTrie**(R)(R range, T defValue = T.init)  
 Constraints: if (isInputRange!R && is(typeof(ElementType!R.init[0]) : T) && is(typeof(ElementType!R.init[1]) : dchar)); 
   struct **MatcherConcept**;  
Conceptual type that outlines the common properties of all UTF Matchers. 



Note
 For illustration purposes only, every method call results in assertion failure. Use [`utfMatcher`](#utfMatcher) to obtain a concrete matcher for UTF-8 or UTF-16 encodings.
 
bool **match**(Range)(ref Range inp)  
 Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char));   
  
bool **skip**(Range)(ref Range inp)  
 Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char));   
  
bool **test**(Range)(ref Range inp)  
 Constraints: if (isRandomAccessRange!Range && is(ElementType!Range : char)); 
 
Perform a semantic equivalent 2 operations: decoding a [code point](#Code%20point) at front of `inp` and testing if it belongs to the set of [code points](#Code%20point) of this matcher. 

 The effect on `inp` depends on the kind of function called:

   
  
 Match. If the codepoint is found in the set then range `inp` is advanced by its size in [code units](#Code%20unit), otherwise the range is not modifed.

   
  
 Skip. The range is always advanced by the size of the tested [code point](#Code%20point) regardless of the result of test.

   
  
 Test. The range is left unaffected regardless of the result of test.

 
Examples:


```
string truth = "2² = 4";
auto m = utfMatcher!char(unicode.Number);
assert(m.match(truth)); // '2' is a number all right
assert(truth == "² = 4"); // skips on match
assert(m.match(truth)); // so is the superscript '2'
assert(!m.match(truth)); // space is not a number
assert(truth == " = 4"); // unaffected on no match
assert(!m.skip(truth)); // same test ...
assert(truth == "= 4"); // but skips a codepoint regardless
assert(!m.test(truth)); // '=' is not a number
assert(truth == "= 4"); // test never affects argument

```
 
  @property auto **subMatcher**(Lengths...)();  
Advanced feature - provide direct access to a subset of matcher based a set of known encoding lengths. Lengths are provided in [code units](#Code%20unit). The sub-matcher then may do less operations per any `test`/`match`. 


Use with care as the sub-matcher won't match any [code points](#Code%20point) that have encoded length that doesn't belong to the selected set of lengths. Also the sub-matcher object references the parent matcher and must not be used past the liftetime of the latter.   
  
 Another caveat of using sub-matcher is that skip is not available preciesly because sub-matcher doesn't detect all lengths.

    enum auto **isUtfMatcher**(M, C);  
Test if `M` is an UTF Matcher for ranges of `Char`.

  auto **utfMatcher**(Char, Set)(Set set)  
 Constraints: if (isCodepointSet!Set); 
 
Constructs a matcher object to classify [code points](#Code%20point) from the `set` for encoding that has `Char` as code unit. 


See [`MatcherConcept`](#MatcherConcept) for API outline.

  auto **toTrie**(size\_t level, Set)(Set set)  
 Constraints: if (isCodepointSet!Set); 
 
Convenience function to construct optimal configurations for packed Trie from any `set` of [code points](#Code%20point). 

The parameter `level` indicates the number of trie levels to use, allowed values are: 1, 2, 3 or 4. Levels represent different trade-offs speed-size wise.   
  
 Level 1 is fastest and the most memory hungry (a bit array). 

 Level 4 is the slowest and has the smallest footprint. 

   
  
 See the [Synopsis](#Synopsis) section for example. 
Note
 Level 4 stays very practical (being faster and more predictable) compared to using direct lookup on the `set` itself.
  auto **toDelegate**(Set)(Set set)  
 Constraints: if (isCodepointSet!Set); 
 
Builds a `Trie` with typically optimal speed-size trade-off and wraps it into a delegate of the following type: `bool delegate(dchar ch)`. 

 Effectively this creates a 'tester' lambda suitable for algorithms like std.algorithm.find that take unary predicates. 

   
  
 See the [Synopsis](#Synopsis) section for example.  struct **unicode**;  
A single entry point to lookup Unicode [code point](#Code%20point) sets by name or alias of a block, script or general category. 


It uses well defined standard rules of property name lookup. This includes fuzzy matching of names, so that 'White\_Space', 'white-SpAce' and 'whitespace' are all considered equal and yield the same set of white space [characters](#Character).

 
pure @property auto **opDispatch**(string name)();  
Performs the lookup of set of [code points](#Code%20point) with compile-time correctness checking. This short-cut version combines 3 searches: across blocks, scripts, and common binary properties. 


Note that since scripts and blocks overlap the usual trick to disambiguate is used - to get a block use `unicode.InBlockName`, to search a script use `unicode.ScriptName`. 

 
See Also:

[`block`](#block), [`script`](#script) and (not included in this search) [`hangulSyllableType`](#hangulSyllableType).
  auto **opCall**(C)(scope const C[] name)  
 Constraints: if (is(C : dchar)); 
 
The same lookup across blocks, scripts, or binary properties, but performed at run-time. This version is provided for cases where `name` is not known beforehand; otherwise compile-time checked [`opDispatch`](#opDispatch) is typically a better choice. 


See the [table of properties](#Unicode%20properties) for available sets.

  struct **block**;  
Narrows down the search for sets of [code points](#Code%20point) to all Unicode blocks. 



Note
 Here block names are unambiguous as no scripts are searched and thus to search use simply `unicode.block.BlockName` notation. 
 See [table of properties](#Unicode%20properties) for available sets. 
See Also:

[table of properties](#Unicode%20properties).
 
Examples:


```
// use .block for explicitness
writeln(unicode.block.Greek_and_Coptic); // unicode.InGreek_and_Coptic

```
 
  struct **script**;  
Narrows down the search for sets of [code points](#Code%20point) to all Unicode scripts. 


See the [table of properties](#Unicode%20properties) for available sets.

 
Examples:


```
auto arabicScript = unicode.script.arabic;
auto arabicBlock = unicode.block.arabic;
// there is an intersection between script and block
assert(arabicBlock['؁']);
assert(arabicScript['؁']);
// but they are different
assert(arabicBlock != arabicScript);
writeln(arabicBlock); // unicode.inArabic
writeln(arabicScript); // unicode.arabic

```
 
  struct **hangulSyllableType**;  
Fetch a set of [code points](#Code%20point) that have the given hangul syllable type. 


Other non-binary properties (once supported) follow the same notation - `unicode.propertyName.propertyValue` for compile-time checked access and `unicode.propertyName(propertyValue)` for run-time checked one.   
  
 See the [table of properties](#Unicode%20properties) for available sets.

 
Examples:


```
// L here is syllable type not Letter as in unicode.L short-cut
auto leadingVowel = unicode.hangulSyllableType("L");
// check that some leading vowels are present
foreach (vowel; '\u1110'..'\u115F')
    assert(leadingVowel[vowel]);
writeln(leadingVowel); // unicode.hangulSyllableType.L

```
 
  CodepointSet **parseSet**(Range)(ref Range range, bool casefold = false)  
 Constraints: if (isInputRange!Range && is(ElementType!Range : dchar)); 
 
Parse unicode codepoint set from given `range` using standard regex syntax '[...]'. The range is advanced skiping over regex set definition. `casefold` parameter determines if the set should be casefolded - that is include both lower and upper case versions for any letters in the set.

    pure @safe size\_t **graphemeStride**(C)(scope const C[] input, size\_t index)  
 Constraints: if (is(C : dchar)); 
 
Computes the length of grapheme cluster starting at `index`. Both the resulting length and the `index` are measured in [code units](#Code%20unit). 



Parameters:


|  |  |
| --- | --- |
| C | type that is implicitly convertible to `dchars` |
| C[] `input` | array of grapheme clusters |
| size\_t `index` | starting index into `input[]` |


 
Returns:
length of grapheme cluster
 
Examples:


```
writeln(graphemeStride("  ", 1)); // 1
// A + combing ring above
string city = "A\u030Arhus";
size_t first = graphemeStride(city, 0);
assert(first == 3); //\u030A has 2 UTF-8 code units
writeln(city[0 .. first]); // "A\u030A"
writeln(city[first .. $]); // "rhus"

```
 
  Grapheme **decodeGrapheme**(Input)(ref Input inp)  
 Constraints: if (isInputRange!Input && is(immutable(ElementType!Input) == immutable(dchar))); 
 
Reads one full grapheme cluster from an [input range](std_range_primitives#isInputRange) of dchar `inp`. 


For examples see the [`Grapheme`](#Grapheme) below. 

 
Note
 This function modifies `inp` and thus `inp` must be an L-value.
  auto **byGrapheme**(Range)(Range range)  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar))); 
 
Iterate a string by [`Grapheme`](#Grapheme).

 Useful for doing string manipulation that needs to be aware of graphemes.

 
See Also:
[`byCodePoint`](#byCodePoint)
 
Examples:


```
import std.algorithm.comparison : equal;
import std.range.primitives : walkLength;
import std.range : take, drop;
auto text = "noe\u0308l"; // noël using e + combining diaeresis
assert(text.walkLength == 5); // 5 code points

auto gText = text.byGrapheme;
assert(gText.walkLength == 4); // 4 graphemes

assert(gText.take(3).equal("noe\u0308".byGrapheme));
assert(gText.drop(3).equal("l".byGrapheme));

```
 
  auto **byCodePoint**(Range)(Range range)  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(Grapheme)));   
  
auto **byCodePoint**(Range)(Range range)  
 Constraints: if (isInputRange!Range && is(immutable(ElementType!Range) == immutable(dchar))); 
 
Lazily transform a range of [`Grapheme`](#Grapheme)s to a range of code points.

 Useful for converting the result to a string after doing operations on graphemes.

   
  
 If passed in a range of code points, returns a range with equivalent capabilities.

 
Examples:


```
import std.array : array;
import std.conv : text;
import std.range : retro;

string s = "noe\u0308l"; // noël

// reverse it and convert the result to a string
string reverse = s.byGrapheme
    .array
    .retro
    .byCodePoint
    .text;

assert(reverse == "le\u0308on"); // lëon

```
 
  struct **Grapheme**;  
A structure designed to effectively pack [characters](#Character) of a [grapheme cluster](#Grapheme%20cluster). 

 `Grapheme` has value semantics so 2 copies of a `Grapheme` always refer to distinct objects. In most actual scenarios a `Grapheme` fits on the stack and avoids memory allocation overhead for all but quite long clusters. 

 
See Also:

[`decodeGrapheme`](#decodeGrapheme), [`graphemeStride`](#graphemeStride)

 
this(C)(scope const C[] chars...)  
 Constraints: if (is(C : dchar));   
  
this(Input)(Input seq)  
 Constraints: if (!isDynamicArray!Input && isInputRange!Input && is(ElementType!Input : dchar)); 
 
Ctor

  const pure nothrow @nogc @trusted dchar **opIndex**(size\_t index);  
Gets a [code point](#Code%20point) at the given index in this cluster.

  pure nothrow @nogc @trusted void **opIndexAssign**(dchar ch, size\_t index);  
Writes a [code point](#Code%20point) `ch` at given index in this cluster. 



Warning
 Use of this facility may invalidate grapheme cluster, see also [`Grapheme.valid`](#Grapheme.valid).
 
Examples:


```
auto g = Grapheme("A\u0302");
writeln(g[0]); // 'A'
assert(g.valid);
g[1] = '~'; // ASCII tilda is not a combining mark
writeln(g[1]); // '~'
assert(!g.valid);

```
 
  pure nothrow @nogc @safe SliceOverIndexed!Grapheme **opSlice**(size\_t a, size\_t b) return;   
  
pure nothrow @nogc @safe SliceOverIndexed!Grapheme **opSlice**() return;  
Random-access range over Grapheme's [characters](#Character). 



Warning
 Invalidates when this Grapheme leaves the scope, attempts to use it then would lead to memory corruption.
  const pure nothrow @nogc @property @safe size\_t **length**();  
Grapheme cluster length in [code points](#Code%20point).

  ref @trusted auto **opOpAssign**(string op)(dchar ch);  
Append [character](#Character) `ch` to this grapheme. 



Warning
 Use of this facility may invalidate grapheme cluster, see also `valid`. 
 
See Also:
[`Grapheme.valid`](#Grapheme.valid)
 
Examples:


```
import std.algorithm.comparison : equal;
auto g = Grapheme("A");
assert(g.valid);
g ~= '\u0301';
assert(g[].equal("A\u0301"));
assert(g.valid);
g ~= "B";
// not a valid grapheme cluster anymore
assert(!g.valid);
// still could be useful though
assert(g[].equal("A\u0301B"));

```
 
  ref auto **opOpAssign**(string op, Input)(scope Input inp)  
 Constraints: if (isInputRange!Input && is(ElementType!Input : dchar)); 
 
Append all [characters](#Character) from the input range `inp` to this Grapheme.

  @property bool **valid**()();  
True if this object contains valid extended grapheme cluster. Decoding primitives of this module always return a valid `Grapheme`. 


Appending to and direct manipulation of grapheme's [characters](#Character) may render it no longer valid. Certain applications may chose to use Grapheme as a "small string" of any [code points](#Code%20point) and ignore this property entirely.

    int **sicmp**(S1, S2)(scope S1 r1, scope S2 r2)  
 Constraints: if (isInputRange!S1 && isSomeChar!(ElementEncodingType!S1) && isInputRange!S2 && isSomeChar!(ElementEncodingType!S2)); 
 
Does basic case-insensitive comparison of `r1` and `r2`. This function uses simpler comparison rule thus achieving better performance than [`icmp`](#icmp). However keep in mind the warning below.

 
Parameters:


|  |  |
| --- | --- |
| S1 `r1` | an [input range](std_range_primitives#isInputRange) of characters |
| S2 `r2` | an [input range](std_range_primitives#isInputRange) of characters |


 
Returns:
An `int` that is 0 if the strings match, <0 if `r1` is lexicographically "less" than `r2`, >0 if `r1` is lexicographically "greater" than `r2` 
 
Warning
 This function only handles 1:1 [code point](#Code%20point) mapping and thus is not sufficient for certain alphabets like German, Greek and few others. 
 
See Also:

[`icmp`](#icmp) [`std.algorithm.comparison.cmp`](std_algorithm_comparison#cmp)

 
Examples:


```
writeln(sicmp("Август", "авгусТ")); // 0
// Greek also works as long as there is no 1:M mapping in sight
writeln(sicmp("ΌΎ", "όύ")); // 0
// things like the following won't get matched as equal
// Greek small letter iota with dialytika and tonos
assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0);

// while icmp has no problem with that
writeln(icmp("ΐ", "\u03B9\u0308\u0301")); // 0
writeln(icmp("ΌΎ", "όύ")); // 0

```
 
  int **icmp**(S1, S2)(S1 r1, S2 r2)  
 Constraints: if (isForwardRange!S1 && isSomeChar!(ElementEncodingType!S1) && isForwardRange!S2 && isSomeChar!(ElementEncodingType!S2)); 
 
Does case insensitive comparison of `r1` and `r2`. Follows the rules of full case-folding mapping. This includes matching as equal german ß with "ss" and other 1:M [code point](#Code%20point) mappings unlike [`sicmp`](#sicmp). The cost of `icmp` being pedantically correct is slightly worse performance. 



Parameters:


|  |  |
| --- | --- |
| S1 `r1` | a forward range of characters |
| S2 `r2` | a forward range of characters |


 
Returns:
An `int` that is 0 if the strings match, <0 if `str1` is lexicographically "less" than `str2`, >0 if `str1` is lexicographically "greater" than `str2` 
 
See Also:

[`sicmp`](#sicmp) [`std.algorithm.comparison.cmp`](std_algorithm_comparison#cmp)

 
Examples:


```
writeln(icmp("Rußland", "Russland")); // 0
writeln(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ")); // 0

```
 
 
Examples:
By using [`std.utf.byUTF`](std_utf#byUTF) and its aliases, GC allocations via auto-decoding and thrown exceptions can be avoided, making `icmp` `@safe @nogc nothrow pure`. 
```
import std.utf : byDchar;

writeln(icmp("Rußland".byDchar, "Russland".byDchar)); // 0
writeln(icmp("ᾩ -> \u1F70\u03B9".byDchar, "\u1F61\u03B9 -> ᾲ".byDchar)); // 0

```
 
  pure nothrow @nogc @safe ubyte **combiningClass**(dchar ch);  
Returns the [combining class](#Combining%20class) of `ch`.



Examples:


```
// shorten the code
alias CC = combiningClass;

// combining tilda
writeln(CC('\u0303')); // 230
// combining ring below
writeln(CC('\u0325')); // 220
// the simple consequence is that  "tilda" should be
// placed after a "ring below" in a sequence

```
 
  enum **UnicodeDecomposition**: int;  
Unicode character decomposition type.

 
**Canonical** 
Canonical decomposition. The result is canonically equivalent sequence.

  **Compatibility** 
Compatibility decomposition. The result is compatibility equivalent sequence. 



Note
 Compatibility decomposition is a **lossy** conversion, typically suitable only for fuzzy matching and internal processing.
    pure nothrow @safe dchar **compose**(dchar first, dchar second);  
Try to canonically compose 2 [characters](#Character). Returns the composed [character](#Character) if they do compose and dchar.init otherwise. 


The assumption is that `first` comes before `second` in the original text, usually meaning that the first is a starter. 

 
Note
 Hangul syllables are not covered by this function. See `composeJamo` below.
 
Examples:


```
writeln(compose('A', '\u0308')); // '\u00C4'
writeln(compose('A', 'B')); // dchar.init
writeln(compose('C', '\u0301')); // '\u0106'
// note that the starter is the first one
// thus the following doesn't compose
writeln(compose('\u0308', 'A')); // dchar.init

```
 
  @safe Grapheme **decompose**(UnicodeDecomposition decompType = Canonical)(dchar ch);  
Returns a full [Canonical](#Canonical%20decomposition) (by default) or [Compatibility](#Compatibility%20decomposition) decomposition of [character](#Character) `ch`. If no decomposition is available returns a [`Grapheme`](#Grapheme) with the `ch` itself. 



Note
 This function also decomposes hangul syllables as prescribed by the standard. 
 
See Also:

[`decomposeHangul`](#decomposeHangul) for a restricted version that takes into account only hangul syllables but no other decompositions.
 
Examples:


```
import std.algorithm.comparison : equal;

writeln(compose('A', '\u0308')); // '\u00C4'
writeln(compose('A', 'B')); // dchar.init
writeln(compose('C', '\u0301')); // '\u0106'
// note that the starter is the first one
// thus the following doesn't compose
writeln(compose('\u0308', 'A')); // dchar.init

assert(decompose('Ĉ')[].equal("C\u0302"));
assert(decompose('D')[].equal("D"));
assert(decompose('\uD4DC')[].equal("\u1111\u1171\u11B7"));
assert(decompose!Compatibility('¹')[].equal("1"));

```
 
  @safe Grapheme **decomposeHangul**(dchar ch);  
Decomposes a Hangul syllable. If `ch` is not a composed syllable then this function returns [`Grapheme`](#Grapheme) containing only `ch` as is.



Examples:


```
import std.algorithm.comparison : equal;
assert(decomposeHangul('\uD4DB')[].equal("\u1111\u1171\u11B6"));

```
 
  pure nothrow @nogc @safe dchar **composeJamo**(dchar lead, dchar vowel, dchar trailing = (dchar).init);  
Try to compose hangul syllable out of a leading consonant (`lead`), a `vowel` and optional `trailing` consonant jamos. 


On success returns the composed LV or LVT hangul syllable.   
  
 If any of `lead` and `vowel` are not a valid hangul jamo of the respective [character](#Character) class returns dchar.init.

 
Examples:


```
writeln(composeJamo('\u1111', '\u1171', '\u11B6')); // '\uD4DB'
// leaving out T-vowel, or passing any codepoint
// that is not trailing consonant composes an LV-syllable
writeln(composeJamo('\u1111', '\u1171')); // '\uD4CC'
writeln(composeJamo('\u1111', '\u1171', ' ')); // '\uD4CC'
writeln(composeJamo('\u1111', 'A')); // dchar.init
writeln(composeJamo('A', '\u1171')); // dchar.init

```
 
  enum **NormalizationForm**: int;  
Enumeration type for normalization forms, passed as template parameter for functions like [`normalize`](#normalize).

  
**NFC**  
  
**NFD**  
  
**NFKC**  
  
**NFKD**
 
Shorthand aliases from values indicating normalization forms.

  inout(C)[] **normalize**(NormalizationForm norm = NFC, C)(inout(C)[] input);  
Returns `input` string normalized to the chosen form. Form C is used by default. 


For more information on normalization forms see the [normalization section](#Normalization). 

 
Note
 In cases where the string in question is already normalized, it is returned unmodified and no memory allocation happens.
 
Examples:


```
// any encoding works
wstring greet = "Hello world";
assert(normalize(greet) is greet); // the same exact slice

// An example of a character with all 4 forms being different:
// Greek upsilon with acute and hook symbol (code point 0x03D3)
writeln(normalize!NFC("ϓ")); // "\u03D3"
writeln(normalize!NFD("ϓ")); // "\u03D2\u0301"
writeln(normalize!NFKC("ϓ")); // "\u038E"
writeln(normalize!NFKD("ϓ")); // "\u03A5\u0301"

```
 
  bool **allowedIn**(NormalizationForm norm)(dchar ch);  
Tests if dchar `ch` is always allowed (Quick\_Check=YES) in normalization form `norm`.



Examples:


```
// e.g. Cyrillic is always allowed, so is ASCII
assert(allowedIn!NFC('я'));
assert(allowedIn!NFD('я'));
assert(allowedIn!NFKC('я'));
assert(allowedIn!NFKD('я'));
assert(allowedIn!NFC('Z'));

```
 
  pure nothrow @nogc @safe bool **isWhite**(dchar c);  
Whether or not `c` is a Unicode whitespace [character](#Character). (general Unicode category: Part of C0(tab, vertical tab, form feed, carriage return, and linefeed characters), Zs, Zl, Zp, and NEL(U+0085))

  pure nothrow @nogc @safe bool **isLower**(dchar c);  
Return whether `c` is a Unicode lowercase [character](#Character).

  pure nothrow @nogc @safe bool **isUpper**(dchar c);  
Return whether `c` is a Unicode uppercase [character](#Character).

  auto **asLowerCase**(Range)(Range str)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);   
  
auto **asUpperCase**(Range)(Range str)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Convert an [input range](std_range_primitives#isInputRange) or a string to upper or lower case. 


Does not allocate memory. Characters in UTF-8 or UTF-16 format that cannot be decoded are treated as [`std.utf.replacementDchar`](std_utf#replacementDchar). 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | string or range of characters |


 
Returns:
an input range of `dchar`s 
 
See Also:

[`toUpper`](#toUpper), [`toLower`](#toLower)

 
Examples:


```
import std.algorithm.comparison : equal;

assert("hEllo".asUpperCase.equal("HELLO"));

```
 
  auto **asCapitalized**(Range)(Range str)  
 Constraints: if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range); 
 
Capitalize an [input range](std_range_primitives#isInputRange) or string, meaning convert the first character to upper case and subsequent characters to lower case. 


Does not allocate memory. Characters in UTF-8 or UTF-16 format that cannot be decoded are treated as [`std.utf.replacementDchar`](std_utf#replacementDchar). 

 
Parameters:


|  |  |
| --- | --- |
| Range `str` | string or range of characters |


 
Returns:
an InputRange of dchars 
 
See Also:

[`toUpper`](#toUpper), [`toLower`](#toLower) [`asUpperCase`](#asUpperCase), [`asLowerCase`](#asLowerCase)

 
Examples:


```
import std.algorithm.comparison : equal;

assert("hEllo".asCapitalized.equal("Hello"));

```
 
  pure @trusted void **toLowerInPlace**(C)(ref C[] s)  
 Constraints: if (is(C == char) || is(C == wchar) || is(C == dchar)); 
 
Converts `s` to lowercase (by performing Unicode lowercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If `s` does not have any uppercase characters, then `s` is unaltered.

  pure @trusted void **toUpperInPlace**(C)(ref C[] s)  
 Constraints: if (is(C == char) || is(C == wchar) || is(C == dchar)); 
 
Converts `s` to uppercase (by performing Unicode uppercase mapping) in place. For a few characters string length may increase after the transformation, in such a case the function reallocates exactly once. If `s` does not have any lowercase characters, then `s` is unaltered.

  pure nothrow @nogc @safe dchar **toLower**(dchar c);  
If `c` is a Unicode uppercase [character](#Character), then its lowercase equivalent is returned. Otherwise `c` is returned. 



Warning
 certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toLower which takes full string instead.
  ElementEncodingType!S[] **toLower**(S)(S s)  
 Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && hasSlicing!S && isSomeChar!(ElementType!S)); 
 
Creates a new array which is identical to `s` except that all of its characters are converted to lowercase (by preforming Unicode lowercase mapping). If none of `s` characters were affected, then `s` itself is returned if `s` is a `string`-like type. 



Parameters:


|  |  |
| --- | --- |
| S `s` | A [random access range](std_range_primitives#isRandomAccessRange) of characters |


 
Returns:
An array with the same element type as `s`.
  pure nothrow @nogc @safe dchar **toUpper**(dchar c);  
If `c` is a Unicode lowercase [character](#Character), then its uppercase equivalent is returned. Otherwise `c` is returned. 



Warning
 Certain alphabets like German and Greek have no 1:1 upper-lower mapping. Use overload of toUpper which takes full string instead. 
 toUpper can be used as an argument to [`std.algorithm.iteration.map`](std_algorithm_iteration#map) to produce an algorithm that can convert a range of characters to upper case without allocating memory. A string can then be produced by using [`std.algorithm.mutation.copy`](std_algorithm_mutation#copy) to send it to an [`std.array.appender`](std_array#appender). 
Examples:


```
import std.algorithm.iteration : map;
import std.algorithm.mutation : copy;
import std.array : appender;

auto abuf = appender!(char[])();
"hello".map!toUpper.copy(abuf);
writeln(abuf.data); // "HELLO"

```
 
  ElementEncodingType!S[] **toUpper**(S)(S s)  
 Constraints: if (isSomeString!S || isRandomAccessRange!S && hasLength!S && hasSlicing!S && isSomeChar!(ElementType!S)); 
 
Allocates a new array which is identical to `s` except that all of its characters are converted to uppercase (by preforming Unicode uppercase mapping). If none of `s` characters were affected, then `s` itself is returned if `s` is a `string`-like type. 



Parameters:


|  |  |
| --- | --- |
| S `s` | A [random access range](std_range_primitives#isRandomAccessRange) of characters |


 
Returns:
An new array with the same element type as `s`.
  pure nothrow @nogc @safe bool **isAlpha**(dchar c);  
Returns whether `c` is a Unicode alphabetic [character](#Character) (general Unicode category: Alphabetic).

  pure nothrow @nogc @safe bool **isMark**(dchar c);  
Returns whether `c` is a Unicode mark (general Unicode category: Mn, Me, Mc).

  pure nothrow @nogc @safe bool **isNumber**(dchar c);  
Returns whether `c` is a Unicode numerical [character](#Character) (general Unicode category: Nd, Nl, No).

  pure nothrow @nogc @safe bool **isAlphaNum**(dchar c);  
Returns whether `c` is a Unicode alphabetic [character](#Character) or number. (general Unicode category: Alphabetic, Nd, Nl, No). 



Parameters:


|  |  |
| --- | --- |
| dchar `c` | any Unicode character |


 
Returns:

`true` if the character is in the Alphabetic, Nd, Nl, or No Unicode categories
  pure nothrow @nogc @safe bool **isPunctuation**(dchar c);  
Returns whether `c` is a Unicode punctuation [character](#Character) (general Unicode category: Pd, Ps, Pe, Pc, Po, Pi, Pf).

  pure nothrow @nogc @safe bool **isSymbol**(dchar c);  
Returns whether `c` is a Unicode symbol [character](#Character) (general Unicode category: Sm, Sc, Sk, So).

  pure nothrow @nogc @safe bool **isSpace**(dchar c);  
Returns whether `c` is a Unicode space [character](#Character) (general Unicode category: Zs) 



Note
 This doesn't include '\n', '\r', \t' and other non-space [character](#Character). For commonly used less strict semantics see [`isWhite`](#isWhite).
  pure nothrow @nogc @safe bool **isGraphical**(dchar c);  
Returns whether `c` is a Unicode graphical [character](#Character) (general Unicode category: L, M, N, P, S, Zs). 

  pure nothrow @nogc @safe bool **isControl**(dchar c);  
Returns whether `c` is a Unicode control [character](#Character) (general Unicode category: Cc).

  pure nothrow @nogc @safe bool **isFormat**(dchar c);  
Returns whether `c` is a Unicode formatting [character](#Character) (general Unicode category: Cf).

  pure nothrow @nogc @safe bool **isPrivateUse**(dchar c);  
Returns whether `c` is a Unicode Private Use [code point](#Code%20point) (general Unicode category: Co).

  pure nothrow @nogc @safe bool **isSurrogate**(dchar c);  
Returns whether `c` is a Unicode surrogate [code point](#Code%20point) (general Unicode category: Cs).

  pure nothrow @nogc @safe bool **isSurrogateHi**(dchar c);  
Returns whether `c` is a Unicode high surrogate (lead surrogate).

  pure nothrow @nogc @safe bool **isSurrogateLo**(dchar c);  
Returns whether `c` is a Unicode low surrogate (trail surrogate).

  pure nothrow @nogc @safe bool **isNonCharacter**(dchar c);  
Returns whether `c` is a Unicode non-character i.e. a [code point](#Code%20point) with no assigned abstract character. (general Unicode category: Cn)

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_uni.html>

std.xml
=======

 Warning: This module is considered out-dated and not up to Phobos' current standards. It will be removed from Phobos in 2.101.0. If you still need it, go to <https://github.com/DigitalMars/undeaD> 


Classes and functions for creating and parsing XML   
  
 The basic architecture of this module is that there are standalone functions, classes for constructing an XML document from scratch (Tag, Element and Document), and also classes for parsing a pre-existing XML file (ElementParser and DocumentParser). The parsing classes *may* be used to build a Document, but that is not their primary purpose. The handling capabilities of DocumentParser and ElementParser are sufficiently customizable that you can make them do pretty much whatever you want. 

 
Example
 This example creates a DOM (Document Object Model) tree from an XML file. 


```
import std.xml;
import std.stdio;
import std.string;
import std.file;

// books.xml is used in various samples throughout the Microsoft XML Core
// Services (MSXML) SDK.
//
// See http://msdn2.microsoft.com/en-us/library/ms762271(VS.85).aspx

void main()
{
    string s = cast(string) std.file.read("books.xml");

    // Check for well-formedness
    check(s);

    // Make a DOM tree
    auto doc = new Document(s);

    // Plain-print it
    writeln(doc);
}

```
 
Example
 This example does much the same thing, except that the file is deconstructed and reconstructed by hand. This is more work, but the techniques involved offer vastly more power. 


```
import std.xml;
import std.stdio;
import std.string;

struct Book
{
    string id;
    string author;
    string title;
    string genre;
    string price;
    string pubDate;
    string description;
}

void main()
{
    string s = cast(string) std.file.read("books.xml");

    // Check for well-formedness
    check(s);

    // Take it apart
    Book[] books;

    auto xml = new DocumentParser(s);
    xml.onStartTag["book"] = (ElementParser xml)
    {
        Book book;
        book.id = xml.tag.attr["id"];

        xml.onEndTag["author"]       = (in Element e) { book.author      = e.text(); };
        xml.onEndTag["title"]        = (in Element e) { book.title       = e.text(); };
        xml.onEndTag["genre"]        = (in Element e) { book.genre       = e.text(); };
        xml.onEndTag["price"]        = (in Element e) { book.price       = e.text(); };
        xml.onEndTag["publish-date"] = (in Element e) { book.pubDate     = e.text(); };
        xml.onEndTag["description"]  = (in Element e) { book.description = e.text(); };

        xml.parse();

        books ~= book;
    };
    xml.parse();

    // Put it back together again;
    auto doc = new Document(new Tag("catalog"));
    foreach (book;books)
    {
        auto element = new Element("book");
        element.tag.attr["id"] = book.id;

        element ~= new Element("author",      book.author);
        element ~= new Element("title",       book.title);
        element ~= new Element("genre",       book.genre);
        element ~= new Element("price",       book.price);
        element ~= new Element("publish-date",book.pubDate);
        element ~= new Element("description", book.description);

        doc ~= element;
    }

    // Pretty-print it
    writefln(join(doc.pretty(3),"\n"));
}

```
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Janice Caron 
 
Source
 [std/xml.d](https://github.com/dlang/phobos/blob/master/std/xml.d)

 
pure nothrow @nogc @safe bool **isChar**(dchar c);  
Returns true if the character is a character according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isSpace**(dchar c);  
Returns true if the character is whitespace according to the XML standard 


Only the following characters are considered whitespace in XML - space, tab, carriage return and linefeed 

 
Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isDigit**(dchar c);  
Returns true if the character is a digit according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isLetter**(dchar c);  
Returns true if the character is a letter according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isIdeographic**(dchar c);  
Returns true if the character is an ideographic character according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isBaseChar**(dchar c);  
Returns true if the character is a base character according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isCombiningChar**(dchar c);  
Returns true if the character is a combining character according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  pure nothrow @nogc @safe bool **isExtender**(dchar c);  
Returns true if the character is an extender according to the XML standard 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| dchar `c` | the character to be tested |


  S **encode**(S)(S s);  
Encodes a string by replacing all characters which need to be escaped with appropriate predefined XML entities. 


encode() escapes certain characters (ampersand, quote, apostrophe, less-than and greater-than), and similarly, decode() unescapes them. These functions are provided for convenience only. You do not need to use them when using the std.xml classes, because then all the encoding and decoding will be done for you automatically.   
  
 If the string is not modified, the original will be returned. 

 
Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| S `s` | The string to be encoded |


 
Returns:
The encoded string 
 
Example


```
writefln(encode("a > b")); // writes "a &gt; b"

```
  enum **DecodeMode**: int;  
Mode to use for decoding. 


NONE Do not decode LOOSE Decode, but ignore errors STRICT Decode, and throw exception on error

  pure @safe string **decode**(string s, DecodeMode mode = DecodeMode.LOOSE);  
Decodes a string by unescaping all predefined XML entities. 


encode() escapes certain characters (ampersand, quote, apostrophe, less-than and greater-than), and similarly, decode() unescapes them. These functions are provided for convenience only. You do not need to use them when using the std.xml classes, because then all the encoding and decoding will be done for you automatically.   
  
 This function decodes the entities &amp;, &quot;, &apos;, &lt; and &gt, as well as decimal and hexadecimal entities such as &#x20AC;   
  
 If the string does not contain an ampersand, the original will be returned.   
  
 Note that the "mode" parameter can be one of DecodeMode.NONE (do not decode), DecodeMode.LOOSE (decode, but ignore errors), or DecodeMode.STRICT (decode, and throw a DecodeException in the event of an error). 

 
Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Parameters:


|  |  |
| --- | --- |
| string `s` | The string to be decoded |
| DecodeMode `mode` | (optional) Mode to use for decoding. (Defaults to LOOSE). |


 
Throws:
DecodeException if mode == DecodeMode.STRICT and decode fails 
 
Returns:
The decoded string 
 
Example


```
writefln(decode("a &gt; b")); // writes "a > b"

```
  class **Document**: std.xml.Element;  
Class representing an XML document. 



Standards:
[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210)
 
string **prolog**;  
Contains all text which occurs before the root element. Defaults to <?xml version="1.0"?>

  string **epilog**;  
Contains all text which occurs after the root element. Defaults to the empty string

  this(string s);  
Constructs a Document by parsing XML text. 


This function creates a complete DOM (Document Object Model) tree.   
  
 The input to this function MUST be valid XML. This is enforced by DocumentParser's in contract. 

 
Parameters:


|  |  |
| --- | --- |
| string `s` | the complete XML text. |


  this(const(Tag) tag);  
Constructs a Document from a Tag. 



Parameters:


|  |  |
| --- | --- |
| const(Tag) `tag` | the start tag of the document. |


  const bool **opEquals**(scope const Object o);  
Compares two Documents for equality 



Example


```
Document d1,d2;
if (d1 == d2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two Documents 


You should rarely need to call this function. It exists so that Documents can be used as associative array keys. 

 
Example


```
Document d1,d2;
if (d1 < d2) { }

```
  const scope @trusted size\_t **toHash**();  
Returns the hash of a Document 


You should rarely need to call this function. It exists so that Documents can be used as associative array keys.

  const scope @safe string **toString**();  
Returns the string representation of a Document. (That is, the complete XML of a document).

    class **Element**: std.xml.Item;  
Class representing an XML element. 



Standards:
[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210)
 
Tag **tag**;  
The start tag of the element

  Item[] **items**;  
The element's items

  Text[] **texts**;  
The element's text items

  CData[] **cdatas**;  
The element's CData items

  Comment[] **comments**;  
The element's comments

  ProcessingInstruction[] **pis**;  
The element's processing instructions

  Element[] **elements**;  
The element's child elements

  pure @safe this(string name, string interior = null);  
Constructs an Element given a name and a string to be used as a Text interior. 



Parameters:


|  |  |
| --- | --- |
| string `name` | the name of the element. |
| string `interior` | (optional) the string interior. |


 
Example


```
auto element = new Element("title","Serenity")
    // constructs the element <title>Serenity</title>

```
  pure @safe this(const(Tag) tag\_);  
Constructs an Element from a Tag. 



Parameters:


|  |  |
| --- | --- |
| const(Tag) `tag_` | the start or empty tag of the element. |


  pure @safe void **opOpAssign**(string op)(Text item)  
 Constraints: if (op == "~"); 
 
Append a text item to the interior of this element 



Parameters:


|  |  |
| --- | --- |
| Text `item` | the item you wish to append. |


 
Example


```
Element element;
element ~= new Text("hello");

```
  pure @safe void **opOpAssign**(string op)(CData item)  
 Constraints: if (op == "~"); 
 
Append a CData item to the interior of this element 



Parameters:


|  |  |
| --- | --- |
| CData `item` | the item you wish to append. |


 
Example


```
Element element;
element ~= new CData("hello");

```
  pure @safe void **opOpAssign**(string op)(Comment item)  
 Constraints: if (op == "~"); 
 
Append a comment to the interior of this element 



Parameters:


|  |  |
| --- | --- |
| Comment `item` | the item you wish to append. |


 
Example


```
Element element;
element ~= new Comment("hello");

```
  pure @safe void **opOpAssign**(string op)(ProcessingInstruction item)  
 Constraints: if (op == "~"); 
 
Append a processing instruction to the interior of this element 



Parameters:


|  |  |
| --- | --- |
| ProcessingInstruction `item` | the item you wish to append. |


 
Example


```
Element element;
element ~= new ProcessingInstruction("hello");

```
  pure @safe void **opOpAssign**(string op)(Element item)  
 Constraints: if (op == "~"); 
 
Append a complete element to the interior of this element 



Parameters:


|  |  |
| --- | --- |
| Element `item` | the item you wish to append. |


 
Example


```
Element element;
Element other = new Element("br");
element ~= other;
   // appends element representing <br />

```
  const bool **opEquals**(scope const Object o);  
Compares two Elements for equality 



Example


```
Element e1,e2;
if (e1 == e2) { }

```
  const @safe int **opCmp**(scope const Object o);  
Compares two Elements 


You should rarely need to call this function. It exists so that Elements can be used as associative array keys. 

 
Example


```
Element e1,e2;
if (e1 < e2) { }

```
  const scope @safe size\_t **toHash**();  
Returns the hash of an Element 


You should rarely need to call this function. It exists so that Elements can be used as associative array keys.

  const string **text**(DecodeMode mode = DecodeMode.LOOSE);  
Returns the decoded interior of an element. 


The element is assumed to contain text *only*. So, for example, given XML such as "<title>Good &amp; Bad</title>", will return "Good & Bad". 

 
Parameters:


|  |  |
| --- | --- |
| DecodeMode `mode` | (optional) Mode to use for decoding. (Defaults to LOOSE). |


 
Throws:
DecodeException if decode fails
  const scope string[] **pretty**(uint indent = 2);  
Returns an indented string representation of this item 



Parameters:


|  |  |
| --- | --- |
| uint `indent` | (optional) number of spaces by which to indent this element. Defaults to 2. |


  const scope @safe string **toString**();  
Returns the string representation of an Element 



Example


```
auto element = new Element("br");
writefln(element.toString()); // writes "<br />"

```
    enum **TagType**: int;  
Tag types. 


START Used for start tags END Used for end tags EMPTY Used for empty tags

  class **Tag**;  
Class representing an XML tag. 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) The class invariant guarantees * that **type** is a valid enum TagType value
* that **name** consists of valid characters
* that each attribute name consists of valid characters



 
TagType **type**;  
Type of tag

  string **name**;  
Tag name

  string[string] **attr**;  
Associative array of attributes

  pure @safe this(string name, TagType type = TagType.START);  
Constructs an instance of Tag with a specified name and type 


The constructor does not initialize the attributes. To initialize the attributes, you access the **attr** member variable. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | the Tag's name |
| TagType `type` | (optional) the Tag's type. If omitted, defaults to TagType.START. |


 
Example


```
auto tag = new Tag("img",Tag.EMPTY);
tag.attr["src"] = "http://example.com/example.jpg";

```
  const bool **opEquals**(scope Object o);  
Compares two Tags for equality 


You should rarely need to call this function. It exists so that Tags can be used as associative array keys. 

 
Example


```
Tag tag1,tag2
if (tag1 == tag2) { }

```
  const int **opCmp**(Object o);  
Compares two Tags 



Example


```
Tag tag1,tag2
if (tag1 < tag2) { }

```
  const size\_t **toHash**();  
Returns the hash of a Tag 


You should rarely need to call this function. It exists so that Tags can be used as associative array keys.

  const @safe string **toString**();  
Returns the string representation of a Tag 



Example


```
auto tag = new Tag("book",TagType.START);
writefln(tag.toString()); // writes "<book>"

```
  const pure nothrow @nogc @property @safe bool **isStart**();  
Returns true if the Tag is a start tag 



Example


```
if (tag.isStart) { }

```
  const pure nothrow @nogc @property @safe bool **isEnd**();  
Returns true if the Tag is an end tag 



Example


```
if (tag.isEnd) { }

```
  const pure nothrow @nogc @property @safe bool **isEmpty**();  
Returns true if the Tag is an empty tag 



Example


```
if (tag.isEmpty) { }

```
    class **Comment**: std.xml.Item;  
Class representing a comment

 
pure @safe this(string content);  
Construct a comment 



Parameters:


|  |  |
| --- | --- |
| string `content` | the body of the comment |


 
Throws:
CommentException if the comment body is illegal (contains "--" or exactly equals "-") 
 
Example


```
auto item = new Comment("This is a comment");
   // constructs <!--This is a comment-->

```
  const bool **opEquals**(scope const Object o);  
Compares two comments for equality 



Example


```
Comment item1,item2;
if (item1 == item2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two comments 


You should rarely need to call this function. It exists so that Comments can be used as associative array keys. 

 
Example


```
Comment item1,item2;
if (item1 < item2) { }

```
  const nothrow scope size\_t **toHash**();  
Returns the hash of a Comment 


You should rarely need to call this function. It exists so that Comments can be used as associative array keys.

  const pure nothrow scope @safe string **toString**();  
Returns a string representation of this comment

  const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns false always

    class **CData**: std.xml.Item;  
Class representing a Character Data section

 
pure @safe this(string content);  
Construct a character data section 



Parameters:


|  |  |
| --- | --- |
| string `content` | the body of the character data segment |


 
Throws:
CDataException if the segment body is illegal (contains "]]>") 
 
Example


```
auto item = new CData("<b>hello</b>");
   // constructs <![CDATA[<b>hello</b>]]>

```
  const bool **opEquals**(scope const Object o);  
Compares two CDatas for equality 



Example


```
CData item1,item2;
if (item1 == item2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two CDatas 


You should rarely need to call this function. It exists so that CDatas can be used as associative array keys. 

 
Example


```
CData item1,item2;
if (item1 < item2) { }

```
  const nothrow scope size\_t **toHash**();  
Returns the hash of a CData 


You should rarely need to call this function. It exists so that CDatas can be used as associative array keys.

  const pure nothrow scope @safe string **toString**();  
Returns a string representation of this CData section

  const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns false always

    class **Text**: std.xml.Item;  
Class representing a text (aka Parsed Character Data) section

 
pure @safe this(string content);  
Construct a text (aka PCData) section 



Parameters:


|  |  |
| --- | --- |
| string `content` | the text. This function encodes the text before insertion, so it is safe to insert any text |


 
Example


```
auto Text = new CData("a < b");
   // constructs a &lt; b

```
  const bool **opEquals**(scope const Object o);  
Compares two text sections for equality 



Example


```
Text item1,item2;
if (item1 == item2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two text sections 


You should rarely need to call this function. It exists so that Texts can be used as associative array keys. 

 
Example


```
Text item1,item2;
if (item1 < item2) { }

```
  const nothrow scope size\_t **toHash**();  
Returns the hash of a text section 


You should rarely need to call this function. It exists so that Texts can be used as associative array keys.

  const pure nothrow @nogc scope @safe string **toString**();  
Returns a string representation of this Text section

  const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns true if the content is the empty string

    class **XMLInstruction**: std.xml.Item;  
Class representing an XML Instruction section

 
pure @safe this(string content);  
Construct an XML Instruction section 



Parameters:


|  |  |
| --- | --- |
| string `content` | the body of the instruction segment |


 
Throws:
XIException if the segment body is illegal (contains ">") 
 
Example


```
auto item = new XMLInstruction("ATTLIST");
   // constructs <!ATTLIST>

```
  const bool **opEquals**(scope const Object o);  
Compares two XML instructions for equality 



Example


```
XMLInstruction item1,item2;
if (item1 == item2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two XML instructions 


You should rarely need to call this function. It exists so that XmlInstructions can be used as associative array keys. 

 
Example


```
XMLInstruction item1,item2;
if (item1 < item2) { }

```
  const nothrow scope size\_t **toHash**();  
Returns the hash of an XMLInstruction 


You should rarely need to call this function. It exists so that XmlInstructions can be used as associative array keys.

  const pure nothrow scope @safe string **toString**();  
Returns a string representation of this XmlInstruction

  const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns false always

    class **ProcessingInstruction**: std.xml.Item;  
Class representing a Processing Instruction section

 
pure @safe this(string content);  
Construct a Processing Instruction section 



Parameters:


|  |  |
| --- | --- |
| string `content` | the body of the instruction segment |


 
Throws:
PIException if the segment body is illegal (contains "?>") 
 
Example


```
auto item = new ProcessingInstruction("php");
   // constructs <?php?>

```
  const bool **opEquals**(scope const Object o);  
Compares two processing instructions for equality 



Example


```
ProcessingInstruction item1,item2;
if (item1 == item2) { }

```
  const scope int **opCmp**(scope const Object o);  
Compares two processing instructions 


You should rarely need to call this function. It exists so that ProcessingInstructions can be used as associative array keys. 

 
Example


```
ProcessingInstruction item1,item2;
if (item1 < item2) { }

```
  const nothrow scope size\_t **toHash**();  
Returns the hash of a ProcessingInstruction 


You should rarely need to call this function. It exists so that ProcessingInstructions can be used as associative array keys.

  const pure nothrow scope @safe string **toString**();  
Returns a string representation of this ProcessingInstruction

  const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns false always

    abstract class **Item**;  
Abstract base class for XML items

 
abstract const @safe bool **opEquals**(scope const Object o);  
Compares with another Item of same type for equality

  abstract const @safe int **opCmp**(scope const Object o);  
Compares with another Item of same type

  abstract const scope @safe size\_t **toHash**();  
Returns the hash of this item

  abstract const scope @safe string **toString**();  
Returns a string representation of this item

  const scope @safe string[] **pretty**(uint indent);  
Returns an indented string representation of this item 



Parameters:


|  |  |
| --- | --- |
| uint `indent` | number of spaces by which to indent child elements |


  abstract const pure nothrow @nogc @property scope @safe bool **isEmptyXML**();  
Returns true if the item represents empty XML text

    class **DocumentParser**: std.xml.ElementParser;  
Class for parsing an XML Document. 


This is a subclass of ElementParser. Most of the useful functions are documented there. 

 
Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) 
 
Bugs:
Currently only supports UTF documents. If there is an encoding attribute in the prolog, it is ignored.
 
this(string xmlText\_);  
Constructs a DocumentParser. 


The input to this function MUST be valid XML. This is enforced by the function's in contract. 

 
Parameters:


|  |  |
| --- | --- |
| string `xmlText_` | the entire XML document as text |


    class **ElementParser**;  
Class for parsing an XML element. 



Standards:

[XML 1.0](http://www.w3.org/TR/1998/REC-xml-19980210) Note that you cannot construct instances of this class directly. You can construct a DocumentParser (which is a subclass of ElementParser), but otherwise, Instances of ElementParser will be created for you by the library, and passed your way via onStartTag handlers.
 
const pure nothrow @nogc @property @safe const(Tag) **tag**();  
The Tag at the start of the element being parsed. You can read this to determine the tag's name and attributes.

  ParserHandler[string] **onStartTag**;  
Register a handler which will be called whenever a start tag is encountered which matches the specified name. You can also pass null as the name, in which case the handler will be called for any unmatched start tag. 



Example


```
// Call this function whenever a <podcast> start tag is encountered
onStartTag["podcast"] = (ElementParser xml)
{
    // Your code here
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

// call myEpisodeStartHandler (defined elsewhere) whenever an <episode>
// start tag is encountered
onStartTag["episode"] = &myEpisodeStartHandler;

// call delegate dg for all other start tags
onStartTag[null] = dg;

```
 This library will supply your function with a new instance of ElementHandler, which may be used to parse inside the element whose start tag was just found, or to identify the tag attributes of the element, etc. Note that your function will be called for both start tags and empty tags. That is, we make no distinction between <br></br> and <br/>.  ElementHandler[string] **onEndTag**;  
Register a handler which will be called whenever an end tag is encountered which matches the specified name. You can also pass null as the name, in which case the handler will be called for any unmatched end tag. 



Example


```
// Call this function whenever a </podcast> end tag is encountered
onEndTag["podcast"] = (in Element e)
{
    // Your code here
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

// call myEpisodeEndHandler (defined elsewhere) whenever an </episode>
// end tag is encountered
onEndTag["episode"] = &myEpisodeEndHandler;

// call delegate dg for all other end tags
onEndTag[null] = dg;

```
 Note that your function will be called for both start tags and empty tags. That is, we make no distinction between <br></br> and <br/>.  pure nothrow @nogc @property @safe void **onText**(Handler handler);  
Register a handler which will be called whenever text is encountered. 



Example


```
// Call this function whenever text is encountered
onText = (string s)
{
    // Your code here

    // The passed parameter s will have been decoded by the time you see
    // it, and so may contain any character.
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  pure nothrow @nogc @safe void **onTextRaw**(Handler handler);  
Register an alternative handler which will be called whenever text is encountered. This differs from onText in that onText will decode the text, whereas onTextRaw will not. This allows you to make design choices, since onText will be more accurate, but slower, while onTextRaw will be faster, but less accurate. Of course, you can still call decode() within your handler, if you want, but you'd probably want to use onTextRaw only in circumstances where you know that decoding is unnecessary. 



Example


```
// Call this function whenever text is encountered
onText = (string s)
{
    // Your code here

    // The passed parameter s will NOT have been decoded.
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  pure nothrow @nogc @property @safe void **onCData**(Handler handler);  
Register a handler which will be called whenever a character data segment is encountered. 



Example


```
// Call this function whenever a CData section is encountered
onCData = (string s)
{
    // Your code here

    // The passed parameter s does not include the opening <![CDATA[
    // nor closing ]]>
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  pure nothrow @nogc @property @safe void **onComment**(Handler handler);  
Register a handler which will be called whenever a comment is encountered. 



Example


```
// Call this function whenever a comment is encountered
onComment = (string s)
{
    // Your code here

    // The passed parameter s does not include the opening <!-- nor
    // closing -->
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  pure nothrow @nogc @property @safe void **onPI**(Handler handler);  
Register a handler which will be called whenever a processing instruction is encountered. 



Example


```
// Call this function whenever a processing instruction is encountered
onPI = (string s)
{
    // Your code here

    // The passed parameter s does not include the opening <? nor
    // closing ?>
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  pure nothrow @nogc @property @safe void **onXI**(Handler handler);  
Register a handler which will be called whenever an XML instruction is encountered. 



Example


```
// Call this function whenever an XML instruction is encountered
// (Note: XML instructions may only occur preceding the root tag of a
// document).
onPI = (string s)
{
    // Your code here

    // The passed parameter s does not include the opening <! nor
    // closing >
    //
    // This is a a closure, so code here may reference
    // variables which are outside of this scope
};

```
  void **parse**();  
Parse an XML element. 


Parsing will continue until the end of the current element. Any items encountered for which a handler has been registered will invoke that handler. 

 
Throws:
various kinds of XMLException
  const pure nothrow @nogc @safe string **toString**();  
Returns that part of the element which has already been parsed

    pure @safe void **check**(string s);  
Check an entire XML document for well-formedness 



Parameters:


|  |  |
| --- | --- |
| string `s` | the document to be checked, passed as a string |


 
Throws:
CheckException if the document is not well formed CheckException's toString() method will yield the complete hierarchy of parse failure (the XML equivalent of a stack trace), giving the line and column number of every failure at every level.
  class **XMLException**: object.Exception;  
The base class for exceptions thrown by this module

  class **CommentException**: std.xml.XMLException;  
Thrown during Comment constructor

  class **CDataException**: std.xml.XMLException;  
Thrown during CData constructor

  class **XIException**: std.xml.XMLException;  
Thrown during XMLInstruction constructor

  class **PIException**: std.xml.XMLException;  
Thrown during ProcessingInstruction constructor

  class **TextException**: std.xml.XMLException;  
Thrown during Text constructor

  class **DecodeException**: std.xml.XMLException;  
Thrown during decode()

  class **InvalidTypeException**: std.xml.XMLException;  
Thrown if comparing with wrong type

  class **TagException**: std.xml.XMLException;  
Thrown when parsing for Tags

  class **CheckException**: std.xml.XMLException;  
Thrown during check()

 
CheckException **err**;  
Parent in hierarchy

  string **msg**;  
Name of production rule which failed to parse, or specific error message

  size\_t **line**;  
Line number at which parse failure occurred

  size\_t **column**;  
Column number at which parse failure occurred

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_xml.html>

etc.c.zlib
==========

 
immutable void\* **Z\_NULL**;  
for initializing zalloc, zfree, opaque (extern(D) for mangling)

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_zlib.html>

std.typecons
============

 This module implements a variety of type constructors, i.e., templates that allow construction of new, useful general-purpose types. 


 

| Category | Functions |
| --- | --- |
| Tuple | [`isTuple`](#isTuple) [`Tuple`](#Tuple) [`tuple`](#tuple) [`reverse`](#reverse) |
| Flags | [`BitFlags`](#BitFlags) [`isBitFlagEnum`](#isBitFlagEnum) [`Flag`](#Flag) [`No`](#No) [`Yes`](#Yes) |
| Memory allocation | [`RefCounted`](#RefCounted) [`refCounted`](#refCounted) [`RefCountedAutoInitialize`](#RefCountedAutoInitialize) [`scoped`](#scoped) [`Unique`](#Unique) |
| Code generation | [`AutoImplement`](#AutoImplement) [`BlackHole`](#BlackHole) [`generateAssertTrap`](#generateAssertTrap) [`generateEmptyFunction`](#generateEmptyFunction) [`WhiteHole`](#WhiteHole) |
| Nullable | [`Nullable`](#Nullable) [`nullable`](#nullable) [`NullableRef`](#NullableRef) [`nullableRef`](#nullableRef) |
| Proxies | [`Proxy`](#Proxy) [`rebindable`](#rebindable) [`Rebindable`](#Rebindable) [`ReplaceType`](#ReplaceType) [`unwrap`](#unwrap) [`wrap`](#wrap) |
| Types | [`alignForSize`](#alignForSize) [`Ternary`](#Ternary) [`Typedef`](#Typedef) [`TypedefType`](#TypedefType) [`UnqualRef`](#UnqualRef) |

 

 
License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Source
 [std/typecons.d](https://github.com/dlang/phobos/blob/master/std/typecons.d) 
 
Authors:

[Andrei Alexandrescu](http://erdani.org), [Bartosz Milewski](http://bartoszmilewski.wordpress.com), Don Clugston, Shin Fujishiro, Kenji Hara
 
Examples:


```
// value tuples
alias Coord = Tuple!(int, "x", int, "y", int, "z");
Coord c;
c[1] = 1;       // access by index
c.z = 1;        // access by given name
writeln(c); // Coord(0, 1, 1)

// names can be omitted
alias DicEntry = Tuple!(string, string);

// tuples can also be constructed on instantiation
writeln(tuple(2, 3, 4)[1]); // 3
// construction on instantiation works with names too
writeln(tuple!("x", "y", "z")(2, 3, 4).y); // 3

// Rebindable references to const and immutable objects
{
    class Widget { void foo() const @safe {} }
    const w1 = new Widget, w2 = new Widget;
    w1.foo();
    // w1 = w2 would not work; can't rebind const object
    auto r = Rebindable!(const Widget)(w1);
    // invoke method as if r were a Widget object
    r.foo();
    // rebind r to refer to another object
    r = w2;
}

```
 
 
struct **Unique**(T);  
Encapsulates unique ownership of a resource. 


When a `Unique!T` goes out of scope it will call `destroy` on the resource `T` that it manages, unless it is transferred. One important consequence of `destroy` is that it will call the destructor of the resource `T`. GC-managed references are not guaranteed to be valid during a destructor call, but other members of `T`, such as file handles or pointers to `malloc` memory, will still be valid during the destructor call. This allows the resource `T` to deallocate or clean up any non-GC resources.   
  
 If it is desirable to persist a `Unique!T` outside of its original scope, then it can be transferred. The transfer can be explicit, by calling `release`, or implicit, when returning Unique from a function. The resource `T` can be a polymorphic class object or instance of an interface, in which case Unique behaves polymorphically too.   
  
 If `T` is a value type, then `Unique!T` will be implemented as a reference to a `T`.

 
Examples:


```
static struct S
{
    int i;
    this(int i){this.i = i;}
}
Unique!S produce()
{
    // Construct a unique instance of S on the heap
    Unique!S ut = new S(5);
    // Implicit transfer of ownership
    return ut;
}
// Borrow a unique resource by ref
void increment(ref Unique!S ur)
{
    ur.i++;
}
void consume(Unique!S u2)
{
    writeln(u2.i); // 6
    // Resource automatically deleted here
}
Unique!S u1;
assert(u1.isEmpty);
u1 = produce();
increment(u1);
writeln(u1.i); // 6
//consume(u1); // Error: u1 is not copyable
// Transfer ownership of the resource
consume(u1.release);
assert(u1.isEmpty);

```
 
 
alias **RefT** = T;  
Represents a reference to `T`. Resolves to `T*` if `T` is a value type.

  Unique!T **create**(A...)(auto ref A args)  
 Constraints: if (\_\_traits(compiles, new T(args))); 
 
Allows safe construction of `Unique`. It creates the resource and guarantees unique ownership of it (unless `T` publishes aliases of `this`). 



Note
 Nested structs/classes cannot be created. 
 
Parameters:


|  |  |
| --- | --- |
| A `args` | Arguments to pass to `T`'s constructor. 
```
static class C {}
auto u = Unique!(C).create();

```
 |


  this(RefT p);  
 Constructor that takes an rvalue. It will ensure uniqueness, as long as the rvalue isn't just a view on an lvalue (e.g., a cast). Typical usage: 
```
Unique!Foo f = new Foo;

```
 

  this(ref RefT p);  
Constructor that takes an lvalue. It nulls its source. The nulling will ensure uniqueness as long as there are no previous aliases to the source.

  this(U)(Unique!U u)  
 Constraints: if (is(u.RefT : RefT)); 
 
Constructor that takes a `Unique` of a type that is convertible to our type. 


Typically used to transfer a `Unique` rvalue of derived type to a `Unique` of base type. 

 
Example


```
class C : Object {}

Unique!C uc = new C;
Unique!Object uo = uc.release;

```
  void **opAssign**(U)(Unique!U u)  
 Constraints: if (is(u.RefT : RefT)); 
 
Transfer ownership from a `Unique` of a type that is convertible to our type.

  const @property bool **isEmpty**();  
Returns whether the resource exists.

  Unique **release**();  
Transfer ownership to a `Unique` rvalue. Nullifies the current contents. Same as calling std.algorithm.move on it.

    struct **Tuple**(Specs...) if (distinctFieldNames!Specs);  
Tuple of values, for example `Tuple!(int, string)` is a record that stores an `int` and a `string`. `Tuple` can be used to bundle values together, notably when returning multiple values from a function. If `obj` is a `Tuple`, the individual members are accessible with the syntax `obj[0]` for the first field, `obj[1]` for the second, and so on. 



See Also:

[`tuple`](#tuple). 
 
Parameters:


|  |  |
| --- | --- |
| Specs | A list of types (and optionally, member names) that the `Tuple` contains. |


 
Examples:


```
Tuple!(int, int) point;
// assign coordinates
point[0] = 5;
point[1] = 6;
// read coordinates
auto x = point[0];
auto y = point[1];

```
 
 
Examples:

`Tuple` members can be named. It is legal to mix named and unnamed members. The method above is still applicable to all fields. 
```
alias Entry = Tuple!(int, "index", string, "value");
Entry e;
e.index = 4;
e.value = "Hello";
writeln(e[1]); // "Hello"
writeln(e[0]); // 4

```
 
 
Examples:
A `Tuple` with named fields is a distinct type from a `Tuple` with unnamed fields, i.e. each naming imparts a separate type for the `Tuple`. Two `Tuple`s differing in naming only are still distinct, even though they might have the same structure. 
```
Tuple!(int, "x", int, "y") point1;
Tuple!(int, int) point2;
assert(!is(typeof(point1) == typeof(point2)));

```
 
 
Examples:
Use tuples as ranges 
```
import std.algorithm.iteration : sum;
import std.range : only;
auto t = tuple(1, 2);
writeln(t.expand.only.sum); // 3

```
 
 
Examples:
Concatenate tuples 
```
import std.meta : AliasSeq;
auto t = tuple(1, "2") ~ tuple(ushort(42), true);
static assert(is(t.Types == AliasSeq!(int, string, ushort, bool)));
writeln(t[1]); // "2"
writeln(t[2]); // 42
writeln(t[3]); // true

```
 
 
alias **Types** = staticMap!(extractType, fieldSpecs);  
The types of the `Tuple`'s components.

  alias **fieldNames** = staticMap!(extractName, fieldSpecs);  
The names of the `Tuple`'s components. Unnamed fields have empty names.



Examples:


```
import std.meta : AliasSeq;
alias Fields = Tuple!(int, "id", string, float);
static assert(Fields.fieldNames == AliasSeq!("id", "", ""));

```
 
  Types **expand**;  
Use `t.expand` for a `Tuple` `t` to expand it into its components. The result of `expand` acts as if the `Tuple`'s components were listed as a list of values. (Ordinarily, a `Tuple` acts as a single value.)



Examples:


```
auto t1 = tuple(1, " hello ", 'a');
writeln(t1.toString()); // `Tuple!(int, string, char)(1, " hello ", 'a')`

void takeSeveralTypes(int n, string s, bool b)
{
    assert(n == 4 && s == "test" && b == false);
}

auto t2 = tuple(4, "test", false);
//t.expand acting as a list of values
takeSeveralTypes(t2.expand);

```
 
  this(Types values);  
Constructor taking one value for each field. 



Parameters:


|  |  |
| --- | --- |
| Types `values` | A list of values that are either the same types as those given by the `Types` field of this `Tuple`, or can implicitly convert to those types. They must be in the same order as they appear in `Types`. |


 
Examples:


```
alias ISD = Tuple!(int, string, double);
auto tup = ISD(1, "test", 3.2);
writeln(tup.toString()); // `Tuple!(int, string, double)(1, "test", 3.2)`

```
 
  this(U, size\_t n)(U[n] values)  
 Constraints: if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types)); 
 
Constructor taking a compatible array. 



Parameters:


|  |  |
| --- | --- |
| U[n] `values` | A compatible static array to build the `Tuple` from. Array slices are not supported. |


 
Examples:


```
int[2] ints;
Tuple!(int, int) t = ints;

```
 
  this(U)(U another)  
 Constraints: if (areBuildCompatibleTuples!(typeof(this), U)); 
 
Constructor taking a compatible `Tuple`. Two `Tuple`s are compatible **iff** they are both of the same length, and, for each type `T` on the left-hand side, the corresponding type `U` on the right-hand side can implicitly convert to `T`. 



Parameters:


|  |  |
| --- | --- |
| U `another` | A compatible `Tuple` to build from. Its type must be compatible with the target `Tuple`'s type. |


 
Examples:


```
alias IntVec = Tuple!(int, int, int);
alias DubVec = Tuple!(double, double, double);

IntVec iv = tuple(1, 1, 1);

//Ok, int can implicitly convert to double
DubVec dv = iv;
//Error: double cannot implicitly convert to int
//IntVec iv2 = dv;

```
 
  bool **opEquals**(R)(R rhs)  
 Constraints: if (areCompatibleTuples!(typeof(this), R, "=="));   
  
const bool **opEquals**(R)(R rhs)  
 Constraints: if (areCompatibleTuples!(typeof(this), R, "=="));   
  
bool **opEquals**(R...)(auto ref R rhs)  
 Constraints: if (R.length > 1 && areCompatibleTuples!(typeof(this), Tuple!R, "==")); 
 
Comparison for equality. Two `Tuple`s are considered equal **iff** they fulfill the following criteria: 


* Each `Tuple` is the same length.
* For each type `T` on the left-hand side and each type `U` on the right-hand side, values of type `T` can be compared with values of type `U`.
* For each value `v1` on the left-hand side and each value `v2` on the right-hand side, the expression `v1 == v2` is true.

 

 
Parameters:


|  |  |
| --- | --- |
| R `rhs` | The `Tuple` to compare against. It must meeting the criteria for comparison between `Tuple`s. |


 
Returns:
true if both `Tuple`s are equal, otherwise false.
 
Examples:


```
Tuple!(int, string) t1 = tuple(1, "test");
Tuple!(double, string) t2 =  tuple(1.0, "test");
//Ok, int can be compared with double and
//both have a value of 1
writeln(t1); // t2

```
 
  int **opCmp**(R)(R rhs)  
 Constraints: if (areCompatibleTuples!(typeof(this), R, "<"));   
  
const int **opCmp**(R)(R rhs)  
 Constraints: if (areCompatibleTuples!(typeof(this), R, "<")); 
 
Comparison for ordering. 



Parameters:


|  |  |
| --- | --- |
| R `rhs` | The `Tuple` to compare against. It must meet the criteria for comparison between `Tuple`s. |


 
Returns:
For any values `v1` on the right-hand side and `v2` on the left-hand side: * A negative integer if the expression `v1 < v2` is true.
* A positive integer if the expression `v1 > v2` is true.
* 0 if the expression `v1 == v2` is true.



 
Examples:
The first `v1` for which `v1 > v2` is true determines the result. This could lead to unexpected behaviour. 
```
auto tup1 = tuple(1, 1, 1);
auto tup2 = tuple(1, 100, 100);
assert(tup1 < tup2);

//Only the first result matters for comparison
tup1[0] = 2;
assert(tup1 > tup2);

```
 
  auto **opBinary**(string op, T)(auto ref T t)  
 Constraints: if (op == "~" && !(is(T : U[], U) && isTuple!U));   
  
auto **opBinaryRight**(string op, T)(auto ref T t)  
 Constraints: if (op == "~" && !(is(T : U[], U) && isTuple!U)); 
 
Concatenate Tuples. Tuple concatenation is only allowed if all named fields are distinct (no named field of this tuple occurs in `t` and no named field of `t` occurs in this tuple). 



Parameters:


|  |  |
| --- | --- |
| T `t` | The `Tuple` to concatenate with |


 
Returns:
A concatenation of this tuple and `t`

  ref Tuple **opAssign**(R)(auto ref R rhs)  
 Constraints: if (areCompatibleTuples!(typeof(this), R, "=")); 
 
Assignment from another `Tuple`. 



Parameters:


|  |  |
| --- | --- |
| R `rhs` | The source `Tuple` to assign from. Each element of the source `Tuple` must be implicitly assignable to each respective element of the target `Tuple`. |


  inout ref auto **rename**(names...)() return  
 Constraints: if (names.length == 0 || allSatisfy!(isSomeString, typeof(names))); 
 
Renames the elements of a [`Tuple`](#Tuple). 


`rename` uses the passed `names` and returns a new [`Tuple`](#Tuple) using these names, with the content unchanged. If fewer names are passed than there are members of the [`Tuple`](#Tuple) then those trailing members are unchanged. An empty string will remove the name for that member. It is an compile-time error to pass more names than there are members of the [`Tuple`](#Tuple).

 
Examples:


```
auto t0 = tuple(4, "hello");

auto t0Named = t0.rename!("val", "tag");
writeln(t0Named.val); // 4
writeln(t0Named.tag); // "hello"

Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!"height";
t1Named.height = 3.4f;
writeln(t1Named.height); // 3.4f
writeln(t1Named.pos); // [2, 1]
t1Named.rename!"altitude".altitude = 5;
writeln(t1Named.height); // 5

Tuple!(int, "a", int, int, "c") t2;
t2 = tuple(3,4,5);
auto t2Named = t2.rename!("", "b");
// "a" no longer has a name
static assert(!__traits(hasMember, typeof(t2Named), "a"));
writeln(t2Named[0]); // 3
writeln(t2Named.b); // 4
writeln(t2Named.c); // 5

// not allowed to specify more names than the tuple has members
static assert(!__traits(compiles, t2.rename!("a","b","c","d")));

// use it in a range pipeline
import std.range : iota, zip;
import std.algorithm.iteration : map, sum;
auto res = zip(iota(1, 4), iota(10, 13))
    .map!(t => t.rename!("a", "b"))
    .map!(t => t.a * t.b)
    .sum;
writeln(res); // 68

const tup = Tuple!(int, "a", int, "b")(2, 3);
const renamed = tup.rename!("c", "d");
writeln(renamed.c + renamed.d); // 5

```
 
  inout ref auto **rename**(alias translate)()  
 Constraints: if (is(typeof(translate) : V[K], V, K) && isSomeString!V && (isSomeString!K || is(K : size\_t))); 
 
Overload of [`rename`](#rename) that takes an associative array `translate` as a template parameter, where the keys are either the names or indices of the members to be changed and the new names are the corresponding values. Every key in `translate` must be the name of a member of the [`tuple`](#tuple). The same rules for empty strings apply as for the variadic template overload of [`rename`](#rename).



Examples:


```
//replacing names by their current name

Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!(["dat": "height"]);
t1Named.height = 3.4;
writeln(t1Named.pos); // [2, 1]
t1Named.rename!(["height": "altitude"]).altitude = 5;
writeln(t1Named.height); // 5

Tuple!(int, "a", int, "b") t2;
t2 = tuple(3, 4);
auto t2Named = t2.rename!(["a": "b", "b": "c"]);
writeln(t2Named.b); // 3
writeln(t2Named.c); // 4

const t3 = Tuple!(int, "a", int, "b")(3, 4);
const t3Named = t3.rename!(["a": "b", "b": "c"]);
writeln(t3Named.b); // 3
writeln(t3Named.c); // 4

```
 
 
Examples:


```
//replace names by their position

Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!([0: "height"]);
t1Named.height = 3.4;
writeln(t1Named.pos); // [2, 1]
t1Named.rename!([0: "altitude"]).altitude = 5;
writeln(t1Named.height); // 5

Tuple!(int, "a", int, "b", int, "c") t2;
t2 = tuple(3, 4, 5);
auto t2Named = t2.rename!([0: "c", 2: "a"]);
writeln(t2Named.a); // 5
writeln(t2Named.b); // 4
writeln(t2Named.c); // 3

```
 
  inout @property ref @trusted inout(Tuple!(sliceSpecs!(from, to))) **slice**(size\_t from, size\_t to)()  
 Constraints: if (from <= to && (to <= Types.length)); 
 
Takes a slice by-reference of this `Tuple`. 



Parameters:


|  |  |
| --- | --- |
| from | A `size_t` designating the starting position of the slice. |
| to | A `size_t` designating the ending position (exclusive) of the slice. |


 
Returns:
A new `Tuple` that is a slice from `[from, to)` of the original. It has the same types and values as the range `[from, to)` in the original.
 
Examples:


```
Tuple!(int, string, float, double) a;
a[1] = "abc";
a[2] = 4.5;
auto s = a.slice!(1, 3);
static assert(is(typeof(s) == Tuple!(string, float)));
assert(s[0] == "abc" && s[1] == 4.5);

// https://issues.dlang.org/show_bug.cgi?id=15645
Tuple!(int, short, bool, double) b;
static assert(!__traits(compiles, b.slice!(2, 4)));

```
 
  const nothrow @safe size\_t **toHash**();  
Creates a hash of this `Tuple`. 



Returns:
A `size_t` representing the hash of this `Tuple`.
  const string **toString**()();  
Converts to string. 



Returns:
The string representation of this `Tuple`.
  const void **toString**(DG)(scope DG sink);   
  
const void **toString**(DG, Char)(scope DG sink, ref scope const FormatSpec!Char fmt);  
Formats `Tuple` with either `%s`, `%(inner%)` or `%(inner%|sep%)`. 




Formats supported by Tuple| **Format** | **Description** |
| `%s` | Format like `Tuple!(types)(elements formatted with %s each)`. |
| `%(inner%)` | The format `inner` is applied the expanded `Tuple`, so it may contain as many formats as the `Tuple` has fields. |
| `%(inner%|sep%)` | The format `inner` is one format, that is applied on all fields of the `Tuple`. The inner format must be compatible to all of them. |

 
Parameters:


|  |  |
| --- | --- |
| DG `sink` | A `char` accepting delegate |
| FormatSpec!Char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) |


 
Examples:


```
import std.format : format;

Tuple!(int, double)[3] tupList = [ tuple(1, 1.0), tuple(2, 4.0), tuple(3, 9.0) ];

// Default format
writeln(format("%s", tuple("a", 1))); // `Tuple!(string, int)("a", 1)`

// One Format for each individual component
writeln(format("%(%#x v %.4f w %#x%)", tuple(1, 1.0, 10))); // `0x1 v 1.0000 w 0xa`
writeln(format("%#x v %.4f w %#x", tuple(1, 1.0, 10).expand)); // `0x1 v 1.0000 w 0xa`

// One Format for all components
// `>abc< & >1< & >2.3< & >[4, 5]<`
writeln(format("%(>%s<%| & %)", tuple("abc", 1, 2.3, [4, 5])));

// Array of Tuples
writeln(format("%(%(f(%d) = %.1f%);  %)", tupList)); // `f(1) = 1.0;  f(2) = 4.0;  f(3) = 9.0`

```
 
 
Examples:


```
import std.exception : assertThrown;
import std.format : format, FormatException;

// Error: %( %) missing.
assertThrown!FormatException(
    format("%d, %f", tuple(1, 2.0)) == `1, 2.0`
);

// Error: %( %| %) missing.
assertThrown!FormatException(
    format("%d", tuple(1, 2)) == `1, 2`
);

// Error: %d inadequate for double
assertThrown!FormatException(
    format("%(%d%|, %)", tuple(1, 2.0)) == `1, 2.0`
);

```
 
    auto **reverse**(T)(T t)  
 Constraints: if (isTuple!T); 
 
Creates a copy of a [`Tuple`](#Tuple) with its fields in reverse order. 



Parameters:


|  |  |
| --- | --- |
| T `t` | The `Tuple` to copy. |


 
Returns:
A new `Tuple`.
 
Examples:


```
auto tup = tuple(1, "2");
writeln(tup.reverse); // tuple("2", 1)

```
 
  template **tuple**(Names...) 
Constructs a [`Tuple`](#Tuple) object instantiated and initialized according to the given arguments. 



Parameters:


|  |  |
| --- | --- |
| Names | An optional list of strings naming each successive field of the `Tuple` or a list of types that the elements are being casted to. For a list of names, each name matches up with the corresponding field given by `Args`. A name does not have to be provided for every field, but as the names must proceed in order, it is not possible to skip one field and name the next after it. For a list of types, there must be exactly as many types as parameters. |


 
Examples:


```
auto value = tuple(5, 6.7, "hello");
writeln(value[0]); // 5
writeln(value[1]); // 6.7
writeln(value[2]); // "hello"

// Field names can be provided.
auto entry = tuple!("index", "value")(4, "Hello");
writeln(entry.index); // 4
writeln(entry.value); // "Hello"

```
 
 
auto **tuple**(Args...)(Args args);  

Parameters:


|  |  |
| --- | --- |
| Args `args` | Values to initialize the `Tuple` with. The `Tuple`'s type will be inferred from the types of the values given. |


 
Returns:
A new `Tuple` with its type inferred from the arguments given.
    enum auto **isTuple**(T);  
Returns `true` if and only if `T` is an instance of `std.typecons.Tuple`. 



Parameters:


|  |  |
| --- | --- |
| T | The type to check. |


 
Returns:
true if `T` is a `Tuple` type, false otherwise.
 
Examples:


```
static assert(isTuple!(Tuple!()));
static assert(isTuple!(Tuple!(int)));
static assert(isTuple!(Tuple!(int, real, string)));
static assert(isTuple!(Tuple!(int, "x", real, "y")));
static assert(isTuple!(Tuple!(int, Tuple!(real), string)));

```
 
  template **Rebindable**(T) if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T) 
`Rebindable!(T)` is a simple, efficient wrapper that behaves just like an object of type `T`, except that you can reassign it to refer to another object. For completeness, `Rebindable!(T)` aliases itself away to `T` if `T` is a non-const object type. 


You may want to use `Rebindable` when you want to have mutable storage referring to `const` objects, for example an array of references that must be sorted in place. `Rebindable` does not break the soundness of D's type system and does not incur any of the risks usually associated with `cast`. 

 
Parameters:


|  |  |
| --- | --- |
| T | An object, interface, array slice type, or associative array type. |


 
Examples:
Regular `const` object references cannot be reassigned. 
```
class Widget { int x; int y() @safe const { return x; } }
const a = new Widget;
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// error! can't modify const a
// a = new Widget;

```
 
 
Examples:
However, `Rebindable!(Widget)` does allow reassignment, while otherwise behaving exactly like a `const Widget`. 
```
class Widget { int x; int y() const @safe { return x; } }
auto a = Rebindable!(const Widget)(new Widget);
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// Fine
a = new Widget;

```
 
  Rebindable!T **rebindable**(T)(T obj)  
 Constraints: if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T); 
 
Convenience function for creating a `Rebindable` using automatic type inference. 



Parameters:


|  |  |
| --- | --- |
| T `obj` | A reference to an object, interface, associative array, or an array slice to initialize the `Rebindable` with. |


 
Returns:
A newly constructed `Rebindable` initialized with the given reference.
 
Examples:


```
class C
{
    int payload;
    this(int p) { payload = p; }
}
const c = new C(1);

auto c2 = c.rebindable;
writeln(c2.payload); // 1
// passing Rebindable to rebindable
c2 = c2.rebindable;

c2 = new C(2);
writeln(c2.payload); // 2

const c3 = c2.get;
writeln(c3.payload); // 2

```
 
  Rebindable!T **rebindable**(T)(Rebindable!T obj);  
This function simply returns the `Rebindable` object passed in. It's useful in generic programming cases when a given object may be either a regular `class` or a `Rebindable`. 



Parameters:


|  |  |
| --- | --- |
| Rebindable!T `obj` | An instance of Rebindable!T. |


 
Returns:

`obj` without any modification.
 
Examples:


```
class C
{
    int payload;
    this(int p) { payload = p; }
}
const c = new C(1);

auto c2 = c.rebindable;
writeln(c2.payload); // 1
// passing Rebindable to rebindable
c2 = c2.rebindable;
writeln(c2.payload); // 1

```
 
  template **UnqualRef**(T) if (is(T == class) || is(T == interface)) 
Similar to `Rebindable!(T)` but strips all qualifiers from the reference as opposed to just constness / immutability. Primary intended use case is with shared (having thread-local reference to shared class data) 



Parameters:


|  |  |
| --- | --- |
| T | A class or interface type. |


 
Examples:


```
class Data {}

static shared(Data) a;
static UnqualRef!(shared Data) b;

import core.thread;

auto thread = new core.thread.Thread({
    a = new shared Data();
    b = new shared Data();
});

thread.start();
thread.join();

assert(a !is null);
assert(b is null);

```
 
  string **alignForSize**(E...)(const char[][] names...);  
Order the provided members to minimize size while preserving alignment. Alignment is not always optimal for 80-bit reals, nor for structs declared as align(1). 



Parameters:


|  |  |
| --- | --- |
| E | A list of the types to be aligned, representing fields of an aggregate such as a `struct` or `class`. |
| char[][] `names` | The names of the fields that are to be aligned. |


 
Returns:
A string to be mixed in to an aggregate, such as a `struct` or `class`.
 
Examples:


```
struct Banner {
    mixin(alignForSize!(byte[6], double)(["name", "height"]));
}

```
 
  struct **Nullable**(T);   
  
auto **nullable**(T)(T t);  
Defines a value paired with a distinctive "null" state that denotes the absence of a value. If default constructed, a `Nullable!T` object starts in the null state. Assigning it renders it non-null. Calling `nullify` can nullify it again. 


Practically `Nullable!T` stores a `T` and a `bool`.

 
Examples:


```
struct CustomerRecord
{
    string name;
    string address;
    int customerNum;
}

Nullable!CustomerRecord getByName(string name)
{
    //A bunch of hairy stuff

    return Nullable!CustomerRecord.init;
}

auto queryResult = getByName("Doe, John");
if (!queryResult.isNull)
{
    //Process Mr. Doe's customer record
    auto address = queryResult.get.address;
    auto customerNum = queryResult.get.customerNum;

    //Do some things with this customer's info
}
else
{
    //Add the customer to the database
}

```
 
 
Examples:


```
import std.exception : assertThrown;

auto a = 42.nullable;
assert(!a.isNull);
writeln(a.get); // 42

a.nullify();
assert(a.isNull);
assertThrown!Throwable(a.get);

```
 
 
inout this(inout T value);  
Constructor initializing `this` with `value`. 



Parameters:


|  |  |
| --- | --- |
| T `value` | The value to initialize this `Nullable` with. |


  const bool **opEquals**()(auto ref const(typeof(this)) rhs);   
  
const bool **opEquals**(U)(auto ref const(U) rhs)  
 Constraints: if (!is(U : typeof(this)) && is(typeof(this.get == rhs))); 
 
If they are both null, then they are equal. If one is null and the other is not, then they are not equal. If they are both non-null, then they are equal if their values are equal.



Examples:


```
Nullable!int empty;
Nullable!int a = 42;
Nullable!int b = 42;
Nullable!int c = 27;

writeln(empty); // empty
writeln(empty); // Nullable!int.init
assert(empty != a);
assert(empty != b);
assert(empty != c);

writeln(a); // b
assert(a != c);

assert(empty != 42);
writeln(a); // 42
assert(c != 42);

```
 
  string **toString**();   
  
const string **toString**();   
  
void **toString**(W)(ref W writer, ref scope const FormatSpec!char fmt)  
 Constraints: if (isOutputRange!(W, char));   
  
const void **toString**(W)(ref W writer, ref scope const FormatSpec!char fmt)  
 Constraints: if (isOutputRange!(W, char)); 
 
Gives the string `"Nullable.null"` if `isNull` is `true`. Otherwise, the result is equivalent to calling [`std.format.formattedWrite`](std_format#formattedWrite) on the underlying value. 



Parameters:


|  |  |
| --- | --- |
| W `writer` | A `char` accepting [output range](std_range_primitives#isOutputRange) |
| FormatSpec!char `fmt` | A [`std.format.FormatSpec`](std_format#FormatSpec) which is used to represent the value if this Nullable is not null |


 
Returns:
A `string` if `writer` and `fmt` are not set; `void` otherwise.
  const pure nothrow @property @safe bool **isNull**();  
Check if `this` is in the null state. 



Returns:
true **iff** `this` is in the null state, otherwise false.
 
Examples:


```
Nullable!int ni;
assert(ni.isNull);

ni = 0;
assert(!ni.isNull);

```
 
  void **nullify**()();  
Forces `this` to the null state.



Examples:


```
Nullable!int ni = 0;
assert(!ni.isNull);

ni.nullify();
assert(ni.isNull);

```
 
  void **opAssign**()(T value);  
Assigns `value` to the internally-held state. If the assignment succeeds, `this` becomes non-null. 



Parameters:


|  |  |
| --- | --- |
| T `value` | A value of type `T` to assign to this `Nullable`. |


  void **opAssign**()(Nullable!T value);  
If value is null, sets this to null, otherwise assigns `value.get` to the internally-held state. If the assignment succeeds, `this` becomes non-null. 



Parameters:


|  |  |
| --- | --- |
| Nullable!T `value` | A value of type `Nullable!T` to assign to this `Nullable`. |


 
Examples:
If this `Nullable` wraps a type that already has a null value (such as a pointer), then assigning the null value to this `Nullable` is no different than assigning any other value of type `T`, and the resulting code will look very strange. It is strongly recommended that this be avoided by instead using the version of `Nullable` that takes an additional `nullValue` template argument. 
```
//Passes
Nullable!(int*) npi;
assert(npi.isNull);

//Passes?!
npi = null;
assert(!npi.isNull);

```
 
  inout pure nothrow @property ref @safe inout(T) **get**();   
  
inout pure nothrow @property @safe inout(T) **get**()(inout(T) fallback);   
  
inout pure nothrow @property @safe auto **get**(U)(inout(U) fallback);  
Gets the value if not null. If `this` is in the null state, and the optional parameter `fallback` was provided, it will be returned. Without `fallback`, calling `get` with a null state is invalid. 


When the fallback type is different from the Nullable type, `get(T)` returns the common type. 

 
Parameters:


|  |  |
| --- | --- |
| inout(T) `fallback` | the value to return in case the `Nullable` is null. |


 
Returns:
The value held internally by this `Nullable`.
    struct **Nullable**(T, T nullValue);   
  
auto **nullable**(alias nullValue, T)(T t)  
 Constraints: if (is(typeof(nullValue) == T)); 
 
Just like `Nullable!T`, except that the null state is defined as a particular value. For example, `Nullable!(uint, uint.max)` is an `uint` that sets aside the value `uint.max` to denote a null state. `Nullable!(T, nullValue)` is more storage-efficient than `Nullable!T` because it does not need to store an extra `bool`. 



Parameters:


|  |  |
| --- | --- |
| T | The wrapped type for which Nullable provides a null value. |
| nullValue | The null value which denotes the null state of this `Nullable`. Must be of type `T`. |


 
Examples:


```
Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle)
{
    //Find the needle, returning -1 if not found

    return Nullable!(size_t, size_t.max).init;
}

void sendLunchInvite(string name)
{
}

//It's safer than C...
auto coworkers = ["Jane", "Jim", "Marry", "Fred"];
auto pos = indexOf(coworkers, "Bob");
if (!pos.isNull)
{
    //Send Bob an invitation to lunch
    sendLunchInvite(coworkers[pos]);
}
else
{
    //Bob not found; report the error
}

//And there's no overhead
static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);

```
 
 
Examples:


```
import std.exception : assertThrown;

Nullable!(int, int.min) a;
assert(a.isNull);
assertThrown!Throwable(a.get);
a = 5;
assert(!a.isNull);
writeln(a); // 5
static assert(a.sizeof == int.sizeof);

```
 
 
Examples:


```
auto a = nullable!(int.min)(8);
writeln(a); // 8
a.nullify();
assert(a.isNull);

```
 
 
this(T value);  
Constructor initializing `this` with `value`. 



Parameters:


|  |  |
| --- | --- |
| T `value` | The value to initialize this `Nullable` with. |


  const @property bool **isNull**();  
Check if `this` is in the null state. 



Returns:
true **iff** `this` is in the null state, otherwise false.
 
Examples:


```
Nullable!(int, -1) ni;
//Initialized to "null" state
assert(ni.isNull);

ni = 0;
assert(!ni.isNull);

```
 
  void **nullify**()();  
Forces `this` to the null state.



Examples:


```
Nullable!(int, -1) ni = 0;
assert(!ni.isNull);

ni = -1;
assert(ni.isNull);

```
 
  void **opAssign**()(T value);  
Assigns `value` to the internally-held state. If the assignment succeeds, `this` becomes non-null. No null checks are made. Note that the assignment may leave `this` in the null state. 



Parameters:


|  |  |
| --- | --- |
| T `value` | A value of type `T` to assign to this `Nullable`. If it is `nullvalue`, then the internal state of this `Nullable` will be set to null. |


 
Examples:
If this `Nullable` wraps a type that already has a null value (such as a pointer), and that null value is not given for `nullValue`, then assigning the null value to this `Nullable` is no different than assigning any other value of type `T`, and the resulting code will look very strange. It is strongly recommended that this be avoided by using `T`'s "built in" null value for `nullValue`. 
```
//Passes
enum nullVal = cast(int*) 0xCAFEBABE;
Nullable!(int*, nullVal) npi;
assert(npi.isNull);

//Passes?!
npi = null;
assert(!npi.isNull);

```
 
  inout @property ref inout(T) **get**();  
Gets the value. `this` must not be in the null state. This function is also called for the implicit conversion to `T`. 



Preconditions
 `isNull` must be `false`. 
 
Returns:
The value held internally by this `Nullable`.
 
Examples:


```
import std.exception : assertThrown, assertNotThrown;

Nullable!(int, -1) ni;
//`get` is implicitly called. Will throw
//an error in non-release mode
assertThrown!Throwable(ni == 0);

ni = 0;
assertNotThrown!Throwable(ni == 0);

```
 
    template **apply**(alias fun) 
Unpacks the content of a `Nullable`, performs an operation and packs it again. Does nothing if isNull. 


When called on a `Nullable`, `apply` will unpack the value contained in the `Nullable`, pass it to the function you provide and wrap the result in another `Nullable` (if necessary). If the `Nullable` is null, `apply` will return null itself. 

 
Parameters:


|  |  |
| --- | --- |
| T t | a `Nullable` |
| fun | a function operating on the content of the nullable |


 
Returns:

`fun(t.get).nullable` if `!t.isNull`, else `Nullable.init`. See also: [The `Maybe` monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad)

 
Examples:


```
alias toFloat = i => cast(float) i;

Nullable!int sample;

// apply(null) results in a null `Nullable` of the function's return type.
Nullable!float f = sample.apply!toFloat;
assert(sample.isNull && f.isNull);

sample = 3;

// apply(non-null) calls the function and wraps the result in a `Nullable`.
f = sample.apply!toFloat;
assert(!sample.isNull && !f.isNull);
writeln(f.get); // 3.0f

```
 
 
Examples:


```
alias greaterThree = i => (i > 3) ? i.nullable : Nullable!(typeof(i)).init;

Nullable!int sample;

// when the function already returns a `Nullable`, that `Nullable` is not wrapped.
auto result = sample.apply!greaterThree;
assert(sample.isNull && result.isNull);

// The function may decide to return a null `Nullable`.
sample = 3;
result = sample.apply!greaterThree;
assert(!sample.isNull && result.isNull);

// Or it may return a value already wrapped in a `Nullable`.
sample = 4;
result = sample.apply!greaterThree;
assert(!sample.isNull && !result.isNull);
writeln(result.get); // 4

```
 
  struct **NullableRef**(T);   
  
auto **nullableRef**(T)(T\* t);  
Just like `Nullable!T`, except that the object refers to a value sitting elsewhere in memory. This makes assignments overwrite the initially assigned value. Internally `NullableRef!T` only stores a pointer to `T` (i.e., `Nullable!T.sizeof == (T*).sizeof`).



Examples:


```
import std.exception : assertThrown;

int x = 5, y = 7;
auto a = nullableRef(&x);
assert(!a.isNull);
writeln(a); // 5
writeln(x); // 5
a = 42;
writeln(x); // 42
assert(!a.isNull);
writeln(a); // 42
a.nullify();
writeln(x); // 42
assert(a.isNull);
assertThrown!Throwable(a.get);
assertThrown!Throwable(a = 71);
a.bind(&y);
writeln(a); // 7
y = 135;
writeln(a); // 135

```
 
 
pure nothrow @safe this(T\* value);  
Constructor binding `this` to `value`. 



Parameters:


|  |  |
| --- | --- |
| T\* `value` | The value to bind to. |


  pure nothrow @safe void **bind**(T\* value);  
Binds the internal state to `value`. 



Parameters:


|  |  |
| --- | --- |
| T\* `value` | A pointer to a value of type `T` to bind this `NullableRef` to. |


 
Examples:


```
NullableRef!int nr = new int(42);
writeln(nr); // 42

int* n = new int(1);
nr.bind(n);
writeln(nr); // 1

```
 
  const pure nothrow @property @safe bool **isNull**();  
Returns `true` if and only if `this` is in the null state. 



Returns:
true if `this` is in the null state, otherwise false.
 
Examples:


```
NullableRef!int nr;
assert(nr.isNull);

int* n = new int(42);
nr.bind(n);
assert(!nr.isNull && nr == 42);

```
 
  pure nothrow @safe void **nullify**();  
Forces `this` to the null state.



Examples:


```
NullableRef!int nr = new int(42);
assert(!nr.isNull);

nr.nullify();
assert(nr.isNull);

```
 
  void **opAssign**()(T value)  
 Constraints: if (isAssignable!T); 
 
Assigns `value` to the internally-held state. 



Parameters:


|  |  |
| --- | --- |
| T `value` | A value of type `T` to assign to this `NullableRef`. If the internal state of this `NullableRef` has not been initialized, an error will be thrown in non-release mode. |


 
Examples:


```
import std.exception : assertThrown, assertNotThrown;

NullableRef!int nr;
assert(nr.isNull);
assertThrown!Throwable(nr = 42);

nr.bind(new int(0));
assert(!nr.isNull);
assertNotThrown!Throwable(nr = 42);
writeln(nr); // 42

```
 
  inout pure nothrow @property ref @safe inout(T) **get**();  
Gets the value. `this` must not be in the null state. This function is also called for the implicit conversion to `T`.



Examples:


```
import std.exception : assertThrown, assertNotThrown;

NullableRef!int nr;
//`get` is implicitly called. Will throw
//an error in non-release mode
assertThrown!Throwable(nr == 0);

nr.bind(new int(0));
assertNotThrown!Throwable(nr == 0);

```
 
    template **BlackHole**(Base) 
`BlackHole!Base` is a subclass of `Base` which automatically implements all abstract member functions in `Base` as do-nothing functions. Each auto-implemented function just returns the default value of the return type without doing anything. 


The name came from [Class::BlackHole](http://search.cpan.org/~sburke/Class-BlackHole-0.04/lib/Class/BlackHole.pm) Perl module by Sean M. Burke. 

 
Parameters:


|  |  |
| --- | --- |
| Base | A non-final class for `BlackHole` to inherit from. |


 
See Also:

[`AutoImplement`](#AutoImplement), [`generateEmptyFunction`](#generateEmptyFunction)

 
Examples:


```
import std.math : isNaN;

static abstract class C
{
    int m_value;
    this(int v) { m_value = v; }
    int value() @property { return m_value; }

    abstract real realValue() @property;
    abstract void doSomething();
}

auto c = new BlackHole!C(42);
writeln(c.value); // 42

// Returns real.init which is NaN
assert(c.realValue.isNaN);
// Abstract functions are implemented as do-nothing
c.doSomething();

```
 
  template **WhiteHole**(Base) 
`WhiteHole!Base` is a subclass of `Base` which automatically implements all abstract member functions as functions that always fail. These functions simply throw an `Error` and never return. `Whitehole` is useful for trapping the use of class member functions that haven't been implemented. 


The name came from [Class::WhiteHole](http://search.cpan.org/~mschwern/Class-WhiteHole-0.04/lib/Class/WhiteHole.pm) Perl module by Michael G Schwern. 

 
Parameters:


|  |  |
| --- | --- |
| Base | A non-final class for `WhiteHole` to inherit from. |


 
See Also:

[`AutoImplement`](#AutoImplement), [`generateAssertTrap`](#generateAssertTrap)

 
Examples:


```
import std.exception : assertThrown;

static class C
{
    abstract void notYetImplemented();
}

auto c = new WhiteHole!C;
assertThrown!NotImplementedError(c.notYetImplemented()); // throws an Error

```
 
  class **AutoImplement**(Base, alias how, alias what = isAbstractFunction) if (!is(how == class)): Base;   
  
class **AutoImplement**(Interface, BaseClass, alias how, alias what = isAbstractFunction) if (is(Interface == interface) && is(BaseClass == class)): BaseClass, Interface;  
`AutoImplement` automatically implements (by default) all abstract member functions in the class or interface `Base` in specified way. 


The second version of `AutoImplement` automatically implements `Interface`, while deriving from `BaseClass`. 

 
Parameters:


|  |  |
| --- | --- |
| how | template which specifies how functions will be implemented/overridden. Two arguments are passed to `how`: the type `Base` and an alias to an implemented function. Then `how` must return an implemented function body as a string. The generated function body can use these keywords: * `a0`, `a1`, …: arguments passed to the function;
* `args`: a tuple of the arguments;
* `self`: an alias to the function itself;
* `parent`: an alias to the overridden function (if any).

 You may want to use templated property functions (instead of Implicit Template Properties) to generate complex functions: 
```
// Prints log messages for each call to overridden functions.
string generateLogger(C, alias fun)() @property
{
    import std.traits;
    enum qname = C.stringof ~ "." ~ __traits(identifier, fun);
    string stmt;

    stmt ~= q{ struct Importer { import std.stdio; } };
    stmt ~= `Importer.writeln("Log: ` ~ qname ~ `(", args, ")");`;
    static if (!__traits(isAbstractFunction, fun))
    {
        static if (is(ReturnType!fun == void))
            stmt ~= q{ parent(args); };
        else
            stmt ~= q{
                auto r = parent(args);
                Importer.writeln("--> ", r);
                return r;
            };
    }
    return stmt;
}

```
 |
| what | template which determines what functions should be implemented/overridden. An argument is passed to `what`: an alias to a non-final member function in `Base`. Then `what` must return a boolean value. Return `true` to indicate that the passed function should be implemented/overridden. 
```
// Sees if fun returns something.
enum bool hasValue(alias fun) = !is(ReturnType!(fun) == void);

```
 |


 
Note
 Generated code is inserted in the scope of `std.typecons` module. Thus, any useful functions outside `std.typecons` cannot be used in the generated code. To workaround this problem, you may `import` necessary things in a local struct, as done in the `generateLogger()` template in the above example. 
 
Bugs:
* Variadic arguments to constructors are not forwarded to super.
* Deep interface inheritance causes compile error with messages like "Error: function std.typecons.AutoImplement!(Foo).AutoImplement.bar does not override any function". [[Bugzilla 2525](https://issues.dlang.org/show_bug.cgi?id=2525)]
* The `parent` keyword is actually a delegate to the super class' corresponding member function. [[Bugzilla 2540](https://issues.dlang.org/show_bug.cgi?id=2540)]
* Using alias template parameter in `how` and/or `what` may cause strange compile error. Use template tuple parameter instead to workaround this problem. [[Bugzilla 4217](https://issues.dlang.org/show_bug.cgi?id=4217)]

 
Examples:


```
interface PackageSupplier
{
    int foo();
    int bar();
}

static abstract class AbstractFallbackPackageSupplier : PackageSupplier
{
    protected PackageSupplier default_, fallback;

    this(PackageSupplier default_, PackageSupplier fallback)
    {
        this.default_ = default_;
        this.fallback = fallback;
    }

    abstract int foo();
    abstract int bar();
}

template fallback(T, alias func)
{
    import std.format : format;
    // for all implemented methods:
    // - try default first
    // - only on a failure run & return fallback
    enum fallback = q{
        scope (failure) return fallback.%1&dollar;s(args);
        return default_.%1&dollar;s(args);
    }.format(__traits(identifier, func));
}

// combines two classes and use the second one as fallback
alias FallbackPackageSupplier = AutoImplement!(AbstractFallbackPackageSupplier, fallback);

class FailingPackageSupplier : PackageSupplier
{
    int foo(){ throw new Exception("failure"); }
    int bar(){ return 2;}
}

class BackupPackageSupplier : PackageSupplier
{
    int foo(){ return -1; }
    int bar(){ return -1;}
}

auto registry = new FallbackPackageSupplier(new FailingPackageSupplier(), new BackupPackageSupplier());

writeln(registry.foo()); // -1
writeln(registry.bar()); // 2

```
 
  template **generateEmptyFunction**(C, func...)  
  
enum string **generateAssertTrap**(C, func...);  
Predefined how-policies for `AutoImplement`. These templates are also used by `BlackHole` and `WhiteHole`, respectively.



Examples:


```
alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction);

interface I
{
    int foo();
    string bar();
}

auto i = new BlackHole!I();
// generateEmptyFunction returns the default value of the return type without doing anything
writeln(i.foo); // 0
assert(i.bar is null);

```
 
 
Examples:


```
import std.exception : assertThrown;

alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap);

interface I
{
    int foo();
    string bar();
}

auto i = new WhiteHole!I();
// generateAssertTrap throws an exception for every unimplemented function of the interface
assertThrown!NotImplementedError(i.foo);
assertThrown!NotImplementedError(i.bar);

```
 
  template **wrap**(Targets...) if (Targets.length >= 1 && allSatisfy!(isMutable, Targets))  
  
template **wrap**(Targets...) if (Targets.length >= 1 && !allSatisfy!(isMutable, Targets))  
  
template **unwrap**(Target) if (isMutable!Target)  
  
template **unwrap**(Target) if (!isMutable!Target) 
Supports structural based typesafe conversion. 


If `Source` has structural conformance with the `interface` `Targets`, wrap creates an internal wrapper class which inherits `Targets` and wraps the `src` object, then returns it.   
  
 `unwrap` can be used to extract objects which have been wrapped by `wrap`.

 
Examples:


```
interface Quack
{
    int quack();
    @property int height();
}
interface Flyer
{
    @property int height();
}
class Duck : Quack
{
    int quack() { return 1; }
    @property int height() { return 10; }
}
class Human
{
    int quack() { return 2; }
    @property int height() { return 20; }
}

Duck d1 = new Duck();
Human h1 = new Human();

interface Refleshable
{
    int reflesh();
}

// does not have structural conformance
static assert(!__traits(compiles, d1.wrap!Refleshable));
static assert(!__traits(compiles, h1.wrap!Refleshable));

// strict upcast
Quack qd = d1.wrap!Quack;
assert(qd is d1);
assert(qd.quack() == 1);    // calls Duck.quack
// strict downcast
Duck d2 = qd.unwrap!Duck;
assert(d2 is d1);

// structural upcast
Quack qh = h1.wrap!Quack;
assert(qh.quack() == 2);    // calls Human.quack
// structural downcast
Human h2 = qh.unwrap!Human;
assert(h2 is h1);

// structural upcast (two steps)
Quack qx = h1.wrap!Quack;   // Human -> Quack
Flyer fx = qx.wrap!Flyer;   // Quack -> Flyer
assert(fx.height == 20);    // calls Human.height
// structural downcast (two steps)
Quack qy = fx.unwrap!Quack; // Flyer -> Quack
Human hy = qy.unwrap!Human; // Quack -> Human
assert(hy is h1);
// structural downcast (one step)
Human hz = fx.unwrap!Human; // Flyer -> Human
assert(hz is h1);

```
 
 
Examples:


```
import std.traits : FunctionAttribute, functionAttributes;
interface A { int run(); }
interface B { int stop(); @property int status(); }
class X
{
    int run() { return 1; }
    int stop() { return 2; }
    @property int status() { return 3; }
}

auto x = new X();
auto ab = x.wrap!(A, B);
A a = ab;
B b = ab;
writeln(a.run()); // 1
writeln(b.stop()); // 2
writeln(b.status); // 3
static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);

```
 
  enum **RefCountedAutoInitialize**: int;  
Options regarding auto-initialization of a `RefCounted` object (see the definition of `RefCounted` below).



Examples:


```
import core.exception : AssertError;
import std.exception : assertThrown;

struct Foo
{
    int a = 42;
}

RefCounted!(Foo, RefCountedAutoInitialize.yes) rcAuto;
RefCounted!(Foo, RefCountedAutoInitialize.no) rcNoAuto;

writeln(rcAuto.refCountedPayload.a); // 42

assertThrown!AssertError(rcNoAuto.refCountedPayload);
rcNoAuto.refCountedStore.ensureInitialized;
writeln(rcNoAuto.refCountedPayload.a); // 42

```
 
 
**no** 
Do not auto-initialize the object

  **yes** 
Auto-initialize the object

    struct **RefCounted**(T, RefCountedAutoInitialize autoInit = RefCountedAutoInitialize.yes) if (!is(T == class) && !is(T == interface));  
Defines a reference-counted object containing a `T` value as payload. 


An instance of `RefCounted` is a reference to a structure, which is referred to as the *store*, or *storage implementation struct* in this documentation. The store contains a reference count and the `T` payload. `RefCounted` uses `malloc` to allocate the store. As instances of `RefCounted` are copied or go out of scope, they will automatically increment or decrement the reference count. When the reference count goes down to zero, `RefCounted` will call `destroy` against the payload and call `free` to deallocate the store. If the `T` payload contains any references to GC-allocated memory, then `RefCounted` will add it to the GC memory that is scanned for pointers, and remove it from GC scanning before `free` is called on the store.   
  
 One important consequence of `destroy` is that it will call the destructor of the `T` payload. GC-managed references are not guaranteed to be valid during a destructor call, but other members of `T`, such as file handles or pointers to `malloc` memory, will still be valid during the destructor call. This allows the `T` to deallocate or clean up any non-GC resources immediately after the reference count has reached zero.   
  
 `RefCounted` is unsafe and should be used with care. No references to the payload should be escaped outside the `RefCounted` object.   
  
 The `autoInit` option makes the object ensure the store is automatically initialized. Leaving `autoInit == RefCountedAutoInitialize.yes` (the default option) is convenient but has the cost of a test whenever the payload is accessed. If `autoInit == RefCountedAutoInitialize.no`, user code must call either `refCountedStore.isInitialized` or `refCountedStore.ensureInitialized` before attempting to access the payload. Not doing so results in null pointer dereference.

 
Examples:


```
// A pair of an `int` and a `size_t` - the latter being the
// reference count - will be dynamically allocated
auto rc1 = RefCounted!int(5);
writeln(rc1); // 5
// No more allocation, add just one extra reference count
auto rc2 = rc1;
// Reference semantics
rc2 = 42;
writeln(rc1); // 42
// the pair will be freed when rc1 and rc2 go out of scope

```
 
 
struct **RefCountedStore**;  
`RefCounted` storage implementation.

 
const pure nothrow @nogc @property @safe bool **isInitialized**();  
Returns `true` if and only if the underlying store has been allocated and initialized.

  const pure nothrow @nogc @property @safe size\_t **refCount**();  
Returns underlying reference count if it is allocated and initialized (a positive integer), and `0` otherwise.

  void **ensureInitialized**();  
Makes sure the payload was properly initialized. Such a call is typically inserted before using the payload.

    inout nothrow @property ref @safe inout(RefCountedStore) **refCountedStore**();  
Returns storage implementation struct.

  this(A...)(auto ref A args)  
 Constraints: if (A.length > 0);   
  
this(T val);  
Constructor that initializes the payload. 



Postcondition
 `refCountedStore.isInitialized`

  void **opAssign**(typeof(this) rhs);   
  
void **opAssign**(T rhs);  
Assignment operators

  @property ref @trusted T **refCountedPayload**() return;   
  
inout pure nothrow @nogc @property ref @safe inout(T) **refCountedPayload**() return;  
Returns a reference to the payload. If (autoInit == RefCountedAutoInitialize.yes), calls  `refCountedStore.ensureInitialized`. Otherwise, just issues  `assert(refCountedStore.isInitialized)`. Used with `alias refCountedPayload this;`, so callers can just use the `RefCounted` object as a `T`. 


The first overload exists only if `autoInit == RefCountedAutoInitialize.yes`. So if `autoInit == RefCountedAutoInitialize.no` or called for a constant or immutable object, then `refCountedPayload` will also be qualified as safe and nothrow (but will still assert if not initialized).

    RefCounted!(T, RefCountedAutoInitialize.no) **refCounted**(T)(T val);  
Initializes a `RefCounted` with `val`. The template parameter `T` of `RefCounted` is inferred from `val`. This function can be used to move non-copyable values to the heap. It also disables the `autoInit` option of `RefCounted`. 



Parameters:


|  |  |
| --- | --- |
| T `val` | The value to be reference counted |


 
Returns:
An initialized `RefCounted` containing `val`. 
 
See Also:
[C++'s make\_shared](http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared)
 
Examples:


```
static struct File
{
    string name;
    @disable this(this); // not copyable
    ~this() { name = null; }
}

auto file = File("name");
writeln(file.name); // "name"
// file cannot be copied and has unique ownership
static assert(!__traits(compiles, {auto file2 = file;}));

// make the file refcounted to share ownership
import std.algorithm.mutation : move;
auto rcFile = refCounted(move(file));
writeln(rcFile.name); // "name"
writeln(file.name); // null
auto rcFile2 = rcFile;
writeln(rcFile.refCountedStore.refCount); // 2
// file gets properly closed when last reference is dropped

```
 
  template **Proxy**(alias a) 
Creates a proxy for the value `a` that will forward all operations while disabling implicit conversions. The aliased item `a` must be an **lvalue**. This is useful for creating a new type from the "base" type (though this is **not** a subtype-supertype relationship; the new type is not related to the old type in any way, by design). 


The new type supports all operations that the underlying type does, including all operators such as `+`, `--`, `<`, `[]`, etc. 

 
Parameters:


|  |  |
| --- | --- |
| a | The value to act as a proxy for all operations. It must be an lvalue. |


 
Examples:


```
struct MyInt
{
    private int value;
    mixin Proxy!value;

    this(int n){ value = n; }
}

MyInt n = 10;

// Enable operations that original type has.
++n;
writeln(n); // 11
writeln(n * 2); // 22

void func(int n) { }

// Disable implicit conversions to original type.
//int x = n;
//func(n);

```
 
 
Examples:
The proxied value must be an **lvalue**. 
```
struct NewIntType
{
    //Won't work; the literal '1'
    //is an rvalue, not an lvalue
    //mixin Proxy!1;

    //Okay, n is an lvalue
    int n;
    mixin Proxy!n;

    this(int n) { this.n = n; }
}

NewIntType nit = 0;
nit++;
writeln(nit); // 1


struct NewObjectType
{
    Object obj;
    //Ok, obj is an lvalue
    mixin Proxy!obj;

    this (Object o) { obj = o; }
}

NewObjectType not = new Object();
assert(__traits(compiles, not.toHash()));

```
 
 
Examples:
There is one exception to the fact that the new type is not related to the old type. [Pseudo-member](https://dlang.org/spec/function.html#pseudo-member) functions are usable with the new type; they will be forwarded on to the proxied value. 
```
import std.math;

float f = 1.0;
assert(!f.isInfinity);

struct NewFloat
{
    float _;
    mixin Proxy!_;

    this(float f) { _ = f; }
}

NewFloat nf = 1.0f;
assert(!nf.isInfinity);

```
 
  struct **Typedef**(T, T init = T.init, string cookie = null);  
**Typedef** allows the creation of a unique type which is based on an existing type. Unlike the `alias` feature, **Typedef** ensures the two types are not considered as equals. 



Parameters:


|  |  |
| --- | --- |
| init | Optional initial value for the new type. |
| cookie | Optional, used to create multiple unique types which are based on the same origin type `T` |


 
Note
 If a library routine cannot handle the Typedef type, you can use the `TypedefType` template to extract the type which the Typedef wraps.
 
Examples:


```
alias MyInt = Typedef!int;
MyInt foo = 10;
foo++;
writeln(foo); // 11

```
 
 
Examples:
custom initialization values 
```
alias MyIntInit = Typedef!(int, 42);
static assert(is(TypedefType!MyIntInit == int));
static assert(MyIntInit() == 42);

```
 
 
Examples:
Typedef creates a new type 
```
alias MyInt = Typedef!int;
static void takeInt(int) {}
static void takeMyInt(MyInt) {}

int i;
takeInt(i);    // ok
static assert(!__traits(compiles, takeMyInt(i)));

MyInt myInt;
static assert(!__traits(compiles, takeInt(myInt)));
takeMyInt(myInt);  // ok

```
 
 
Examples:
Use the optional `cookie` argument to create different types of the same base type 
```
alias TypeInt1 = Typedef!int;
alias TypeInt2 = Typedef!int;

// The two Typedefs are the same type.
static assert(is(TypeInt1 == TypeInt2));

alias MoneyEuros = Typedef!(float, float.init, "euros");
alias MoneyDollars = Typedef!(float, float.init, "dollars");

// The two Typedefs are _not_ the same type.
static assert(!is(MoneyEuros == MoneyDollars));

```
 
 
string **toString**(this T)();   
  
void **toString**(this T, W)(ref W writer, ref scope const FormatSpec!char fmt)  
 Constraints: if (isOutputRange!(W, char)); 
 
Convert wrapped value to a human readable string



Examples:


```
import std.conv : to;

int i = 123;
auto td = Typedef!int(i);
writeln(i.to!string); // td.to!string

```
 
    template **TypedefType**(T) 
Get the underlying type which a `Typedef` wraps. If `T` is not a `Typedef` it will alias itself to `T`.



Examples:


```
import std.conv : to;

alias MyInt = Typedef!int;
static assert(is(TypedefType!MyInt == int));

/// Instantiating with a non-Typedef will return that type
static assert(is(TypedefType!int == int));

string num = "5";

// extract the needed type
MyInt myInt = MyInt( num.to!(TypedefType!MyInt) );
writeln(myInt); // 5

// cast to the underlying type to get the value that's being wrapped
int x = cast(TypedefType!MyInt) myInt;

alias MyIntInit = Typedef!(int, 42);
static assert(is(TypedefType!MyIntInit == int));
static assert(MyIntInit() == 42);

```
 
  template **scoped**(T) if (is(T == class)) 
Allocates a `class` object right inside the current scope, therefore avoiding the overhead of `new`. This facility is unsafe; it is the responsibility of the user to not escape a reference to the object outside the scope. 


The class destructor will be called when the result of `scoped()` is itself destroyed.   
  
 Scoped class instances can be embedded in a parent `class` or `struct`, just like a child struct instance. Scoped member variables must have type `typeof(scoped!Class(args))`, and be initialized with a call to scoped. See below for an example. 

 
Note
 It's illegal to move a class instance even if you are sure there are no pointers to it. As such, it is illegal to move a scoped object.
 
Examples:


```
class A
{
    int x;
    this()     {x = 0;}
    this(int i){x = i;}
    ~this()    {}
}

// Standard usage, constructing A on the stack
auto a1 = scoped!A();
a1.x = 42;

// Result of `scoped` call implicitly converts to a class reference
A aRef = a1;
writeln(aRef.x); // 42

// Scoped destruction
{
    auto a2 = scoped!A(1);
    writeln(a2.x); // 1
    aRef = a2;
    // a2 is destroyed here, calling A's destructor
}
// aRef is now an invalid reference

// Here the temporary scoped A is immediately destroyed.
// This means the reference is then invalid.
version (Bug)
{
    // Wrong, should use `auto`
    A invalid = scoped!A();
}

// Restrictions
version (Bug)
{
    import std.algorithm.mutation : move;
    auto invalid = a1.move; // illegal, scoped objects can't be moved
}
static assert(!is(typeof({
    auto e1 = a1; // illegal, scoped objects can't be copied
    assert([a1][0].x == 42); // ditto
})));
static assert(!is(typeof({
    alias ScopedObject = typeof(a1);
    auto e2 = ScopedObject();  // illegal, must be built via scoped!A
    auto e3 = ScopedObject(1); // ditto
})));

// Use with alias
alias makeScopedA = scoped!A;
auto a3 = makeScopedA();
auto a4 = makeScopedA(1);

// Use as member variable
struct B
{
    typeof(scoped!A()) a; // note the trailing parentheses

    this(int i)
    {
        // construct member
        a = scoped!A(i);
    }
}

// Stack-allocate
auto b1 = B(5);
aRef = b1.a;
writeln(aRef.x); // 5
destroy(b1); // calls A's destructor for b1.a
// aRef is now an invalid reference

// Heap-allocate
auto b2 = new B(6);
writeln(b2.a.x); // 6
destroy(*b2); // calls A's destructor for b2.a

```
 
 
@system auto **scoped**(Args...)(auto ref Args args);  
Returns the scoped object. 



Parameters:


|  |  |
| --- | --- |
| Args `args` | Arguments to pass to `T`'s constructor. |


    template **Flag**(string name) 
Defines a simple, self-documenting yes/no flag. This makes it easy for APIs to define functions accepting flags without resorting to `bool`, which is opaque in calls, and without needing to define an enumerated type separately. Using `Flag!"Name"` instead of `bool` makes the flag's meaning visible in calls. Each yes/no flag has its own type, which makes confusions and mix-ups impossible. 



Example
 Code calling `getLine` (usually far away from its definition) can't be understood without looking at the documentation, even by users familiar with the API: 


```
string getLine(bool keepTerminator)
{
    ...
    if (keepTerminator) ...
    ...
}
...
auto line = getLine(false);

```
 Assuming the reverse meaning (i.e. "ignoreTerminator") and inserting the wrong code compiles and runs with erroneous results. After replacing the boolean parameter with an instantiation of `Flag`, code calling `getLine` can be easily read and understood even by people not fluent with the API: 
```
string getLine(Flag!"keepTerminator" keepTerminator)
{
    ...
    if (keepTerminator) ...
    ...
}
...
auto line = getLine(Yes.keepTerminator);

```
 The structs `Yes` and `No` are provided as shorthand for `Flag!"Name".yes` and `Flag!"Name".no` and are preferred for brevity and readability. These convenience structs mean it is usually unnecessary and counterproductive to create an alias of a `Flag` as a way of avoiding typing out the full type while specifying the affirmative or negative options. Passing categorical data by means of unstructured `bool` parameters is classified under "simple-data coupling" by Steve McConnell in the [Code Complete](https://google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=Code%20Complete) book, along with three other kinds of coupling. The author argues citing several studies that coupling has a negative effect on code quality. `Flag` offers a simple structuring method for passing yes/no flags to APIs. 
Examples:


```
Flag!"abc" flag;

writeln(flag); // Flag!"abc".no
writeln(flag); // No.abc
assert(!flag);
if (flag) assert(0);

```
 
 
Examples:


```
auto flag = Yes.abc;

assert(flag);
writeln(flag); // Yes.abc
if (!flag) assert(0);
if (flag) {} else assert(0);

```
 
 
enum **Flag**: bool;   
**no** 
When creating a value of type `Flag!"Name"`, use  `Flag!"Name".no` for the negative option. When using a value of type `Flag!"Name"`, compare it against  `Flag!"Name".no` or just `false` or `0`.

  **yes** 
When creating a value of type `Flag!"Name"`, use  `Flag!"Name".yes` for the affirmative option. When using a value of type `Flag!"Name"`, compare it against  `Flag!"Name".yes`.

      struct **Yes**;   
  
struct **No**;  
Convenience names that allow using e.g. `Yes.encryption` instead of `Flag!"encryption".yes` and `No.encryption` instead of `Flag!"encryption".no`.



Examples:


```
Flag!"abc" flag;

writeln(flag); // Flag!"abc".no
writeln(flag); // No.abc
assert(!flag);
if (flag) assert(0);

```
 
 
Examples:


```
auto flag = Yes.abc;

assert(flag);
writeln(flag); // Yes.abc
if (!flag) assert(0);
if (flag) {} else assert(0);

```
 
  template **isBitFlagEnum**(E) 
Detect whether an enum is of integral type and has only "flag" values (i.e. values with a bit count of exactly 1). Additionally, a zero value is allowed for compatibility with enums including a "None" value.



Examples:


```
enum A
{
    None,
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
    D = 1 << 3,
}

static assert(isBitFlagEnum!A);

```
 
 
Examples:
Test an enum with default (consecutive) values 
```
enum B
{
    A,
    B,
    C,
    D // D == 3
}

static assert(!isBitFlagEnum!B);

```
 
 
Examples:
Test an enum with non-integral values 
```
enum C: double
{
    A = 1 << 0,
    B = 1 << 1
}

static assert(!isBitFlagEnum!C);

```
 
  struct **BitFlags**(E, Flag!"unsafe" unsafe = No.unsafe) if (unsafe || isBitFlagEnum!E);  
A typesafe structure for storing combinations of enum values. 


This template defines a simple struct to represent bitwise OR combinations of enum values. It can be used if all the enum values are integral constants with a bit count of at most 1, or if the `unsafe` parameter is explicitly set to Yes. This is much safer than using the enum itself to store the OR combination, which can produce surprising effects like this: 
```
enum E
{
    A = 1 << 0,
    B = 1 << 1
}
E e = E.A | E.B;
// will throw SwitchError
final switch (e)
{
    case E.A:
        return;
    case E.B:
        return;
}

```
 

 
Examples:
Set values with the | operator and test with & 
```
enum Enum
{
    A = 1 << 0,
}

// A default constructed BitFlags has no value set
immutable BitFlags!Enum flags_empty;
assert(!flags_empty.A);

// Value can be set with the | operator
immutable flags_A = flags_empty | Enum.A;

// and tested using property access
assert(flags_A.A);

// or the & operator
assert(flags_A & Enum.A);
// which commutes.
assert(Enum.A & flags_A);

```
 
 
Examples:
A default constructed BitFlags has no value set 
```
enum Enum
{
    None,
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2
}

immutable BitFlags!Enum flags_empty;
assert(!(flags_empty & (Enum.A | Enum.B | Enum.C)));
assert(!(flags_empty & Enum.A) && !(flags_empty & Enum.B) && !(flags_empty & Enum.C));

```
 
 
Examples:
Binary operations: subtracting and intersecting flags 
```
enum Enum
{
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
}
immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B);
immutable BitFlags!Enum flags_BC = BitFlags!Enum(Enum.B, Enum.C);

// Use the ~ operator for subtracting flags
immutable BitFlags!Enum flags_B = flags_AB & ~BitFlags!Enum(Enum.A);
assert(!flags_B.A && flags_B.B && !flags_B.C);

// use & between BitFlags for intersection
writeln(flags_B); // (flags_BC & flags_AB)

```
 
 
Examples:
All the binary operators work in their assignment version 
```
enum Enum
{
    A = 1 << 0,
    B = 1 << 1,
}

BitFlags!Enum flags_empty, temp, flags_AB;
flags_AB = Enum.A | Enum.B;

temp |= flags_AB;
writeln(temp); // (flags_empty | flags_AB)

temp = flags_empty;
temp |= Enum.B;
writeln(temp); // (flags_empty | Enum.B)

temp = flags_empty;
temp &= flags_AB;
writeln(temp); // (flags_empty & flags_AB)

temp = flags_empty;
temp &= Enum.A;
writeln(temp); // (flags_empty & Enum.A)

```
 
 
Examples:
Conversion to bool and int 
```
enum Enum
{
    A = 1 << 0,
    B = 1 << 1,
}

BitFlags!Enum flags;

// BitFlags with no value set evaluate to false
assert(!flags);

// BitFlags with at least one value set evaluate to true
flags |= Enum.A;
assert(flags);

// This can be useful to check intersection between BitFlags
BitFlags!Enum flags_AB = Enum.A | Enum.B;
assert(flags & flags_AB);
assert(flags & Enum.A);

// You can of course get you raw value out of flags
auto value = cast(int) flags;
writeln(value); // Enum.A

```
 
 
Examples:
You need to specify the `unsafe` parameter for enums with custom values 
```
enum UnsafeEnum
{
    A = 1,
    B = 2,
    C = 4,
    BC = B|C
}
static assert(!__traits(compiles, { BitFlags!UnsafeEnum flags; }));
BitFlags!(UnsafeEnum, Yes.unsafe) flags;

// property access tests for exact match of unsafe enums
flags.B = true;
assert(!flags.BC); // only B
flags.C = true;
assert(flags.BC); // both B and C
flags.B = false;
assert(!flags.BC); // only C

// property access sets all bits of unsafe enum group
flags = flags.init;
flags.BC = true;
assert(!flags.A && flags.B && flags.C);
flags.A = true;
flags.BC = false;
assert(flags.A && !flags.B && !flags.C);

```
 
  template **ReplaceType**(From, To, T...) 
Replaces all occurrences of `From` into `To`, in one or more types `T`. For example, `ReplaceType!(int, uint, Tuple!(int, float)[string])` yields `Tuple!(uint, float)[string]`. The types in which replacement is performed may be arbitrarily complex, including qualifiers, built-in type constructors (pointers, arrays, associative arrays, functions, and delegates), and template instantiations; replacement proceeds transitively through the type definition. However, member types in `struct`s or `class`es are not replaced because there are no ways to express the types resulting after replacement. 


This is an advanced type manipulation necessary e.g. for replacing the placeholder type `This` in [`std.variant.Algebraic`](std_variant#Algebraic). 

 
Returns:

`ReplaceType` aliases itself to the type(s) that result after replacement.
 
Examples:


```
static assert(
    is(ReplaceType!(int, string, int[]) == string[]) &&
    is(ReplaceType!(int, string, int[int]) == string[string]) &&
    is(ReplaceType!(int, string, const(int)[]) == const(string)[]) &&
    is(ReplaceType!(int, string, Tuple!(int[], float))
        == Tuple!(string[], float))
);

```
 
  template **ReplaceTypeUnless**(alias pred, From, To, T...) 
Like [`ReplaceType`](#ReplaceType), but does not perform replacement in types for which `pred` evaluates to `true`.



Examples:


```
import std.traits : isArray;

static assert(
    is(ReplaceTypeUnless!(isArray, int, string, int*) == string*) &&
    is(ReplaceTypeUnless!(isArray, int, string, int[]) == int[]) &&
    is(ReplaceTypeUnless!(isArray, int, string, Tuple!(int, int[]))
        == Tuple!(string, int[]))
);

```
 
  struct **Ternary**;  
Ternary type with three truth values: 


* `Ternary.yes` for `true`
* `Ternary.no` for `false`
* `Ternary.unknown` as an unknown state

   
  
 Also known as trinary, trivalent, or trilean. 

 
See Also:
 [Three Valued Logic on Wikipedia](http://en.wikipedia.org/wiki/Three-valued_logic)
 
Examples:


```
Ternary a;
writeln(a); // Ternary.unknown

writeln(~Ternary.yes); // Ternary.no
writeln(~Ternary.no); // Ternary.yes
writeln(~Ternary.unknown); // Ternary.unknown

```
 
 
enum Ternary **no**;   
  
enum Ternary **yes**;   
  
enum Ternary **unknown**;  
The possible states of the `Ternary`

  pure nothrow @nogc @safe this(bool b);   
  
pure nothrow @nogc @safe void **opAssign**(bool b);  
Construct and assign from a `bool`, receiving `no` for `false` and `yes` for `true`.

  pure nothrow @nogc @safe this(const Ternary b);  
Construct a ternary value from another ternary value

  Ternary **opUnary**(string s)()  
 Constraints: if (s == "~");   
  
Ternary **opBinary**(string s)(Ternary rhs)  
 Constraints: if (s == "|");   
  
Ternary **opBinary**(string s)(Ternary rhs)  
 Constraints: if (s == "&");   
  
Ternary **opBinary**(string s)(Ternary rhs)  
 Constraints: if (s == "^");   
  
Ternary **opBinary**(string s)(bool rhs)  
 Constraints: if (s == "|" || s == "&" || s == "^"); 
 


Truth table for logical operations| `a` | `b` | `˜a` | `a | b` | `a & b` | `a ^ b` |
| `no` | `no` | `yes` | `no` | `no` | `no` |
| `no` | `yes` |  | `yes` | `no` | `yes` |
| `no` | `unknown` |  | `unknown` | `no` | `unknown` |
| `yes` | `no` | `no` | `yes` | `no` | `yes` |
| `yes` | `yes` |  | `yes` | `yes` | `no` |
| `yes` | `unknown` |  | `yes` | `unknown` | `unknown` |
| `unknown` | `no` | `unknown` | `unknown` | `no` | `unknown` |
| `unknown` | `yes` |  | `yes` | `unknown` | `unknown` |
| `unknown` | `unknown` |  | `unknown` | `unknown` | `unknown` |



    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_typecons.html>

etc.c.odbc.sqlucode
===================

 Declarations for interfacing with the ODBC library. 


Adapted with minimal changes from the work of David L. Davis (refer to the [original announcement](http://forum.dlang.org/post/cfk7ql&dollar;1p4n&dollar;1@digitaldaemon.com)).   
  
 `etc.c.odbc.sqlucode` corresponds to the `sqlucode.h` C include file. 

 
See Also:
 [ODBC API Reference on MSN Online](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/odbc-api-reference)


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_odbc_sqlucode.html>

core.checkedint
===============

 This module implements integral arithmetic primitives that check for out-of-range results. 


Integral arithmetic operators operate on fixed width types. Results that are not representable in those fixed widths are silently truncated to fit. This module offers integral arithmetic primitives that produce the same results, but set an 'overflow' flag when such truncation occurs. The setting is sticky, meaning that numerous operations can be cascaded and then the flag need only be checked at the end. Whether the operation is signed or unsigned is indicated by an 's' or 'u' suffix, respectively. While this could be achieved without such suffixes by using overloading on the signedness of the types, the suffix makes it clear which is happening without needing to examine the types.   
  
 While the generic versions of these functions are computationally expensive relative to the cost of the operation itself, compiler implementations are free to recognize them and generate equivalent and faster code. 

 
References
 [Fast Integer Overflow Checks](http://blog.regehr.org/archives/1139) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Walter Bright 
 
Source
 [core/checkedint.d](https://github.com/dlang/druntime/blob/master/src/core/checkedint.d)

 
int **adds**()(int x, int y, ref bool overflow);   
  
long **adds**()(long x, long y, ref bool overflow);  
Add two signed integers, checking for overflow. 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| int `x` | left operand |
| int `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the sum
  uint **addu**()(uint x, uint y, ref bool overflow);   
  
ulong **addu**()(ulong x, ulong y, ref bool overflow);  
Add two unsigned integers, checking for overflow (aka carry). 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| uint `x` | left operand |
| uint `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the sum
  int **subs**()(int x, int y, ref bool overflow);   
  
long **subs**()(long x, long y, ref bool overflow);  
Subtract two signed integers, checking for overflow. 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| int `x` | left operand |
| int `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the difference
  uint **subu**()(uint x, uint y, ref bool overflow);   
  
ulong **subu**()(ulong x, ulong y, ref bool overflow);  
Subtract two unsigned integers, checking for overflow (aka borrow). 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| uint `x` | left operand |
| uint `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the difference
  int **negs**()(int x, ref bool overflow);   
  
long **negs**()(long x, ref bool overflow);  
Negate an integer. 



Parameters:


|  |  |
| --- | --- |
| int `x` | operand |
| bool `overflow` | set if x cannot be negated, is not affected otherwise |


 
Returns:
the negation of x
  int **muls**()(int x, int y, ref bool overflow);   
  
long **muls**()(long x, long y, ref bool overflow);  
Multiply two signed integers, checking for overflow. 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| int `x` | left operand |
| int `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the product
  uint **mulu**()(uint x, uint y, ref bool overflow);   
  
ulong **mulu**()(ulong x, uint y, ref bool overflow);   
  
ulong **mulu**()(ulong x, ulong y, ref bool overflow);  
Multiply two unsigned integers, checking for overflow (aka carry). 


The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end. 

 
Parameters:


|  |  |
| --- | --- |
| uint `x` | left operand |
| uint `y` | right operand |
| bool `overflow` | set if an overflow occurs, is not affected otherwise |


 
Returns:
the product
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_checkedint.html>

core.attribute
==============

 This module contains UDA's (User Defined Attributes) either used in the runtime or special UDA's recognized by compiler. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Jacob Carlborg 
 
Source
 [core/attribute.d](https://github.com/dlang/druntime/blob/master/src/core/attribute.d)

 
struct **selector**;  
Use this attribute to attach an Objective-C selector to a method. 


This is a special compiler recognized attribute, it has several requirements, which all will be enforced by the compiler:   
  
 * The attribute can only be attached to methods or constructors which have Objective-C linkage. That is, a method or a constructor in a class or interface declared as 
```
extern(Objective-C)
```
.
,   
  
* It cannot be attached to a method or constructor that is a template
,   
  
* The number of colons in the string need to match the number of arguments the method accept.
,   
  
* It can only be used once in a method declaration

 

 
Examples:


```
extern (Objective-C)
class NSObject
{
 this() @selector("init");
 static NSObject alloc() @selector("alloc");
 NSObject initWithUTF8String(in char* str) @selector("initWithUTF8String:");
 ObjcObject copyScriptingValue(ObjcObject value, NSString key, NSDictionary properties)
     @selector("copyScriptingValue:forKey:withProperties:");
}

```
 
  enum **optional**;  
Use this attribute to make an Objective-C interface method optional. 


An optional method is a method that does **not** have to be implemented in the class that implements the interface. To safely call an optional method, a runtime check should be performed to make sure the receiver implements the method.   
  
 This is a special compiler recognized attribute, it has several requirements, which all will be enforced by the compiler: * The attribute can only be attached to methods which have Objective-C linkage. That is, a method inside an interface declared as `extern (Objective-C)`
* It can only be used for methods that are declared inside an interface
* It can only be used once in a method declaration
* It cannot be attached to a method that is a template

 

 
Examples:


```
import core.attribute : optional, selector;

extern (Objective-C):

struct objc_selector;
alias SEL = objc_selector*;

SEL sel_registerName(in char* str);

extern class NSObject
{
    bool respondsToSelector(SEL sel) @selector("respondsToSelector:");
}

interface Foo
{
    @optional void foo() @selector("foo");
    @optional void bar() @selector("bar");
}

class Bar : NSObject
{
    static Bar alloc() @selector("alloc");
    Bar init() @selector("init");

    void bar() @selector("bar")
    {
    }
}

extern (D) void main()
{
    auto bar = Bar.alloc.init;

    if (bar.respondsToSelector(sel_registerName("bar")))
        bar.bar();
}

```
 
  struct **gnuAbiTag**;  
Use this attribute to declare an ABI tag on a C++ symbol. 


ABI tag is an attribute introduced by the GNU C++ compiler. It modifies the mangled name of the symbol to incorporate the tag name, in order to distinguish from an earlier version with a different ABI.   
  
 This is a special compiler recognized attribute, it has a few requirements, which all will be enforced by the compiler:   
  
 * There can only be one such attribute per symbol.
, * The attribute can only be attached to an `extern(C++)` symbol (`struct`, `class`, `enum`, function, and their templated counterparts).
, * The attribute cannot be applied to C++ namespaces. This is to prevent confusion with the C++ semantic, which allows it to be applied to namespaces.
, * The string arguments must only contain valid characters for C++ name mangling which currently include alphanumerics and the underscore character.
, 
   
  
 This UDA is not transitive, and inner scope do not inherit outer scopes' ABI tag. See examples below for how to translate a C++ declaration to D. Also note that entries in this UDA will be automatically sorted alphabetically, hence `gnuAbiTag("c", "b", "a")` will appear as `@gnuAbiTag("a", "b", "c")`. 

 
See Also:

[Itanium ABI spec](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.abi-tag) [GCC attributes documentation](https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html). 
 
Examples:


```
// ---- foo.cpp
struct [[gnu::abi_tag ("tag1", "tag2")]] Tagged1_2
{
    struct [[gnu::abi_tag ("tag3")]] Tagged3
    {
        [[gnu::abi_tag ("tag4")]]
        int Tagged4 () { return 42; }
    }
}
Tagged1_2 inst1;
// ---- foo.d
@gnuAbiTag("tag1", "tag2") struct Tagged1_2
{
    // Notice the repetition
    @gnuAbiTag("tag1", "tag2", "tag3") struct Tagged3
    {
        @gnuAbiTag("tag1", "tag2", "tag3", "tag4") int Tagged4 ();
    }
}
extern __gshared Tagged1_2 inst1;

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_attribute.html>

core.bitop
==========

 This module contains a collection of bit-level operations. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Don Clugston, Sean Kelly, Walter Bright, Alex Rønne Petersen, Thomas Stuart Bockman 
 
Source
 [core/bitop.d](https://github.com/dlang/druntime/blob/master/src/core/bitop.d)

 
pure nothrow @nogc @safe int **bsf**(uint v);   
  
pure nothrow @nogc @safe int **bsf**(ulong v);  
Scans the bits in v starting with bit 0, looking for the first set bit. 



Returns:
The bit number of the first bit set. The return value is undefined if v is zero.
 
Examples:


```
assert(bsf(0x21) == 0);
assert(bsf(ulong.max << 39) == 39);

```
 
  pure nothrow @nogc @safe int **bsr**(uint v);   
  
pure nothrow @nogc @safe int **bsr**(ulong v);  
Scans the bits in v from the most significant bit to the least significant bit, looking for the first set bit. 



Returns:
The bit number of the first bit set. The return value is undefined if v is zero.
 
Examples:


```
assert(bsr(0x21) == 5);
assert(bsr((ulong.max >> 15) - 1) == 48);

```
 
  pure nothrow @nogc @system int **bt**(scope const size\_t\* p, size\_t bitnum);  
Tests the bit. (No longer an intrisic - the compiler recognizes the patterns in the body.)



Examples:


```
size_t[2] array;

array[0] = 2;
array[1] = 0x100;

assert(bt(array.ptr, 1));
assert(array[0] == 2);
assert(array[1] == 0x100);

```
 
  pure nothrow @nogc @system int **btc**(size\_t\* p, size\_t bitnum);  
Tests and complements the bit.

  pure nothrow @nogc @system int **btr**(size\_t\* p, size\_t bitnum);  
Tests and resets (sets to 0) the bit.

  pure nothrow @nogc @system int **bts**(size\_t\* p, size\_t bitnum);  
Tests and sets the bit. 



Parameters:


|  |  |
| --- | --- |
| size\_t\* `p` | a non-NULL pointer to an array of size\_ts. |
| size\_t `bitnum` | a bit number, starting with bit 0 of p[0], and progressing. It addresses bits like the expression: 
```
p[index / (size_t.sizeof*8)] & (1 << (index & ((size_t.sizeof*8) - 1)))

```
 |


 
Returns:
A non-zero value if the bit was set, and a zero if it was clear.
 
Examples:


```
size_t[2] array;

array[0] = 2;
array[1] = 0x100;

assert(btc(array.ptr, 35) == 0);
if (size_t.sizeof == 8)
{
    assert(array[0] == 0x8_0000_0002);
    assert(array[1] == 0x100);
}
else
{
    assert(array[0] == 2);
    assert(array[1] == 0x108);
}

assert(btc(array.ptr, 35));
assert(array[0] == 2);
assert(array[1] == 0x100);

assert(bts(array.ptr, 35) == 0);
if (size_t.sizeof == 8)
{
    assert(array[0] == 0x8_0000_0002);
    assert(array[1] == 0x100);
}
else
{
    assert(array[0] == 2);
    assert(array[1] == 0x108);
}

assert(btr(array.ptr, 35));
assert(array[0] == 2);
assert(array[1] == 0x100);

```
 
  struct **BitRange**;  
Range over bit set. Each element is the bit number that is set. 


This is more efficient than testing each bit in a sparsely populated bit set. Note that the first bit in the bit set would be bit 0.

 
Examples:


```
import core.stdc.stdlib : malloc, free;
import core.stdc.string : memset;

// initialize a bit array
enum nBytes = (100 + BitRange.bitsPerWord - 1) / 8;
size_t *bitArr = cast(size_t *)malloc(nBytes);
scope(exit) free(bitArr);
memset(bitArr, 0, nBytes);

// set some bits
bts(bitArr, 48);
bts(bitArr, 24);
bts(bitArr, 95);
bts(bitArr, 78);

enum sum = 48 + 24 + 95 + 78;

// iterate
size_t testSum;
size_t nBits;
foreach (b; BitRange(bitArr, 100))
{
    testSum += b;
    ++nBits;
}

assert(testSum == sum);
assert(nBits == 4);

```
 
 
enum ulong **bitsPerWord**;  
Number of bits in each size\_t

  pure nothrow @nogc @system this(const(size\_t)\* bitarr, size\_t numBits);  
Construct a BitRange. 



Parameters:


|  |  |
| --- | --- |
| const(size\_t)\* `bitarr` | The array of bits to iterate over |
| size\_t `numBits` | The total number of valid bits in the given bit array |


  pure nothrow @nogc @safe size\_t **front**();   
  
const pure nothrow @nogc @safe bool **empty**();   
  
pure nothrow @nogc @system void **popFront**();  
Range functions

    pure nothrow @nogc @safe ushort **byteswap**(ushort x);  
Swaps bytes in a 2 byte ushort. 



Parameters:


|  |  |
| --- | --- |
| ushort `x` | value |


 
Returns:

`x` with bytes swapped
 
Examples:


```
assert(byteswap(cast(ushort)0xF234) == 0x34F2);
static ushort xx = 0xF234;
assert(byteswap(xx) == 0x34F2);

```
 
  pure nothrow @nogc @safe uint **bswap**(uint v);  
Swaps bytes in a 4 byte uint end-to-end, i.e. byte 0 becomes byte 3, byte 1 becomes byte 2, byte 2 becomes byte 1, byte 3 becomes byte 0.



Examples:


```
assert(bswap(0x01020304u) == 0x04030201u);
static uint xx = 0x10203040u;
assert(bswap(xx) == 0x40302010u);

```
 
  pure nothrow @nogc @safe ulong **bswap**(ulong v);  
Swaps bytes in an 8 byte ulong end-to-end, i.e. byte 0 becomes byte 7, byte 1 becomes byte 6, etc. This is meant to be recognized by the compiler as an intrinsic.



Examples:


```
assert(bswap(0x01020304_05060708uL) == 0x08070605_04030201uL);
static ulong xx = 0x10203040_50607080uL;
assert(bswap(xx) == 0x80706050_40302010uL);

```
 
  nothrow @nogc @system ubyte **inp**(uint port\_address);   
  
nothrow @nogc @system ushort **inpw**(uint port\_address);   
  
nothrow @nogc @system uint **inpl**(uint port\_address);  
Reads I/O port at port\_address.

  nothrow @nogc @system ubyte **outp**(uint port\_address, ubyte value);   
  
nothrow @nogc @system ushort **outpw**(uint port\_address, ushort value);   
  
nothrow @nogc @system uint **outpl**(uint port\_address, uint value);  
Writes and returns value to I/O port at port\_address.

  pure nothrow @nogc @safe int **popcnt**(uint x);   
  
pure nothrow @nogc @safe int **popcnt**(ulong x);  
Calculates the number of set bits in an integer.

  pure nothrow @nogc @safe ushort **\_popcnt**(ushort x);   
  
pure nothrow @nogc @safe int **\_popcnt**(uint x);   
  
pure nothrow @nogc @safe int **\_popcnt**(ulong x);  
Calculates the number of set bits in an integer using the X86 SSE4 POPCNT instruction. POPCNT is not available on all X86 CPUs.

  pure nothrow @nogc @safe uint **bitswap**(uint x);  
Reverses the order of bits in a 32-bit integer.

  pure nothrow @nogc @safe ulong **bitswap**(ulong x);  
Reverses the order of bits in a 64-bit integer.

  pure T **rol**(T)(const T value, const uint count)  
 Constraints: if (\_\_traits(isIntegral, T) && \_\_traits(isUnsigned, T));   
  
pure T **ror**(T)(const T value, const uint count)  
 Constraints: if (\_\_traits(isIntegral, T) && \_\_traits(isUnsigned, T));   
  
pure T **rol**(uint count, T)(const T value)  
 Constraints: if (\_\_traits(isIntegral, T) && \_\_traits(isUnsigned, T));   
  
pure T **ror**(uint count, T)(const T value)  
 Constraints: if (\_\_traits(isIntegral, T) && \_\_traits(isUnsigned, T)); 
 
Bitwise rotate `value` left (`rol`) or right (`ror`) by `count` bit positions.



Examples:


```
ubyte a = 0b11110000U;
ulong b = ~1UL;

assert(rol(a, 1) == 0b11100001);
assert(ror(a, 1) == 0b01111000);
assert(rol(a, 3) == 0b10000111);
assert(ror(a, 3) == 0b00011110);

assert(rol(a, 0) == a);
assert(ror(a, 0) == a);

assert(rol(b, 63) == ~(1UL << 63));
assert(ror(b, 63) == ~2UL);

assert(rol!3(a) == 0b10000111);
assert(ror!3(a) == 0b00011110);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_bitop.html>

core.demangle
=============

 The demangle module converts mangled D symbols to a representation similar to what would have existed in code. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/demangle.d](https://github.com/dlang/druntime/blob/master/src/core/demangle.d)

 
pure nothrow @safe char[] **demangle**(const(char)[] buf, char[] dst = null);  
Demangles D mangled names. If it is not a D mangled name, it returns its argument name. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `buf` | The string to demangle. |
| char[] `dst` | An optional destination buffer. |


 
Returns:
The demangled name or the original string if the name is not a mangled D name.
  pure nothrow @safe char[] **demangleType**(const(char)[] buf, char[] dst = null);  
Demangles a D mangled type. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `buf` | The string to demangle. |
| char[] `dst` | An optional destination buffer. |


 
Returns:
The demangled type name or the original string if the name is not a mangled D type.
  pure nothrow @safe char[] **reencodeMangled**(const(char)[] mangled);  
reencode a mangled symbol name that might include duplicate occurrences of the same identifier by replacing all but the first occurence with a back reference. 



Parameters:


|  |  |
| --- | --- |
| const(char)[] `mangled` | The mangled string representing the type |


 
Returns:
The mangled name with deduplicated identifiers
  pure nothrow @safe char[] **mangle**(T)(const(char)[] fqn, char[] dst = null);  
Mangles a D symbol. 



Parameters:


|  |  |
| --- | --- |
| T | The type of the symbol. |
| const(char)[] `fqn` | The fully qualified name of the symbol. |
| char[] `dst` | An optional destination buffer. |


 
Returns:
The mangled name for a symbols of type T and the given fully qualified name.
 
Examples:


```
assert(mangle!int("a.b") == "_D1a1bi");
assert(mangle!(char[])("test.foo") == "_D4test3fooAa");
assert(mangle!(int function(int))("a.b") == "_D1a1bPFiZi");

```
 
  pure nothrow @safe char[] **mangleFunc**(T : FT\*, FT)(const(char)[] fqn, char[] dst = null)  
 Constraints: if (is(FT == function)); 
 
Mangles a D function. 



Parameters:


|  |  |
| --- | --- |
| T | function pointer type. |
| const(char)[] `fqn` | The fully qualified name of the symbol. |
| char[] `dst` | An optional destination buffer. |


 
Returns:
The mangled name for a function with function pointer type T and the given fully qualified name.
  enum string **cPrefix**;  
C name mangling is done by adding a prefix on some platforms.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_demangle.html>

core.exception
==============

 The exception module defines all system-level exceptions and provides a mechanism to alter system-level error handling. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Sean Kelly and [Jonathan M Davis](http://jmdavisprog.com) 
 
Source
 [core/exception.d](https://github.com/dlang/druntime/blob/master/src/core/exception.d)

 
class **RangeError**: object.Error;  
Thrown on a range error.

  class **AssertError**: object.Error;  
Thrown on an assert error.

  class **FinalizeError**: object.Error;  
Thrown on finalize error.

  class **OutOfMemoryError**: object.Error;  
Thrown on an out of memory error.

  class **InvalidMemoryOperationError**: object.Error;  
Thrown on an invalid memory operation. 


An invalid memory operation error occurs in circumstances when the garbage collector has detected an operation it cannot reliably handle. The default D GC is not re-entrant, so this can happen due to allocations done from within finalizers called during a garbage collection cycle.

  class **SwitchError**: object.Error;  
Thrown on a switch error.

  class **UnicodeException**: object.Exception;  
Thrown on a unicode conversion error.

  alias **AssertHandler** = void function(string file, ulong line, string msg) nothrow;   
  
nothrow @nogc @property @trusted AssertHandler **assertHandler**();   
  
nothrow @nogc @property @trusted void **assertHandler**(AssertHandler handler);  
Gets/sets assert hander. null means the default handler is used.

  nothrow void **onAssertError**(string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
A callback for assert errors in D. The user-supplied assert handler will be called if one has been supplied, otherwise an [`AssertError`](#AssertError) will be thrown. 



Parameters:


|  |  |
| --- | --- |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |


  nothrow void **onAssertErrorMsg**(string file, size\_t line, string msg);  
A callback for assert errors in D. The user-supplied assert handler will be called if one has been supplied, otherwise an [`AssertError`](#AssertError) will be thrown. 



Parameters:


|  |  |
| --- | --- |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |
| string `msg` | An error message supplied by the user. |


  nothrow void **onUnittestErrorMsg**(string file, size\_t line, string msg);  
A callback for unittest errors in D. The user-supplied unittest handler will be called if one has been supplied, otherwise the error will be written to stderr. 



Parameters:


|  |  |
| --- | --- |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |
| string `msg` | An error message supplied by the user. |


  pure nothrow @nogc @trusted void **onRangeError**(string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
A callback for array bounds errors in D. A [`RangeError`](#RangeError) will be thrown. 



Parameters:


|  |  |
| --- | --- |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |


 
Throws:

[`RangeError`](#RangeError).
  nothrow @trusted void **onFinalizeError**(TypeInfo info, Throwable e, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
A callback for finalize errors in D. A [`FinalizeError`](#FinalizeError) will be thrown. 



Parameters:


|  |  |
| --- | --- |
| TypeInfo `info` | The TypeInfo instance for the object that failed finalization. |
| Throwable `e` | The exception thrown during finalization. |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |


 
Throws:

[`FinalizeError`](#FinalizeError).
  pure nothrow @nogc @trusted void **onOutOfMemoryError**(void\* pretend\_sideffect = null);  
A callback for out of memory errors in D. An [`OutOfMemoryError`](#OutOfMemoryError) will be thrown. 



Throws:

[`OutOfMemoryError`](#OutOfMemoryError).
  pure nothrow @nogc @trusted void **onInvalidMemoryOperationError**(void\* pretend\_sideffect = null);  
A callback for invalid memory operations in D. An [`InvalidMemoryOperationError`](#InvalidMemoryOperationError) will be thrown. 



Throws:

[`InvalidMemoryOperationError`](#InvalidMemoryOperationError).
  pure @safe void **onUnicodeError**(string msg, size\_t idx, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
A callback for unicode errors in D. A [`UnicodeException`](#UnicodeException) will be thrown. 



Parameters:


|  |  |
| --- | --- |
| string `msg` | Information about the error. |
| size\_t `idx` | String index where this error was detected. |
| string `file` | The name of the file that signaled this error. |
| size\_t `line` | The line number on which this error occurred. |


 
Throws:

[`UnicodeException`](#UnicodeException).
  void **\_d\_assertp**(immutable(char)\* file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_assert\_msg**(string msg, string file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_assert**(string file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_unittestp**(immutable(char)\* file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_unittest\_msg**(string msg, string file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_unittest**(string file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_arrayboundsp**(immutable(char\*) file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  void **\_d\_arraybounds**(string file, uint line);  
These functions must be defined for any D program linked against this library. 


Function calls to these are generated by the compiler and inserted into the object code.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_exception.html>

core.gc.config
==============

 Contains the garbage collector configuration. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt).


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_gc_config.html>

core.gc.gcinterface
===================

 Contains the internal GC interface. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly, Jeremy DeHaan


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_gc_gcinterface.html>

core.atomic
===========

 The atomic module provides basic support for lock-free concurrent programming. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly, Alex Rønne Petersen, Manu Evans 
 
Source
 [core/atomic.d](https://github.com/dlang/druntime/blob/master/src/core/atomic.d)

 
enum **MemoryOrder**: int;  
Specifies the memory ordering semantics of an atomic operation. 



See Also:
[en.cppreference.com/w/cpp/atomic/memory\_order](http://en.cppreference.com/w/cpp/atomic/memory_order)
 
**raw** 
Not sequenced. Corresponds to [LLVM AtomicOrdering.Monotonic](https://llvm.org/docs/Atomics.html#monotonic) and C++11/C11 `memory_order_relaxed`.

  **acq** 
Hoist-load + hoist-store barrier. Corresponds to [LLVM AtomicOrdering.Acquire](https://llvm.org/docs/Atomics.html#acquire) and C++11/C11 `memory_order_acquire`.

  **rel** 
Sink-load + sink-store barrier. Corresponds to [LLVM AtomicOrdering.Release](https://llvm.org/docs/Atomics.html#release) and C++11/C11 `memory_order_release`.

  **acq\_rel** 
Acquire + release barrier. Corresponds to [LLVM AtomicOrdering.AcquireRelease](https://llvm.org/docs/Atomics.html#acquirerelease) and C++11/C11 `memory_order_acq_rel`.

  **seq** 
Fully sequenced (acquire + release). Corresponds to [LLVM AtomicOrdering.SequentiallyConsistent](https://llvm.org/docs/Atomics.html#sequentiallyconsistent) and C++11/C11 `memory_order_seq_cst`.

    pure nothrow @nogc @trusted T **atomicLoad**(MemoryOrder ms = MemoryOrder.seq, T)(ref const T val)  
 Constraints: if (!is(T == shared(U), U) && !is(T == shared(inout(U)), U) && !is(T == shared(const(U)), U));   
  
pure nothrow @nogc @trusted T **atomicLoad**(MemoryOrder ms = MemoryOrder.seq, T)(ref const shared T val)  
 Constraints: if (!hasUnsharedIndirections!T);   
  
pure nothrow @nogc @trusted TailShared!T **atomicLoad**(MemoryOrder ms = MemoryOrder.seq, T)(ref const shared T val)  
 Constraints: if (hasUnsharedIndirections!T); 
 
Loads 'val' from memory and returns it. The memory barrier specified by 'ms' is applied to the operation, which is fully sequenced by default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq, and MemoryOrder.seq. 



Parameters:


|  |  |
| --- | --- |
| T `val` | The target variable. |


 
Returns:
The value of 'val'.
  pure nothrow @nogc @trusted void **atomicStore**(MemoryOrder ms = MemoryOrder.seq, T, V)(ref T val, V newval)  
 Constraints: if (!is(T == shared) && !is(V == shared));   
  
pure nothrow @nogc @trusted void **atomicStore**(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, V newval)  
 Constraints: if (!is(T == class));   
  
pure nothrow @nogc @trusted void **atomicStore**(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, shared V newval)  
 Constraints: if (is(T == class)); 
 
Writes 'newval' into 'val'. The memory barrier specified by 'ms' is applied to the operation, which is fully sequenced by default. Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and MemoryOrder.seq. 



Parameters:


|  |  |
| --- | --- |
| T `val` | The target variable. |
| V `newval` | The value to store. |


  pure nothrow @nogc @trusted T **atomicFetchAdd**(MemoryOrder ms = MemoryOrder.seq, T)(ref T val, size\_t mod)  
 Constraints: if ((\_\_traits(isIntegral, T) || is(T == U\*, U)) && !is(T == shared));   
  
pure nothrow @nogc @trusted T **atomicFetchAdd**(MemoryOrder ms = MemoryOrder.seq, T)(ref shared T val, size\_t mod)  
 Constraints: if (\_\_traits(isIntegral, T) || is(T == U\*, U)); 
 
Atomically adds `mod` to the value referenced by `val` and returns the value `val` held previously. This operation is both lock-free and atomic. 



Parameters:


|  |  |
| --- | --- |
| T `val` | Reference to the value to modify. |
| size\_t `mod` | The value to add. |


 
Returns:
The value held previously by `val`.
  pure nothrow @nogc @trusted T **atomicFetchSub**(MemoryOrder ms = MemoryOrder.seq, T)(ref T val, size\_t mod)  
 Constraints: if ((\_\_traits(isIntegral, T) || is(T == U\*, U)) && !is(T == shared));   
  
pure nothrow @nogc @trusted T **atomicFetchSub**(MemoryOrder ms = MemoryOrder.seq, T)(ref shared T val, size\_t mod)  
 Constraints: if (\_\_traits(isIntegral, T) || is(T == U\*, U)); 
 
Atomically subtracts `mod` from the value referenced by `val` and returns the value `val` held previously. This operation is both lock-free and atomic. 



Parameters:


|  |  |
| --- | --- |
| T `val` | Reference to the value to modify. |
| size\_t `mod` | The value to subtract. |


 
Returns:
The value held previously by `val`.
  pure nothrow @nogc @trusted T **atomicExchange**(MemoryOrder ms = MemoryOrder.seq, T, V)(T\* here, V exchangeWith)  
 Constraints: if (!is(T == shared) && !is(V == shared));   
  
pure nothrow @nogc @trusted TailShared!T **atomicExchange**(MemoryOrder ms = MemoryOrder.seq, T, V)(shared(T)\* here, V exchangeWith)  
 Constraints: if (!is(T == class) && !is(T == interface));   
  
pure nothrow @nogc @trusted shared(T) **atomicExchange**(MemoryOrder ms = MemoryOrder.seq, T, V)(shared(T)\* here, shared(V) exchangeWith)  
 Constraints: if (is(T == class) || is(T == interface)); 
 
Exchange `exchangeWith` with the memory referenced by `here`. This operation is both lock-free and atomic. 



Parameters:


|  |  |
| --- | --- |
| T\* `here` | The address of the destination variable. |
| V `exchangeWith` | The value to exchange. |


 
Returns:
The value held previously by `here`.
  template **cas**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq) 
Performs either compare-and-set or compare-and-swap (or exchange). 


There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (`ifThis`) is treated as an rvalue.   
  
 The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects `ifThis` to be a pointer type, where the previous value of `here` will be written.   
  
 This operation is both lock-free and atomic. 

 
Parameters:


|  |  |
| --- | --- |
| T\* here | The address of the destination variable. |
| V2 writeThis | The value to store. |
| V1 ifThis | The comparison value. |


 
Returns:
true if the store occurred, false if not.
 
pure nothrow @nogc @trusted bool **cas**(T, V1, V2)(T\* here, V1 ifThis, V2 writeThis)  
 Constraints: if (!is(T == shared) && is(T : V1)); 
 
Compare-and-set for non-shared values

  pure nothrow @nogc @trusted bool **cas**(T, V1, V2)(shared(T)\* here, V1 ifThis, V2 writeThis)  
 Constraints: if (!is(T == class) && (is(T : V1) || is(shared(T) : V1))); 
 
Compare-and-set for shared value type

  pure nothrow @nogc @trusted bool **cas**(T, V1, V2)(shared(T)\* here, shared(V1) ifThis, shared(V2) writeThis)  
 Constraints: if (is(T == class)); 
 
Compare-and-set for `shared` reference type (`class`)

  pure nothrow @nogc @trusted bool **cas**(T, V)(T\* here, T\* ifThis, V writeThis)  
 Constraints: if (!is(T == shared) && !is(V == shared)); 
 
Compare-and-exchange for non-`shared` types

  pure nothrow @nogc @trusted bool **cas**(T, V1, V2)(shared(T)\* here, V1\* ifThis, V2 writeThis)  
 Constraints: if (!is(T == class) && (is(T : V1) || is(shared(T) : V1))); 
 
Compare and exchange for mixed-`shared`ness types

  pure nothrow @nogc @trusted bool **cas**(T, V)(shared(T)\* here, shared(T)\* ifThis, shared(V) writeThis)  
 Constraints: if (is(T == class)); 
 
Compare-and-exchange for `class`

    pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V1, V2)(T\* here, V1 ifThis, V2 writeThis)  
 Constraints: if (!is(T == shared) && is(T : V1));   
  
pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V1, V2)(shared(T)\* here, V1 ifThis, V2 writeThis)  
 Constraints: if (!is(T == class) && (is(T : V1) || is(shared(T) : V1)));   
  
pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V1, V2)(shared(T)\* here, shared(V1) ifThis, shared(V2) writeThis)  
 Constraints: if (is(T == class)); 
 
Stores 'writeThis' to the memory referenced by 'here' if the value referenced by 'here' is equal to 'ifThis'. The 'weak' version of cas may spuriously fail. It is recommended to use `casWeak` only when `cas` would be used in a loop. This operation is both lock-free and atomic. 



Parameters:


|  |  |
| --- | --- |
| T\* `here` | The address of the destination variable. |
| V2 `writeThis` | The value to store. |
| V1 `ifThis` | The comparison value. |


 
Returns:
true if the store occurred, false if not.
  pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V)(T\* here, T\* ifThis, V writeThis)  
 Constraints: if (!is(T == shared(S), S) && !is(V == shared(U), U));   
  
pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V1, V2)(shared(T)\* here, V1\* ifThis, V2 writeThis)  
 Constraints: if (!is(T == class) && (is(T : V1) || is(shared(T) : V1)));   
  
pure nothrow @nogc @trusted bool **casWeak**(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T, V)(shared(T)\* here, shared(T)\* ifThis, shared(V) writeThis)  
 Constraints: if (is(T == class)); 
 
Stores 'writeThis' to the memory referenced by 'here' if the value referenced by 'here' is equal to the value referenced by 'ifThis'. The prior value referenced by 'here' is written to `ifThis` and returned to the user. The 'weak' version of cas may spuriously fail. It is recommended to use `casWeak` only when `cas` would be used in a loop. This operation is both lock-free and atomic. 



Parameters:


|  |  |
| --- | --- |
| T\* `here` | The address of the destination variable. |
| V `writeThis` | The value to store. |
| T\* `ifThis` | The address of the value to compare, and receives the prior value of `here` as output. |


 
Returns:
true if the store occurred, false if not.
  pure nothrow @nogc @safe void **atomicFence**(MemoryOrder order = MemoryOrder.seq)();  
Inserts a full load/store memory fence (on platforms that need it). This ensures that all loads and stores before a call to this function are executed before any loads and stores after the call.

  pure nothrow @nogc @safe void **pause**();  
Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

  pure nothrow @nogc @safe TailShared!T **atomicOp**(string op, T, V1)(ref shared T val, V1 mod)  
 Constraints: if (\_\_traits(compiles, mixin("\*cast(T\*)&val" ~ op ~ "mod"))); 
 
Performs the binary operation 'op' on val using 'mod' as the modifier. 



Parameters:


|  |  |
| --- | --- |
| T `val` | The target variable. |
| V1 `mod` | The modifier to apply. |


 
Returns:
The result of the operation.
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_atomic.html>

core.cpuid
==========

 Identify the characteristics of the host CPU, providing information about cache sizes and assembly optimisation hints. This module is provided primarily for assembly language programmers. 



References
 Some of this information was extremely difficult to track down. Some of the documents below were found only in cached versions stored by search engines! This code relies on information found in: 
 * "Intel(R) 64 and IA-32 Architectures Software Developers Manual, Volume 2A: Instruction Set Reference, A-M" (2007).
* "AMD CPUID Specification", Advanced Micro Devices, Rev 2.28 (2008).
* "AMD Processor Recognition Application Note For Processors Prior to AMD Family 0Fh Processors", Advanced Micro Devices, Rev 3.13 (2005).
* "AMD Geode(TM) GX Processors Data Book", Advanced Micro Devices, Publication ID 31505E, (2005).
* "AMD K6 Processor Code Optimisation", Advanced Micro Devices, Rev D (2000).
* "Application note 106: Software Customization for the 6x86 Family", Cyrix Corporation, Rev 1.5 (1998)
* <http://www.datasheetcatalog.org/datasheet/nationalsemiconductor/GX1.pdf>
* "Geode(TM) GX1 Processor Series Low Power Integrated X86 Solution", National Semiconductor, (2002)
* "The VIA Isaiah Architecture", G. Glenn Henry, Centaur Technology, Inc (2008).
* <http://www.sandpile.org/ia32/cpuid.htm>
* <http://www.akkadia.org/drepper/cpumemory.pdf>
* "What every programmer should know about memory", Ulrich Depper, Red Hat, Inc., (2007).
* "CPU Identification by the Windows Kernel", G. Chappell (2009). <http://www.geoffchappell.com/viewer.htm?doc=studies/windows/km/cpu/cx8.htm>
* "Intel(R) Processor Identification and the CPUID Instruction, Application Note 485" (2009).

 
Bugs:
Currently only works on x86 and Itanium CPUs. Many processors have bugs in their microcode for the CPUID instruction, so sometimes the cache information may be incorrect. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Don Clugston, Tomas Lindquist Olsen <tomas@famolsen.dk> 
 
Source
 [core/cpuid.d](https://github.com/dlang/druntime/blob/master/src/core/cpuid.d)

 
struct **CacheInfo**;  
Cache size and behaviour

 
size\_t **size**;  
Size of the cache, in kilobytes, per CPU. For L1 unified (data + code) caches, this size is half the physical size. (we don't halve it for larger sizes, since normally data size is much greater than code size for critical loops).

  ubyte **associativity**;  
Number of ways of associativity, eg: * 1 = direct mapped
* 2 = 2-way set associative
* 3 = 3-way set associative
* ubyte.max = fully associative


  uint **lineSize**;  
Number of bytes read into the cache when a cache miss occurs.

    CacheInfo[5] **datacache**;  
Scheduled for deprecation. Please use `dataCaches` instead.

  pure nothrow @nogc @property @trusted const(CacheInfo)[5] **dataCaches**();  
The data caches. If there are fewer than 5 physical caches levels, the remaining levels are set to size\_t.max (== entire memory space)

  pure nothrow @nogc @property @trusted string **vendor**();  
Returns vendor string, for display purposes only. Do NOT use this to determine features! Note that some CPUs have programmable vendorIDs.

  pure nothrow @nogc @property @trusted string **processor**();  
Returns processor string, for display purposes only

  pure nothrow @nogc @property @trusted bool **x87onChip**();  
Does it have an x87 FPU on-chip?

  pure nothrow @nogc @property @trusted bool **mmx**();  
Is MMX supported?

  pure nothrow @nogc @property @trusted bool **sse**();  
Is SSE supported?

  pure nothrow @nogc @property @trusted bool **sse2**();  
Is SSE2 supported?

  pure nothrow @nogc @property @trusted bool **sse3**();  
Is SSE3 supported?

  pure nothrow @nogc @property @trusted bool **ssse3**();  
Is SSSE3 supported?

  pure nothrow @nogc @property @trusted bool **sse41**();  
Is SSE4.1 supported?

  pure nothrow @nogc @property @trusted bool **sse42**();  
Is SSE4.2 supported?

  pure nothrow @nogc @property @trusted bool **sse4a**();  
Is SSE4a supported?

  pure nothrow @nogc @property @trusted bool **aes**();  
Is AES supported

  pure nothrow @nogc @property @trusted bool **hasPclmulqdq**();  
Is pclmulqdq supported

  pure nothrow @nogc @property @trusted bool **hasRdrand**();  
Is rdrand supported

  pure nothrow @nogc @property @trusted bool **avx**();  
Is AVX supported

  pure nothrow @nogc @property @trusted bool **vaes**();  
Is VEX-Encoded AES supported

  pure nothrow @nogc @property @trusted bool **hasVpclmulqdq**();  
Is vpclmulqdq supported

  pure nothrow @nogc @property @trusted bool **fma**();  
Is FMA supported

  pure nothrow @nogc @property @trusted bool **fp16c**();  
Is FP16C supported

  pure nothrow @nogc @property @trusted bool **avx2**();  
Is AVX2 supported

  pure nothrow @nogc @property @trusted bool **hle**();  
Is HLE (hardware lock elision) supported

  pure nothrow @nogc @property @trusted bool **rtm**();  
Is RTM (restricted transactional memory) supported

  pure nothrow @nogc @property @trusted bool **hasRdseed**();  
Is rdseed supported

  pure nothrow @nogc @property @trusted bool **hasSha**();  
Is SHA supported

  pure nothrow @nogc @property @trusted bool **amd3dnow**();  
Is AMD 3DNOW supported?

  pure nothrow @nogc @property @trusted bool **amd3dnowExt**();  
Is AMD 3DNOW Ext supported?

  pure nothrow @nogc @property @trusted bool **amdMmx**();  
Are AMD extensions to MMX supported?

  pure nothrow @nogc @property @trusted bool **hasFxsr**();  
Is fxsave/fxrstor supported?

  pure nothrow @nogc @property @trusted bool **hasCmov**();  
Is cmov supported?

  pure nothrow @nogc @property @trusted bool **hasRdtsc**();  
Is rdtsc supported?

  pure nothrow @nogc @property @trusted bool **hasCmpxchg8b**();  
Is cmpxchg8b supported?

  pure nothrow @nogc @property @trusted bool **hasCmpxchg16b**();  
Is cmpxchg8b supported?

  pure nothrow @nogc @property @trusted bool **hasSysEnterSysExit**();  
Is SYSENTER/SYSEXIT supported?

  pure nothrow @nogc @property @trusted bool **has3dnowPrefetch**();  
Is 3DNow prefetch supported?

  pure nothrow @nogc @property @trusted bool **hasLahfSahf**();  
Are LAHF and SAHF supported in 64-bit mode?

  pure nothrow @nogc @property @trusted bool **hasPopcnt**();  
Is POPCNT supported?

  pure nothrow @nogc @property @trusted bool **hasLzcnt**();  
Is LZCNT supported?

  pure nothrow @nogc @property @trusted bool **isX86\_64**();  
Is this an Intel64 or AMD 64?

  pure nothrow @nogc @property @trusted bool **isItanium**();  
Is this an IA64 (Itanium) processor?

  pure nothrow @nogc @property @trusted bool **hyperThreading**();  
Is hyperthreading supported?

  pure nothrow @nogc @property @trusted uint **threadsPerCPU**();  
Returns number of threads per CPU

  pure nothrow @nogc @property @trusted uint **coresPerCPU**();  
Returns number of cores in CPU

  pure nothrow @nogc @property @trusted bool **preferAthlon**();  
Optimisation hints for assembly code. 


For forward compatibility, the CPU is compared against different microarchitectures. For 32-bit x86, comparisons are made against the Intel PPro/PII/PIII/PM family.   
  
 The major 32-bit x86 microarchitecture 'dynasties' have been:   
  
 * Intel P6 (PentiumPro, PII, PIII, PM, Core, Core2).
* AMD Athlon (K7, K8, K10).
* Intel NetBurst (Pentium 4, Pentium D).
* In-order Pentium (Pentium1, PMMX, Atom)

   
  
 Other early CPUs (Nx586, AMD K5, K6, Centaur C3, Transmeta, Cyrix, Rise) were mostly in-order.   
  
 Some new processors do not fit into the existing categories:   
  
 * Intel Atom 230/330 (family 6, model 0x1C) is an in-order core.
* Centaur Isiah = VIA Nano (family 6, model F) is an out-of-order core.

   
  
 Within each dynasty, the optimisation techniques are largely identical (eg, use instruction pairing for group 4). Major instruction set improvements occur within each dynasty.   
  
 Does this CPU perform better on AMD K7 code than PentiumPro..Core2 code?

  pure nothrow @nogc @property @trusted bool **preferPentium4**();  
Does this CPU perform better on Pentium4 code than PentiumPro..Core2 code?

  pure nothrow @nogc @property @trusted bool **preferPentium1**();  
Does this CPU perform better on Pentium I code than Pentium Pro code?

  uint **stepping**;  
Warning: This field will be turned into a property in a future release. 


Processor type (vendor-dependent). This should be visible ONLY for display purposes.

  uint **model**;  
Warning: This field will be turned into a property in a future release. 


Processor type (vendor-dependent). This should be visible ONLY for display purposes.

  uint **family**;  
Warning: This field will be turned into a property in a future release. 


Processor type (vendor-dependent). This should be visible ONLY for display purposes.

  uint **numCacheLevels**;  
This field has been deprecated. Please use `cacheLevels` instead.

  nothrow @nogc @property @trusted uint **cacheLevels**();  
The number of cache levels in the CPU.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_cpuid.html>

std.traits
==========

 Templates which extract information about types and symbols at compile time. 

 

| Category | Templates |
| --- | --- |
| Symbol Name traits | [`fullyQualifiedName`](#fullyQualifiedName) [`moduleName`](#moduleName) [`packageName`](#packageName) |
| Function traits | [`isFunction`](#isFunction) [`arity`](#arity) [`functionAttributes`](#functionAttributes) [`hasFunctionAttributes`](#hasFunctionAttributes) [`functionLinkage`](#functionLinkage) [`FunctionTypeOf`](#FunctionTypeOf) [`isSafe`](#isSafe) [`isUnsafe`](#isUnsafe) [`isFinal`](#isFinal) [`ParameterDefaults`](#ParameterDefaults) [`ParameterIdentifierTuple`](#ParameterIdentifierTuple) [`ParameterStorageClassTuple`](#ParameterStorageClassTuple) [`Parameters`](#Parameters) [`ReturnType`](#ReturnType) [`SetFunctionAttributes`](#SetFunctionAttributes) [`variadicFunctionStyle`](#variadicFunctionStyle) |
| Aggregate Type traits | [`BaseClassesTuple`](#BaseClassesTuple) [`BaseTypeTuple`](#BaseTypeTuple) [`classInstanceAlignment`](#classInstanceAlignment) [`EnumMembers`](#EnumMembers) [`FieldNameTuple`](#FieldNameTuple) [`Fields`](#Fields) [`hasAliasing`](#hasAliasing) [`hasElaborateAssign`](#hasElaborateAssign) [`hasElaborateCopyConstructor`](#hasElaborateCopyConstructor) [`hasElaborateDestructor`](#hasElaborateDestructor) [`hasElaborateMove`](#hasElaborateMove) [`hasIndirections`](#hasIndirections) [`hasMember`](#hasMember) [`hasStaticMember`](#hasStaticMember) [`hasNested`](#hasNested) [`hasUnsharedAliasing`](#hasUnsharedAliasing) [`InterfacesTuple`](#InterfacesTuple) [`isInnerClass`](#isInnerClass) [`isNested`](#isNested) [`MemberFunctionsTuple`](#MemberFunctionsTuple) [`RepresentationTypeTuple`](#RepresentationTypeTuple) [`TemplateArgsOf`](#TemplateArgsOf) [`TemplateOf`](#TemplateOf) [`TransitiveBaseTypeTuple`](#TransitiveBaseTypeTuple) |
| Type Conversion | [`CommonType`](#CommonType) [`ImplicitConversionTargets`](#ImplicitConversionTargets) [`CopyTypeQualifiers`](#CopyTypeQualifiers) [`CopyConstness`](#CopyConstness) [`isAssignable`](#isAssignable) [`isCovariantWith`](#isCovariantWith) [`isImplicitlyConvertible`](#isImplicitlyConvertible) |
| SomethingTypeOf | [`rvalueOf`](#rvalueOf) [`lvalueOf`](#lvalueOf) [`InoutOf`](#InoutOf) [`ConstOf`](#ConstOf) [`SharedOf`](#SharedOf) [`SharedInoutOf`](#SharedInoutOf) [`SharedConstOf`](#SharedConstOf) [`ImmutableOf`](#ImmutableOf) [`QualifierOf`](#QualifierOf) |
| Categories of types | [`allSameType`](#allSameType) [`ifTestable`](#ifTestable) [`isType`](#isType) [`isAggregateType`](#isAggregateType) [`isArray`](#isArray) [`isAssociativeArray`](#isAssociativeArray) [`isAutodecodableString`](#isAutodecodableString) [`isBasicType`](#isBasicType) [`isBoolean`](#isBoolean) [`isBuiltinType`](#isBuiltinType) [`isCopyable`](#isCopyable) [`isDynamicArray`](#isDynamicArray) [`isEqualityComparable`](#isEqualityComparable) [`isFloatingPoint`](#isFloatingPoint) [`isIntegral`](#isIntegral) [`isNarrowString`](#isNarrowString) [`isConvertibleToString`](#isConvertibleToString) [`isNumeric`](#isNumeric) [`isOrderingComparable`](#isOrderingComparable) [`isPointer`](#isPointer) [`isScalarType`](#isScalarType) [`isSigned`](#isSigned) [`isSIMDVector`](#isSIMDVector) [`isSomeChar`](#isSomeChar) [`isSomeString`](#isSomeString) [`isStaticArray`](#isStaticArray) [`isUnsigned`](#isUnsigned) |
| Type behaviours | [`isAbstractClass`](#isAbstractClass) [`isAbstractFunction`](#isAbstractFunction) [`isCallable`](#isCallable) [`isDelegate`](#isDelegate) [`isExpressions`](#isExpressions) [`isFinalClass`](#isFinalClass) [`isFinalFunction`](#isFinalFunction) [`isFunctionPointer`](#isFunctionPointer) [`isInstanceOf`](#isInstanceOf) [`isIterable`](#isIterable) [`isMutable`](#isMutable) [`isSomeFunction`](#isSomeFunction) [`isTypeTuple`](#isTypeTuple) |
| General Types | [`ForeachType`](#ForeachType) [`KeyType`](#KeyType) [`Largest`](#Largest) [`mostNegative`](#mostNegative) [`OriginalType`](#OriginalType) [`PointerTarget`](#PointerTarget) [`Signed`](#Signed) [`Unconst`](#Unconst) [`Unqual`](#Unqual) [`Unsigned`](#Unsigned) [`ValueType`](#ValueType) [`Promoted`](#Promoted) |
| Misc | [`mangledName`](#mangledName) [`Select`](#Select) [`select`](#select) |
| User-Defined Attributes | [`hasUDA`](#hasUDA) [`getUDAs`](#getUDAs) [`getSymbolsByUDA`](#getSymbolsByUDA) |

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Tomasz Stachowiak (`isExpressions`), [Andrei Alexandrescu](http://erdani.org), Shin Fujishiro, [Robert Clipsham](http://octarineparrot.com), [David Nadlinger](http://klickverbot.at), Kenji Hara, Shoichi Kato 
 
Source
 [std/traits.d](https://github.com/dlang/phobos/blob/master/std/traits.d)

 
template **InoutOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `inout` qualifier added.
 
Examples:


```
static assert(is(InoutOf!(int) == inout int));
static assert(is(InoutOf!(inout int) == inout int));
static assert(is(InoutOf!(const int) == inout const int));
static assert(is(InoutOf!(shared int) == inout shared int));

```
 
  template **ConstOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `const` qualifier added.
 
Examples:


```
static assert(is(ConstOf!(int) == const int));
static assert(is(ConstOf!(const int) == const int));
static assert(is(ConstOf!(inout int) == const inout int));
static assert(is(ConstOf!(shared int) == const shared int));

```
 
  template **SharedOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `shared` qualifier added.
 
Examples:


```
static assert(is(SharedOf!(int) == shared int));
static assert(is(SharedOf!(shared int) == shared int));
static assert(is(SharedOf!(inout int) == shared inout int));
static assert(is(SharedOf!(immutable int) == shared immutable int));

```
 
  template **SharedInoutOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `inout` and `shared` qualifiers added.
 
Examples:


```
static assert(is(SharedInoutOf!(int) == shared inout int));
static assert(is(SharedInoutOf!(int) == inout shared int));

static assert(is(SharedInoutOf!(const int) == shared inout const int));
static assert(is(SharedInoutOf!(immutable int) == shared inout immutable int));

```
 
  template **SharedConstOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `const` and `shared` qualifiers added.
 
Examples:


```
static assert(is(SharedConstOf!(int) == shared const int));
static assert(is(SharedConstOf!(int) == const shared int));

static assert(is(SharedConstOf!(inout int) == shared inout const int));
// immutable variables are implicitly shared and const
static assert(is(SharedConstOf!(immutable int) == immutable int));

```
 
  template **ImmutableOf**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to qualify |


 
Returns:

`T` with the `immutable` qualifier added.
 
Examples:


```
static assert(is(ImmutableOf!(int) == immutable int));
static assert(is(ImmutableOf!(const int) == immutable int));
static assert(is(ImmutableOf!(inout int) == immutable int));
static assert(is(ImmutableOf!(shared int) == immutable int));

```
 
  template **QualifierOf**(T) 
Gives a template that can be used to apply the same attributes that are on the given type `T`. E.g. passing `inout shared int` will return `SharedInoutOf`. 



Parameters:


|  |  |
| --- | --- |
| T | the type to check qualifiers from |


 
Returns:
The qualifier template from the given type `T`

 
Examples:


```
static assert(__traits(isSame, QualifierOf!(immutable int), ImmutableOf));
static assert(__traits(isSame, QualifierOf!(shared int), SharedOf));
static assert(__traits(isSame, QualifierOf!(shared inout int), SharedInoutOf));

```
 
  template **packageName**(alias T) 
Get the full package name for the given symbol.



Examples:


```
static assert(packageName!packageName == "std");

```
 
 
Examples:


```
static assert(packageName!moduleName == "std");

```
 
  template **moduleName**(alias T) 
Get the module name (including package) for the given symbol.



Examples:


```
static assert(moduleName!moduleName == "std.traits");

```
 
  template **fullyQualifiedName**(T...) if (T.length == 1) 
Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter. 



Example


```
module myModule;
struct MyStruct {}
static assert(fullyQualifiedName!(const MyStruct[]) == "const(myModule.MyStruct[])");

```
 
Examples:


```
static assert(fullyQualifiedName!fullyQualifiedName == "std.traits.fullyQualifiedName");

```
 
  template **ReturnType**(func...) if (func.length == 1 && isCallable!func) 
Get the type of the return value from a function, a pointer to function, a delegate, a struct with an opCall, a pointer to a struct with an opCall, or a class with an `opCall`. Please note that ref is not part of a type, but the attribute of the function (see template [`functionAttributes`](#functionAttributes)).



Examples:


```
int foo();
ReturnType!foo x;   // x is declared as int

```
 
  template **Parameters**(func...) if (func.length == 1 && isCallable!func) 
Get, as a tuple, the types of the parameters to a function, a pointer to function, a delegate, a struct with an `opCall`, a pointer to a struct with an `opCall`, or a class with an `opCall`.



Examples:


```
int foo(int, long);
void bar(Parameters!foo);      // declares void bar(int, long);
void abc(Parameters!foo[1]);   // declares void abc(long);

```
 
  alias **ParameterTypeTuple** = Parameters(func...) if (func.length == 1 && isCallable!func);  
Alternate name for [`Parameters`](#Parameters), kept for legacy compatibility.

  template **arity**(func...) if (func.length == 1 && isCallable!func && (variadicFunctionStyle!func == Variadic.no)) 
Returns the number of arguments of function `func`. arity is undefined for variadic functions.



Examples:


```
void foo(){}
static assert(arity!foo == 0);
void bar(uint){}
static assert(arity!bar == 1);
void variadicFoo(uint...){}
static assert(!__traits(compiles, arity!variadicFoo));

```
 
  enum **ParameterStorageClass**: uint;   
  
template **ParameterStorageClassTuple**(func...) if (func.length == 1 && isCallable!func) 
Get tuple, one per function parameter, of the storage classes of the parameters. 



Parameters:


|  |  |
| --- | --- |
| func | function symbol or type of function, delegate, or pointer to function |


 
Returns:
A tuple of ParameterStorageClass bits
 
Examples:


```
alias STC = ParameterStorageClass; // shorten the enum name

void func(ref int ctx, out real result, in real param, void* ptr)
{
}
alias pstc = ParameterStorageClassTuple!func;
static assert(pstc.length == 4); // number of parameters
static assert(pstc[0] == STC.ref_);
static assert(pstc[1] == STC.out_);
version (none)
{
    // TODO: When the DMD PR (dlang/dmd#11474) gets merged,
    // remove the versioning and the second test
    static assert(pstc[2] == STC.in_);
    // This is the current behavior, before `in` is fixed to not be an alias
    static assert(pstc[2] == STC.scope_);
}
static assert(pstc[3] == STC.none);

```
 
 

**none**  
  
**in\_**  
  
**ref\_**  
  
**out\_**  
  
**lazy\_**  
  
**scope\_**  
  
**return\_**
 
These flags can be bitwise OR-ed together to represent complex storage class.

    enum ParameterStorageClass **extractParameterStorageClassFlags**(Attribs...);  
Convert the result of `__traits(getParameterStorageClasses)` to [`ParameterStorageClass`](#ParameterStorageClass) `enum`s. 



Parameters:


|  |  |
| --- | --- |
| Attribs | The return value of `__traits(getParameterStorageClasses)` |


 
Returns:
The bitwise OR of the equivalent [`ParameterStorageClass`](#ParameterStorageClass) `enum`s.
 
Examples:


```
static void func(ref int ctx, out real result);

enum param1 = extractParameterStorageClassFlags!(
    __traits(getParameterStorageClasses, func, 0)
);
static assert(param1 == ParameterStorageClass.ref_);

enum param2 = extractParameterStorageClassFlags!(
    __traits(getParameterStorageClasses, func, 1)
);
static assert(param2 == ParameterStorageClass.out_);

enum param3 = extractParameterStorageClassFlags!(
    __traits(getParameterStorageClasses, func, 0),
    __traits(getParameterStorageClasses, func, 1)
);
static assert(param3 == (ParameterStorageClass.ref_ | ParameterStorageClass.out_));

```
 
  template **ParameterIdentifierTuple**(func...) if (func.length == 1 && isCallable!func) 
Get, as a tuple, the identifiers of the parameters to a function symbol.



Examples:


```
int foo(int num, string name, int);
static assert([ParameterIdentifierTuple!foo] == ["num", "name", ""]);

```
 
  template **ParameterDefaults**(func...) if (func.length == 1 && isCallable!func) 
Get, as a tuple, the default value of the parameters to a function symbol. If a parameter doesn't have the default value, `void` is returned instead.



Examples:


```
int foo(int num, string name = "hello", int[] = [1,2,3], lazy int x = 0);
static assert(is(ParameterDefaults!foo[0] == void));
static assert(   ParameterDefaults!foo[1] == "hello");
static assert(   ParameterDefaults!foo[2] == [1,2,3]);
static assert(   ParameterDefaults!foo[3] == 0);

```
 
  alias **ParameterDefaultValueTuple** = ParameterDefaults(func...) if (func.length == 1 && isCallable!func);  
Alternate name for [`ParameterDefaults`](#ParameterDefaults), kept for legacy compatibility.

  enum **FunctionAttribute**: uint;   
  
template **functionAttributes**(func...) if (func.length == 1 && isCallable!func) 
Returns the FunctionAttribute mask for function `func`. 



See Also:
[`hasFunctionAttributes`](#hasFunctionAttributes)
 
Examples:


```
alias FA = FunctionAttribute; // shorten the enum name

real func(real x) pure nothrow @safe
{
    return x;
}
static assert(functionAttributes!func & FA.pure_);
static assert(functionAttributes!func & FA.safe);
static assert(!(functionAttributes!func & FA.trusted)); // not @trusted

```
 
 

**none**  
  
**pure\_**  
  
**nothrow\_**  
  
**ref\_**  
  
**property**  
  
**trusted**  
  
**safe**  
  
**nogc**  
  
**system**  
  
**const\_**  
  
**immutable\_**  
  
**inout\_**  
  
**shared\_**  
  
**return\_**  
  
**scope\_**  
  
**live**
 
These flags can be bitwise OR-ed together to represent a complex attribute.

    template **hasFunctionAttributes**(args...) if (args.length > 0 && isCallable!(args[0]) && allSatisfy!(isSomeString, typeof(args[1..$]))) 
Checks whether a function has the given attributes attached. 



Parameters:


|  |  |
| --- | --- |
| args | Function to check, followed by a variadic number of function attributes as strings |


 
Returns:

`true`, if the function has the list of attributes attached and `false` otherwise. 
 
See Also:
[`functionAttributes`](#functionAttributes)
 
Examples:


```
real func(real x) pure nothrow @safe;
static assert(hasFunctionAttributes!(func, "@safe", "pure"));
static assert(!hasFunctionAttributes!(func, "@trusted"));

// for templates attributes are automatically inferred
bool myFunc(T)(T b)
{
    return !b;
}
static assert(hasFunctionAttributes!(myFunc!bool, "@safe", "pure", "@nogc", "nothrow"));
static assert(!hasFunctionAttributes!(myFunc!bool, "shared"));

```
 
  template **isSafe**(alias func) if (isCallable!func) 
`true` if `func` is `@safe` or `@trusted`.



Examples:


```
@safe    int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system  int mul(int a, int b) {return a*b;}

static assert( isSafe!add);
static assert( isSafe!sub);
static assert(!isSafe!mul);

```
 
  enum auto **isUnsafe**(alias func);  
`true` if `func` is `@system`.



Examples:


```
@safe    int add(int a, int b) {return a+b;}
@trusted int sub(int a, int b) {return a-b;}
@system  int mul(int a, int b) {return a*b;}

static assert(!isUnsafe!add);
static assert(!isUnsafe!sub);
static assert( isUnsafe!mul);

```
 
  template **functionLinkage**(func...) if (func.length == 1 && isCallable!func) 
Determine the linkage attribute of the function. 



Parameters:


|  |  |
| --- | --- |
| func | the function symbol, or the type of a function, delegate, or pointer to function |


 
Returns:
one of the strings "D", "C", "C++", "Windows", "Objective-C", or "System".
 
Examples:


```
extern(D) void Dfunc() {}
extern(C) void Cfunc() {}
static assert(functionLinkage!Dfunc == "D");
static assert(functionLinkage!Cfunc == "C");

string a = functionLinkage!Dfunc;
writeln(a); // "D"

auto fp = &Cfunc;
string b = functionLinkage!fp;
writeln(b); // "C"

```
 
  enum **Variadic**: int;   
  
template **variadicFunctionStyle**(func...) if (func.length == 1 && isCallable!func) 
Determines what kind of variadic parameters function has. 



Parameters:


|  |  |
| --- | --- |
| func | function symbol or type of function, delegate, or pointer to function |


 
Returns:
enum Variadic
 
Examples:


```
void func() {}
static assert(variadicFunctionStyle!func == Variadic.no);

extern(C) int printf(in char*, ...);
static assert(variadicFunctionStyle!printf == Variadic.c);

```
 
 
**no** 
Function is not variadic.

  **c** 
Function is a C-style variadic function, which uses `core.stdc.stdarg`

  **d** 
Function is a D-style variadic function, which uses `__argptr` and `__arguments`.

  **typesafe** 
Function is a typesafe variadic function.

    template **FunctionTypeOf**(func...) if (func.length == 1 && isCallable!func) 
Get the function type from a callable object `func`. 


Using builtin `typeof` on a property function yields the types of the property value, not of the property function itself. Still, `FunctionTypeOf` is able to obtain function types of properties. 

 
Note
 Do not confuse function types with function pointer types; function types are usually used for compile-time reflection purposes.
 
Examples:


```
class C
{
    int value() @property { return 0; }
}
static assert(is( typeof(C.value) == int ));
static assert(is( FunctionTypeOf!(C.value) == function ));

```
 
  template **SetFunctionAttributes**(T, string linkage, uint attrs) if (isFunctionPointer!T || isDelegate!T)  
  
template **SetFunctionAttributes**(T, string linkage, uint attrs) if (is(T == function)) 
Constructs a new function or delegate type with the same basic signature as the given one, but different attributes (including linkage). 


This is especially useful for adding/removing attributes to/from types in generic code, where the actual type name cannot be spelt out. 

 
Parameters:


|  |  |
| --- | --- |
| T | The base type. |
| linkage | The desired linkage of the result type. |
| attrs | The desired [`FunctionAttribute`](#FunctionAttribute)s of the result type. |


 
Examples:


```
alias ExternC(T) = SetFunctionAttributes!(T, "C", functionAttributes!T);

auto assumePure(T)(T t)
if (isFunctionPointer!T || isDelegate!T)
{
    enum attrs = functionAttributes!T | FunctionAttribute.pure_;
    return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t;
}

int f()
{
    import core.thread : getpid;
    return getpid();
}

int g() pure @trusted
{
    auto pureF = assumePure(&f);
    return pureF();
}
assert(g() > 0);

```
 
  template **isInnerClass**(T) if (is(T == class)) 
Determines whether `T` is a class nested inside another class and that `T.outer` is the implicit reference to the outer class (i.e. `outer` has not been used as a field or method name) 



Parameters:


|  |  |
| --- | --- |
| T | type to test |


 
Returns:

`true` if `T` is a class nested inside another, with the conditions described above; `false` otherwise
 
Examples:


```
class C
{
    int outer;
}
static assert(!isInnerClass!C);

class Outer1
{
    class Inner1 { }
    class Inner2
    {
        int outer;
    }
}
static assert(isInnerClass!(Outer1.Inner1));
static assert(!isInnerClass!(Outer1.Inner2));

static class Outer2
{
    static class Inner
    {
        int outer;
    }
}
static assert(!isInnerClass!(Outer2.Inner));

```
 
  template **isNested**(T) if (is(T == class) || is(T == struct) || is(T == union)) 
Determines whether `T` has its own context pointer. `T` must be either `class`, `struct`, or `union`.



Examples:


```
static struct S { }
static assert(!isNested!S);

int i;
struct NestedStruct { void f() { ++i; } }
static assert(isNested!NestedStruct);

```
 
  template **hasNested**(T) 
Determines whether `T` or any of its representation types have a context pointer.



Examples:


```
static struct S { }

int i;
struct NS { void f() { ++i; } }

static assert(!hasNested!(S[2]));
static assert(hasNested!(NS[2]));

```
 
  template **Fields**(T) 
Get as a tuple the types of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. If `T` isn't a struct, class, or union returns a tuple with one element `T`.



Examples:


```
import std.meta : AliasSeq;
struct S { int x; float y; }
static assert(is(Fields!S == AliasSeq!(int, float)));

```
 
  alias **FieldTypeTuple** = Fields(T);  
Alternate name for [`Fields`](#Fields), kept for legacy compatibility.

  template **FieldNameTuple**(T) 
Get as an expression tuple the names of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. Inherited fields (for classes) are not included. If `T` isn't a struct, class, or union, an expression tuple with an empty string is returned.



Examples:


```
import std.meta : AliasSeq;
struct S { int x; float y; }
static assert(FieldNameTuple!S == AliasSeq!("x", "y"));
static assert(FieldNameTuple!int == AliasSeq!"");

```
 
  template **RepresentationTypeTuple**(T) 
Get the primitive types of the fields of a struct or class, in topological order.



Examples:


```
struct S1 { int a; float b; }
struct S2 { char[] a; union { S1 b; S1 * c; } }
alias R = RepresentationTypeTuple!S2;
assert(R.length == 4
    && is(R[0] == char[]) && is(R[1] == int)
    && is(R[2] == float) && is(R[3] == S1*));

```
 
  enum auto **hasAliasing**(T...);  
Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*` and `U` is not immutable;
2. an array `U[]` and `U` is not immutable;
3. a reference to a class or interface type `C` and `C` is not immutable.
4. an associative array that is not immutable.
5. a delegate.




Examples:


```
struct S1 { int a; Object b; }
struct S2 { string a; }
struct S3 { int a; immutable Object b; }
struct S4 { float[3] vals; }
static assert( hasAliasing!S1);
static assert(!hasAliasing!S2);
static assert(!hasAliasing!S3);
static assert(!hasAliasing!S4);

```
 
  template **hasIndirections**(T) 
Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*`;
2. an array `U[]`;
3. a reference to a class type `C`;
4. an associative array;
5. a delegate;
6. a [`context pointer`](#isNested).




Examples:


```
static assert( hasIndirections!(int[string]));
static assert( hasIndirections!(void delegate()));
static assert( hasIndirections!(void delegate() immutable));
static assert( hasIndirections!(immutable(void delegate())));
static assert( hasIndirections!(immutable(void delegate() immutable)));

static assert(!hasIndirections!(void function()));
static assert( hasIndirections!(void*[1]));
static assert(!hasIndirections!(byte[1]));

```
 
  enum auto **hasUnsharedAliasing**(T...);  
Returns `true` if and only if `T`'s representation includes at least one of the following: 1. a raw pointer `U*` and `U` is not immutable or shared;
2. an array `U[]` and `U` is not immutable or shared;
3. a reference to a class type `C` and `C` is not immutable or shared.
4. an associative array that is not immutable or shared.
5. a delegate that is not shared.




Examples:


```
struct S1 { int a; Object b; }
struct S2 { string a; }
struct S3 { int a; immutable Object b; }
static assert( hasUnsharedAliasing!S1);
static assert(!hasUnsharedAliasing!S2);
static assert(!hasUnsharedAliasing!S3);

struct S4 { int a; shared Object b; }
struct S5 { char[] a; }
struct S6 { shared char[] b; }
struct S7 { float[3] vals; }
static assert(!hasUnsharedAliasing!S4);
static assert( hasUnsharedAliasing!S5);
static assert(!hasUnsharedAliasing!S6);
static assert(!hasUnsharedAliasing!S7);

```
 
  template **hasElaborateCopyConstructor**(S) 
True if `S` or any type embedded directly in the representation of `S` defines an elaborate copy constructor. Elaborate copy constructors are introduced by defining `this(this)` for a `struct`. 


Classes and unions never have elaborate copy constructors.

 
Examples:


```
static assert(!hasElaborateCopyConstructor!int);

static struct S1 { }
static struct S2 { this(this) {} }
static struct S3 { S2 field; }
static struct S4 { S3[1] field; }
static struct S5 { S3[] field; }
static struct S6 { S3[0] field; }
static struct S7 { @disable this(); S3 field; }
static assert(!hasElaborateCopyConstructor!S1);
static assert( hasElaborateCopyConstructor!S2);
static assert( hasElaborateCopyConstructor!(immutable S2));
static assert( hasElaborateCopyConstructor!S3);
static assert( hasElaborateCopyConstructor!(S3[1]));
static assert(!hasElaborateCopyConstructor!(S3[0]));
static assert( hasElaborateCopyConstructor!S4);
static assert(!hasElaborateCopyConstructor!S5);
static assert(!hasElaborateCopyConstructor!S6);
static assert( hasElaborateCopyConstructor!S7);

```
 
  template **hasElaborateAssign**(S) 
True if `S` or any type directly embedded in the representation of `S` defines an elaborate assignment. Elaborate assignments are introduced by defining `opAssign(typeof(this))` or `opAssign(ref typeof(this))` for a `struct` or when there is a compiler-generated `opAssign`. 


A type `S` gets compiler-generated `opAssign` if it has an elaborate destructor.   
  
 Classes and unions never have elaborate assignments. 

 
Note
 Structs with (possibly nested) postblit operator(s) will have a hidden yet elaborate compiler generated assignment operator (unless explicitly disabled).
 
Examples:


```
static assert(!hasElaborateAssign!int);

static struct S  { void opAssign(S) {} }
static assert( hasElaborateAssign!S);
static assert(!hasElaborateAssign!(const(S)));

static struct S1 { void opAssign(ref S1) {} }
static struct S2 { void opAssign(int) {} }
static struct S3 { S s; }
static assert( hasElaborateAssign!S1);
static assert(!hasElaborateAssign!S2);
static assert( hasElaborateAssign!S3);
static assert( hasElaborateAssign!(S3[1]));
static assert(!hasElaborateAssign!(S3[0]));

```
 
  template **hasElaborateDestructor**(S) 
True if `S` or any type directly embedded in the representation of `S` defines an elaborate destructor. Elaborate destructors are introduced by defining `~this()` for a  `struct`. 


Classes and unions never have elaborate destructors, even though classes may define `~this()`.

 
Examples:


```
static assert(!hasElaborateDestructor!int);

static struct S1 { }
static struct S2 { ~this() {} }
static struct S3 { S2 field; }
static struct S4 { S3[1] field; }
static struct S5 { S3[] field; }
static struct S6 { S3[0] field; }
static struct S7 { @disable this(); S3 field; }
static assert(!hasElaborateDestructor!S1);
static assert( hasElaborateDestructor!S2);
static assert( hasElaborateDestructor!(immutable S2));
static assert( hasElaborateDestructor!S3);
static assert( hasElaborateDestructor!(S3[1]));
static assert(!hasElaborateDestructor!(S3[0]));
static assert( hasElaborateDestructor!S4);
static assert(!hasElaborateDestructor!S5);
static assert(!hasElaborateDestructor!S6);
static assert( hasElaborateDestructor!S7);

```
 
  template **hasElaborateMove**(S) 
True if `S` or any type embedded directly in the representation of `S` defines elaborate move semantics. Elaborate move semantics are introduced by defining `opPostMove(ref typeof(this))` for a `struct`. 


Classes and unions never have elaborate move semantics.

 
Examples:


```
static assert(!hasElaborateMove!int);

static struct S1 { }
static struct S2 { void opPostMove(ref S2) {} }
static struct S3 { void opPostMove(inout ref S3) inout {} }
static struct S4 { void opPostMove(const ref S4) {} }
static struct S5 { void opPostMove(S5) {} }
static struct S6 { void opPostMove(int) {} }
static struct S7 { S3[1] field; }
static struct S8 { S3[] field; }
static struct S9 { S3[0] field; }
static struct S10 { @disable this(); S3 field; }
static assert(!hasElaborateMove!S1);
static assert( hasElaborateMove!S2);
static assert( hasElaborateMove!S3);
static assert( hasElaborateMove!(immutable S3));
static assert( hasElaborateMove!S4);
static assert(!hasElaborateMove!S5);
static assert(!hasElaborateMove!S6);
static assert( hasElaborateMove!S7);
static assert(!hasElaborateMove!S8);
static assert(!hasElaborateMove!S9);
static assert( hasElaborateMove!S10);

```
 
  enum auto **hasMember**(T, string name);  
Yields `true` if and only if `T` is an aggregate that defines a symbol called `name`.



Examples:


```
static assert(!hasMember!(int, "blah"));
struct S1 { int blah; }
struct S2 { int blah(){ return 0; } }
class C1 { int blah; }
class C2 { int blah(){ return 0; } }
static assert(hasMember!(S1, "blah"));
static assert(hasMember!(S2, "blah"));
static assert(hasMember!(C1, "blah"));
static assert(hasMember!(C2, "blah"));

```
 
  template **hasStaticMember**(T, string member) 
Whether the symbol represented by the string, member, exists and is a static member of T. 



Parameters:


|  |  |
| --- | --- |
| T | Type containing symbol `member`. |
| member | Name of symbol to test that resides in `T`. |


 
Returns:

`true` iff `member` exists and is static.
 
Examples:


```
static struct S
{
    static void sf() {}
    void f() {}

    static int si;
    int i;
}

static assert( hasStaticMember!(S, "sf"));
static assert(!hasStaticMember!(S, "f"));

static assert( hasStaticMember!(S, "si"));
static assert(!hasStaticMember!(S, "i"));

static assert(!hasStaticMember!(S, "hello"));

```
 
  template **EnumMembers**(E) if (is(E == enum)) 
Retrieves the members of an enumerated type `enum E`. 



Parameters:


|  |  |
| --- | --- |
| E | An enumerated type. `E` may have duplicated values. |


 
Returns:
Static tuple composed of the members of the enumerated type `E`. The members are arranged in the same order as declared in `E`. The name of the enum can be found by querying the compiler for the name of the identifier, i.e. `__traits(identifier, EnumMembers!MyEnum[i])`. For enumerations with unique values, [`std.conv.to`](std_conv#to) can also be used. 
 
Note
 An enum can have multiple members which have the same value. If you want to use EnumMembers to e.g. generate switch cases at compile-time, you should use the [`std.meta.NoDuplicates`](std_meta#NoDuplicates) template to avoid generating duplicate switch cases. 
 
Note
 Returned values are strictly typed with `E`. Thus, the following code does not work without the explicit cast: 


```
enum E : int { a, b, c }
int[] abc = cast(int[]) [ EnumMembers!E ];

```
 Cast is not necessary if the type of the variable is inferred. See the example below. 
Examples:
Create an array of enumerated values 
```
enum Sqrts : real
{
    one = 1,
    two = 1.41421,
    three = 1.73205
}
auto sqrts = [EnumMembers!Sqrts];
writeln(sqrts); // [Sqrts.one, Sqrts.two, Sqrts.three]

```
 
 
Examples:
A generic function `rank(v)` in the following example uses this template for finding a member `e` in an enumerated type `E`. 
```
// Returns i if e is the i-th enumerator of E.
static size_t rank(E)(E e)
if (is(E == enum))
{
    static foreach (i, member; EnumMembers!E)
    {
        if (e == member)
            return i;
    }
    assert(0, "Not an enum member");
}

enum Mode
{
    read = 1,
    write = 2,
    map = 4
}
writeln(rank(Mode.read)); // 0
writeln(rank(Mode.write)); // 1
writeln(rank(Mode.map)); // 2

```
 
 
Examples:
Use EnumMembers to generate a switch statement using static foreach. 
```
import std.conv : to;
class FooClass
{
    string calledMethod;
    void foo() @safe { calledMethod = "foo"; }
    void bar() @safe { calledMethod = "bar"; }
    void baz() @safe { calledMethod = "baz"; }
}

enum FooEnum { foo, bar, baz }

auto var = FooEnum.bar;
auto fooObj = new FooClass();
s: final switch (var)
{
    static foreach (member; EnumMembers!FooEnum)
    {
        case member: // Generate a case for each enum value.
            // Call fooObj.{name of enum value}().
            __traits(getMember, fooObj, to!string(member))();
            break s;
    }
}
// As we pass in FooEnum.bar, the bar() method gets called.
writeln(fooObj.calledMethod); // "bar"

```
 
  template **BaseTypeTuple**(A) 
Get a AliasSeq of the base class and base interfaces of this class or interface. BaseTypeTuple!Object returns the empty type tuple.



Examples:


```
import std.meta : AliasSeq;

interface I1 { }
interface I2 { }
interface I12 : I1, I2 { }
static assert(is(BaseTypeTuple!I12 == AliasSeq!(I1, I2)));

interface I3 : I1 { }
interface I123 : I1, I2, I3 { }
static assert(is(BaseTypeTuple!I123 == AliasSeq!(I1, I2, I3)));

```
 
  template **BaseClassesTuple**(T) if (is(T == class)) 
Get a AliasSeq of *all* base classes of this class, in decreasing order. Interfaces are not included.  BaseClassesTuple!Object yields the empty type tuple.



Examples:


```
import std.meta : AliasSeq;

class C1 { }
class C2 : C1 { }
class C3 : C2 { }
static assert(!BaseClassesTuple!Object.length);
static assert(is(BaseClassesTuple!C1 == AliasSeq!(Object)));
static assert(is(BaseClassesTuple!C2 == AliasSeq!(C1, Object)));
static assert(is(BaseClassesTuple!C3 == AliasSeq!(C2, C1, Object)));

```
 
  template **InterfacesTuple**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The `class` or `interface` to search. |


 
Returns:

[`std.meta.AliasSeq`](std_meta#AliasSeq) of all interfaces directly or indirectly inherited by this class or interface. Interfaces do not repeat if multiply implemented. `InterfacesTuple!Object` yields an empty `AliasSeq`.
 
Examples:


```
interface I1 {}
interface I2 {}
class A : I1, I2 {}
class B : A, I1 {}
class C : B {}

alias TL = InterfacesTuple!C;
static assert(is(TL[0] == I1) && is(TL[1] == I2));

```
 
  template **TransitiveBaseTypeTuple**(T) 
Get a AliasSeq of *all* base classes of  T, in decreasing order, followed by T's interfaces. TransitiveBaseTypeTuple!Object yields the empty type tuple.



Examples:


```
interface J1 {}
interface J2 {}
class B1 {}
class B2 : B1, J1, J2 {}
class B3 : B2, J1 {}
alias TL = TransitiveBaseTypeTuple!B3;
writeln(TL.length); // 5
assert(is (TL[0] == B2));
assert(is (TL[1] == B1));
assert(is (TL[2] == Object));
assert(is (TL[3] == J1));
assert(is (TL[4] == J2));

writeln(TransitiveBaseTypeTuple!Object.length); // 0

```
 
  template **MemberFunctionsTuple**(C, string name) if (is(C == class) || is(C == interface)) 
Returns a tuple of non-static functions with the name `name` declared in the class or interface `C`. Covariant duplicates are shrunk into the most derived one.



Examples:


```
interface I { I foo(); }
class B
{
    real foo(real v) { return v; }
}
class C : B, I
{
    override C foo() { return this; } // covariant overriding of I.foo()
}
alias foos = MemberFunctionsTuple!(C, "foo");
static assert(foos.length == 2);
static assert(__traits(isSame, foos[0], C.foo));
static assert(__traits(isSame, foos[1], B.foo));

```
 
  template **TemplateOf**(alias T : Base!Args, alias Base, Args...)  
  
template **TemplateOf**(T : Base!Args, alias Base, Args...)  
  
template **TemplateOf**(T) 
Returns an alias to the template that `T` is an instance of. It will return `void` if a symbol without a template is given.



Examples:


```
struct Foo(T, U) {}
static assert(__traits(isSame, TemplateOf!(Foo!(int, real)), Foo));

```
 
  template **TemplateArgsOf**(alias T : Base!Args, alias Base, Args...)  
  
template **TemplateArgsOf**(T : Base!Args, alias Base, Args...) 
Returns a `AliasSeq` of the template arguments used to instantiate `T`.



Examples:


```
import std.meta : AliasSeq;

struct Foo(T, U) {}
static assert(is(TemplateArgsOf!(Foo!(int, real)) == AliasSeq!(int, real)));

```
 
  template **classInstanceAlignment**(T) if (is(T == class)) 
Returns class instance alignment.



Examples:


```
class A { byte b; }
class B { long l; }

// As class instance always has a hidden pointer
static assert(classInstanceAlignment!A == (void*).alignof);
static assert(classInstanceAlignment!B == long.alignof);

```
 
  template **CommonType**(T...) 
Get the type that all types can be implicitly converted to. Useful e.g. in figuring out an array type from a bunch of initializing values. Returns void if passed an empty list, or if the types have no common type.



Examples:


```
alias X = CommonType!(int, long, short);
assert(is(X == long));
alias Y = CommonType!(int, char[], short);
assert(is(Y == void));

```
 
 
Examples:


```
static assert(is(CommonType!(3) == int));
static assert(is(CommonType!(double, 4, float) == double));
static assert(is(CommonType!(string, char[]) == const(char)[]));
static assert(is(CommonType!(3, 3U) == uint));
static assert(is(CommonType!(double, int) == double));

```
 
  template **ImplicitConversionTargets**(T) 

Parameters:


|  |  |
| --- | --- |
| T | The type to check |


 
Returns:
An [`std.meta.AliasSeq`](std_meta#AliasSeq) with all possible target types of an implicit conversion `T`. If `T` is a class derived from `Object`, the the result of [`TransitiveBaseTypeTuple`](#TransitiveBaseTypeTuple) is returned. If the type is not a built-in value type or a class derived from `Object`, the an empty [`std.meta.AliasSeq`](std_meta#AliasSeq) is returned. 
 
Note
 The possible targets are computed more conservatively than the language allows, eliminating all dangerous conversions. For example, `ImplicitConversionTargets!double` does not include `float`. 
 
See Also:
[`isImplicitlyConvertible`](#isImplicitlyConvertible)
 
Examples:


```
import std.meta : AliasSeq;

static assert(is(ImplicitConversionTargets!(ulong) == AliasSeq!(float, double, real)));
static assert(is(ImplicitConversionTargets!(int) == AliasSeq!(long, ulong, float, double, real)));
static assert(is(ImplicitConversionTargets!(float) == AliasSeq!(double, real)));
static assert(is(ImplicitConversionTargets!(double) == AliasSeq!(real)));

static assert(is(ImplicitConversionTargets!(char) == AliasSeq!(
    wchar, dchar, byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real
)));
static assert(is(ImplicitConversionTargets!(wchar) == AliasSeq!(
    dchar, short, ushort, int, uint, long, ulong, float, double, real
)));
static assert(is(ImplicitConversionTargets!(dchar) == AliasSeq!(
    int, uint, long, ulong, float, double, real
)));

static assert(is(ImplicitConversionTargets!(string) == AliasSeq!(const(char)[])));
static assert(is(ImplicitConversionTargets!(void*) == AliasSeq!(void*)));

interface A {}
interface B {}
class C : A, B {}

static assert(is(ImplicitConversionTargets!(C) == AliasSeq!(Object, A, B)));
static assert(is(ImplicitConversionTargets!(const C) == AliasSeq!(const Object, const A, const B)));
static assert(is(ImplicitConversionTargets!(immutable C) == AliasSeq!(
    immutable Object, immutable A, immutable B
)));

```
 
  enum bool **isImplicitlyConvertible**(From, To);  
Is `From` implicitly convertible to `To`?



Examples:


```
static assert( isImplicitlyConvertible!(immutable(char), char));
static assert( isImplicitlyConvertible!(const(char), char));
static assert( isImplicitlyConvertible!(char, wchar));
static assert(!isImplicitlyConvertible!(wchar, char));

static assert(!isImplicitlyConvertible!(const(ushort), ubyte));
static assert(!isImplicitlyConvertible!(const(uint), ubyte));
static assert(!isImplicitlyConvertible!(const(ulong), ubyte));

static assert(!isImplicitlyConvertible!(const(char)[], string));
static assert( isImplicitlyConvertible!(string, const(char)[]));

```
 
  enum auto **isAssignable**(Lhs, Rhs = Lhs);  
Returns `true` iff a value of type `Rhs` can be assigned to a variable of type `Lhs`. 


`isAssignable` returns whether both an lvalue and rvalue can be assigned.   
  
 If you omit `Rhs`, `isAssignable` will check identity assignable of `Lhs`.

 
Examples:


```
static assert( isAssignable!(long, int));
static assert(!isAssignable!(int, long));
static assert( isAssignable!(const(char)[], string));
static assert(!isAssignable!(string, char[]));

// int is assignable to int
static assert( isAssignable!int);

// immutable int is not assignable to immutable int
static assert(!isAssignable!(immutable int));

```
 
  enum auto **isRvalueAssignable**(Lhs, Rhs = Lhs);  
Returns `true` iff an rvalue of type `Rhs` can be assigned to a variable of type `Lhs`

  enum auto **isLvalueAssignable**(Lhs, Rhs = Lhs);  
Returns `true` iff an lvalue of type `Rhs` can be assigned to a variable of type `Lhs`

  template **isCovariantWith**(F, G) if (is(F == function) && is(G == function) || is(F == delegate) && is(G == delegate) || isFunctionPointer!F && isFunctionPointer!G) 
Determines whether the function type `F` is covariant with `G`, i.e., functions of the type `F` can override ones of the type `G`.



Examples:


```
interface I { I clone(); }
interface J { J clone(); }
class C : I
{
    override C clone()   // covariant overriding of I.clone()
    {
        return new C;
    }
}

// C.clone() can override I.clone(), indeed.
static assert(isCovariantWith!(typeof(C.clone), typeof(I.clone)));

// C.clone() can't override J.clone(); the return type C is not implicitly
// convertible to J.
static assert(!isCovariantWith!(typeof(C.clone), typeof(J.clone)));

```
 
  @property T **rvalueOf**(T)(inout \_\_InoutWorkaroundStruct = \_\_InoutWorkaroundStruct.init);   
  
@property ref T **lvalueOf**(T)(inout \_\_InoutWorkaroundStruct = \_\_InoutWorkaroundStruct.init);  
Creates an lvalue or rvalue of type `T` for `typeof(...)` and `__traits(compiles, ...)` purposes. No actual value is returned. 



Parameters:


|  |  |
| --- | --- |
| T | The type to transform |


 
Note
 Trying to use returned value will result in a "Symbol Undefined" error at link time.
 
Examples:


```
static int f(int);
static assert(is(typeof(f(rvalueOf!int)) == int));

```
 
 
Examples:


```
static bool f(ref int);
static assert(is(typeof(f(lvalueOf!int)) == bool));

```
 
  enum bool **isBoolean**(T);  
Detect whether `T` is a built-in boolean type.



Examples:


```
static assert( isBoolean!bool);
enum EB : bool { a = true }
static assert( isBoolean!EB);
static assert(!isBoolean!(SubTypeOf!bool));

```
 
  enum bool **isIntegral**(T);  
Detect whether `T` is a built-in integral type. Types `bool`, `char`, `wchar`, and `dchar` are not considered integral.



Examples:


```
static assert(
    isIntegral!byte &&
    isIntegral!short &&
    isIntegral!int &&
    isIntegral!long &&
    isIntegral!(const(long)) &&
    isIntegral!(immutable(long))
);

static assert(
    !isIntegral!bool &&
    !isIntegral!char &&
    !isIntegral!double
);

// types which act as integral values do not pass
struct S
{
    int val;
    alias val this;
}

static assert(!isIntegral!S);

```
 
  enum bool **isFloatingPoint**(T);  
Detect whether `T` is a built-in floating point type.



Examples:


```
static assert(
    isFloatingPoint!float &&
    isFloatingPoint!double &&
    isFloatingPoint!real &&
    isFloatingPoint!(const(real)) &&
    isFloatingPoint!(immutable(real))
);

static assert(!isFloatingPoint!int);

// complex and imaginary numbers do not pass
static assert(
    !isFloatingPoint!cfloat &&
    !isFloatingPoint!ifloat
);

// types which act as floating point values do not pass
struct S
{
    float val;
    alias val this;
}

static assert(!isFloatingPoint!S);

```
 
  enum bool **isNumeric**(T);  
Detect whether `T` is a built-in numeric type (integral or floating point).



Examples:


```
static assert(
    isNumeric!byte &&
    isNumeric!short &&
    isNumeric!int &&
    isNumeric!long &&
    isNumeric!float &&
    isNumeric!double &&
    isNumeric!real &&
    isNumeric!(const(real)) &&
    isNumeric!(immutable(real))
);

static assert(
    !isNumeric!void &&
    !isNumeric!bool &&
    !isNumeric!char &&
    !isNumeric!wchar &&
    !isNumeric!dchar
);

// types which act as numeric values do not pass
struct S
{
    int val;
    alias val this;
}

static assert(!isIntegral!S);

```
 
  enum bool **isScalarType**(T);  
Detect whether `T` is a scalar type (a built-in numeric, character or boolean type).



Examples:


```
static assert(!isScalarType!void);
static assert( isScalarType!(immutable(byte)));
static assert( isScalarType!(immutable(ushort)));
static assert( isScalarType!(immutable(int)));
static assert( isScalarType!(ulong));
static assert( isScalarType!(shared(float)));
static assert( isScalarType!(shared(const bool)));
static assert( isScalarType!(const(char)));
static assert( isScalarType!(wchar));
static assert( isScalarType!(const(dchar)));
static assert( isScalarType!(const(double)));
static assert( isScalarType!(const(real)));

```
 
  enum bool **isBasicType**(T);  
Detect whether `T` is a basic type (scalar type or void).



Examples:


```
static assert(isBasicType!void);
static assert(isBasicType!(const(void)));
static assert(isBasicType!(shared(void)));
static assert(isBasicType!(immutable(void)));
static assert(isBasicType!(shared const(void)));
static assert(isBasicType!(shared inout(void)));
static assert(isBasicType!(shared inout const(void)));
static assert(isBasicType!(inout(void)));
static assert(isBasicType!(inout const(void)));
static assert(isBasicType!(immutable(int)));
static assert(isBasicType!(shared(float)));
static assert(isBasicType!(shared(const bool)));
static assert(isBasicType!(const(dchar)));

```
 
  enum bool **isUnsigned**(T);  
Detect whether `T` is a built-in unsigned numeric type.



Examples:


```
static assert(
    isUnsigned!uint &&
    isUnsigned!ulong
);

static assert(
    !isUnsigned!char &&
    !isUnsigned!int &&
    !isUnsigned!long &&
    !isUnsigned!char &&
    !isUnsigned!wchar &&
    !isUnsigned!dchar
);

```
 
  enum bool **isSigned**(T);  
Detect whether `T` is a built-in signed numeric type.



Examples:


```
static assert(
    isSigned!int &&
    isSigned!long
);

static assert(
    !isSigned!uint &&
    !isSigned!ulong
);

```
 
  enum bool **isSomeChar**(T);  
Detect whether `T` is one of the built-in character types. 


The built-in char types are any of `char`, `wchar` or `dchar`, with or without qualifiers.

 
Examples:


```
//Char types
static assert( isSomeChar!char);
static assert( isSomeChar!wchar);
static assert( isSomeChar!dchar);
static assert( isSomeChar!(typeof('c')));
static assert( isSomeChar!(immutable char));
static assert( isSomeChar!(const dchar));

//Non char types
static assert(!isSomeChar!int);
static assert(!isSomeChar!byte);
static assert(!isSomeChar!string);
static assert(!isSomeChar!wstring);
static assert(!isSomeChar!dstring);
static assert(!isSomeChar!(char[4]));

```
 
  enum bool **isSomeString**(T);  
Detect whether `T` is one of the built-in string types. 


The built-in string types are `Char[]`, where `Char` is any of `char`, `wchar` or `dchar`, with or without qualifiers.   
  
 Static arrays of characters (like `char[80]`) are not considered built-in string types.

 
Examples:


```
//String types
static assert( isSomeString!string);
static assert( isSomeString!(wchar[]));
static assert( isSomeString!(dchar[]));
static assert( isSomeString!(typeof("aaa")));
static assert( isSomeString!(const(char)[]));

//Non string types
static assert(!isSomeString!int);
static assert(!isSomeString!(int[]));
static assert(!isSomeString!(byte[]));
static assert(!isSomeString!(typeof(null)));
static assert(!isSomeString!(char[4]));

enum ES : string { a = "aaa", b = "bbb" }
static assert(!isSomeString!ES);

static struct Stringish
{
    string str;
    alias str this;
}
static assert(!isSomeString!Stringish);

```
 
  enum bool **isNarrowString**(T);  
Detect whether type `T` is a narrow string. 


All arrays that use char, wchar, and their qualified versions are narrow strings. (Those include string and wstring).

 
Examples:


```
static assert(isNarrowString!string);
static assert(isNarrowString!wstring);
static assert(isNarrowString!(char[]));
static assert(isNarrowString!(wchar[]));

static assert(!isNarrowString!dstring);
static assert(!isNarrowString!(dchar[]));

static assert(!isNarrowString!(typeof(null)));
static assert(!isNarrowString!(char[4]));

enum ES : string { a = "aaa", b = "bbb" }
static assert(!isNarrowString!ES);

static struct Stringish
{
    string str;
    alias str this;
}
static assert(!isNarrowString!Stringish);

```
 
  enum bool **isOrderingComparable**(T);   
  
enum bool **isEqualityComparable**(T);  
Detects whether `T` is a comparable type. Basic types and structs and classes that implement opCmp are ordering comparable.



Examples:


```
static assert(isOrderingComparable!int);
static assert(isOrderingComparable!string);
static assert(!isOrderingComparable!creal);

static struct Foo {}
static assert(!isOrderingComparable!Foo);

static struct Bar
{
    int a;
    auto opCmp(Bar b1) const { return a - b1.a; }
}

Bar b1 = Bar(5);
Bar b2 = Bar(7);
assert(isOrderingComparable!Bar && b2 > b1);

```
 
  enum auto **isConvertibleToString**(T);  
Warning: This trait will be deprecated as soon as it is no longer used in Phobos. For a function parameter to safely accept a type that implicitly converts to string as a string, the conversion needs to happen at the callsite; otherwise, the conversion is done inside the function, and in many cases, that means that local memory is sliced (e.g. if a static array is passed to the function, then it's copied, and the resulting dynamic array will be a slice of a local variable). So, if the resulting string escapes the function, the string refers to invalid memory, and accessing it would mean accessing invalid memory. As such, the only safe way for a function to accept types that implicitly convert to string is for the implicit conversion to be done at the callsite, and that can only occur if the parameter is explicitly typed as an array, whereas using isConvertibleToString in a template constraint would result in the conversion being done inside the function. As such, isConvertibleToString is inherently unsafe and is going to be deprecated. 


Detect whether `T` is a struct, static array, or enum that is implicitly convertible to a string.

 
Examples:


```
static struct AliasedString
{
    string s;
    alias s this;
}

enum StringEnum { a = "foo" }

assert(!isConvertibleToString!string);
assert(isConvertibleToString!AliasedString);
assert(isConvertibleToString!StringEnum);
assert(isConvertibleToString!(char[25]));
assert(!isConvertibleToString!(char[]));

```
 
  enum auto **isAutodecodableString**(T);  
Detect whether type `T` is a string that will be autodecoded. 


Given a type `S` that is one of: 1. `const(char)[]`
2. `const(wchar)[]`

 Type `T` can be one of: 1. `S`
2. implicitly convertible to `T`
3. an enum with a base type `T`
4. an aggregate with a base type `T`

 with the proviso that `T` cannot be a static array. 

 
Parameters:


|  |  |
| --- | --- |
| T | type to be tested |


 
Returns:
true if T represents a string that is subject to autodecoding See Also: [`isNarrowString`](#isNarrowString)

 
Examples:


```
static struct Stringish
{
    string s;
    alias s this;
}
static assert(isAutodecodableString!wstring);
static assert(isAutodecodableString!Stringish);
static assert(!isAutodecodableString!dstring);

enum E : const(char)[3] { X = "abc" }
enum F : const(char)[] { X = "abc" }
enum G : F { X = F.init }

static assert(isAutodecodableString!(char[]));
static assert(!isAutodecodableString!(E));
static assert(isAutodecodableString!(F));
static assert(isAutodecodableString!(G));

struct Stringish2
{
    Stringish s;
    alias s this;
}

enum H : Stringish { X = Stringish() }
enum I : Stringish2 { X = Stringish2() }

static assert(isAutodecodableString!(H));
static assert(isAutodecodableString!(I));

```
 
  enum bool **isStaticArray**(T);  
Detect whether type `T` is a static array.



Examples:


```
static assert( isStaticArray!(int[3]));
static assert( isStaticArray!(const(int)[5]));
static assert( isStaticArray!(const(int)[][5]));

static assert(!isStaticArray!(const(int)[]));
static assert(!isStaticArray!(immutable(int)[]));
static assert(!isStaticArray!(const(int)[4][]));
static assert(!isStaticArray!(int[]));
static assert(!isStaticArray!(int[char]));
static assert(!isStaticArray!(int[1][]));
static assert(!isStaticArray!(int[int]));
static assert(!isStaticArray!int);

```
 
  enum bool **isDynamicArray**(T);  
Detect whether type `T` is a dynamic array.



Examples:


```
static assert( isDynamicArray!(int[]));
static assert( isDynamicArray!(string));
static assert( isDynamicArray!(long[3][]));

static assert(!isDynamicArray!(int[5]));
static assert(!isDynamicArray!(typeof(null)));

```
 
  enum bool **isArray**(T);  
Detect whether type `T` is an array (static or dynamic; for associative arrays see [`isAssociativeArray`](#isAssociativeArray)).



Examples:


```
static assert( isArray!(int[]));
static assert( isArray!(int[5]));
static assert( isArray!(string));

static assert(!isArray!uint);
static assert(!isArray!(uint[uint]));
static assert(!isArray!(typeof(null)));

```
 
  enum bool **isAssociativeArray**(T);  
Detect whether `T` is an associative array type

  enum bool **isBuiltinType**(T);  
Detect whether type `T` is a builtin type.



Examples:


```
class C;
union U;
struct S;
interface I;

static assert( isBuiltinType!void);
static assert( isBuiltinType!string);
static assert( isBuiltinType!(int[]));
static assert( isBuiltinType!(C[string]));
static assert(!isBuiltinType!C);
static assert(!isBuiltinType!U);
static assert(!isBuiltinType!S);
static assert(!isBuiltinType!I);
static assert(!isBuiltinType!(void delegate(int)));

```
 
  enum bool **isSIMDVector**(T);  
Detect whether type `T` is a SIMD vector type.

  enum bool **isPointer**(T);  
Detect whether type `T` is a pointer.

  template **PointerTarget**(T : T\*) 
Returns the target type of a pointer.



Examples:


```
static assert(is(PointerTarget!(int*) == int));
static assert(is(PointerTarget!(void*) == void));

```
 
  enum bool **isAggregateType**(T);  
Detect whether type `T` is an aggregate type.



Examples:


```
class C;
union U;
struct S;
interface I;

static assert( isAggregateType!C);
static assert( isAggregateType!U);
static assert( isAggregateType!S);
static assert( isAggregateType!I);
static assert(!isAggregateType!void);
static assert(!isAggregateType!string);
static assert(!isAggregateType!(int[]));
static assert(!isAggregateType!(C[string]));
static assert(!isAggregateType!(void delegate(int)));

```
 
  enum bool **isIterable**(T);  
Returns `true` if T can be iterated over using a `foreach` loop with a single loop variable of automatically inferred type, regardless of how the `foreach` loop is implemented. This includes ranges, structs/classes that define `opApply` with a single loop variable, and builtin dynamic, static and associative arrays.



Examples:


```
struct OpApply
{
    int opApply(scope int delegate(ref uint) dg) { assert(0); }
}

struct Range
{
    @property uint front() { assert(0); }
    void popFront() { assert(0); }
    enum bool empty = false;
}

static assert( isIterable!(uint[]));
static assert( isIterable!OpApply);
static assert( isIterable!(uint[string]));
static assert( isIterable!Range);

static assert(!isIterable!uint);

```
 
  enum bool **isMutable**(T);  
Returns true if T is not const or immutable. Note that isMutable is true for string, or immutable(char)[], because the 'head' is mutable.



Examples:


```
static assert( isMutable!int);
static assert( isMutable!string);
static assert( isMutable!(shared int));
static assert( isMutable!(shared const(int)[]));

static assert(!isMutable!(const int));
static assert(!isMutable!(inout int));
static assert(!isMutable!(shared(const int)));
static assert(!isMutable!(shared(inout int)));
static assert(!isMutable!(immutable string));

```
 
  enum bool **isInstanceOf**(alias S, T);   
  
enum auto **isInstanceOf**(alias S, alias T);  
Returns true if T is an instance of the template S.



Examples:


```
static struct Foo(T...) { }
static struct Bar(T...) { }
static struct Doo(T) { }
static struct ABC(int x) { }
static void fun(T)() { }
template templ(T) { }

static assert(isInstanceOf!(Foo, Foo!int));
static assert(!isInstanceOf!(Foo, Bar!int));
static assert(!isInstanceOf!(Foo, int));
static assert(isInstanceOf!(Doo, Doo!int));
static assert(isInstanceOf!(ABC, ABC!1));
static assert(!isInstanceOf!(Foo, Foo));
static assert(isInstanceOf!(fun, fun!int));
static assert(isInstanceOf!(templ, templ!int));

```
 
 
Examples:
To use `isInstanceOf` to check the identity of a template while inside of said template, use [`TemplateOf`](#TemplateOf). 
```
static struct A(T = void)
{
    // doesn't work as expected, only accepts A when T = void
    void func(B)(B b) if (isInstanceOf!(A, B)) {}

    // correct behavior
    void method(B)(B b) if (isInstanceOf!(TemplateOf!(A), B)) {}
}

A!(void) a1;
A!(void) a2;
A!(int) a3;

static assert(!__traits(compiles, a1.func(a3)));
static assert( __traits(compiles, a1.method(a2)));
static assert( __traits(compiles, a1.method(a3)));

```
 
  template **isExpressions**(T...) 
Check whether the tuple T is an expression tuple. An expression tuple only contains expressions. 



See Also:

[`isTypeTuple`](#isTypeTuple).
 
Examples:


```
static assert(isExpressions!(1, 2.0, "a"));
static assert(!isExpressions!(int, double, string));
static assert(!isExpressions!(int, 2.0, "a"));

```
 
  alias **isExpressionTuple** = isExpressions(T...);  
Alternate name for [`isExpressions`](#isExpressions), kept for legacy compatibility.

  template **isTypeTuple**(T...) 
Check whether the tuple `T` is a type tuple. A type tuple only contains types. 



See Also:

[`isExpressions`](#isExpressions).
 
Examples:


```
static assert(isTypeTuple!(int, float, string));
static assert(!isTypeTuple!(1, 2.0, "a"));
static assert(!isTypeTuple!(1, double, string));

```
 
  template **isFunctionPointer**(T...) if (T.length == 1) 
Detect whether symbol or type `T` is a function pointer.



Examples:


```
static void foo() {}
void bar() {}

auto fpfoo = &foo;
static assert( isFunctionPointer!fpfoo);
static assert( isFunctionPointer!(void function()));

auto dgbar = &bar;
static assert(!isFunctionPointer!dgbar);
static assert(!isFunctionPointer!(void delegate()));
static assert(!isFunctionPointer!foo);
static assert(!isFunctionPointer!bar);

static assert( isFunctionPointer!((int a) {}));

```
 
  template **isDelegate**(T...) if (T.length == 1) 
Detect whether symbol or type `T` is a delegate.



Examples:


```
static void sfunc() { }
int x;
void func() { x++; }

int delegate() dg;
assert(isDelegate!dg);
assert(isDelegate!(int delegate()));
assert(isDelegate!(typeof(&func)));

int function() fp;
assert(!isDelegate!fp);
assert(!isDelegate!(int function()));
assert(!isDelegate!(typeof(&sfunc)));

```
 
  template **isSomeFunction**(T...) if (T.length == 1) 
Detect whether symbol or type `T` is a function, a function pointer or a delegate. 



Parameters:


|  |  |
| --- | --- |
| T | The type to check |


 
Returns:
A `bool`

 
Examples:


```
static real func(ref int) { return 0; }
static void prop() @property { }
class C
{
    real method(ref int) { return 0; }
    real prop() @property { return 0; }
}
auto c = new C;
auto fp = &func;
auto dg = &c.method;
real val;

static assert( isSomeFunction!func);
static assert( isSomeFunction!prop);
static assert( isSomeFunction!(C.method));
static assert( isSomeFunction!(C.prop));
static assert( isSomeFunction!(c.prop));
static assert( isSomeFunction!(c.prop));
static assert( isSomeFunction!fp);
static assert( isSomeFunction!dg);

static assert(!isSomeFunction!int);
static assert(!isSomeFunction!val);

```
 
  template **isCallable**(alias callable) 
Detect whether `T` is a callable object, which can be called with the function call operator `(...)`.



Examples:
Functions, lambdas, and aggregate types with (static) opCall. 
```
void f() { }
int g(int x) { return x; }

static assert( isCallable!f);
static assert( isCallable!g);

class C { int opCall(int) { return 0; } }
auto c = new C;
struct S { static int opCall(int) { return 0; } }
interface I { real value() @property; }

static assert( isCallable!c);
static assert( isCallable!(c.opCall));
static assert( isCallable!S);
static assert( isCallable!(I.value));
static assert( isCallable!((int a) { return a; }));

static assert(!isCallable!I);

```
 
 
Examples:
Templates 
```
void f()() { }
T g(T = int)(T x) { return x; }

static assert( isCallable!f);
static assert( isCallable!g);

```
 
 
Examples:
Overloaded functions and function templates. 
```
static struct Wrapper
{
    void f() { }
    int f(int x) { return x; }

    void g()() { }
    T g(T = int)(T x) { return x; }
}

static assert(isCallable!(Wrapper.f));
static assert(isCallable!(Wrapper.g));

```
 
  template **isAbstractFunction**(T...) if (T.length == 1) 
Detect whether `T` is an abstract function. 



Parameters:


|  |  |
| --- | --- |
| T | The type to check |


 
Returns:
A `bool`

 
Examples:


```
struct S { void foo() { } }
class C { void foo() { } }
class AC { abstract void foo(); }
static assert(!isAbstractFunction!(int));
static assert(!isAbstractFunction!(S.foo));
static assert(!isAbstractFunction!(C.foo));
static assert( isAbstractFunction!(AC.foo));

```
 
  template **isFinalFunction**(T...) if (T.length == 1) 
Detect whether `T` is a final function.



Examples:


```
struct S { void bar() { } }
final class FC { void foo(); }
class C
{
    void bar() { }
    final void foo();
}
static assert(!isFinalFunction!(int));
static assert(!isFinalFunction!(S.bar));
static assert( isFinalFunction!(FC.foo));
static assert(!isFinalFunction!(C.bar));
static assert( isFinalFunction!(C.foo));

```
 
  enum auto **isNestedFunction**(alias f);  
Determines if `f` is a function that requires a context pointer. 



Parameters:


|  |  |
| --- | --- |
| f | The type to check Returns A `bool` |


 
Examples:


```
static void f() {}
static void fun()
{
    int i;
    int f() { return i; }

    static assert(isNestedFunction!(f));
}

static assert(!isNestedFunction!f);

```
 
  template **isAbstractClass**(T...) if (T.length == 1) 
Detect whether `T` is an abstract class.



Examples:


```
struct S { }
class C { }
abstract class AC { }
static assert(!isAbstractClass!S);
static assert(!isAbstractClass!C);
static assert( isAbstractClass!AC);
C c;
static assert(!isAbstractClass!c);
AC ac;
static assert( isAbstractClass!ac);

```
 
  template **isFinalClass**(T...) if (T.length == 1) 
Detect whether `T` is a final class.



Examples:


```
class C { }
abstract class AC { }
final class FC1 : C { }
final class FC2 { }
static assert(!isFinalClass!C);
static assert(!isFinalClass!AC);
static assert( isFinalClass!FC1);
static assert( isFinalClass!FC2);
C c;
static assert(!isFinalClass!c);
FC1 fc1;
static assert( isFinalClass!fc1);

```
 
  template **Unconst**(T) 
Removes `const`, `inout` and `immutable` qualifiers, if any, from type `T`.



Examples:


```
static assert(is(Unconst!int == int));
static assert(is(Unconst!(const int) == int));
static assert(is(Unconst!(immutable int) == int));
static assert(is(Unconst!(shared int) == shared int));
static assert(is(Unconst!(shared(const int)) == shared int));

```
 
  template **Unqual**(T) 
Removes all qualifiers, if any, from type `T`.



Examples:


```
static assert(is(Unqual!int == int));
static assert(is(Unqual!(const int) == int));
static assert(is(Unqual!(immutable int) == int));
static assert(is(Unqual!(shared int) == int));
static assert(is(Unqual!(shared(const int)) == int));

```
 
  template **CopyTypeQualifiers**(FromType, ToType) 
Copies type qualifiers from `FromType` to `ToType`. 


Supported type qualifiers: * `const`
* `inout`
* `immutable`
* `shared`


 
Examples:


```
static assert(is(CopyTypeQualifiers!(inout const real, int) == inout const int));

```
 
  template **CopyConstness**(FromType, ToType) 
Returns the type of `ToType` with the "constness" of `FromType`. A type's **constness** refers to whether it is `const`, `immutable`, or `inout`. If `FromType` has no constness, the returned type will be the same as `ToType`.



Examples:


```
const(int) i;
CopyConstness!(typeof(i), float) f;
assert( is(typeof(f) == const float));

CopyConstness!(char, uint) u;
assert( is(typeof(u) == uint));

//The 'shared' qualifier will not be copied
assert(!is(CopyConstness!(shared bool, int) == shared int));

//But the constness will be
assert( is(CopyConstness!(shared const real, double) == const double));

//Careful, const(int)[] is a mutable array of const(int)
alias MutT = CopyConstness!(const(int)[], int);
assert(!is(MutT == const(int)));

//Okay, const(int[]) applies to array and contained ints
alias CstT = CopyConstness!(const(int[]), int);
assert( is(CstT == const(int)));

```
 
  template **ForeachType**(T) 
Returns the inferred type of the loop variable when a variable of type T is iterated over using a `foreach` loop with a single loop variable and automatically inferred return type. Note that this may not be the same as `std.range.ElementType!Range` in the case of narrow strings, or if T has both opApply and a range interface.



Examples:


```
static assert(is(ForeachType!(uint[]) == uint));
static assert(is(ForeachType!string == immutable(char)));
static assert(is(ForeachType!(string[string]) == string));
static assert(is(ForeachType!(inout(int)[]) == inout(int)));

```
 
  template **OriginalType**(T) 
Strips off all `enum`s from type `T`.



Examples:


```
enum E : real { a = 0 } // NOTE: explicit initialization to 0 required during Enum init deprecation cycle
enum F : E    { a = E.a }
alias G = const(F);
static assert(is(OriginalType!E == real));
static assert(is(OriginalType!F == real));
static assert(is(OriginalType!G == const real));

```
 
  template **KeyType**(V : V[K], K) 
Get the Key type of an Associative Array.



Examples:


```
alias Hash = int[string];
static assert(is(KeyType!Hash == string));
static assert(is(ValueType!Hash == int));
KeyType!Hash str = "a"; // str is declared as string
ValueType!Hash num = 1; // num is declared as int

```
 
  template **ValueType**(V : V[K], K) 
Get the Value type of an Associative Array.



Examples:


```
alias Hash = int[string];
static assert(is(KeyType!Hash == string));
static assert(is(ValueType!Hash == int));
KeyType!Hash str = "a"; // str is declared as string
ValueType!Hash num = 1; // num is declared as int

```
 
  template **Unsigned**(T) 

Parameters:


|  |  |
| --- | --- |
| T | A built in integral or vector type. |


 
Returns:
The corresponding unsigned numeric type for `T` with the same type qualifiers. If `T` is not a integral or vector, a compile-time error is given.
 
Examples:


```
static assert(is(Unsigned!(int) == uint));
static assert(is(Unsigned!(long) == ulong));
static assert(is(Unsigned!(const short) == const ushort));
static assert(is(Unsigned!(immutable byte) == immutable ubyte));
static assert(is(Unsigned!(inout int) == inout uint));

```
 
 
Examples:
Unsigned types are forwarded 
```
static assert(is(Unsigned!(uint) == uint));
static assert(is(Unsigned!(const uint) == const uint));

static assert(is(Unsigned!(ubyte) == ubyte));
static assert(is(Unsigned!(immutable uint) == immutable uint));

```
 
  template **Largest**(T...) if (T.length >= 1) 
Returns the largest type, i.e. T such that T.sizeof is the largest. If more than one type is of the same size, the leftmost argument of these in will be returned.



Examples:


```
static assert(is(Largest!(uint, ubyte, ushort, real) == real));
static assert(is(Largest!(ulong, double) == ulong));
static assert(is(Largest!(double, ulong) == double));
static assert(is(Largest!(uint, byte, double, short) == double));
static if (is(ucent))
    static assert(is(Largest!(uint, ubyte, ucent, ushort) == ucent));

```
 
  template **Signed**(T) 
Returns the corresponding signed type for T. T must be a numeric integral type, otherwise a compile-time error occurs.



Examples:


```
alias S1 = Signed!uint;
static assert(is(S1 == int));
alias S2 = Signed!(const(uint));
static assert(is(S2 == const(int)));
alias S3 = Signed!(immutable(uint));
static assert(is(S3 == immutable(int)));
static if (is(ucent))
{
    alias S4 = Signed!ucent;
    static assert(is(S4 == cent));
}

```
 
  template **mostNegative**(T) if (isNumeric!T || isSomeChar!T || isBoolean!T) 
Returns the most negative value of the numeric type T.



Examples:


```
static assert(mostNegative!float == -float.max);
static assert(mostNegative!double == -double.max);
static assert(mostNegative!real == -real.max);
static assert(mostNegative!bool == false);

```
 
 
Examples:


```
import std.meta : AliasSeq;

static foreach (T; AliasSeq!(bool, byte, short, int, long))
    static assert(mostNegative!T == T.min);

static foreach (T; AliasSeq!(ubyte, ushort, uint, ulong, char, wchar, dchar))
    static assert(mostNegative!T == 0);

```
 
  template **Promoted**(T) if (isScalarType!T) 
Get the type that a scalar type `T` will [promote](https://dlang.org/spec/type.html#integer-promotions) to in multi-term arithmetic expressions.



Examples:


```
ubyte a = 3, b = 5;
static assert(is(typeof(a * b) == Promoted!ubyte));
static assert(is(Promoted!ubyte == int));

static assert(is(Promoted!(shared(bool)) == shared(int)));
static assert(is(Promoted!(const(int)) == const(int)));
static assert(is(Promoted!double == double));

```
 
  template **mangledName**(sth...) if (sth.length == 1) 
Returns the mangled name of symbol or type `sth`. 


`mangledName` is the same as builtin `.mangleof` property, but might be more convenient in generic code, e.g. as a template argument when invoking staticMap.

 
Examples:


```
import std.meta : AliasSeq;
alias TL = staticMap!(mangledName, int, const int, immutable int);
static assert(TL == AliasSeq!("i", "xi", "yi"));

```
 
  template **Select**(bool condition, T...) if (T.length == 2) 
Aliases itself to `T[0]` if the boolean `condition` is `true` and to `T[1]` otherwise.



Examples:


```
// can select types
static assert(is(Select!(true, int, long) == int));
static assert(is(Select!(false, int, long) == long));
static struct Foo {}
static assert(is(Select!(false, const(int), const(Foo)) == const(Foo)));

// can select symbols
int a = 1;
int b = 2;
alias selA = Select!(true, a, b);
alias selB = Select!(false, a, b);
writeln(selA); // 1
writeln(selB); // 2

// can select (compile-time) expressions
enum val = Select!(false, -4, 9 - 6);
static assert(val == 3);

```
 
  A **select**(bool cond : true, A, B)(A a, lazy B b);   
  
B **select**(bool cond : false, A, B)(lazy A a, B b);  
Select one of two functions to run via template parameter. 



Parameters:


|  |  |
| --- | --- |
| cond | A `bool` which determines which function is run |
| A `a` | The first function |
| B `b` | The second function |


 
Returns:

`a` without evaluating `b` if `cond` is `true`. Otherwise, returns `b` without evaluating `a`.
 
Examples:


```
real run() { return 0; }
int fail() { assert(0); }
auto a = select!true(run(), fail());
auto b = select!false(fail(), run());
static assert(is(typeof(a) == real));
static assert(is(typeof(b) == real));

```
 
  enum auto **hasUDA**(alias symbol, alias attribute);  
Determine if a symbol has a given [user-defined attribute](https://dlang.org/spec/attribute.html#uda). 



See Also:
[`getUDAs`](#getUDAs)
 
Examples:


```
enum E;
struct S {}

@("alpha") int a;
static assert(hasUDA!(a, "alpha"));
static assert(!hasUDA!(a, S));
static assert(!hasUDA!(a, E));

@(E) int b;
static assert(!hasUDA!(b, "alpha"));
static assert(!hasUDA!(b, S));
static assert(hasUDA!(b, E));

@E int c;
static assert(!hasUDA!(c, "alpha"));
static assert(!hasUDA!(c, S));
static assert(hasUDA!(c, E));

@(S, E) int d;
static assert(!hasUDA!(d, "alpha"));
static assert(hasUDA!(d, S));
static assert(hasUDA!(d, E));

@S int e;
static assert(!hasUDA!(e, "alpha"));
static assert(hasUDA!(e, S));
static assert(!hasUDA!(e, S()));
static assert(!hasUDA!(e, E));

@S() int f;
static assert(!hasUDA!(f, "alpha"));
static assert(hasUDA!(f, S));
static assert(hasUDA!(f, S()));
static assert(!hasUDA!(f, E));

@(S, E, "alpha") int g;
static assert(hasUDA!(g, "alpha"));
static assert(hasUDA!(g, S));
static assert(hasUDA!(g, E));

@(100) int h;
static assert(hasUDA!(h, 100));

struct Named { string name; }

@Named("abc") int i;
static assert(hasUDA!(i, Named));
static assert(hasUDA!(i, Named("abc")));
static assert(!hasUDA!(i, Named("def")));

struct AttrT(T)
{
    string name;
    T value;
}

@AttrT!int("answer", 42) int j;
static assert(hasUDA!(j, AttrT));
static assert(hasUDA!(j, AttrT!int));
static assert(!hasUDA!(j, AttrT!string));

@AttrT!string("hello", "world") int k;
static assert(hasUDA!(k, AttrT));
static assert(!hasUDA!(k, AttrT!int));
static assert(hasUDA!(k, AttrT!string));

struct FuncAttr(alias f) { alias func = f; }
static int fourtyTwo() { return 42; }
static size_t getLen(string s) { return s.length; }

@FuncAttr!getLen int l;
static assert(hasUDA!(l, FuncAttr));
static assert(!hasUDA!(l, FuncAttr!fourtyTwo));
static assert(hasUDA!(l, FuncAttr!getLen));
static assert(!hasUDA!(l, FuncAttr!fourtyTwo()));
static assert(!hasUDA!(l, FuncAttr!getLen()));

@FuncAttr!getLen() int m;
static assert(hasUDA!(m, FuncAttr));
static assert(!hasUDA!(m, FuncAttr!fourtyTwo));
static assert(hasUDA!(m, FuncAttr!getLen));
static assert(!hasUDA!(m, FuncAttr!fourtyTwo()));
static assert(hasUDA!(m, FuncAttr!getLen()));

```
 
  template **getUDAs**(alias symbol, alias attribute) 
Gets the matching [user-defined attributes](https://dlang.org/spec/attribute.html#uda) from the given symbol. 


If the UDA is a type, then any UDAs of the same type on the symbol will match. If the UDA is a template for a type, then any UDA which is an instantiation of that template will match. And if the UDA is a value, then any UDAs on the symbol which are equal to that value will match. 

 
See Also:
[`hasUDA`](#hasUDA)
 
Examples:


```
struct Attr
{
    string name;
    int value;
}

@Attr("Answer", 42) int a;
static assert(getUDAs!(a, Attr).length == 1);
static assert(getUDAs!(a, Attr)[0].name == "Answer");
static assert(getUDAs!(a, Attr)[0].value == 42);

@(Attr("Answer", 42), "string", 9999) int b;
static assert(getUDAs!(b, Attr).length == 1);
static assert(getUDAs!(b, Attr)[0].name == "Answer");
static assert(getUDAs!(b, Attr)[0].value == 42);

@Attr("Answer", 42) @Attr("Pi", 3) int c;
static assert(getUDAs!(c, Attr).length == 2);
static assert(getUDAs!(c, Attr)[0].name == "Answer");
static assert(getUDAs!(c, Attr)[0].value == 42);
static assert(getUDAs!(c, Attr)[1].name == "Pi");
static assert(getUDAs!(c, Attr)[1].value == 3);

static assert(getUDAs!(c, Attr("Answer", 42)).length == 1);
static assert(getUDAs!(c, Attr("Answer", 42))[0].name == "Answer");
static assert(getUDAs!(c, Attr("Answer", 42))[0].value == 42);

static assert(getUDAs!(c, Attr("Answer", 99)).length == 0);

struct AttrT(T)
{
    string name;
    T value;
}

@AttrT!uint("Answer", 42) @AttrT!int("Pi", 3) @AttrT int d;
static assert(getUDAs!(d, AttrT).length == 2);
static assert(getUDAs!(d, AttrT)[0].name == "Answer");
static assert(getUDAs!(d, AttrT)[0].value == 42);
static assert(getUDAs!(d, AttrT)[1].name == "Pi");
static assert(getUDAs!(d, AttrT)[1].value == 3);

static assert(getUDAs!(d, AttrT!uint).length == 1);
static assert(getUDAs!(d, AttrT!uint)[0].name == "Answer");
static assert(getUDAs!(d, AttrT!uint)[0].value == 42);

static assert(getUDAs!(d, AttrT!int).length == 1);
static assert(getUDAs!(d, AttrT!int)[0].name == "Pi");
static assert(getUDAs!(d, AttrT!int)[0].value == 3);

struct SimpleAttr {}

@SimpleAttr int e;
static assert(getUDAs!(e, SimpleAttr).length == 1);
static assert(is(getUDAs!(e, SimpleAttr)[0] == SimpleAttr));

@SimpleAttr() int f;
static assert(getUDAs!(f, SimpleAttr).length == 1);
static assert(is(typeof(getUDAs!(f, SimpleAttr)[0]) == SimpleAttr));

struct FuncAttr(alias f) { alias func = f; }
static int add42(int v) { return v + 42; }
static string concat(string l, string r) { return l ~ r; }

@FuncAttr!add42 int g;
static assert(getUDAs!(g, FuncAttr).length == 1);
static assert(getUDAs!(g, FuncAttr)[0].func(5) == 47);

static assert(getUDAs!(g, FuncAttr!add42).length == 1);
static assert(getUDAs!(g, FuncAttr!add42)[0].func(5) == 47);

static assert(getUDAs!(g, FuncAttr!add42()).length == 0);

static assert(getUDAs!(g, FuncAttr!concat).length == 0);
static assert(getUDAs!(g, FuncAttr!concat()).length == 0);

@FuncAttr!add42() int h;
static assert(getUDAs!(h, FuncAttr).length == 1);
static assert(getUDAs!(h, FuncAttr)[0].func(5) == 47);

static assert(getUDAs!(h, FuncAttr!add42).length == 1);
static assert(getUDAs!(h, FuncAttr!add42)[0].func(5) == 47);

static assert(getUDAs!(h, FuncAttr!add42()).length == 1);
static assert(getUDAs!(h, FuncAttr!add42())[0].func(5) == 47);

static assert(getUDAs!(h, FuncAttr!concat).length == 0);
static assert(getUDAs!(h, FuncAttr!concat()).length == 0);

@("alpha") @(42) int i;
static assert(getUDAs!(i, "alpha").length == 1);
static assert(getUDAs!(i, "alpha")[0] == "alpha");

static assert(getUDAs!(i, 42).length == 1);
static assert(getUDAs!(i, 42)[0] == 42);

static assert(getUDAs!(i, 'c').length == 0);

```
 
  template **getSymbolsByUDA**(alias symbol, alias attribute) 

Parameters:


|  |  |
| --- | --- |
| symbol | The aggregate type or module to search |
| attribute | The user-defined attribute to search for |


 
Returns:
All symbols within `symbol` that have the given UDA `attribute`. 
 
Note
 This is not recursive; it will not search for symbols within symbols such as nested structs or unions.
 
Examples:


```
enum Attr;
struct A
{
    @Attr int a;
    int b;
}

static assert(getSymbolsByUDA!(A, Attr).length == 1);
static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr));

```
 
 
Examples:


```
enum Attr;

static struct A
{
    @Attr int a;
    int b;
    @Attr void doStuff() {}
    void doOtherStuff() {}
    static struct Inner
    {
        // Not found by getSymbolsByUDA
        @Attr int c;
    }
}

// Finds both variables and functions with the attribute, but
// doesn't include the variables and functions without it.
static assert(getSymbolsByUDA!(A, Attr).length == 2);
// Can access attributes on the symbols returned by getSymbolsByUDA.
static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr));
static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[1], Attr));

```
 
 
Examples:
Finds multiple attributes 
```
static struct UDA { string name; }

static struct B
{
    @UDA("X")
    int x;
    @UDA("Y")
    int y;
    @(100)
    int z;
}

// Finds both UDA attributes.
static assert(getSymbolsByUDA!(B, UDA).length == 2);
// Finds one `100` attribute.
static assert(getSymbolsByUDA!(B, 100).length == 1);
// Can get the value of the UDA from the return value
static assert(getUDAs!(getSymbolsByUDA!(B, UDA)[0], UDA)[0].name == "X");

```
 
 
Examples:
Checks for UDAs on the aggregate symbol itself 
```
static struct UDA { string name; }

@UDA("A")
static struct C
{
    @UDA("B")
    int d;
}

static assert(getSymbolsByUDA!(C, UDA).length == 2);
static assert(getSymbolsByUDA!(C, UDA)[0].stringof == "C");
static assert(getSymbolsByUDA!(C, UDA)[1].stringof == "d");

```
 
 
Examples:
Finds nothing if there is no member with specific UDA 
```
static struct UDA { string name; }

static struct D
{
    int x;
}

static assert(getSymbolsByUDA!(D, UDA).length == 0);

```
 
  template **allSameType**(T...) 

Returns:

`true` iff all types `T` are the same.
 
Examples:


```
static assert(allSameType!(int, int));
static assert(allSameType!(int, int, int));
static assert(allSameType!(float, float, float));
static assert(!allSameType!(int, double));
static assert(!allSameType!(int, float, double));
static assert(!allSameType!(int, float, double, real));
static assert(!allSameType!(short, int, float, double, real));

```
 
  enum auto **ifTestable**(T, alias pred = (a) => a);  

Returns:

`true` iff the type `T` can be tested in an  `if`-expression, that is if `if (pred(T.init)) {}` is compilable.
  template **isType**(X...) if (X.length == 1) 
Detect whether `X` is a type. Analogous to `is(X)`. This is useful when used in conjunction with other templates, e.g. `allSatisfy!(isType, X)`. 



Returns:

`true` if `X` is a type, `false` otherwise
 
Examples:


```
struct S {
    template Test() {}
}
class C {}
interface I {}
union U {}
static assert(isType!int);
static assert(isType!string);
static assert(isType!(int[int]));
static assert(isType!S);
static assert(isType!C);
static assert(isType!I);
static assert(isType!U);

int n;
void func(){}
static assert(!isType!n);
static assert(!isType!func);
static assert(!isType!(S.Test));
static assert(!isType!(S.Test!()));

```
 
  template **isFunction**(X...) if (X.length == 1) 
Detect whether symbol or type `X` is a function. This is different that finding if a symbol is callable or satisfying `is(X == function)`, it finds specifically if the symbol represents a normal function declaration, i.e. not a delegate or a function pointer. 



Returns:

`true` if `X` is a function, `false` otherwise 
 
See Also:
Use [`isFunctionPointer`](#isFunctionPointer) or [`isDelegate`](#isDelegate) for detecting those types respectively.
 
Examples:


```
static void func(){}
static assert(isFunction!func);

struct S
{
    void func(){}
}
static assert(isFunction!(S.func));

```
 
  template **isFinal**(X...) if (X.length == 1) 
Detect whether `X` is a final method or class. 



Returns:

`true` if `X` is final, `false` otherwise
 
Examples:


```
class C
{
    void nf() {}
    static void sf() {}
    final void ff() {}
}
final class FC { }

static assert(!isFinal!(C));
static assert( isFinal!(FC));

static assert(!isFinal!(C.nf));
static assert(!isFinal!(C.sf));
static assert( isFinal!(C.ff));

```
 
  enum auto **isCopyable**(S);  
Determines whether the type `S` can be copied. If a type cannot be copied, then code such as `MyStruct x; auto y = x;` will fail to compile. Copying for structs can be disabled by using `@disable this(this)`. 



Parameters:


|  |  |
| --- | --- |
| S | The type to check. |


 
Returns:

`true` if `S` can be copied. `false` otherwise.
 
Examples:


```
struct S1 {}                        // Fine. Can be copied
struct S2 {         this(this) {}}  // Fine. Can be copied
struct S3 {@disable this(this);  }  // Not fine. Copying is disabled.
struct S4 {S3 s;}                   // Not fine. A field has copying disabled.

class C1 {}

static assert( isCopyable!S1);
static assert( isCopyable!S2);
static assert(!isCopyable!S3);
static assert(!isCopyable!S4);

static assert(isCopyable!C1);
static assert(isCopyable!int);
static assert(isCopyable!(int[]));

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/std_traits.html>

core.lifetime
=============

 
pure nothrow @safe T\* **emplace**(T)(T\* chunk);  
Given a pointer `chunk` to uninitialized memory (but already typed as `T`), constructs an object of non-`class` type `T` at that address. If `T` is a class, initializes the class reference to null. 



Returns:
A pointer to the newly constructed object (which is the same as `chunk`).
 
Examples:


```
static struct S
{
    int i = 42;
}
S[2] s2 = void;
emplace(&s2);
assert(s2[0].i == 42 && s2[1].i == 42);

```
 
 
Examples:


```
interface I {}
class K : I {}

K k = void;
emplace(&k);
assert(k is null);

I i = void;
emplace(&i);
assert(i is null);

```
 
  T\* **emplace**(T, Args...)(T\* chunk, auto ref Args args)  
 Constraints: if (is(T == struct) || Args.length == 1); 
 
Given a pointer `chunk` to uninitialized memory (but already typed as a non-class type `T`), constructs an object of type `T` at that address from arguments `args`. If `T` is a class, initializes the class reference to `args[0]`. This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 



Returns:
A pointer to the newly constructed object (which is the same as `chunk`).
 
Examples:


```
int a;
int b = 42;
assert(*emplace!int(&a, b) == 42);

```
 
  T **emplace**(T, Args...)(T chunk, auto ref Args args)  
 Constraints: if (is(T == class)); 
 
Given a raw memory area `chunk` (but already typed as a class type `T`), constructs an object of `class` type `T` at that address. The constructor is passed the arguments `Args`. If `T` is an inner class whose `outer` field can be used to access an instance of the enclosing class, then `Args` must not be empty, and the first member of it must be a valid initializer for that `outer` field. Correct initialization of this field is essential to access members of the outer class inside `T` methods. 



Note
 This function is `@safe` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
The newly constructed object.
 
Examples:


```
() @safe {
    class SafeClass
    {
        int x;
        @safe this(int x) { this.x = x; }
    }

    auto buf = new void[__traits(classInstanceSize, SafeClass)];
    auto support = (() @trusted => cast(SafeClass)(buf.ptr))();
    auto safeClass = emplace!SafeClass(support, 5);
    assert(safeClass.x == 5);

    class UnsafeClass
    {
        int x;
        @system this(int x) { this.x = x; }
    }

    auto buf2 = new void[__traits(classInstanceSize, UnsafeClass)];
    auto support2 = (() @trusted => cast(UnsafeClass)(buf2.ptr))();
    static assert(!__traits(compiles, emplace!UnsafeClass(support2, 5)));
    static assert(!__traits(compiles, emplace!UnsafeClass(buf2, 5)));
}();

```
 
  T **emplace**(T, Args...)(void[] chunk, auto ref Args args)  
 Constraints: if (is(T == class)); 
 
Given a raw memory area `chunk`, constructs an object of `class` type `T` at that address. The constructor is passed the arguments `Args`. If `T` is an inner class whose `outer` field can be used to access an instance of the enclosing class, then `Args` must not be empty, and the first member of it must be a valid initializer for that `outer` field. Correct initialization of this field is essential to access members of the outer class inside `T` methods. 



Preconditions
 `chunk` must be at least as large as `T` needs and should have an alignment multiple of `T`'s alignment. (The size of a `class` instance is obtained by using `_traits(classInstanceSize, T)`). 
 
Note
 This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
The newly constructed object.
 
Examples:


```
static class C
{
    int i;
    this(int i){this.i = i;}
}
auto buf = new void[__traits(classInstanceSize, C)];
auto c = emplace!C(buf, 5);
assert(c.i == 5);

```
 
  T\* **emplace**(T, Args...)(void[] chunk, auto ref Args args)  
 Constraints: if (!is(T == class)); 
 
Given a raw memory area `chunk`, constructs an object of non-`class` type `T` at that address. The constructor is passed the arguments `args`, if any. 



Preconditions
 `chunk` must be at least as large as `T` needs and should have an alignment multiple of `T`'s alignment. 
 
Note
 This function can be `@trusted` if the corresponding constructor of `T` is `@safe`. 
 
Returns:
A pointer to the newly constructed object.
 
Examples:


```
struct S
{
    int a, b;
}
auto buf = new void[S.sizeof];
S s;
s.a = 42;
s.b = 43;
auto s1 = emplace!S(buf, s);
assert(s1.a == 42 && s1.b == 43);

```
 
  @system void **copyEmplace**(S, T)(ref S source, ref T target)  
 Constraints: if (is(immutable(S) == immutable(T))); 
 
Emplaces a copy of the specified source value into uninitialized memory, i.e., simulates `T target = source` copy-construction for cases where the target memory is already allocated and to be initialized with a copy. 



Parameters:


|  |  |
| --- | --- |
| S `source` | value to be copied into target |
| T `target` | uninitialized value to be initialized with a copy of source |


 
Examples:


```
int source = 123;
int target = void;
copyEmplace(source, target);
assert(target == 123);

```
 
 
Examples:


```
immutable int[1][1] source = [ [123] ];
immutable int[1][1] target = void;
copyEmplace(source, target);
assert(target[0][0] == 123);

```
 
 
Examples:


```
struct S
{
    int x;
    void opAssign(const scope ref S rhs) @safe pure nothrow @nogc
    {
        assert(0);
    }
}

S source = S(42);
S target = void;
copyEmplace(source, target);
assert(target.x == 42);

```
 
  template **forward**(args...) 
Forwards function arguments while keeping `out`, `ref`, and `lazy` on the parameters. 



Parameters:


|  |  |
| --- | --- |
| args | a parameter list or an [`std.meta.AliasSeq`](std_meta#AliasSeq). |


 
Returns:
An `AliasSeq` of `args` with `out`, `ref`, and `lazy` saved.
 
Examples:


```
class C
{
    static int foo(int n) { return 1; }
    static int foo(ref int n) { return 2; }
}

// with forward
int bar()(auto ref int x) { return C.foo(forward!x); }

// without forward
int baz()(auto ref int x) { return C.foo(x); }

int i;
assert(bar(1) == 1);
assert(bar(i) == 2);

assert(baz(1) == 2);
assert(baz(i) == 2);

```
 
 
Examples:


```
void foo(int n, ref string s) { s = null; foreach (i; 0 .. n) s ~= "Hello"; }

// forwards all arguments which are bound to parameter tuple
void bar(Args...)(auto ref Args args) { return foo(forward!args); }

// forwards all arguments with swapping order
void baz(Args...)(auto ref Args args) { return foo(forward!args[$/2..$], forward!args[0..$/2]); }

string s;
bar(1, s);
assert(s == "Hello");
baz(s, 2);
assert(s == "HelloHello");

```
 
 
Examples:


```
struct X {
    int i;
    this(this)
    {
        ++i;
    }
}

struct Y
{
    private X x_;
    this()(auto ref X x)
    {
        x_ = forward!x;
    }
}

struct Z
{
    private const X x_;
    this()(auto ref X x)
    {
        x_ = forward!x;
    }
    this()(auto const ref X x)
    {
        x_ = forward!x;
    }
}

X x;
const X cx;
auto constX = (){ const X x; return x; };
static assert(__traits(compiles, { Y y = x; }));
static assert(__traits(compiles, { Y y = X(); }));
static assert(!__traits(compiles, { Y y = cx; }));
static assert(!__traits(compiles, { Y y = constX(); }));
static assert(__traits(compiles, { Z z = x; }));
static assert(__traits(compiles, { Z z = X(); }));
static assert(__traits(compiles, { Z z = cx; }));
static assert(__traits(compiles, { Z z = constX(); }));


Y y1 = x;
// ref lvalue, copy
assert(y1.x_.i == 1);
Y y2 = X();
// rvalue, move
assert(y2.x_.i == 0);

Z z1 = x;
// ref lvalue, copy
assert(z1.x_.i == 1);
Z z2 = X();
// rvalue, move
assert(z2.x_.i == 0);
Z z3 = cx;
// ref const lvalue, copy
assert(z3.x_.i == 1);
Z z4 = constX();
// const rvalue, copy
assert(z4.x_.i == 1);

```
 
  void **move**(T)(ref T source, ref T target);   
  
T **move**(T)(return ref scope T source);  
Moves `source` into `target`, via a destructive copy when necessary. 


If `T` is a struct with a destructor or postblit defined, source is reset to its `.init` value after it is moved into target, otherwise it is left unchanged. 

 
Preconditions
 If source has internal pointers that point to itself and doesn't define opPostMove, it cannot be moved, and will trigger an assertion failure. 
 
Parameters:


|  |  |
| --- | --- |
| T `source` | Data to copy. |
| T `target` | Where to copy into. The destructor, if any, is invoked before the copy is performed. |


 
Examples:
For non-struct types, `move` just performs `target = source`: 
```
Object obj1 = new Object;
Object obj2 = obj1;
Object obj3;

move(obj2, obj3);
assert(obj3 is obj1);
// obj2 unchanged
assert(obj2 is obj1);

```
 
 
Examples:


```
// Structs without destructors are simply copied
struct S1
{
    int a = 1;
    int b = 2;
}
S1 s11 = { 10, 11 };
S1 s12;

move(s11, s12);

assert(s12 == S1(10, 11));
assert(s11 == s12);

// But structs with destructors or postblits are reset to their .init value
// after copying to the target.
struct S2
{
    int a = 1;
    int b = 2;

    ~this() pure nothrow @safe @nogc { }
}
S2 s21 = { 3, 4 };
S2 s22;

move(s21, s22);

assert(s21 == S2(1, 2));
assert(s22 == S2(3, 4));

```
 
 
Examples:
Non-copyable structs can still be moved: 
```
struct S
{
    int a = 1;
    @disable this(this);
    ~this() pure nothrow @safe @nogc {}
}
S s1;
s1.a = 2;
S s2 = move(s1);
assert(s1.a == 1);
assert(s2.a == 2);

```
 
  @system void **moveEmplace**(T)(ref T source, ref T target);  
Similar to [`move`](#move) but assumes `target` is uninitialized. This is more efficient because `source` can be blitted over `target` without destroying or initializing it first. 



Parameters:


|  |  |
| --- | --- |
| T `source` | value to be moved into target |
| T `target` | uninitialized value to be filled by source |


 
Examples:


```
static struct Foo
{
pure nothrow @nogc:
    this(int* ptr) { _ptr = ptr; }
    ~this() { if (_ptr) ++*_ptr; }
    int* _ptr;
}

int val;
Foo foo1 = void; // uninitialized
auto foo2 = Foo(&val); // initialized
assert(foo2._ptr is &val);

// Using `move(foo2, foo1)` would have an undefined effect because it would destroy
// the uninitialized foo1.
// moveEmplace directly overwrites foo1 without destroying or initializing it first.
moveEmplace(foo2, foo1);
assert(foo1._ptr is &val);
assert(foo2._ptr is null);
assert(val == 0);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_lifetime.html>

core.gc.registry
================

 Contains a registry for GC factories. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak
 
alias **GCFactory** = GC function();  
A factory function that instantiates an implementation of the GC interface. In case the instance was allocated on the C heap, it is supposed to free itself upon calling it's destructor. 


The factory should print an error and abort the program if it cannot successfully initialize the GC instance.

  nothrow @nogc void **registerGCFactory**(string name, GCFactory factory);  
Register a GC factory under the given `name`. This function must be called from a C constructor before druntime is initialized. 


To use the registered GC, it's name must be specified gcopt runtime option, e.g. by passing *, --DRT-gcopt=gc:my\_gc\_name* as application argument. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | name of the GC implementation; should be unique |
| GCFactory `factory` | function to instantiate the implementation |


 
Note
 The registry does not perform synchronization, as registration is assumed to be executed serially, as is the case for C constructors. 
 
See Also:
[Configuring the Garbage Collector](https://dlang.org/spec/garbage.html#gc_config)
  GC **createGCInstance**(string name);  
Called during runtime initialization to initialize a GC instance of given `name`. 



Parameters:


|  |  |
| --- | --- |
| string `name` | name of the GC to instantiate |


 
Returns:
The created GC instance or `null` if no factory for that name was registered
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_gc_registry.html>

core.stdc.assert\_
==================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<assert.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/assert.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Source
 [core/stdc/assert\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/assert_.d) 
 
Standards:
ISO/IEC 9899:1999 (E) These are the various functions called by the assert() macro. They are all noreturn functions, although D doesn't have a specific attribute for that.
 
nothrow @nogc @trusted void **\_\_assert**(const(char)\* exp, const(char)\* file, uint line);  
Assert failure functions in the GLIBC library.

  nothrow @nogc @trusted void **\_\_assert\_fail**(const(char)\* exp, const(char)\* file, uint line, const(char)\* func);  nothrow @nogc @trusted void **\_\_assert\_perror\_fail**(int errnum, const(char)\* file, uint line, const(char)\* func);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_assert_.html>

core.math
=========

 Builtin mathematical intrinsics 



Source
 [core/math.d](https://github.com/dlang/druntime/blob/master/src/core/math.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com), Don Clugston
 
nothrow @nogc @safe real **rndtonl**(real x);  
Returns x rounded to a long value using the FE\_TONEAREST rounding mode. If the integer value of x is greater than long.max, the result is indeterminate.

  pure nothrow @nogc @safe float **cos**(float x);   
  
pure nothrow @nogc @safe double **cos**(double x);   
  
pure nothrow @nogc @safe real **cos**(real x);  
Returns cosine of x. x is in radians. 




Special Values| x | cos(x) | invalid? |
| NAN | NAN | yes |
| ±∞ | NAN | yes |

 

 
Bugs:
Results are undefined if |x| >= 264.
  pure nothrow @nogc @safe float **sin**(float x);   
  
pure nothrow @nogc @safe double **sin**(double x);   
  
pure nothrow @nogc @safe real **sin**(real x);  
Returns sine of x. x is in radians. 




Special Values| x | sin(x) | invalid? |
| NAN | NAN | yes |
| ±0.0 | ±0.0 | no |
| ±∞ | NAN | yes |

 

 
Bugs:
Results are undefined if |x| >= 264.
  pure nothrow @nogc @safe long **rndtol**(float x);   
  
pure nothrow @nogc @safe long **rndtol**(double x);   
  
pure nothrow @nogc @safe long **rndtol**(real x);  
Returns x rounded to a long value using the current rounding mode. If the integer value of x is greater than long.max, the result is indeterminate.

  pure nothrow @nogc @safe float **sqrt**(float x);   
  
pure nothrow @nogc @safe double **sqrt**(double x);   
  
pure nothrow @nogc @safe real **sqrt**(real x);  
Compute square root of x. 




Special Values| x | sqrt(x) | invalid? |
| -0.0 | -0.0 | no |
| <0.0 | NAN | yes |
| +∞ | +∞ | no |



  pure nothrow @nogc @safe float **ldexp**(float n, int exp);   
  
pure nothrow @nogc @safe double **ldexp**(double n, int exp);   
  
pure nothrow @nogc @safe real **ldexp**(real n, int exp);  
Compute n \* 2exp 



References
 frexp
  pure nothrow @nogc @safe float **fabs**(float x);  
Compute the absolute value. 

Special Values| x | fabs(x) |
| ±0.0 | +0.0 |
| ±∞ | +∞ |

 It is implemented as a compiler intrinsic. 



Parameters:


|  |  |
| --- | --- |
| float `x` | floating point value |


 
Returns:
|x| 
 
References
 equivalent to `std.math.fabs`

  pure nothrow @nogc @safe double **fabs**(double x);  
ditto 


Compute the absolute value. 

Special Values| x | fabs(x) |
| ±0.0 | +0.0 |
| ±∞ | +∞ |

 It is implemented as a compiler intrinsic. 

 
Parameters:


|  |  |
| --- | --- |
| double `x` | floating point value |


 
Returns:
|x| 
 
References
 equivalent to `std.math.fabs`

  pure nothrow @nogc @safe real **fabs**(real x);  
ditto 


Compute the absolute value. 

Special Values| x | fabs(x) |
| ±0.0 | +0.0 |
| ±∞ | +∞ |

 It is implemented as a compiler intrinsic. 

 
Parameters:


|  |  |
| --- | --- |
| real `x` | floating point value |


 
Returns:
|x| 
 
References
 equivalent to `std.math.fabs`

  pure nothrow @nogc @safe float **rint**(float x);   
  
pure nothrow @nogc @safe double **rint**(double x);   
  
pure nothrow @nogc @safe real **rint**(real x);  
Rounds x to the nearest integer value, using the current rounding mode. If the return value is not equal to x, the FE\_INEXACT exception is raised. **nearbyint** performs the same operation, but does not set the FE\_INEXACT exception.

  pure nothrow @nogc @safe float **yl2x**(float x, float y);   
  
pure nothrow @nogc @safe double **yl2x**(double x, double y);   
  
pure nothrow @nogc @safe real **yl2x**(real x, real y);   
  
pure nothrow @nogc @safe double **yl2xp1**(double x, double y);   
  
pure nothrow @nogc @safe real **yl2xp1**(real x, real y);  
Building block functions, they translate to a single x87 instruction.

  T **toPrec**(T : float)(float f);   
  
T **toPrec**(T : float)(double f);   
  
T **toPrec**(T : float)(real f);   
  
T **toPrec**(T : double)(float f);   
  
T **toPrec**(T : double)(double f);   
  
T **toPrec**(T : double)(real f);   
  
T **toPrec**(T : real)(float f);   
  
T **toPrec**(T : real)(double f);   
  
T **toPrec**(T : real)(real f);  
Round argument to a specific precision. 


D language types specify only a minimum precision, not a maximum. The `toPrec()` function forces rounding of the argument `f` to the precision of the specified floating point type `T`. The rounding mode used is inevitably target-dependent, but will be done in a way to maximize accuracy. In most cases, the default is round-to-nearest. 

 
Parameters:


|  |  |
| --- | --- |
| T | precision type to round to |
| float `f` | value to convert |


 
Returns:
f in precision of type `T`

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_math.html>

core.simd
=========

 Builtin SIMD intrinsics 



Source
 [core/simd.d](https://github.com/dlang/druntime/blob/master/src/core/simd.d) 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com),
 
template **Vector**(T) 
Create a vector type. 



Parameters
 T = one of double[2], float[4], void[16], byte[16], ubyte[16], short[8], ushort[8], int[4], uint[4], long[2], ulong[2]. For 256 bit vectors, one of double[4], float[8], void[32], byte[32], ubyte[32], short[16], ushort[16], int[8], uint[8], long[4], ulong[4]
  alias **void16** = \_\_vector(void[16]);  alias **double2** = \_\_vector(double[2]);  alias **float4** = \_\_vector(float[4]);  alias **byte16** = \_\_vector(byte[16]);  alias **ubyte16** = \_\_vector(ubyte[16]);  alias **short8** = \_\_vector(short[8]);  alias **ushort8** = \_\_vector(ushort[8]);  alias **int4** = \_\_vector(int[4]);  alias **uint4** = \_\_vector(uint[4]);  alias **long2** = \_\_vector(long[2]);  alias **ulong2** = \_\_vector(ulong[2]);  enum **XMM**: int;  
XMM opcodes that conform to the following: 


opcode xmm1,xmm2/mem   
  
 and do not have side effects (i.e. do not write to memory).

  pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1, void16 op2);  
Generate two operand instruction with XMM 128 bit operands. 


This is a compiler magic function - it doesn't behave like regular D functions. 

 
Parameters
 opcode = any of the XMM opcodes; it must be a compile time constant op1 = first operand op2 = second operand 
 
Returns:
result of opcode
 
Examples:


```
float4 a;
a = cast(float4)__simd(XMM.PXOR, a, a);

```
 
  pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1);  
Unary SIMD instructions.

  pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, double d);  pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, float f);  

Examples:


```
float4 a;
a = cast(float4)__simd(XMM.LODSS, a);

```
 
  pure nothrow @nogc @safe void16 **\_\_simd**(XMM opcode, void16 op1, void16 op2, ubyte imm8);  
For instructions: CMPPD, CMPSS, CMPSD, CMPPS, PSHUFD, PSHUFHW, PSHUFLW, BLENDPD, BLENDPS, DPPD, DPPS, MPSADBW, PBLENDW, ROUNDPD, ROUNDPS, ROUNDSD, ROUNDSS 



Parameters
 opcode = any of the above XMM opcodes; it must be a compile time constant op1 = first operand op2 = second operand imm8 = third operand; must be a compile time constant 
 
Returns:
result of opcode
 
Examples:


```
float4 a;
a = cast(float4)__simd(XMM.CMPPD, a, a, 0x7A);

```
 
  pure nothrow @nogc @safe void16 **\_\_simd\_ib**(XMM opcode, void16 op1, ubyte imm8);  
For instructions with the imm8 version: PSLLD, PSLLQ, PSLLW, PSRAD, PSRAW, PSRLD, PSRLQ, PSRLW, PSRLDQ, PSLLDQ 



Parameters
 opcode = any of the XMM opcodes; it must be a compile time constant op1 = first operand imm8 = second operand; must be a compile time constant 
 
Returns:
result of opcode
 
Examples:


```
float4 a;
a = cast(float4) __simd_ib(XMM.PSRLQ, a, 0x7A);

```
 
  pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, void16 op1, void16 op2);  
For "store" operations of the form: op1 op= op2 



Returns:
op2 These cannot be marked as pure, as semantic() doesn't check them.
  pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, double op1, void16 op2);  pure nothrow @nogc @safe void16 **\_\_simd\_sto**(XMM opcode, float op1, void16 op2);  

Examples:


```
void16 a;
float f = 1;
double d = 1;

cast(void)__simd_sto(XMM.STOUPS, a, a);
cast(void)__simd_sto(XMM.STOUPS, f, a);
cast(void)__simd_sto(XMM.STOUPS, d, a);

```
 
  void **prefetch**(bool writeFetch, ubyte locality)(const(void)\* address);  
Emit prefetch instruction. 



Parameters:


|  |  |
| --- | --- |
| const(void)\* `address` | address to be prefetched |
| writeFetch | true for write fetch, false for read fetch |
| locality | 0..3 (0 meaning least local, 3 meaning most local) |


 
Note
 The Intel mappings are: 



| **writeFetch** | **locality** | **Instruction** |
| --- | --- | --- |
| false | 0 | prefetchnta |
| false | 1 | prefetch2 |
| false | 2 | prefetch1 |
| false | 3 | prefetch0 |
| true | 0 | prefetchw |
| true | 1 | prefetchw |
| true | 2 | prefetchw |
| true | 3 | prefetchw |

  V **loadUnaligned**(V)(const V\* p)  
 Constraints: if (is(V == void16) || is(V == byte16) || is(V == ubyte16) || is(V == short8) || is(V == ushort8) || is(V == int4) || is(V == uint4) || is(V == long2) || is(V == ulong2) || is(V == double2) || is(V == float4)); 
 
Load unaligned vector from address. This is a compiler intrinsic. 



Parameters:


|  |  |
| --- | --- |
| V\* `p` | pointer to vector |


 
Returns:
vector
  V **storeUnaligned**(V)(V\* p, V value)  
 Constraints: if (is(V == void16) || is(V == byte16) || is(V == ubyte16) || is(V == short8) || is(V == ushort8) || is(V == int4) || is(V == uint4) || is(V == long2) || is(V == ulong2) || is(V == double2) || is(V == float4)); 
 
Store vector to unaligned address. This is a compiler intrinsic. 



Parameters:


|  |  |
| --- | --- |
| V\* `p` | pointer to vector |
| V `value` | value to store |


 
Returns:
value
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_simd.html>

core.stdc.complex
=================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<complex.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/complex.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/complex.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/complex.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **complex** = creal;  alias **imaginary** = ireal;  nothrow @nogc @trusted cdouble **cacos**(cdouble z);  nothrow @nogc @trusted cfloat **cacosf**(cfloat z);  nothrow @nogc @trusted creal **cacosl**(creal z);  nothrow @nogc @trusted cdouble **casin**(cdouble z);  nothrow @nogc @trusted cfloat **casinf**(cfloat z);  nothrow @nogc @trusted creal **casinl**(creal z);  nothrow @nogc @trusted cdouble **catan**(cdouble z);  nothrow @nogc @trusted cfloat **catanf**(cfloat z);  nothrow @nogc @trusted creal **catanl**(creal z);  nothrow @nogc @trusted cdouble **ccos**(cdouble z);  nothrow @nogc @trusted cfloat **ccosf**(cfloat z);  nothrow @nogc @trusted creal **ccosl**(creal z);  nothrow @nogc @trusted cdouble **csin**(cdouble z);  nothrow @nogc @trusted cfloat **csinf**(cfloat z);  nothrow @nogc @trusted creal **csinl**(creal z);  nothrow @nogc @trusted cdouble **ctan**(cdouble z);  nothrow @nogc @trusted cfloat **ctanf**(cfloat z);  nothrow @nogc @trusted creal **ctanl**(creal z);  nothrow @nogc @trusted cdouble **cacosh**(cdouble z);  nothrow @nogc @trusted cfloat **cacoshf**(cfloat z);  nothrow @nogc @trusted creal **cacoshl**(creal z);  nothrow @nogc @trusted cdouble **casinh**(cdouble z);  nothrow @nogc @trusted cfloat **casinhf**(cfloat z);  nothrow @nogc @trusted creal **casinhl**(creal z);  nothrow @nogc @trusted cdouble **catanh**(cdouble z);  nothrow @nogc @trusted cfloat **catanhf**(cfloat z);  nothrow @nogc @trusted creal **catanhl**(creal z);  nothrow @nogc @trusted cdouble **ccosh**(cdouble z);  nothrow @nogc @trusted cfloat **ccoshf**(cfloat z);  nothrow @nogc @trusted creal **ccoshl**(creal z);  nothrow @nogc @trusted cdouble **csinh**(cdouble z);  nothrow @nogc @trusted cfloat **csinhf**(cfloat z);  nothrow @nogc @trusted creal **csinhl**(creal z);  nothrow @nogc @trusted cdouble **ctanh**(cdouble z);  nothrow @nogc @trusted cfloat **ctanhf**(cfloat z);  nothrow @nogc @trusted creal **ctanhl**(creal z);  nothrow @nogc @trusted cdouble **cexp**(cdouble z);  nothrow @nogc @trusted cfloat **cexpf**(cfloat z);  nothrow @nogc @trusted creal **cexpl**(creal z);  nothrow @nogc @trusted cdouble **clog**(cdouble z);  nothrow @nogc @trusted cfloat **clogf**(cfloat z);  nothrow @nogc @trusted creal **clogl**(creal z);  nothrow @nogc @trusted double **cabs**(cdouble z);  nothrow @nogc @trusted float **cabsf**(cfloat z);  nothrow @nogc @trusted real **cabsl**(creal z);  nothrow @nogc @trusted cdouble **cpow**(cdouble x, cdouble y);  nothrow @nogc @trusted cfloat **cpowf**(cfloat x, cfloat y);  nothrow @nogc @trusted creal **cpowl**(creal x, creal y);  nothrow @nogc @trusted cdouble **csqrt**(cdouble z);  nothrow @nogc @trusted cfloat **csqrtf**(cfloat z);  nothrow @nogc @trusted creal **csqrtl**(creal z);  nothrow @nogc @trusted double **carg**(cdouble z);  nothrow @nogc @trusted float **cargf**(cfloat z);  nothrow @nogc @trusted real **cargl**(creal z);  nothrow @nogc @trusted double **cimag**(cdouble z);  nothrow @nogc @trusted float **cimagf**(cfloat z);  nothrow @nogc @trusted real **cimagl**(creal z);  nothrow @nogc @trusted cdouble **conj**(cdouble z);  nothrow @nogc @trusted cfloat **conjf**(cfloat z);  nothrow @nogc @trusted creal **conjl**(creal z);  nothrow @nogc @trusted cdouble **cproj**(cdouble z);  nothrow @nogc @trusted cfloat **cprojf**(cfloat z);  nothrow @nogc @trusted creal **cprojl**(creal z);  nothrow @nogc @trusted double **creald**(cdouble z);  nothrow @nogc @trusted float **crealf**(cfloat z);  nothrow @nogc @trusted real **creall**(creal z);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_complex.html>

core.stdc.ctype
===============

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<ctype.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/ctype.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/ctype.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/ctype.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
pure nothrow @nogc @trusted int **isalnum**(int c);  pure nothrow @nogc @trusted int **isalpha**(int c);  pure nothrow @nogc @trusted int **isblank**(int c);  pure nothrow @nogc @trusted int **iscntrl**(int c);  pure nothrow @nogc @trusted int **isdigit**(int c);  pure nothrow @nogc @trusted int **isgraph**(int c);  pure nothrow @nogc @trusted int **islower**(int c);  pure nothrow @nogc @trusted int **isprint**(int c);  pure nothrow @nogc @trusted int **ispunct**(int c);  pure nothrow @nogc @trusted int **isspace**(int c);  pure nothrow @nogc @trusted int **isupper**(int c);  pure nothrow @nogc @trusted int **isxdigit**(int c);  pure nothrow @nogc @trusted int **tolower**(int c);  pure nothrow @nogc @trusted int **toupper**(int c);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_ctype.html>

etc.c.sqlite3
=============

 
enum string **SQLITE\_VERSION**;   
  
enum int **SQLITE\_VERSION\_NUMBER**;   
  
enum string **SQLITE\_SOURCE\_ID**;  

CAPI3REF
 Compile-Time Library Version Numbers
  immutable(char)\* **sqlite3\_version**;   
  
nothrow immutable(char)\* **sqlite3\_libversion**();   
  
nothrow immutable(char)\* **sqlite3\_sourceid**();   
  
nothrow int **sqlite3\_libversion\_number**();  

CAPI3REF
 Run-Time Library Version Numbers
  nothrow int **sqlite3\_compileoption\_used**(const char\* zOptName);   
  
nothrow immutable(char)\* **sqlite3\_compileoption\_get**(int N);  

CAPI3REF
 Run-Time Library Compilation Options Diagnostics
  nothrow int **sqlite3\_threadsafe**();  

CAPI3REF
 Test To See If The Library Is Threadsafe
  struct **sqlite3**;  

CAPI3REF
 Database Connection Handle
  alias **sqlite3\_int64** = long;  alias **sqlite3\_uint64** = ulong;  nothrow int **sqlite3\_close**(sqlite3\*);  

CAPI3REF
 Closing A Database Connection
  alias **sqlite3\_callback** = extern (C) int function(void\*, int, char\*\*, char\*\*) nothrow;  
The type for a callback function. This is legacy and deprecated. It is included for historical compatibility and is not documented.

  nothrow int **sqlite3\_exec**(sqlite3\*, const(char)\* sql, int function(void\*, int, char\*\*, char\*\*) callback, void\*, char\*\* errmsg);  

CAPI3REF
 One-Step Query Execution Interface
  **SQLITE\_OK** 
Successful result

  **SQLITE\_ERROR** 
Ditto 


Generic error

  **SQLITE\_INTERNAL** 
Internal logic error in SQLite

  **SQLITE\_PERM** 
Access permission denied

  **SQLITE\_ABORT** 
Callback routine requested an abort

  **SQLITE\_BUSY** 
The database file is locked

  **SQLITE\_LOCKED** 
A table in the database is locked

  **SQLITE\_NOMEM** 
A malloc() failed

  **SQLITE\_READONLY** 
Attempt to write a readonly database

  **SQLITE\_INTERRUPT** 
Operation terminated by sqlite3\_interrupt()

  **SQLITE\_IOERR** 
Some kind of disk I/O error occurred

  **SQLITE\_CORRUPT** 
The database disk image is malformed

  **SQLITE\_NOTFOUND** 
Unknown opcode in sqlite3\_file\_control()

  **SQLITE\_FULL** 
Insertion failed because database is full

  **SQLITE\_CANTOPEN** 
Unable to open the database file

  **SQLITE\_PROTOCOL** 
Database lock protocol error

  **SQLITE\_EMPTY** 
Internal use only

  **SQLITE\_SCHEMA** 
The database schema changed

  **SQLITE\_TOOBIG** 
String or BLOB exceeds size limit

  **SQLITE\_CONSTRAINT** 
Abort due to constraint violation

  **SQLITE\_MISMATCH** 
Data type mismatch

  **SQLITE\_MISUSE** 
Library used incorrectly

  **SQLITE\_NOLFS** 
Uses OS features not supported on host

  **SQLITE\_AUTH** 
Authorization denied

  **SQLITE\_FORMAT** 
Not used

  **SQLITE\_RANGE** 
2nd parameter to sqlite3\_bind out of range

  **SQLITE\_NOTADB** 
File opened that is not a database file

  **SQLITE\_ROW** 
sqlite3\_step() has another row ready

  **SQLITE\_DONE** 
sqlite3\_step() has finished executing

  **SQLITE\_OPEN\_READONLY** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_READWRITE** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_CREATE** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_DELETEONCLOSE** 
VFS only

  **SQLITE\_OPEN\_EXCLUSIVE** 
VFS only

  **SQLITE\_OPEN\_AUTOPROXY** 
VFS only

  **SQLITE\_OPEN\_URI** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_MEMORY** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_MAIN\_DB** 
VFS only

  **SQLITE\_OPEN\_TEMP\_DB** 
VFS only

  **SQLITE\_OPEN\_TRANSIENT\_DB** 
VFS only

  **SQLITE\_OPEN\_MAIN\_JOURNAL** 
VFS only

  **SQLITE\_OPEN\_TEMP\_JOURNAL** 
VFS only

  **SQLITE\_OPEN\_SUBJOURNAL** 
VFS only

  **SQLITE\_OPEN\_SUPER\_JOURNAL** 
VFS only

  **SQLITE\_OPEN\_NOMUTEX** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_FULLMUTEX** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_SHAREDCACHE** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_PRIVATECACHE** 
Ok for sqlite3\_open\_v2()

  **SQLITE\_OPEN\_WAL** 
VFS only

  **SQLITE\_OPEN\_NOFOLLOW** 
Ok for sqlite3\_open\_v2()

  deprecated alias **SQLITE\_OPEN\_MASTER\_JOURNAL** = SQLITE\_OPEN\_SUPER\_JOURNAL;  
VFS only

  struct **sqlite3\_file**;  

CAPI3REF
 OS Interface Open File Handle
  struct **sqlite3\_io\_methods**;  

CAPI3REF
 OS Interface File Virtual Methods Object
  struct **sqlite3\_mutex**;  

CAPI3REF
 Mutex Handle
  struct **sqlite3\_api\_routines**;  

CAPI3REF
 Loadable Extension Thunk
  alias **xDlSymReturn** = extern (C) void\* function() nothrow;   
  
alias **sqlite3\_syscall\_ptr** = extern (C) void function() nothrow;  

CAPI3REF
 OS Interface Object
  **SQLITE\_ACCESS\_READWRITE** 
Used by PRAGMA temp\_store\_directory

  **SQLITE\_ACCESS\_READ** 
Unused

  enum int **SQLITE\_SHM\_NLOCK**;  

CAPI3REF
 Maximum xShmLock index
  nothrow int **sqlite3\_initialize**();   
  
nothrow int **sqlite3\_shutdown**();   
  
nothrow int **sqlite3\_os\_init**();   
  
nothrow int **sqlite3\_os\_end**();  

CAPI3REF
 Initialize The SQLite Library
  nothrow int **sqlite3\_config**(int, ...);  

CAPI3REF
 Configuring The SQLite Library
  nothrow int **sqlite3\_db\_config**(sqlite3\*, int op, ...);  

CAPI3REF
 Configure database connections
  struct **sqlite3\_mem\_methods**;  

CAPI3REF
 Memory Allocation Routines
 
void\* function(int) **xMalloc**;  
Memory allocation function

  void function(void\*) **xFree**;  
Free a prior allocation

  void\* function(void\*, int) **xRealloc**;  
Resize an allocation

  int function(void\*) **xSize**;  
Return the size of an allocation

  int function(int) **xRoundup**;  
Round up request size to allocation size

  int function(void\*) **xInit**;  
Initialize the memory allocator

  void function(void\*) **xShutdown**;  
Deinitialize the memory allocator

  void\* **pAppData**;  
Argument to xInit() and xShutdown()

    **SQLITE\_CONFIG\_SINGLETHREAD** 
nil

  **SQLITE\_CONFIG\_MULTITHREAD** 
nil

  **SQLITE\_CONFIG\_SERIALIZED** 
nil

  **SQLITE\_CONFIG\_MALLOC** 
sqlite3\_mem\_methods\*

  **SQLITE\_CONFIG\_GETMALLOC** 
sqlite3\_mem\_methods\*

  **SQLITE\_CONFIG\_SCRATCH** 
No longer used

  **SQLITE\_CONFIG\_PAGECACHE** 
void\*, int sz, int N

  **SQLITE\_CONFIG\_HEAP** 
void\*, int nByte, int min

  **SQLITE\_CONFIG\_MEMSTATUS** 
boolean

  **SQLITE\_CONFIG\_MUTEX** 
sqlite3\_mutex\_methods\*

  **SQLITE\_CONFIG\_GETMUTEX** 
sqlite3\_mutex\_methods\*

  **SQLITE\_CONFIG\_LOOKASIDE** 
int int

  **SQLITE\_CONFIG\_PCACHE** 
no-op

  **SQLITE\_CONFIG\_GETPCACHE** 
no-op

  **SQLITE\_CONFIG\_LOG** 
xFunc, void\*

  **SQLITE\_CONFIG\_URI** 
int

  **SQLITE\_CONFIG\_PCACHE2** 
sqlite3\_pcache\_methods2\*

  **SQLITE\_CONFIG\_GETPCACHE2** 
sqlite3\_pcache\_methods2\*

  **SQLITE\_CONFIG\_COVERING\_INDEX\_SCAN** 
int

  **SQLITE\_CONFIG\_SQLLOG** 
xSqllog, void\*

  **SQLITE\_CONFIG\_MMAP\_SIZE** 
sqlite3\_int64, sqlite3\_int64

  **SQLITE\_CONFIG\_WIN32\_HEAPSIZE** 
int nByte

  **SQLITE\_CONFIG\_PCACHE\_HDRSZ** 
int \*psz

  **SQLITE\_CONFIG\_PMASZ** 
unsigned int szPma

  **SQLITE\_CONFIG\_STMTJRNL\_SPILL** 
int nByte

  **SQLITE\_CONFIG\_SMALL\_MALLOC** 
boolean

  **SQLITE\_CONFIG\_SORTERREF\_SIZE** 
int nByte

  **SQLITE\_CONFIG\_MEMDB\_MAXSIZE** 
sqlite3\_int64

  **SQLITE\_DBCONFIG\_MAINDBNAME** 
const char\*

  **SQLITE\_DBCONFIG\_LOOKASIDE** 
void\* int int

  **SQLITE\_DBCONFIG\_ENABLE\_FKEY** 
int int\*

  **SQLITE\_DBCONFIG\_ENABLE\_TRIGGER** 
int int\*

  **SQLITE\_DBCONFIG\_ENABLE\_FTS3\_TOKENIZER** 
int int\*

  **SQLITE\_DBCONFIG\_ENABLE\_LOAD\_EXTENSION** 
int int\*

  **SQLITE\_DBCONFIG\_NO\_CKPT\_ON\_CLOSE** 
int int\*

  **SQLITE\_DBCONFIG\_ENABLE\_QPSG** 
int int\*

  **SQLITE\_DBCONFIG\_TRIGGER\_EQP** 
int int\*

  **SQLITE\_DBCONFIG\_RESET\_DATABASE** 
int int\*

  **SQLITE\_DBCONFIG\_DEFENSIVE** 
int int\*

  **SQLITE\_DBCONFIG\_WRITABLE\_SCHEMA** 
int int\*

  **SQLITE\_DBCONFIG\_LEGACY\_ALTER\_TABLE** 
int int\*

  **SQLITE\_DBCONFIG\_DQS\_DML** 
int int\*

  **SQLITE\_DBCONFIG\_DQS\_DDL** 
int int\*

  **SQLITE\_DBCONFIG\_ENABLE\_VIEW** 
int int\*

  **SQLITE\_DBCONFIG\_LEGACY\_FILE\_FORMAT** 
int int\*

  **SQLITE\_DBCONFIG\_TRUSTED\_SCHEMA** 
int int\*

  **SQLITE\_DBCONFIG\_MAX** 
Largest DBCONFIG

  nothrow int **sqlite3\_extended\_result\_codes**(sqlite3\*, int onoff);  

CAPI3REF
 Enable Or Disable Extended Result Codes
  nothrow sqlite3\_int64 **sqlite3\_last\_insert\_rowid**(sqlite3\*);  

CAPI3REF
 Last Insert Rowid
  nothrow void **sqlite3\_set\_last\_insert\_rowid**(sqlite3\*, sqlite3\_int64);  

CAPI3REF
 Set the Last Insert Rowid value
  nothrow int **sqlite3\_changes**(sqlite3\*);  

CAPI3REF
 Count The Number Of Rows Modified
  nothrow int **sqlite3\_total\_changes**(sqlite3\*);  

CAPI3REF
 Total Number Of Rows Modified
  nothrow void **sqlite3\_interrupt**(sqlite3\*);  

CAPI3REF
 Interrupt A Long-Running Query
  nothrow int **sqlite3\_complete**(const char\* sql);   
  
nothrow int **sqlite3\_complete16**(const void\* sql);  

CAPI3REF
 Determine If An SQL Statement Is Complete
  nothrow int **sqlite3\_busy\_handler**(sqlite3\*, int function(void\*, int), void\*);  

CAPI3REF
 Register A Callback To Handle SQLITE\_BUSY Errors
  nothrow int **sqlite3\_busy\_timeout**(sqlite3\*, int ms);  

CAPI3REF
 Set A Busy Timeout
  nothrow int **sqlite3\_get\_table**(sqlite3\* db, const(char)\* zSql, char\*\*\* pazResult, int\* pnRow, int\* pnColumn, char\*\* pzErrmsg);  

CAPI3REF
 Convenience Routines For Running Queries
  nothrow void **sqlite3\_free\_table**(char\*\* result);  nothrow char\* **sqlite3\_mprintf**(const char\*, ...);  

CAPI3REF
 Formatted String Printing Functions
  nothrow void\* **sqlite3\_malloc**(int);   
  
nothrow void\* **sqlite3\_malloc64**(sqlite3\_uint64);   
  
nothrow void\* **sqlite3\_realloc**(void\*, int);   
  
nothrow void\* **sqlite3\_realloc64**(void\*, sqlite3\_uint64);   
  
nothrow void **sqlite3\_free**(void\*);   
  
nothrow sqlite3\_uint64 **sqlite3\_msize**(void\*);  

CAPI3REF
 Memory Allocation Subsystem
  nothrow sqlite3\_int64 **sqlite3\_memory\_used**();  

CAPI3REF
 Memory Allocator Statistics
  nothrow void **sqlite3\_randomness**(int N, void\* P);  

CAPI3REF
 Pseudo-Random Number Generator
  nothrow int **sqlite3\_set\_authorizer**(sqlite3\*, int function(void\*, int, const char\*, const char\*, const char\*, const char\*) xAuth, void\* pUserData);  

CAPI3REF
 Compile-Time Authorization Callbacks
  **SQLITE\_DENY** 
Abort the SQL statement with an error

  **SQLITE\_IGNORE** 
Don't allow access, but don't generate an error

  **SQLITE\_CREATE\_INDEX** 
Index Name Table Name

  **SQLITE\_CREATE\_TABLE** 
Table Name NULL

  **SQLITE\_CREATE\_TEMP\_INDEX** 
Index Name Table Name

  **SQLITE\_CREATE\_TEMP\_TABLE** 
Table Name NULL

  **SQLITE\_CREATE\_TEMP\_TRIGGER** 
Trigger Name Table Name

  **SQLITE\_CREATE\_TEMP\_VIEW** 
View Name NULL

  **SQLITE\_CREATE\_TRIGGER** 
Trigger Name Table Name

  **SQLITE\_CREATE\_VIEW** 
View Name NULL

  **SQLITE\_DELETE** 
Table Name NULL

  **SQLITE\_DROP\_INDEX** 
Index Name Table Name

  **SQLITE\_DROP\_TABLE** 
Table Name NULL

  **SQLITE\_DROP\_TEMP\_INDEX** 
Index Name Table Name

  **SQLITE\_DROP\_TEMP\_TABLE** 
Table Name NULL

  **SQLITE\_DROP\_TEMP\_TRIGGER** 
Trigger Name Table Name

  **SQLITE\_DROP\_TEMP\_VIEW** 
View Name NULL

  **SQLITE\_DROP\_TRIGGER** 
Trigger Name Table Name

  **SQLITE\_DROP\_VIEW** 
View Name NULL

  **SQLITE\_INSERT** 
Table Name NULL

  **SQLITE\_PRAGMA** 
Pragma Name 1st arg or NULL

  **SQLITE\_READ** 
Table Name Column Name

  **SQLITE\_SELECT** 
NULL NULL

  **SQLITE\_TRANSACTION** 
Operation NULL

  **SQLITE\_UPDATE** 
Table Name Column Name

  **SQLITE\_ATTACH** 
Filename NULL

  **SQLITE\_DETACH** 
Database Name NULL

  **SQLITE\_ALTER\_TABLE** 
Database Name Table Name

  **SQLITE\_REINDEX** 
Index Name NULL

  **SQLITE\_ANALYZE** 
Table Name NULL

  **SQLITE\_CREATE\_VTABLE** 
Table Name Module Name

  **SQLITE\_DROP\_VTABLE** 
Table Name Module Name

  **SQLITE\_FUNCTION** 
NULL Function Name

  **SQLITE\_SAVEPOINT** 
Operation Savepoint Name

  **SQLITE\_COPY** 
No longer used

  **SQLITE\_RECURSIVE** 
NULL NULL

  deprecated nothrow void\* **sqlite3\_trace**(sqlite3\*, void function(void\*, const char\*) xTrace, void\*);   
  
deprecated nothrow void\* **sqlite3\_profile**(sqlite3\*, void function(void\*, const char\*, sqlite3\_uint64) xProfile, void\*);  

CAPI3REF
 Tracing And Profiling Functions
  nothrow int **sqlite3\_trace\_v2**(sqlite3\*, uint uMask, int function(uint, void\*, void\*, void\*) xCallback, void\* pCtx);  

CAPI3REF
 SQL Trace Hook
  nothrow void **sqlite3\_progress\_handler**(sqlite3\*, int, int function(void\*), void\*);  

CAPI3REF
 Query Progress Callbacks
  nothrow int **sqlite3\_open**(const(char)\* filename, sqlite3\*\* ppDb);   
  
nothrow int **sqlite3\_open16**(const(void)\* filename, sqlite3\*\* ppDb);   
  
nothrow int **sqlite3\_open\_v2**(const(char)\* filename, sqlite3\*\* ppDb, int flags, const(char)\* zVfs);   
  
nothrow int **sqlite3\_uri\_boolean**(const(char)\* zFile, const(char)\* zParam, int bDefault);   
  
nothrow sqlite3\_int64 **sqlite3\_uri\_int64**(const char\*, const char\*, sqlite3\_int64);   
  
nothrow const(char)\* **sqlite3\_uri\_key**(const(char)\* zFilename, int N);   
  
nothrow const(char)\* **sqlite3\_filename\_journal**(const(char)\*);   
  
nothrow const(char)\* **sqlite3\_filename\_wal**(const(char)\*);   
  
nothrow void **sqlite3\_free\_filename**(char\*);  

CAPI3REF
 Opening A New Database Connection
  nothrow int **sqlite3\_errcode**(sqlite3\* db);   
  
nothrow int **sqlite3\_extended\_errcode**(sqlite3\* db);   
  
nothrow const(char)\* **sqlite3\_errmsg**(sqlite3\*);   
  
nothrow const(void)\* **sqlite3\_errmsg16**(sqlite3\*);   
  
nothrow const(char)\* **sqlite3\_errstr**(int);  

CAPI3REF
 Error Codes And Messages
  struct **sqlite3\_stmt**;  

CAPI3REF
 SQL Statement Object
  nothrow int **sqlite3\_limit**(sqlite3\*, int id, int newVal);  

CAPI3REF
 Run-time Limits
  nothrow int **sqlite3\_prepare**(sqlite3\* db, const(char)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail);   
  
nothrow int **sqlite3\_prepare\_v2**(sqlite3\* db, const(char)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail);   
  
nothrow int **sqlite3\_prepare\_v3**(sqlite3\* db, const(char)\* zSql, int nByte, uint prepFlags, sqlite3\_stmt\*\* ppStmt, const(char\*)\* pzTail);   
  
nothrow int **sqlite3\_prepare16**(sqlite3\* db, const(void)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail);   
  
nothrow int **sqlite3\_prepare16\_v2**(sqlite3\* db, const(void)\* zSql, int nByte, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail);   
  
nothrow int **sqlite3\_prepare16\_v3**(sqlite3\* db, const(void)\* zSql, int nByte, uint prepFlags, sqlite3\_stmt\*\* ppStmt, const(void\*)\* pzTail);  

CAPI3REF
 Compiling An SQL Statement
  nothrow const(char)\* **sqlite3\_sql**(sqlite3\_stmt\* pStmt);   
  
nothrow char\* **sqlite3\_expanded\_sql**(sqlite3\_stmt\* pStmt);  

CAPI3REF
 Retrieving Statement SQL
  nothrow int **sqlite3\_stmt\_busy**(sqlite3\_stmt\*);  

CAPI3REF
 Determine If A Prepared Statement Has Been Reset
  struct **sqlite3\_value**;  

CAPI3REF
 Dynamically Typed Value Object
  struct **sqlite3\_context**;  

CAPI3REF
 SQL Function Context Object
  nothrow int **sqlite3\_bind\_blob**(sqlite3\_stmt\*, int, const void\*, int n, void function(void\*));   
  
nothrow int **sqlite3\_bind\_blob64**(sqlite3\_stmt\*, int, const void\*, sqlite3\_uint64, void function(void\*));   
  
nothrow int **sqlite3\_bind\_double**(sqlite3\_stmt\*, int, double);   
  
nothrow int **sqlite3\_bind\_int**(sqlite3\_stmt\*, int, int);   
  
nothrow int **sqlite3\_bind\_int64**(sqlite3\_stmt\*, int, sqlite3\_int64);   
  
nothrow int **sqlite3\_bind\_null**(sqlite3\_stmt\*, int);   
  
nothrow int **sqlite3\_bind\_text**(sqlite3\_stmt\*, int, const char\*, int n, void function(void\*));   
  
nothrow int **sqlite3\_bind\_text16**(sqlite3\_stmt\*, int, const void\*, int, void function(void\*));   
  
nothrow int **sqlite3\_bind\_text64**(sqlite3\_stmt\*, int, const char\*, sqlite3\_uint64, void function(void\*), ubyte encoding);   
  
nothrow int **sqlite3\_bind\_value**(sqlite3\_stmt\*, int, const sqlite3\_value\*);   
  
nothrow int **sqlite3\_bind\_zeroblob**(sqlite3\_stmt\*, int, int n);   
  
nothrow int **sqlite3\_bind\_zeroblob64**(sqlite3\_stmt\*, int, sqlite3\_uint64 n);  

CAPI3REF
 Binding Values To Prepared Statements
  nothrow int **sqlite3\_bind\_parameter\_count**(sqlite3\_stmt\*);  

CAPI3REF
 Number Of SQL Parameters
  nothrow const(char)\* **sqlite3\_bind\_parameter\_name**(sqlite3\_stmt\*, int);  

CAPI3REF
 Name Of A Host Parameter
  nothrow int **sqlite3\_bind\_parameter\_index**(sqlite3\_stmt\*, const char\* zName);  

CAPI3REF
 Index Of A Parameter With A Given Name
  nothrow int **sqlite3\_clear\_bindings**(sqlite3\_stmt\*);  

CAPI3REF
 Reset All Bindings On A Prepared Statement
  nothrow int **sqlite3\_column\_count**(sqlite3\_stmt\* pStmt);  

CAPI3REF
 Number Of Columns In A Result Set
  nothrow const(char)\* **sqlite3\_column\_name**(sqlite3\_stmt\*, int N);   
  
nothrow const(void)\* **sqlite3\_column\_name16**(sqlite3\_stmt\*, int N);  

CAPI3REF
 Column Names In A Result Set
  nothrow const(char)\* **sqlite3\_column\_database\_name**(sqlite3\_stmt\*, int);   
  
nothrow const(void)\* **sqlite3\_column\_database\_name16**(sqlite3\_stmt\*, int);   
  
nothrow const(char)\* **sqlite3\_column\_table\_name**(sqlite3\_stmt\*, int);   
  
nothrow const(void)\* **sqlite3\_column\_table\_name16**(sqlite3\_stmt\*, int);   
  
nothrow const(char)\* **sqlite3\_column\_origin\_name**(sqlite3\_stmt\*, int);   
  
nothrow const(void)\* **sqlite3\_column\_origin\_name16**(sqlite3\_stmt\*, int);  

CAPI3REF
 Source Of Data In A Query Result
  nothrow const(char)\* **sqlite3\_column\_decltype**(sqlite3\_stmt\*, int);   
  
nothrow const(void)\* **sqlite3\_column\_decltype16**(sqlite3\_stmt\*, int);  

CAPI3REF
 Declared Datatype Of A Query Result
  nothrow int **sqlite3\_step**(sqlite3\_stmt\*);  

CAPI3REF
 Evaluate An SQL Statement
  nothrow int **sqlite3\_data\_count**(sqlite3\_stmt\* pStmt);  

CAPI3REF
 Number of columns in a result set
  nothrow const(void)\* **sqlite3\_column\_blob**(sqlite3\_stmt\*, int iCol);   
  
nothrow double **sqlite3\_column\_double**(sqlite3\_stmt\*, int iCol);   
  
nothrow int **sqlite3\_column\_int**(sqlite3\_stmt\*, int iCol);   
  
nothrow sqlite3\_int64 **sqlite3\_column\_int64**(sqlite3\_stmt\*, int iCol);   
  
nothrow const(char)\* **sqlite3\_column\_text**(sqlite3\_stmt\*, int iCol);   
  
nothrow const(void)\* **sqlite3\_column\_text16**(sqlite3\_stmt\*, int iCol);   
  
nothrow sqlite3\_value\* **sqlite3\_column\_value**(sqlite3\_stmt\*, int iCol);   
  
nothrow int **sqlite3\_column\_bytes**(sqlite3\_stmt\*, int iCol);   
  
nothrow int **sqlite3\_column\_bytes16**(sqlite3\_stmt\*, int iCol);   
  
nothrow int **sqlite3\_column\_type**(sqlite3\_stmt\*, int iCol);  

CAPI3REF
 Result Values From A Query
  nothrow int **sqlite3\_finalize**(sqlite3\_stmt\* pStmt);  

CAPI3REF
 Destroy A Prepared Statement Object
  nothrow int **sqlite3\_reset**(sqlite3\_stmt\* pStmt);  

CAPI3REF
 Reset A Prepared Statement Object
  nothrow int **sqlite3\_create\_function**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal);   
  
nothrow int **sqlite3\_create\_function16**(sqlite3\* db, const(void)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal);   
  
nothrow int **sqlite3\_create\_function\_v2**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xFunc, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal, void function(void\*) xDestroy);   
  
nothrow int **sqlite3\_create\_window\_function**(sqlite3\* db, const(char)\* zFunctionName, int nArg, int eTextRep, void\* pApp, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xStep, void function(sqlite3\_context\*) xFinal, void function(sqlite3\_context\*) xValue, void function(sqlite3\_context\*, int, sqlite3\_value\*\*) xInverse, void function(void\*) xDestroy);  

CAPI3REF
 Create Or Redefine SQL Functions
  **SQLITE\_UTF8** 

IMP
 R-37514-35566
  **SQLITE\_UTF16LE** 

IMP
 R-03371-37637
  **SQLITE\_UTF16BE** 

IMP
 R-51971-34154
  **SQLITE\_UTF16** 
Use native byte order

  **SQLITE\_ANY** 
sqlite3\_create\_function only

  **SQLITE\_UTF16\_ALIGNED** 
sqlite3\_create\_collation only

  enum int **SQLITE\_DETERMINISTIC**;  

CAPI3REF
 Function Flags
  deprecated nothrow int **sqlite3\_aggregate\_count**(sqlite3\_context\*);  

CAPI3REF
 Deprecated Functions
  nothrow const(void)\* **sqlite3\_value\_blob**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_bytes**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_bytes16**(sqlite3\_value\*);   
  
nothrow double **sqlite3\_value\_double**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_int**(sqlite3\_value\*);   
  
nothrow sqlite3\_int64 **sqlite3\_value\_int64**(sqlite3\_value\*);   
  
nothrow const(char)\* **sqlite3\_value\_text**(sqlite3\_value\*);   
  
nothrow const(void)\* **sqlite3\_value\_text16**(sqlite3\_value\*);   
  
nothrow const(void)\* **sqlite3\_value\_text16le**(sqlite3\_value\*);   
  
nothrow const(void)\* **sqlite3\_value\_text16be**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_type**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_numeric\_type**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_nochange**(sqlite3\_value\*);   
  
nothrow int **sqlite3\_value\_frombind**(sqlite3\_value\*);  

CAPI3REF
 Obtaining SQL Function Parameter Values
  nothrow void\* **sqlite3\_aggregate\_context**(sqlite3\_context\*, int nBytes);  

CAPI3REF
 Obtain Aggregate Function Context
  nothrow void\* **sqlite3\_user\_data**(sqlite3\_context\*);  

CAPI3REF
 User Data For Functions
  nothrow sqlite3\* **sqlite3\_context\_db\_handle**(sqlite3\_context\*);  

CAPI3REF
 Database Connection For Functions
  nothrow void\* **sqlite3\_get\_auxdata**(sqlite3\_context\*, int N);   
  
nothrow void **sqlite3\_set\_auxdata**(sqlite3\_context\*, int N, void\*, void function(void\*));  

CAPI3REF
 Function Auxiliary Data
  alias **sqlite3\_destructor\_type** = extern (C) void function(void\*) nothrow;  

CAPI3REF
 Constants Defining Special Destructor Behavior
  nothrow void **sqlite3\_result\_blob**(sqlite3\_context\*, const void\*, int, void function(void\*));   
  
nothrow void **sqlite3\_result\_blob64**(sqlite3\_context\*, const void\*, sqlite3\_uint64, void function(void\*));   
  
nothrow void **sqlite3\_result\_double**(sqlite3\_context\*, double);   
  
nothrow void **sqlite3\_result\_error**(sqlite3\_context\*, const char\*, int);   
  
nothrow void **sqlite3\_result\_error16**(sqlite3\_context\*, const void\*, int);   
  
nothrow void **sqlite3\_result\_error\_toobig**(sqlite3\_context\*);   
  
nothrow void **sqlite3\_result\_error\_nomem**(sqlite3\_context\*);   
  
nothrow void **sqlite3\_result\_error\_code**(sqlite3\_context\*, int);   
  
nothrow void **sqlite3\_result\_int**(sqlite3\_context\*, int);   
  
nothrow void **sqlite3\_result\_int64**(sqlite3\_context\*, sqlite3\_int64);   
  
nothrow void **sqlite3\_result\_null**(sqlite3\_context\*);   
  
nothrow void **sqlite3\_result\_text**(sqlite3\_context\*, const char\*, int, void function(void\*));   
  
nothrow void **sqlite3\_result\_text64**(sqlite3\_context\*, const char\*, sqlite3\_uint64, void function(void\*), ubyte encoding);   
  
nothrow void **sqlite3\_result\_text16**(sqlite3\_context\*, const void\*, int, void function(void\*));   
  
nothrow void **sqlite3\_result\_text16le**(sqlite3\_context\*, const void\*, int, void function(void\*));   
  
nothrow void **sqlite3\_result\_text16be**(sqlite3\_context\*, const void\*, int, void function(void\*));   
  
nothrow void **sqlite3\_result\_value**(sqlite3\_context\*, sqlite3\_value\*);   
  
nothrow void **sqlite3\_result\_zeroblob**(sqlite3\_context\*, int n);   
  
nothrow int **sqlite3\_result\_zeroblob64**(sqlite3\_context\*, sqlite3\_uint64 n);  

CAPI3REF
 Setting The Result Of An SQL Function
  nothrow int **sqlite3\_create\_collation**(sqlite3\*, const(char)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare);   
  
nothrow int **sqlite3\_create\_collation\_v2**(sqlite3\*, const(char)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare, void function(void\*) xDestroy);   
  
nothrow int **sqlite3\_create\_collation16**(sqlite3\*, const(void)\* zName, int eTextRep, void\* pArg, int function(void\*, int, const void\*, int, const void\*) xCompare);  

CAPI3REF
 Define New Collating Sequences
  nothrow int **sqlite3\_collation\_needed**(sqlite3\*, void\*, void function(void\*, sqlite3\*, int eTextRep, const char\*));   
  
nothrow int **sqlite3\_collation\_needed16**(sqlite3\*, void\*, void function(void\*, sqlite3\*, int eTextRep, const void\*));  

CAPI3REF
 Collation Needed Callbacks
  nothrow void **sqlite3\_activate\_cerod**(const(char)\* zPassPhrase);  
Specify the activation key for a CEROD database. Unless activated, none of the CEROD routines will work.

  nothrow int **sqlite3\_sleep**(int);  

CAPI3REF
 Suspend Execution For A Short Time
  char\* **sqlite3\_temp\_directory**;  

CAPI3REF
 Name Of The Folder Holding Temporary Files
  char\* **sqlite3\_data\_directory**;  

CAPI3REF
 Name Of The Folder Holding Database Files
  nothrow int **sqlite3\_win32\_set\_directory**(c\_ulong type, void\* zValue);   
  
nothrow int **sqlite3\_win32\_set\_directory8**(c\_ulong type, void\* zValue);   
  
nothrow int **sqlite3\_win32\_set\_directory16**(c\_ulong type, void\* zValue);  

CAPI3REF
 Win32 Specific Interface
  nothrow int **sqlite3\_get\_autocommit**(sqlite3\*);  

CAPI3REF
 Test For Auto-Commit Mode
  nothrow sqlite3\* **sqlite3\_db\_handle**(sqlite3\_stmt\*);  

CAPI3REF
 Find The Database Handle Of A Prepared Statement
  nothrow const(char)\* **sqlite3\_db\_filename**(sqlite3\* db, const char\* zDbName);  

CAPI3REF
 Return The Filename For A Database Connection
  nothrow int **sqlite3\_db\_readonly**(sqlite3\* db, const char\* zDbName);  

CAPI3REF
 Determine if a database is read-only
  nothrow void\* **sqlite3\_commit\_hook**(sqlite3\*, int function(void\*), void\*);   
  
nothrow void\* **sqlite3\_rollback\_hook**(sqlite3\*, void function(void\*), void\*);  

CAPI3REF
 Commit And Rollback Notification Callbacks
  nothrow void\* **sqlite3\_update\_hook**(sqlite3\*, void function(void\*, int, char\*, char\*, sqlite3\_int64), void\*);  

CAPI3REF
 Data Change Notification Callbacks
  nothrow int **sqlite3\_enable\_shared\_cache**(int);  

CAPI3REF
 Enable Or Disable Shared Pager Cache
  nothrow int **sqlite3\_release\_memory**(int);  

CAPI3REF
 Attempt To Free Heap Memory
  nothrow int **sqlite3\_db\_release\_memory**(sqlite3\*);  

CAPI3REF
 Free Memory Used By A Database Connection
  deprecated nothrow void **sqlite3\_soft\_heap\_limit**(int N);  

CAPI3REF
 Deprecated Soft Heap Limit Interface
  nothrow int **sqlite3\_table\_column\_metadata**(sqlite3\* db, const(char)\* zDbName, const(char)\* zTableName, const(char)\* zColumnName, char\*\* pzDataType, char\*\* pzCollSeq, int\* pNotNull, int\* pPrimaryKey, int\* pAutoinc);  

CAPI3REF
 Extract Metadata About A Column Of A Table
  nothrow int **sqlite3\_load\_extension**(sqlite3\* db, const(char)\* zFile, const(char)\* zProc, char\*\* pzErrMsg);  

CAPI3REF
 Load An Extension
  nothrow int **sqlite3\_enable\_load\_extension**(sqlite3\* db, int onoff);  

CAPI3REF
 Enable Or Disable Extension Loading
  nothrow int **sqlite3\_auto\_extension**(void function() xEntryPoint);  

CAPI3REF
 Automatically Load Statically Linked Extensions
  nothrow int **sqlite3\_cancel\_auto\_extension**(void function() xEntryPoint);  

CAPI3REF
 Cancel Automatic Extension Loading
  nothrow void **sqlite3\_reset\_auto\_extension**();  

CAPI3REF
 Reset Automatic Extension Loading
  alias **mapFunction** = extern (C) void function(sqlite3\_context\*, int, sqlite3\_value\*\*) nothrow;   
  
struct **sqlite3\_module**;  
The interface to the virtual-table mechanism is currently considered to be experimental. The interface might change in incompatible ways. If this is a problem for you, do not use the interface at this time. 


When the virtual-table mechanism stabilizes, we will declare the interface fixed, support it indefinitely, and remove this comment. 

 
CAPI3REF
 Virtual Table Object
  struct **sqlite3\_index\_info**;  

CAPI3REF
 Virtual Table Indexing Information
 
int **nConstraint**;  
Number of entries in aConstraint

  sqlite3\_index\_constraint\* **aConstraint**;  
Table of WHERE clause constraints

  int **nOrderBy**;  
Number of terms in the ORDER BY clause

  sqlite3\_index\_orderby\* **aOrderBy**;  
The ORDER BY clause

  int **idxNum**;  
Number used to identify the index

  char\* **idxStr**;  
String, possibly obtained from sqlite3\_malloc

  int **needToFreeIdxStr**;  
Free idxStr using sqlite3\_free() if true

  int **orderByConsumed**;  
True if output is already ordered

  double **estimatedCost**;  
Estimated cost of using this index

    nothrow int **sqlite3\_create\_module**(sqlite3\* db, const(char)\* zName, const(sqlite3\_module)\* p, void\* pClientData);   
  
nothrow int **sqlite3\_create\_module\_v2**(sqlite3\* db, const(char)\* zName, const(sqlite3\_module)\* p, void\* pClientData, void function(void\*) xDestroy);  

CAPI3REF
 Register A Virtual Table Implementation
  nothrow int **sqlite3\_drop\_modules**(sqlite3\* db, const(char\*)\* azKeep);  

CAPI3REF
 Remove Unnecessary Virtual Table Implementations
  struct **sqlite3\_vtab**;  

CAPI3REF
 Virtual Table Instance Object
 
const(sqlite3\_module)\* **pModule**;  
The module for this virtual table

  int **nRef**;  
NO LONGER USED

  char\* **zErrMsg**;  
Error message from sqlite3\_mprintf()

    struct **sqlite3\_vtab\_cursor**;  

CAPI3REF
 Virtual Table Cursor Object
 
sqlite3\_vtab\* **pVtab**;  
Virtual table of this cursor

    nothrow int **sqlite3\_declare\_vtab**(sqlite3\*, const char\* zSQL);  

CAPI3REF
 Declare The Schema Of A Virtual Table
  nothrow int **sqlite3\_overload\_function**(sqlite3\*, const char\* zFuncName, int nArg);  

CAPI3REF
 Overload A Function For A Virtual Table
  struct **sqlite3\_blob**;  
The interface to the virtual-table mechanism defined above (back up to a comment remarkably similar to this one) is currently considered to be experimental. The interface might change in incompatible ways. If this is a problem for you, do not use the interface at this time. 


When the virtual-table mechanism stabilizes, we will declare the interface fixed, support it indefinitely, and remove this comment.

  nothrow int **sqlite3\_blob\_open**(sqlite3\*, const(char)\* zDb, const(char)\* zTable, const(char)\* zColumn, sqlite3\_int64 iRow, int flags, sqlite3\_blob\*\* ppBlob);  

CAPI3REF
 Open A BLOB For Incremental I/O
  nothrow int **sqlite3\_blob\_reopen**(sqlite3\_blob\*, sqlite3\_int64);  

CAPI3REF
 Move a BLOB Handle to a New Row
  nothrow int **sqlite3\_blob\_close**(sqlite3\_blob\*);  

CAPI3REF
 Close A BLOB Handle
  nothrow int **sqlite3\_blob\_bytes**(sqlite3\_blob\*);  

CAPI3REF
 Return The Size Of An Open BLOB
  nothrow int **sqlite3\_blob\_read**(sqlite3\_blob\*, void\* Z, int N, int iOffset);  

CAPI3REF
 Read Data From A BLOB Incrementally
  nothrow int **sqlite3\_blob\_write**(sqlite3\_blob\*, const void\* z, int n, int iOffset);  

CAPI3REF
 Write Data Into A BLOB Incrementally
  nothrow sqlite3\_vfs\* **sqlite3\_vfs\_find**(const char\* zVfsName);   
  
nothrow int **sqlite3\_vfs\_register**(sqlite3\_vfs\*, int makeDflt);   
  
nothrow int **sqlite3\_vfs\_unregister**(sqlite3\_vfs\*);  

CAPI3REF
 Virtual File System Objects
  nothrow sqlite3\_mutex\* **sqlite3\_mutex\_alloc**(int);   
  
nothrow void **sqlite3\_mutex\_free**(sqlite3\_mutex\*);   
  
nothrow void **sqlite3\_mutex\_enter**(sqlite3\_mutex\*);   
  
nothrow int **sqlite3\_mutex\_try**(sqlite3\_mutex\*);   
  
nothrow void **sqlite3\_mutex\_leave**(sqlite3\_mutex\*);  

CAPI3REF
 Mutexes
  struct **sqlite3\_mutex\_methods**;  

CAPI3REF
 Mutex Methods Object
  nothrow int **sqlite3\_mutex\_held**(sqlite3\_mutex\*);   
  
nothrow int **sqlite3\_mutex\_notheld**(sqlite3\_mutex\*);  

CAPI3REF
 Mutex Verification Routines
  **SQLITE\_MUTEX\_STATIC\_MEM** 
sqlite3\_malloc()

  **SQLITE\_MUTEX\_STATIC\_MEM2** 
NOT USED

  **SQLITE\_MUTEX\_STATIC\_OPEN** 
sqlite3BtreeOpen()

  **SQLITE\_MUTEX\_STATIC\_PRNG** 
sqlite3\_randomness()

  **SQLITE\_MUTEX\_STATIC\_LRU** 
lru page list

  **SQLITE\_MUTEX\_STATIC\_LRU2** 
NOT USED

  **SQLITE\_MUTEX\_STATIC\_PMEM** 
sqlite3PageMalloc()

  **SQLITE\_MUTEX\_STATIC\_APP1** 
For use by application

  **SQLITE\_MUTEX\_STATIC\_APP2** 
For use by application

  **SQLITE\_MUTEX\_STATIC\_APP3** 
For use by application

  **SQLITE\_MUTEX\_STATIC\_VFS1** 
For use by built-in VFS

  **SQLITE\_MUTEX\_STATIC\_VFS2** 
For use by extension VFS

  **SQLITE\_MUTEX\_STATIC\_VFS3** 
For use by application VFS

  nothrow sqlite3\_mutex\* **sqlite3\_db\_mutex**(sqlite3\*);  

CAPI3REF
 Retrieve the mutex for a database connection
  nothrow int **sqlite3\_file\_control**(sqlite3\*, const char\* zDbName, int op, void\*);  

CAPI3REF
 Low-Level Control Of Database Files
  nothrow int **sqlite3\_test\_control**(int op, ...);  

CAPI3REF
 Testing Interface
  **SQLITE\_TESTCTRL\_PRNG\_RESET** 
NOT USED

  **SQLITE\_TESTCTRL\_RESERVE** 
NOT USED

  **SQLITE\_TESTCTRL\_ISKEYWORD** 
NOT USED

  **SQLITE\_TESTCTRL\_SCRATCHMALLOC** 
NOT USED

  **SQLITE\_TESTCTRL\_EXPLAIN\_STMT** 
NOT USED

  **SQLITE\_TESTCTRL\_LAST** 
Largest TESTCTRL

  nothrow int **sqlite3\_keyword\_count**();   
  
nothrow int **sqlite3\_keyword\_name**(int, const(char\*)\*, int\*);   
  
nothrow int **sqlite3\_keyword\_check**(const(char)\*, int);  

CAPI3REF
 SQL Keyword Checking
  struct **sqlite3\_str**;  

CAPI3REF
 Dynamic String Object
  nothrow sqlite3\_str\* **sqlite3\_str\_new**(sqlite3\*);  

CAPI3REF
 Create A New Dynamic String Object
  nothrow char\* **sqlite3\_str\_finish**(sqlite3\_str\*);  

CAPI3REF
 Finalize A Dynamic String
  nothrow void **sqlite3\_str\_appendf**(sqlite3\_str\*, const(char)\* zFormat, ...);   
  
nothrow void **sqlite3\_str\_vappendf**(sqlite3\_str\*, const(char)\* zFormat, va\_list);   
  
nothrow void **sqlite3\_str\_append**(sqlite3\_str\*, const(char)\* zIn, int N);   
  
nothrow void **sqlite3\_str\_appendall**(sqlite3\_str\*, const(char)\* zIn);   
  
nothrow void **sqlite3\_str\_appendchar**(sqlite3\_str\*, int N, char C);   
  
nothrow void **sqlite3\_str\_reset**(sqlite3\_str\*);  

CAPI3REF
 Add Content To A Dynamic String
  nothrow int **sqlite3\_str\_errcode**(sqlite3\_str\*);  

CAPI3REF
 Status Of A Dynamic String
  nothrow int **sqlite3\_status**(int op, int\* pCurrent, int\* pHighwater, int resetFlag);   
  
nothrow int **sqlite3\_status64**(int op, long\* pCurrent, long\* pHighwater, int resetFlag);  

CAPI3REF
 SQLite Runtime Status
  **SQLITE\_STATUS\_SCRATCH\_USED** 
NOT USED

  **SQLITE\_STATUS\_SCRATCH\_OVERFLOW** 
NOT USED

  **SQLITE\_STATUS\_SCRATCH\_SIZE** 
NOT USED

  nothrow int **sqlite3\_db\_status**(sqlite3\*, int op, int\* pCur, int\* pHiwtr, int resetFlg);  

CAPI3REF
 Database Connection Status
  **SQLITE\_DBSTATUS\_MAX** 
Largest defined DBSTATUS

  nothrow int **sqlite3\_stmt\_status**(sqlite3\_stmt\*, int op, int resetFlg);  

CAPI3REF
 Prepared Statement Status
  struct **sqlite3\_pcache**;  

CAPI3REF
 Custom Page Cache Object
  struct **sqlite3\_pcache\_page**;  

CAPI3REF
 Custom Page Cache Object
  struct **sqlite3\_pcache\_methods2**;  

CAPI3REF
 Application Defined Page Cache.
  struct **sqlite3\_backup**;  

CAPI3REF
 Online Backup Object
  nothrow sqlite3\_backup\* **sqlite3\_backup\_init**(sqlite3\* pDest, const(char)\* zDestName, sqlite3\* pSource, const(char)\* zSourceName);   
  
nothrow int **sqlite3\_backup\_step**(sqlite3\_backup\* p, int nPage);   
  
nothrow int **sqlite3\_backup\_finish**(sqlite3\_backup\* p);   
  
nothrow int **sqlite3\_backup\_remaining**(sqlite3\_backup\* p);   
  
nothrow int **sqlite3\_backup\_pagecount**(sqlite3\_backup\* p);  

CAPI3REF
 Online Backup API.
  nothrow int **sqlite3\_unlock\_notify**(sqlite3\* pBlocked, void function(void\*\* apArg, int nArg) xNotify, void\* pNotifyArg);  

CAPI3REF
 Unlock Notification
  nothrow int **sqlite3\_stricmp**(const char\*, const char\*);  

CAPI3REF
 String Comparison
  nothrow void **sqlite3\_log**(int iErrCode, const char\* zFormat, ...);  

CAPI3REF
 Error Logging Interface
  nothrow void\* **sqlite3\_wal\_hook**(sqlite3\*, int function(void\*, sqlite3\*, const char\*, int), void\*);  

CAPI3REF
 Write-Ahead Log Commit Hook
  nothrow int **sqlite3\_wal\_autocheckpoint**(sqlite3\* db, int N);  

CAPI3REF
 Configure an auto-checkpoint
  nothrow int **sqlite3\_wal\_checkpoint**(sqlite3\* db, const char\* zDb);  

CAPI3REF
 Checkpoint a database
  nothrow int **sqlite3\_wal\_checkpoint\_v2**(sqlite3\* db, const(char)\* zDb, int eMode, int\* pnLog, int\* pnCkpt);  

CAPI3REF
 Checkpoint a database
  enum int **SQLITE\_VTAB\_CONSTRAINT\_SUPPORT**;   
  
nothrow int **sqlite3\_preupdate\_old**(sqlite3\*, int, sqlite3\_value\*\*);   
  
nothrow int **sqlite3\_preupdate\_count**(sqlite3\*);   
  
nothrow int **sqlite3\_preupdate\_depth**(sqlite3\*);   
  
nothrow int **sqlite3\_preupdate\_new**(sqlite3\*, int, sqlite3\_value\*\*);  

CAPI3REF
 Virtual Table Configuration Options
  nothrow int **sqlite3\_rtree\_geometry\_callback**(sqlite3\* db, const(char)\* zGeom, int function(sqlite3\_rtree\_geometry\*, int nCoord, double\* aCoord, int\* pRes) xGeom, void\* pContext);  
Register a geometry callback named zGeom that can be used as part of an R-Tree geometry query as follows: 


SELECT ... FROM <rtree> WHERE <rtree col> MATCH zGeom(... params ...)

  struct **sqlite3\_rtree\_geometry**;  
A pointer to a structure of the following type is passed as the first argument to callbacks registered using rtree\_geometry\_callback().

 
void\* **pContext**;  
Copy of pContext passed to s\_r\_g\_c()

  int **nParam**;  
Size of array aParam[]

  double\* **aParam**;  
Parameters passed to SQL geom function

  void\* **pUser**;  
Callback implementation user data

  void function(void\*) **xDelUser**;  
Called by SQLite to clean up pUser

    **NOT\_WITHIN** 
Object completely outside of query region

  **PARTLY\_WITHIN** 
Object partially overlaps query region

  
**FULLY\_WITHIN**  
  
nothrow int **sqlite3changeset\_start\_v2**(sqlite3\_changeset\_iter\*\* pp, int nChangeset, void\* pChangeset, int flags);   
  
nothrow int **sqlite3changeset\_apply\_v2**(sqlite3\* db, int nChangeset, void\* pChangeset, int function(void\* pCtx, const(char)\* zTab) xFilter, int function(void\* pCtx, int eConflict, sqlite3\_changeset\_iter\* p) xConflict, void\* pCtx, void\*\* ppRebase, int\* pnRebase, int flags);   
  
nothrow int **sqlite3changeset\_apply\_v2\_strm**(sqlite3\* db, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pCtx, const(char)\* zTab) xFilter, int function(void\* pCtx, int eConflict, sqlite3\_changeset\_iter\* p) xConflict, void\* pCtx, void\*\* ppRebase, int\* pnRebase, int flags);   
  
nothrow int **sqlite3changeset\_concat\_strm**(int function(void\* pIn, void\* pData, int\* pnData) xInputA, void\* pInA, int function(void\* pIn, void\* pData, int\* pnData) xInputB, void\* pInB, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);   
  
nothrow int **sqlite3changeset\_invert\_strm**(int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);   
  
nothrow int **sqlite3changeset\_start\_strm**(sqlite3\_changeset\_iter\*\* pp, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn);   
  
nothrow int **sqlite3changeset\_start\_v2\_strm**(sqlite3\_changeset\_iter\*\* pp, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int flags);   
  
nothrow int **sqlite3session\_changeset\_strm**(sqlite3\_session\* pSession, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);   
  
nothrow int **sqlite3session\_patchset\_strm**(sqlite3\_session\* pSession, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);   
  
nothrow int **sqlite3changegroup\_add\_strm**(sqlite3\_changegroup\*, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn);   
  
nothrow int **sqlite3changegroup\_output\_strm**(sqlite3\_changegroup\*, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);   
  
nothrow int **sqlite3rebaser\_rebase\_strm**(sqlite3\_rebaser\* pRebaser, int function(void\* pIn, void\* pData, int\* pnData) xInput, void\* pIn, int function(void\* pOut, const(void)\* pData, int nData) xOutput, void\* pOut);  
Object fully contained within query region

  struct **Fts5Context**;   
  
alias **fts5\_extension\_function** = extern (C) void function(const(Fts5ExtensionApi\*) pApi, Fts5Context\* pFts, sqlite3\_context\* pCtx, int nVal, sqlite3\_value\*\* apVal) nothrow;   
  
struct **Fts5PhraseIter**;   
  
struct **Fts5ExtensionApi**;   
  
struct **Fts5Tokenizer**;   
  
enum int **FTS5\_TOKENIZE\_QUERY**;   
  
enum int **FTS5\_TOKENIZE\_PREFIX**;   
  
enum int **FTS5\_TOKENIZE\_DOCUMENT**;   
  
enum int **FTS5\_TOKENIZE\_AUX**;   
  
enum int **FTS5\_TOKEN\_COLOCATED**;   
  
struct **fts5\_api**;  
Interfaces to extend FTS5.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_sqlite3.html>

core.runtime
============

 The runtime module exposes information specific to the D runtime code. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [runtime.d](https://github.com/dlang/druntime/blob/master/src/core/runtime.d) 
 
Documentation
 [https://dlang.org/phobos/core\_runtime.html](core_runtime)

 
void\* **rt\_loadLibrary**(const char\* name);  
C interface for Runtime.loadLibrary

  int **rt\_unloadLibrary**(void\* ptr);  
C interface for Runtime.unloadLibrary, returns 1/0 instead of bool

  int **rt\_init**();  
C interface for Runtime.initialize, returns 1/0 instead of bool

  int **rt\_term**();  
C interface for Runtime.terminate, returns 1/0 instead of bool

  struct **UnitTestResult**;  
This type is returned by the module unit test handler to indicate testing results.

 
size\_t **executed**;  
Number of modules which were tested

  size\_t **passed**;  
Number of modules passed the unittests

  bool **runMain**;  
Should the main function be run or not? This is ignored if any tests failed.

  bool **summarize**;  
Should we print a summary of the results?

  const bool **opCast**(T : bool)();  
Simple check for whether execution should continue after unit tests have been run. Works with legacy code that expected a bool return. 



Returns:
true if execution should continue after testing is complete, false if not.
  enum UnitTestResult **pass**;  
Simple return code that says unit tests pass, and main should be run

  enum UnitTestResult **fail**;  
Simple return code that says unit tests failed.

    alias **ModuleUnitTester** = bool function();  
Legacy module unit test handler

  alias **ExtendedModuleUnitTester** = UnitTestResult function();  
Module unit test handler

  struct **CArgs**;  
Stores the unprocessed arguments supplied when the process was started.

 
int **argc**;  
The argument count.

  char\*\* **argv**;  
The arguments as a C array of strings.

    struct **Runtime**;  
This struct encapsulates all functionality related to the underlying runtime module for the calling context.

 
static bool **initialize**();  
Initializes the runtime. This call is to be used in instances where the standard program initialization process is not executed. This is most often in shared libraries or in libraries linked to a C program. If the runtime was already successfully initialized this returns true. Each call to initialize must be paired by a call to [`terminate`](#terminate). 



Returns:
true if initialization succeeded or false if initialization failed.
  static bool **terminate**();  
Terminates the runtime. This call is to be used in instances where the standard program termination process will not be not executed. This is most often in shared libraries or in libraries linked to a C program. If the runtime was not successfully initialized the function returns false. 



Returns:
true if termination succeeded or false if termination failed.
  static @property string[] **args**();  
Returns the arguments supplied when the process was started. 



Returns:
The arguments supplied when this process was started.
  static @nogc @property CArgs **cArgs**();  
Returns the unprocessed C arguments supplied when the process was started. Use this when you need to supply argc and argv to C libraries. 



Returns:
A [`CArgs`](#CArgs) struct with the arguments supplied when this process was started. 
 
Example


```
import core.runtime;

// A C library function requiring char** arguments
extern(C) void initLibFoo(int argc, char** argv);

void main()
{
    auto args = Runtime.cArgs;
    initLibFoo(args.argc, args.argv);
}

```
  void\* **loadLibrary**()(scope const char[] name);  
Locates a dynamic library with the supplied library name and dynamically loads it into the caller's address space. If the library contains a D runtime it will be integrated with the current runtime. 



Parameters:


|  |  |
| --- | --- |
| char[] `name` | The name of the dynamic library to load. |


 
Returns:
A reference to the library or null on error.
  bool **unloadLibrary**()(void\* p);  
Unloads the dynamic library referenced by p. If this library contains a D runtime then any necessary finalization or cleanup of that runtime will be performed. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A reference to the library to unload. |


  static @property void **traceHandler**(TraceHandler h);  
Overrides the default trace mechanism with a user-supplied version. A trace represents the context from which an exception was thrown, and the trace handler will be called when this occurs. The pointer supplied to this routine indicates the base address from which tracing should occur. If the supplied pointer is null then the trace routine should determine an appropriate calling context from which to begin the trace. 



Parameters:


|  |  |
| --- | --- |
| TraceHandler `h` | The new trace handler. Set to null to use the default handler. |


  static @property TraceHandler **traceHandler**();  
Gets the current trace handler. 



Returns:
The current trace handler or null if none has been set.
  static @property void **collectHandler**(CollectHandler h);  
Overrides the default collect hander with a user-supplied version. This routine will be called for each resource object that is finalized in a non-deterministic manner--typically during a garbage collection cycle. If the supplied routine returns true then the object's dtor will called as normal, but if the routine returns false than the dtor will not be called. The default behavior is for all object dtors to be called. 



Parameters:


|  |  |
| --- | --- |
| CollectHandler `h` | The new collect handler. Set to null to use the default handler. |


  static @property CollectHandler **collectHandler**();  
Gets the current collect handler. 



Returns:
The current collect handler or null if none has been set.
  static @property void **extendedModuleUnitTester**(ExtendedModuleUnitTester h);   
  
static @property void **moduleUnitTester**(ModuleUnitTester h);  
Overrides the default module unit tester with a user-supplied version. This routine will be called once on program initialization. The return value of this routine indicates to the runtime whether the tests ran without error. 


There are two options for handlers. The `bool` version is deprecated but will be kept for legacy support. Returning `true` from the handler is equivalent to returning `UnitTestResult.pass` from the extended version. Returning `false` from the handler is equivalent to returning `UnitTestResult.fail` from the extended version.   
  
 See the documentation for `UnitTestResult` to see how you should set up the return structure.   
  
 See the documentation for `runModuleUnitTests` for how the default algorithm works, or read the example below. 

 
Parameters:


|  |  |
| --- | --- |
| ExtendedModuleUnitTester `h` | The new unit tester. Set both to null to use the default unit tester. |


 
Example


```
shared static this()
{
    import core.runtime;

    Runtime.extendedModuleUnitTester = &customModuleUnitTester;
}

UnitTestResult customModuleUnitTester()
{
    import std.stdio;

    writeln("Using customModuleUnitTester");

    // Do the same thing as the default moduleUnitTester:
    UnitTestResult result;
    foreach (m; ModuleInfo)
    {
        if (m)
        {
            auto fp = m.unitTest;

            if (fp)
            {
                ++result.executed;
                try
                {
                    fp();
                    ++result.passed;
                }
                catch (Throwable e)
                {
                    writeln(e);
                }
            }
        }
    }
    if (result.executed != result.passed)
    {
        result.runMain = false;  // don't run main
        result.summarize = true; // print failure
    }
    else
    {
        result.runMain = true;    // all UT passed
        result.summarize = false; // be quiet about it.
    }
    return result;
}

```
  static @property ModuleUnitTester **moduleUnitTester**();  
Gets the current legacy module unit tester. 


This property should not be used, but is supported for legacy purposes.   
  
 Note that if the extended unit test handler is set, this handler will be ignored. 

 
Returns:
The current legacy module unit tester handler or null if none has been set.
  static @property ExtendedModuleUnitTester **extendedModuleUnitTester**();  
Gets the current module unit tester. 


This handler overrides any legacy module unit tester set by the moduleUnitTester property. 

 
Returns:
The current module unit tester handler or null if none has been set.
    void **dmd\_coverSourcePath**(string path);  
Set source file path for coverage reports. 



Parameters:


|  |  |
| --- | --- |
| string `path` | The new path name. |


 
Note
 This is a dmd specific setting.
  void **dmd\_coverDestPath**(string path);  
Set output path for coverage reports. 



Parameters:


|  |  |
| --- | --- |
| string `path` | The new path name. |


 
Note
 This is a dmd specific setting.
  void **dmd\_coverSetMerge**(bool flag);  
Enable merging of coverage reports with existing data. 



Parameters:


|  |  |
| --- | --- |
| bool `flag` | enable/disable coverage merge mode |


 
Note
 This is a dmd specific setting.
  void **trace\_setlogfilename**(string name);  
Set the output file name for profile reports (-profile switch). An empty name will set the output to stdout. 



Parameters:


|  |  |
| --- | --- |
| string `name` | file name |


 
Note
 This is a dmd specific setting.
  void **trace\_setdeffilename**(string name);  
Set the output file name for the optimized profile linker DEF file (-profile switch). An empty name will set the output to stdout. 



Parameters:


|  |  |
| --- | --- |
| string `name` | file name |


 
Note
 This is a dmd specific setting.
  void **profilegc\_setlogfilename**(string name);  
Set the output file name for memory profile reports (-profile=gc switch). An empty name will set the output to stdout. 



Parameters:


|  |  |
| --- | --- |
| string `name` | file name |


 
Note
 This is a dmd specific setting.
  UnitTestResult **runModuleUnitTests**();  
This routine is called by the runtime to run module unit tests on startup. The user-supplied unit tester will be called if one has been set, otherwise all unit tests will be run in sequence. 


If the extended unittest handler is registered, this function returns the result from that handler directly.   
  
 If a legacy boolean returning custom handler is used, `false` maps to `UnitTestResult.fail`, and `true` maps to `UnitTestResult.pass`. This was the original behavior of the unit testing system.   
  
 If no unittest custom handlers are registered, the following algorithm is executed (the behavior can be affected by the `--DRT-testmode` switch below): 1. Execute any unittests present. For each that fails, print the stack trace and continue.
2. If no unittests were present, set summarize to false, and runMain to true.
3. Otherwise, set summarize to true, and runMain to false.

 See the documentation for `UnitTestResult` for details on how the runtime treats the return value from this function.   
  
 If the switch `--DRT-testmode` is passed to the executable, it can have one of 3 values: 1. "run-main": even if unit tests are run (and all pass), runMain is set to true.
2. "test-or-main": any unit tests present will cause the program to summarize the results and exit regardless of the result. This is the default.
3. "test-only", runMain is set to false, even with no tests present.

 This command-line parameter does not affect custom unit test handlers. 

 
Returns:
A `UnitTestResult` struct indicating the result of running unit tests.
  Throwable.TraceInfo **defaultTraceHandler**(void\* ptr = null);  
Get the default `Throwable.TraceInfo` implementation for the platform 


This functions returns a trace handler, allowing to inspect the current stack trace. 

 
Parameters:


|  |  |
| --- | --- |
| void\* `ptr` | (Windows only) The context to get the stack trace from. When `null` (the default), start from the current frame. |


 
Returns:
A `Throwable.TraceInfo` implementation suitable to iterate over the stack, or `null`. If called from a finalizer (destructor), always returns `null` as trace handlers allocate.
 
Examples:
Example of a simple program printing its stack trace 
```
import core.runtime;
import core.stdc.stdio;

void main()
{
    auto trace = defaultTraceHandler(null);
    foreach (line; trace)
    {
        printf("%.*s\n", cast(int)line.length, line.ptr);
    }
}

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_runtime.html>

core.stdc.fenv
==============

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<fenv.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/fenv.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/fenv.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/fenv.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
**FE\_INVALID** **FE\_DENORMAL** 
non-standard

  **FE\_DIVBYZERO** **FE\_OVERFLOW** **FE\_UNDERFLOW** **FE\_INEXACT** **FE\_ALL\_EXCEPT** **FE\_TONEAREST** **FE\_DOWNWARD** **FE\_UPWARD** **FE\_TOWARDZERO** enum fenv\_t\* **FE\_DFL\_ENV**;  nothrow @nogc @system int **feclearexcept**(int excepts);  nothrow @nogc @system int **fetestexcept**(int excepts);  nothrow @nogc @system int **feholdexcept**(fenv\_t\* envp);  nothrow @nogc @system int **fegetexceptflag**(fexcept\_t\* flagp, int excepts);  nothrow @nogc @system int **fesetexceptflag**(scope const fexcept\_t\* flagp, int excepts);  nothrow @nogc @system int **fegetround**();  nothrow @nogc @system int **fesetround**(int round);  nothrow @nogc @system int **fegetenv**(fenv\_t\* envp);  nothrow @nogc @system int **fesetenv**(scope const fenv\_t\* envp);  nothrow @nogc @system int **feraiseexcept**(int excepts);  nothrow @nogc @system int **feupdateenv**(scope const fenv\_t\* envp);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_fenv.html>

core.stdc.float\_
=================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<float.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/float.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/float\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/float_.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
enum int **FLT\_ROUNDS**;  enum int **FLT\_EVAL\_METHOD**;  enum int **FLT\_RADIX**;  enum int **DECIMAL\_DIG**;  enum int **FLT\_DIG**;  enum int **DBL\_DIG**;  enum int **LDBL\_DIG**;  enum int **FLT\_MANT\_DIG**;  enum int **DBL\_MANT\_DIG**;  enum int **LDBL\_MANT\_DIG**;  enum float **FLT\_MIN**;  enum double **DBL\_MIN**;  enum real **LDBL\_MIN**;  enum float **FLT\_MAX**;  enum double **DBL\_MAX**;  enum real **LDBL\_MAX**;  enum float **FLT\_EPSILON**;  enum double **DBL\_EPSILON**;  enum real **LDBL\_EPSILON**;  enum int **FLT\_MIN\_EXP**;  enum int **DBL\_MIN\_EXP**;  enum int **LDBL\_MIN\_EXP**;  enum int **FLT\_MAX\_EXP**;  enum int **DBL\_MAX\_EXP**;  enum int **LDBL\_MAX\_EXP**;  enum int **FLT\_MIN\_10\_EXP**;  enum int **DBL\_MIN\_10\_EXP**;  enum int **LDBL\_MIN\_10\_EXP**;  enum int **FLT\_MAX\_10\_EXP**;  enum int **DBL\_MAX\_10\_EXP**;  enum int **LDBL\_MAX\_10\_EXP**;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_float_.html>

core.stdc.limits
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<limits.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/limits.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/limits.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/limits.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
enum int **CHAR\_BIT**;  enum byte **SCHAR\_MIN**;  enum byte **SCHAR\_MAX**;  enum ubyte **UCHAR\_MAX**;  enum char **CHAR\_MIN**;  enum char **CHAR\_MAX**;  enum int **MB\_LEN\_MAX**;  enum short **SHRT\_MIN**;  enum short **SHRT\_MAX**;  enum ushort **USHRT\_MAX**;  enum int **INT\_MIN**;  enum int **INT\_MAX**;  enum uint **UINT\_MAX**;  enum long **LONG\_MIN**;  enum long **LONG\_MAX**;  enum ulong **ULONG\_MAX**;  enum long **LLONG\_MIN**;  enum long **LLONG\_MAX**;  enum ulong **ULLONG\_MAX**;  enum int **MAX\_CANON**;  enum int **MAX\_INPUT**;  enum int **NAME\_MAX**;  enum int **PATH\_MAX**;  enum int **PIPE\_BUF**;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_limits.html>

core.stdc.locale
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<locale.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/locale.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/locale.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/locale.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
struct **lconv**;  enum int **LC\_CTYPE**;  enum int **LC\_NUMERIC**;  enum int **LC\_TIME**;  enum int **LC\_COLLATE**;  enum int **LC\_MONETARY**;  enum int **LC\_MESSAGES**;  enum int **LC\_ALL**;  enum int **LC\_PAPER**;  enum int **LC\_NAME**;  enum int **LC\_ADDRESS**;  enum int **LC\_TELEPHONE**;  enum int **LC\_MEASUREMENT**;  enum int **LC\_IDENTIFICATION**;  nothrow @nogc @system char\* **setlocale**(int category, scope const char\* locale);  nothrow @nogc @trusted lconv\* **localeconv**();  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_locale.html>

core.memory
===========

 This module provides an interface to the garbage collector used by applications written in the D programming language. It allows the garbage collector in the runtime to be swapped without affecting binary compatibility of applications. 


Using this module is not necessary in typical D code. It is mostly useful when doing low-level memory management. 

 
Notes to users

1. The GC is a conservative mark-and-sweep collector. It only runs a collection cycle when an allocation is requested of it, never otherwise. Hence, if the program is not doing allocations, there will be no GC collection pauses. The pauses occur because all threads the GC knows about are halted so the threads' stacks and registers can be scanned for references to GC allocated data.
2. The GC does not know about threads that were created by directly calling the OS/C runtime thread creation APIs and D threads that were detached from the D runtime after creation. Such threads will not be paused for a GC collection, and the GC might not detect references to GC allocated data held by them. This can cause memory corruption. There are several ways to resolve this issue:
	1. Do not hold references to GC allocated data in such threads.
	2. Register/unregister such data with calls to [`addRoot`](#addRoot)/[`removeRoot`](#removeRoot) and [`addRange`](#addRange)/[`removeRange`](#removeRange).
	3. Maintain another reference to that same data in another thread that the GC does know about.
	4. Disable GC collection cycles while that thread is active with [`disable`](#disable)/[`enable`](#enable).
	5. Register the thread with the GC using [`core.thread.thread_attachThis`](core_thread#thread_attachThis)/[`core.thread.thread_detachThis`](core_thread#thread_detachThis).

 
Notes to implementors

* On POSIX systems, the signals SIGUSR1 and SIGUSR2 are reserved by this module for use in the garbage collector implementation. Typically, they will be used to stop and resume other threads when performing a collection, but an implementation may choose not to use this mechanism (or not stop the world at all, in the case of concurrent garbage collectors).
* Registers, the stack, and any other memory locations added through the `GC.[addRange](#addRange)` function are always scanned conservatively. This means that even if a variable is e.g. of type `float`, it will still be scanned for possible GC pointers. And, if the word-interpreted representation of the variable matches a GC-managed memory block's address, that memory block is considered live.
* Implementations are free to scan the non-root heap in a precise manner, so that fields of types like `float` will not be considered relevant when scanning the heap. Thus, casting a GC pointer to an integral type (e.g. `size_t`) and storing it in a field of that type inside the GC heap may mean that it will not be recognized if the memory block was allocated with precise type info or with the `GC.BlkAttr.[NO\_SCAN](#NO_SCAN)` attribute.
* Destructors will always be executed while other threads are active; that is, an implementation that stops the world must not execute destructors until the world has been resumed.
* A destructor of an object must not access object references within the object. This means that an implementation is free to optimize based on this rule.
* An implementation is free to perform heap compaction and copying so long as no valid GC pointers are invalidated in the process. However, memory allocated with `GC.BlkAttr.[NO\_MOVE](#NO_MOVE)` must not be moved/copied.
* Implementations must support interior pointers. That is, if the only reference to a GC-managed memory block points into the middle of the block rather than the beginning (for example), the GC must consider the memory block live. The exception to this rule is when a memory block is allocated with the `GC.BlkAttr.[NO\_INTERIOR](#NO_INTERIOR)` attribute; it is the user's responsibility to make sure such memory blocks have a proper pointer to them when they should be considered live.
* It is acceptable for an implementation to store bit flags into pointer values and GC-managed memory blocks, so long as such a trick is not visible to the application. In practice, this means that only a stop-the-world collector can do this.
* Implementations are free to assume that GC pointers are only stored on word boundaries. Unaligned pointers may be ignored entirely.
* Implementations are free to run collections at any point. It is, however, recommendable to only do so when an allocation attempt happens and there is insufficient memory available.

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly, Alex Rønne Petersen 
 
Source
 [core/memory.d](https://github.com/dlang/druntime/blob/master/src/core/memory.d)

 
immutable size\_t **pageSize**;  
The size of a system page in bytes. 


This value is set at startup time of the application. It's safe to use early in the start process, like in shared module constructors and initialization of the D runtime itself.

 
Examples:


```
ubyte[] buffer = new ubyte[pageSize];

```
 
  struct **GC**;  
This struct encapsulates all garbage collection functionality for the D programming language.

 
struct **Stats**;  
Aggregation of GC stats to be exposed via public API

 
size\_t **usedSize**;  
number of used bytes on the GC heap (might only get updated after a collection)

  size\_t **freeSize**;  
number of free bytes on the GC heap (might only get updated after a collection)

  ulong **allocatedInCurrentThread**;  
number of bytes allocated for current thread since program start

    struct **ProfileStats**;  
Aggregation of current profile information

 
size\_t **numCollections**;  
total number of GC cycles

  Duration **totalCollectionTime**;  
total time spent doing GC

  Duration **totalPauseTime**;  
total time threads were paused doing GC

  Duration **maxPauseTime**;  
largest time threads were paused during one GC cycle

  Duration **maxCollectionTime**;  
largest time spent doing one GC cycle

    static nothrow void **enable**();  
Enables automatic garbage collection behavior if collections have previously been suspended by a call to disable. This function is reentrant, and must be called once for every call to disable before automatic collections are enabled.

  static nothrow void **disable**();  
Disables automatic garbage collections performed to minimize the process footprint. Collections may continue to occur in instances where the implementation deems necessary for correct program behavior, such as during an out of memory condition. This function is reentrant, but enable must be called once for each call to disable.

  static nothrow void **collect**();  
Begins a full collection. While the meaning of this may change based on the garbage collector implementation, typical behavior is to scan all stack segments for roots, mark accessible memory blocks as alive, and then to reclaim free space. This action may need to suspend all running threads for at least part of the collection process.

  static nothrow void **minimize**();  
Indicates that the managed memory space be minimized by returning free physical memory to the operating system. The amount of free memory returned depends on the allocator design and on program behavior.

  enum **BlkAttr**: uint;  
Elements for a bit field representing memory block attributes. These are manipulated via the getAttr, setAttr, clrAttr functions.

 
**NONE** 
No attributes set.

  **FINALIZE** 
Finalize the data in this block on collect.

  **NO\_SCAN** 
Do not scan through this block on collect.

  **NO\_MOVE** 
Do not move this memory block on collect.

  **APPENDABLE** 
This block contains the info to allow appending. 


This can be used to manually allocate arrays. Initial slice size is 0. 

 
Note
 The slice's usable size will not match the block size. Use [`capacity`](#capacity) to retrieve actual usable capacity. 
 
Example


```
// Allocate the underlying array.
int*  pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE);
// Bind a slice. Check the slice has capacity information.
int[] slice = pToArray[0 .. 0];
assert(capacity(slice) > 0);
// Appending to the slice will not relocate it.
slice.length = 5;
slice ~= 1;
assert(slice.ptr == p);

```
  **NO\_INTERIOR** 
This block is guaranteed to have a pointer to its base while it is alive. Interior pointers can be safely ignored. This attribute is useful for eliminating false pointers in very large data structures and is only implemented for data structures at least a page in size.

    alias **BlkInfo** = .BlkInfo\_;  
Contains aggregate information about a block of managed memory. The purpose of this struct is to support a more efficient query style in instances where detailed information is needed. 


base = A pointer to the base of the block in question. size = The size of the block, calculated from base. attr = Attribute bits set on the memory block.

  static nothrow uint **getAttr**(scope const void\* p);   
  
static pure nothrow uint **getAttr**(void\* p);  
Returns a bit field representing all block attributes set for the memory referenced by p. If p references memory not originally allocated by this garbage collector, points to the interior of a memory block, or if p is null, zero will be returned. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |


 
Returns:
A bit field containing any bits set for the memory block referenced by p or zero on error.
  static nothrow uint **setAttr**(scope const void\* p, uint a);   
  
static pure nothrow uint **setAttr**(void\* p, uint a);  
Sets the specified bits for the memory references by p. If p references memory not originally allocated by this garbage collector, points to the interior of a memory block, or if p is null, no action will be performed. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |
| uint `a` | A bit field containing any bits to set for this memory block. |


 
Returns:
The result of a call to getAttr after the specified bits have been set.
  static nothrow uint **clrAttr**(scope const void\* p, uint a);   
  
static pure nothrow uint **clrAttr**(void\* p, uint a);  
Clears the specified bits for the memory references by p. If p references memory not originally allocated by this garbage collector, points to the interior of a memory block, or if p is null, no action will be performed. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |
| uint `a` | A bit field containing any bits to clear for this memory block. |


 
Returns:
The result of a call to getAttr after the specified bits have been cleared.
  static pure nothrow void\* **malloc**(size\_t sz, uint ba = 0, const TypeInfo ti = null);  
Requests an aligned block of managed memory from the garbage collector. This memory may be deleted at will with a call to free, or it may be discarded and cleaned up automatically during a collection run. If allocation fails, this function will call onOutOfMemory which is expected to throw an OutOfMemoryError. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sz` | The desired allocation size in bytes. |
| uint `ba` | A bitmask of the attributes to set on this block. |
| TypeInfo `ti` | TypeInfo to describe the memory. The GC might use this information to improve scanning for pointers or to call finalizers. |


 
Returns:
A reference to the allocated memory or null if insufficient memory is available. 
 
Throws:
OutOfMemoryError on allocation failure.
  static pure nothrow BlkInfo **qalloc**(size\_t sz, uint ba = 0, const TypeInfo ti = null);  
Requests an aligned block of managed memory from the garbage collector. This memory may be deleted at will with a call to free, or it may be discarded and cleaned up automatically during a collection run. If allocation fails, this function will call onOutOfMemory which is expected to throw an OutOfMemoryError. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sz` | The desired allocation size in bytes. |
| uint `ba` | A bitmask of the attributes to set on this block. |
| TypeInfo `ti` | TypeInfo to describe the memory. The GC might use this information to improve scanning for pointers or to call finalizers. |


 
Returns:
Information regarding the allocated memory block or BlkInfo.init on error. 
 
Throws:
OutOfMemoryError on allocation failure.
  static pure nothrow void\* **calloc**(size\_t sz, uint ba = 0, const TypeInfo ti = null);  
Requests an aligned block of managed memory from the garbage collector, which is initialized with all bits set to zero. This memory may be deleted at will with a call to free, or it may be discarded and cleaned up automatically during a collection run. If allocation fails, this function will call onOutOfMemory which is expected to throw an OutOfMemoryError. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sz` | The desired allocation size in bytes. |
| uint `ba` | A bitmask of the attributes to set on this block. |
| TypeInfo `ti` | TypeInfo to describe the memory. The GC might use this information to improve scanning for pointers or to call finalizers. |


 
Returns:
A reference to the allocated memory or null if insufficient memory is available. 
 
Throws:
OutOfMemoryError on allocation failure.
  static pure nothrow void\* **realloc**(void\* p, size\_t sz, uint ba = 0, const TypeInfo ti = null);  
Extend, shrink or allocate a new block of memory keeping the contents of an existing block 


If `sz` is zero, the memory referenced by p will be deallocated as if by a call to `free`. If `p` is `null`, new memory will be allocated via `malloc`. If `p` is pointing to memory not allocated from the GC or to the interior of an allocated memory block, no operation is performed and null is returned.   
  
 Otherwise, a new memory block of size `sz` will be allocated as if by a call to `malloc`, or the implementation may instead resize or shrink the memory block in place. The contents of the new memory block will be the same as the contents of the old memory block, up to the lesser of the new and old sizes.   
  
 The caller guarantees that there are no other live pointers to the passed memory block, still it might not be freed immediately by `realloc`. The garbage collector can reclaim the memory block in a later collection if it is unused. If allocation fails, this function will throw an `OutOfMemoryError`.   
  
 If `ba` is zero (the default) the attributes of the existing memory will be used for an allocation. If `ba` is not zero and no new memory is allocated, the bits in ba will replace those of the current memory block. 

 
Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the base of a valid memory block or to `null`. |
| size\_t `sz` | The desired allocation size in bytes. |
| uint `ba` | A bitmask of the BlkAttr attributes to set on this block. |
| TypeInfo `ti` | TypeInfo to describe the memory. The GC might use this information to improve scanning for pointers or to call finalizers. |


 
Returns:
A reference to the allocated memory on success or `null` if `sz` is zero or the pointer does not point to the base of an GC allocated memory block. 
 
Throws:

`OutOfMemoryError` on allocation failure.
 
Examples:


```
enum size1 = 1 << 11 + 1; // page in large object pool
enum size2 = 1 << 22 + 1; // larger than large object pool size

auto data1 = cast(ubyte*)GC.calloc(size1);
auto data2 = cast(ubyte*)GC.realloc(data1, size2);

GC.BlkInfo info = GC.query(data2);
assert(info.size >= size2);

```
 
  static pure nothrow size\_t **extend**(void\* p, size\_t mx, size\_t sz, const TypeInfo ti = null);  
Requests that the managed memory block referenced by p be extended in place by at least mx bytes, with a desired extension of sz bytes. If an extension of the required size is not possible or if p references memory not originally allocated by this garbage collector, no action will be taken. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |
| size\_t `mx` | The minimum extension size in bytes. |
| size\_t `sz` | The desired extension size in bytes. |
| TypeInfo `ti` | TypeInfo to describe the full memory block. The GC might use this information to improve scanning for pointers or to call finalizers. |


 
Returns:
The size in bytes of the extended memory block referenced by p or zero if no extension occurred. 
 
Note
 Extend may also be used to extend slices (or memory blocks with [`APPENDABLE`](#APPENDABLE) info). However, use the return value only as an indicator of success. [`capacity`](#capacity) should be used to retrieve actual usable slice capacity.
 
Examples:
Standard extending 
```
size_t size = 1000;
int* p = cast(int*)GC.malloc(size * int.sizeof, GC.BlkAttr.NO_SCAN);

//Try to extend the allocated data by 1000 elements, preferred 2000.
size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
if (u != 0)
    size = u / int.sizeof;

```
 
 
Examples:
slice extending 
```
int[] slice = new int[](1000);
int*  p     = slice.ptr;

//Check we have access to capacity before attempting the extend
if (slice.capacity)
{
    //Try to extend slice by 1000 elements, preferred 2000.
    size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
    if (u != 0)
    {
        slice.length = slice.capacity;
        assert(slice.length >= 2000);
    }
}

```
 
  static nothrow size\_t **reserve**(size\_t sz);  
Requests that at least sz bytes of memory be obtained from the operating system and marked as free. 



Parameters:


|  |  |
| --- | --- |
| size\_t `sz` | The desired size in bytes. |


 
Returns:
The actual number of bytes reserved or zero on error.
  static pure nothrow @nogc void **free**(void\* p);  
Deallocates the memory referenced by p. If p is null, no action occurs. If p references memory not originally allocated by this garbage collector, if p points to the interior of a memory block, or if this method is called from a finalizer, no action will be taken. The block will not be finalized regardless of whether the FINALIZE attribute is set. If finalization is desired, call [`destroy`](object#destroy) prior to `GC.free`. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |


  static nothrow @nogc inout(void)\* **addrOf**(inout(void)\* p);   
  
static pure nothrow @nogc void\* **addrOf**(void\* p);  
Returns the base address of the memory block containing p. This value is useful to determine whether p is an interior pointer, and the result may be passed to routines such as sizeOf which may otherwise fail. If p references memory not originally allocated by this garbage collector, if p is null, or if the garbage collector does not support this operation, null will be returned. 



Parameters:


|  |  |
| --- | --- |
| inout(void)\* `p` | A pointer to the root or the interior of a valid memory block or to null. |


 
Returns:
The base address of the memory block referenced by p or null on error.
  static nothrow @nogc size\_t **sizeOf**(scope const void\* p);   
  
static pure nothrow @nogc size\_t **sizeOf**(void\* p);  
Returns the true size of the memory block referenced by p. This value represents the maximum number of bytes for which a call to realloc may resize the existing block in place. If p references memory not originally allocated by this garbage collector, points to the interior of a memory block, or if p is null, zero will be returned. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root of a valid memory block or to null. |


 
Returns:
The size in bytes of the memory block referenced by p or zero on error.
  static nothrow BlkInfo **query**(scope const void\* p);   
  
static pure nothrow BlkInfo **query**(void\* p);  
Returns aggregate information about the memory block containing p. If p references memory not originally allocated by this garbage collector, if p is null, or if the garbage collector does not support this operation, BlkInfo.init will be returned. Typically, support for this operation is dependent on support for addrOf. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to the root or the interior of a valid memory block or to null. |


 
Returns:
Information regarding the memory block referenced by p or BlkInfo.init on error.
  static nothrow Stats **stats**();  
Returns runtime stats for currently active GC implementation See `core.memory.GC.Stats` for list of available metrics.

  static nothrow @nogc @safe ProfileStats **profileStats**();  
Returns runtime profile stats for currently active GC implementation See `core.memory.GC.ProfileStats` for list of available metrics.

  static nothrow @nogc void **addRoot**(const void\* p);  
Adds an internal root pointing to the GC memory block referenced by p. As a result, the block referenced by p itself and any blocks accessible via it will be considered live until the root is removed again. 


If p is null, no operation is performed. 

 
Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer into a GC-managed memory block or null. |


 
Example


```
// Typical C-style callback mechanism; the passed function
// is invoked with the user-supplied context pointer at a
// later point.
extern(C) void addCallback(void function(void*), void*);

// Allocate an object on the GC heap (this would usually be
// some application-specific context data).
auto context = new Object;

// Make sure that it is not collected even if it is no
// longer referenced from D code (stack, GC heap, …).
GC.addRoot(cast(void*)context);

// Also ensure that a moving collector does not relocate
// the object.
GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);

// Now context can be safely passed to the C library.
addCallback(&myHandler, cast(void*)context);

extern(C) void myHandler(void* ctx)
{
    // Assuming that the callback is invoked only once, the
    // added root can be removed again now to allow the GC
    // to collect it later.
    GC.removeRoot(ctx);
    GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);

    auto context = cast(Object)ctx;
    // Use context here…
}

```
  static nothrow @nogc void **removeRoot**(const void\* p);  
Removes the memory block referenced by p from an internal list of roots to be scanned during a collection. If p is null or is not a value previously passed to addRoot() then no operation is performed. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer into a GC-managed memory block or null. |


  static nothrow @nogc void **addRange**(const void\* p, size\_t sz, const TypeInfo ti = null);  
Adds `p[0 .. sz]` to the list of memory ranges to be scanned for pointers during a collection. If p is null, no operation is performed. 


Note that `p[0 .. sz]` is treated as an opaque range of memory assumed to be suitably managed by the caller. In particular, if p points into a GC-managed memory block, addRange does *not* mark this block as live. 

 
Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to a valid memory address or to null. |
| size\_t `sz` | The size in bytes of the block to add. If sz is zero then the no operation will occur. If p is null then sz must be zero. |
| TypeInfo `ti` | TypeInfo to describe the memory. The GC might use this information to improve scanning for pointers or to call finalizers |


 
Example


```
// Allocate a piece of memory on the C heap.
enum size = 1_000;
auto rawMemory = core.stdc.stdlib.malloc(size);

// Add it as a GC range.
GC.addRange(rawMemory, size);

// Now, pointers to GC-managed memory stored in
// rawMemory will be recognized on collection.

```
  static nothrow @nogc void **removeRange**(const void\* p);  
Removes the memory range starting at p from an internal list of ranges to be scanned during a collection. If p is null or does not represent a value previously passed to addRange() then no operation is performed. 



Parameters:


|  |  |
| --- | --- |
| void\* `p` | A pointer to a valid memory address or to null. |


  static void **runFinalizers**(scope const void[] segment);  
Runs any finalizer that is located in address range of the given code segment. This is used before unloading shared libraries. All matching objects which have a finalizer in this code segment are assumed to be dead, using them while or after calling this method has undefined behavior. 



Parameters:


|  |  |
| --- | --- |
| void[] `segment` | address range of a code segment. |


  static nothrow @nogc @safe bool **inFinalizer**();  
Queries the GC whether the current thread is running object finalization as part of a GC collection, or an explicit call to runFinalizers. 


As some GC implementations (such as the current conservative one) don't support GC memory allocation during object finalization, this function can be used to guard against such programming errors. 

 
Returns:
true if the current thread is in a finalizer, a destructor invoked by the GC.
 
Examples:


```
// Only code called from a destructor is executed during finalization.
assert(!GC.inFinalizer);

```
 
 
Examples:


```
enum Outcome
{
    notCalled,
    calledManually,
    calledFromDruntime
}

static class Resource
{
    static Outcome outcome;

    this()
    {
        outcome = Outcome.notCalled;
    }

    ~this()
    {
        if (GC.inFinalizer)
        {
            outcome = Outcome.calledFromDruntime;

            import core.exception : InvalidMemoryOperationError;
            try
            {
                /*
                 * Presently, allocating GC memory during finalization
                 * is forbidden and leads to
                 * `InvalidMemoryOperationError` being thrown.
                 *
                 * `GC.inFinalizer` can be used to guard against
                 * programming erros such as these and is also a more
                 * efficient way to verify whether a destructor was
                 * invoked by the GC.
                 */
                cast(void) GC.malloc(1);
                assert(false);
            }
            catch (InvalidMemoryOperationError e)
            {
                return;
            }
            assert(false);
        }
        else
            outcome = Outcome.calledManually;
    }
}

static void createGarbage()
{
    auto r = new Resource;
    r = null;
}

assert(Resource.outcome == Outcome.notCalled);
createGarbage();
GC.collect;
assert(
    Resource.outcome == Outcome.notCalled ||
    Resource.outcome == Outcome.calledFromDruntime);

auto r = new Resource;
GC.runFinalizers((cast(const void*)typeid(Resource).destructor)[0..1]);
assert(Resource.outcome == Outcome.calledFromDruntime);
Resource.outcome = Outcome.notCalled;

debug(MEMSTOMP) {} else
{
    // assume Resource data is still available
    r.destroy;
    assert(Resource.outcome == Outcome.notCalled);
}

r = new Resource;
assert(Resource.outcome == Outcome.notCalled);
r.destroy;
assert(Resource.outcome == Outcome.calledManually);

```
 
  static nothrow ulong **allocatedInCurrentThread**();  
Returns the number of bytes allocated for the current thread since program start. It is the same as GC.stats().allocatedInCurrentThread, but faster.



Examples:
Using allocatedInCurrentThread 
```
ulong currentlyAllocated = GC.allocatedInCurrentThread();
struct DataStruct
{
    long l1;
    long l2;
    long l3;
    long l4;
}
DataStruct* unused = new DataStruct;
assert(GC.allocatedInCurrentThread() == currentlyAllocated + 32);
assert(GC.stats().allocatedInCurrentThread == currentlyAllocated + 32);

```
 
    pure nothrow @nogc @trusted void\* **pureMalloc**()(size\_t size);   
  
pure nothrow @nogc @trusted void\* **pureCalloc**()(size\_t nmemb, size\_t size);   
  
pure nothrow @nogc @system void\* **pureRealloc**()(void\* ptr, size\_t size);   
  
pure nothrow @nogc @system void **pureFree**()(void\* ptr);  
Pure variants of C's memory allocation functions `malloc`, `calloc`, and `realloc` and deallocation function `free`. 


UNIX 98 requires that errno be set to ENOMEM upon failure. Purity is achieved by saving and restoring the value of `errno`, thus behaving as if it were never changed. 

 
See Also:

[D's rules for purity](https://dlang.org/spec/function.html#pure-functions), which allow for memory allocation under specific circumstances.
 
Examples:


```
ubyte[] fun(size_t n) pure
{
    void* p = pureMalloc(n);
    p !is null || n == 0 || assert(0);
    scope(failure) p = pureRealloc(p, 0);
    p = pureRealloc(p, n *= 2);
    p !is null || n == 0 || assert(0);
    return cast(ubyte[]) p[0 .. n];
}

auto buf = fun(100);
assert(buf.length == 200);
pureFree(buf.ptr);

```
 
  @system void **\_\_delete**(T)(ref T x);  
Destroys and then deallocates an object. 


In detail, `__delete(x)` returns with no effect if `x` is `null`. Otherwise, it performs the following actions in sequence: * Calls the destructor `~this()` for the object referred to by `x` (if `x` is a class or interface reference) or for the object pointed to by `x` (if `x` is a pointer to a `struct`). Arrays of structs call the destructor, if defined, for each element in the array. If no destructor is defined, this step has no effect.
* Frees the memory allocated for `x`. If `x` is a reference to a class or interface, the memory allocated for the underlying instance is freed. If `x` is a pointer, the memory allocated for the pointed-to object is freed. If `x` is a built-in array, the memory allocated for the array is freed. If `x` does not refer to memory previously allocated with `new` (or the lower-level equivalents in the GC API), the behavior is undefined.
* Lastly, `x` is set to `null`. Any attempt to read or write the freed memory via other references will result in undefined behavior.

 

 
Note
 Users should prefer [`destroy`](object#destroy) to explicitly finalize objects, and only resort to [`core.memory._delete`](core_memory#_delete) when [`object.destroy`](object_#destroy) wouldn't be a feasible option. 
 
Parameters:


|  |  |
| --- | --- |
| T `x` | aggregate object that should be destroyed |


 
See Also:

[`destroy`](object#destroy), [`core.GC.free`](core_gc#free) 
 
History:
The `delete` keyword allowed to free GC-allocated memory. As this is inherently not `@safe`, it has been deprecated. This function has been added to provide an easy transition from `delete`. It performs the same functionality as the former `delete` keyword.
 
Examples:
Deleting classes 
```
bool dtorCalled;
class B
{
    int test;
    ~this()
    {
        dtorCalled = true;
    }
}
B b = new B();
B a = b;
b.test = 10;

assert(GC.addrOf(cast(void*) b) != null);
__delete(b);
assert(b is null);
assert(dtorCalled);
assert(GC.addrOf(cast(void*) b) == null);
// but be careful, a still points to it
assert(a !is null);
assert(GC.addrOf(cast(void*) a) == null); // but not a valid GC pointer

```
 
 
Examples:
Deleting interfaces 
```
bool dtorCalled;
interface A
{
    int quack();
}
class B : A
{
    int a;
    int quack()
    {
        a++;
        return a;
    }
    ~this()
    {
        dtorCalled = true;
    }
}
A a = new B();
a.quack();

assert(GC.addrOf(cast(void*) a) != null);
__delete(a);
assert(a is null);
assert(dtorCalled);
assert(GC.addrOf(cast(void*) a) == null);

```
 
 
Examples:
Deleting structs 
```
bool dtorCalled;
struct A
{
    string test;
    ~this()
    {
        dtorCalled = true;
    }
}
auto a = new A("foo");

assert(GC.addrOf(cast(void*) a) != null);
__delete(a);
assert(a is null);
assert(dtorCalled);
assert(GC.addrOf(cast(void*) a) == null);

```
 
 
Examples:
Deleting arrays 
```
int[] a = [1, 2, 3];
auto b = a;

assert(GC.addrOf(b.ptr) != null);
__delete(b);
assert(b is null);
assert(GC.addrOf(b.ptr) == null);
// but be careful, a still points to it
assert(a !is null);
assert(GC.addrOf(a.ptr) == null); // but not a valid GC pointer

```
 
 
Examples:
Deleting arrays of structs 
```
int dtorCalled;
struct A
{
    int a;
    ~this()
    {
        assert(dtorCalled == a);
        dtorCalled++;
    }
}
auto arr = [A(1), A(2), A(3)];
arr[0].a = 2;
arr[1].a = 1;
arr[2].a = 0;

assert(GC.addrOf(arr.ptr) != null);
__delete(arr);
assert(dtorCalled == 3);
assert(GC.addrOf(arr.ptr) == null);

```
 
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_memory.html>

core.stdc.errno
===============

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<errno.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Alex Rønne Petersen 
 
Source
 <https://github.com/dlang/druntime/blob/master/src/core/stdc/errno.d> 
 
Standards:
ISO/IEC 9899:1999 (E)
 
enum int **EPERM**;  enum int **ENOENT**;  enum int **ESRCH**;  enum int **EINTR**;  enum int **EIO**;  enum int **ENXIO**;  enum int **E2BIG**;  enum int **ENOEXEC**;  enum int **EBADF**;  enum int **ECHILD**;  enum int **EAGAIN**;  enum int **ENOMEM**;  enum int **EACCES**;  enum int **EFAULT**;  enum int **ENOTBLK**;  enum int **EBUSY**;  enum int **EEXIST**;  enum int **EXDEV**;  enum int **ENODEV**;  enum int **ENOTDIR**;  enum int **EISDIR**;  enum int **EINVAL**;  enum int **ENFILE**;  enum int **EMFILE**;  enum int **ENOTTY**;  enum int **ETXTBSY**;  enum int **EFBIG**;  enum int **ENOSPC**;  enum int **ESPIPE**;  enum int **EROFS**;  enum int **EMLINK**;  enum int **EPIPE**;  enum int **EDOM**;  enum int **ERANGE**;  enum int **EDEADLK**;  enum int **ENAMETOOLONG**;  enum int **ENOLCK**;  enum int **ENOSYS**;  enum int **ENOTEMPTY**;  enum int **ELOOP**;  enum int **EWOULDBLOCK**;  enum int **ENOMSG**;  enum int **EIDRM**;  enum int **ECHRNG**;  enum int **EL2NSYNC**;  enum int **EL3HLT**;  enum int **EL3RST**;  enum int **ELNRNG**;  enum int **EUNATCH**;  enum int **ENOCSI**;  enum int **EL2HLT**;  enum int **EBADE**;  enum int **EBADR**;  enum int **EXFULL**;  enum int **ENOANO**;  enum int **EBADRQC**;  enum int **EBADSLT**;  enum int **EDEADLOCK**;  enum int **EBFONT**;  enum int **ENOSTR**;  enum int **ENODATA**;  enum int **ETIME**;  enum int **ENOSR**;  enum int **ENONET**;  enum int **ENOPKG**;  enum int **EREMOTE**;  enum int **ENOLINK**;  enum int **EADV**;  enum int **ESRMNT**;  enum int **ECOMM**;  enum int **EPROTO**;  enum int **EMULTIHOP**;  enum int **EDOTDOT**;  enum int **EBADMSG**;  enum int **EOVERFLOW**;  enum int **ENOTUNIQ**;  enum int **EBADFD**;  enum int **EREMCHG**;  enum int **ELIBACC**;  enum int **ELIBBAD**;  enum int **ELIBSCN**;  enum int **ELIBMAX**;  enum int **ELIBEXEC**;  enum int **EILSEQ**;  enum int **ERESTART**;  enum int **ESTRPIPE**;  enum int **EUSERS**;  enum int **ENOTSOCK**;  enum int **EDESTADDRREQ**;  enum int **EMSGSIZE**;  enum int **EPROTOTYPE**;  enum int **ENOPROTOOPT**;  enum int **EPROTONOSUPPORT**;  enum int **ESOCKTNOSUPPORT**;  enum int **EOPNOTSUPP**;  enum int **ENOTSUP**;  enum int **EPFNOSUPPORT**;  enum int **EAFNOSUPPORT**;  enum int **EADDRINUSE**;  enum int **EADDRNOTAVAIL**;  enum int **ENETDOWN**;  enum int **ENETUNREACH**;  enum int **ENETRESET**;  enum int **ECONNABORTED**;  enum int **ECONNRESET**;  enum int **ENOBUFS**;  enum int **EISCONN**;  enum int **ENOTCONN**;  enum int **ESHUTDOWN**;  enum int **ETOOMANYREFS**;  enum int **ETIMEDOUT**;  enum int **ECONNREFUSED**;  enum int **EHOSTDOWN**;  enum int **EHOSTUNREACH**;  enum int **EALREADY**;  enum int **EINPROGRESS**;  enum int **ESTALE**;  enum int **EUCLEAN**;  enum int **ENOTNAM**;  enum int **ENAVAIL**;  enum int **EISNAM**;  enum int **EREMOTEIO**;  enum int **EDQUOT**;  enum int **ENOMEDIUM**;  enum int **EMEDIUMTYPE**;  enum int **ECANCELED**;  enum int **ENOKEY**;  enum int **EKEYEXPIRED**;  enum int **EKEYREVOKED**;  enum int **EKEYREJECTED**;  enum int **EOWNERDEAD**;  enum int **ENOTRECOVERABLE**;  enum int **ERFKILL**;  enum int **EHWPOISON**;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_errno.html>

core.stdc.stdarg
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<stdarg.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Hauke Duden 
 
Standards:
ISO/IEC 9899:1999 (E) 
 
Source
 [core/stdc/stdarg.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/stdarg.d)

 
alias **va\_list** = \_\_va\_list\_tag\*;  
The argument pointer type.

  public import core.internal.vararg.sysv\_x64 : **\_\_va\_list**, **\_\_va\_list\_tag**;  
The argument pointer type.

  void **va\_start**(T)(out va\_list ap, ref T parmn);  
Initialize ap. parmn should be the last named parameter.

  T **va\_arg**(T)(ref va\_list ap);  
Retrieve and return the next value that is of type T.

  void **va\_arg**(T)(ref va\_list ap, ref T parmn);  
Retrieve and store in parmn the next value that is of type T.

  nothrow @nogc @system void **va\_end**(va\_list ap);  
End use of ap.

  nothrow @nogc @system void **va\_copy**(out va\_list dest, va\_list src, void\* storage = alloca(\_\_va\_list\_tag.sizeof));  
Make a copy of ap.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_stdarg.html>

etc.c.curl
==========

 This is an interface to the libcurl library. 


Converted to D from curl headers by [htod](http://www.digitalmars.com/d/2.0/htod.html) and cleaned up by Jonas Drewsen (jdrewsen)   
  
 Windows x86 note: A DMD compatible libcurl static library can be downloaded from the dlang.org [download page](http://dlang.org/download.html).   
  
 Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.   
  
 This software is licensed as described in the file COPYING, which you should have received as part of this distribution. The terms are also available at <http://curl.haxx.se/docs/copyright.html>.   
  
 You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software, and permit persons to whom the Software is furnished to do so, under the terms of the COPYING file.   
  
 This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.

 
enum string **LIBCURL\_COPYRIGHT**;  
This is the global package copyright

  enum string **LIBCURL\_VERSION**;  
This is the version number of the libcurl package from which this header file origins:

  enum int **LIBCURL\_VERSION\_MAJOR**;   
  
enum int **LIBCURL\_VERSION\_MINOR**;   
  
enum int **LIBCURL\_VERSION\_PATCH**;  
The numeric version number is also available "in parts" by using these constants

  enum int **LIBCURL\_VERSION\_NUM**;  
This is the numeric version of the libcurl version number, meant for easier parsing and comparions by programs. The LIBCURL\_VERSION\_NUM define will always follow this syntax: 


0xXXYYZZ   
  
 Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07".   
  
 This 6-digit (24 bits) hexadecimal number does not show pre-release number, and it is always a greater number in a more recent release. It makes comparisons with greater than and less than work.

  enum string **LIBCURL\_TIMESTAMP**;  
This is the date and time when the full source package was created. The timestamp is not stored in git, as the timestamp is properly set in the tarballs by the maketgz script. 


The format of the date should follow this template:   
  
 "Mon Feb 12 11:35:33 UTC 2007"

  alias **curl\_off\_t** = long;  
Data type definition of curl\_off\_t. 


jdrewsen - Always 64bit signed and that is what long is in D.   
  
 Comment below is from curlbuild.h:   
  
 NOTE 2:   
  
 For any given platform/compiler curl\_off\_t must be typedef'ed to a 64-bit wide signed integral data type. The width of this data type must remain constant and independent of any possible large file support settings.   
  
 As an exception to the above, curl\_off\_t shall be typedef'ed to a 32-bit wide signed integral data type if there is no 64-bit type.

  alias **CURL** = void;  alias **curl\_socket\_t** = std.socket.socket\_t;  
jdrewsen - Get socket alias from std.socket

  struct **curl\_httppost**;   
curl\_httppost\* **next**;  
next entry in the list

  char\* **name**;  
pointer to allocated name

  c\_long **namelength**;  
length of name length

  char\* **contents**;  
pointer to allocated data contents

  c\_long **contentslength**;  
length of contents field

  char\* **buffer**;  
pointer to allocated buffer contents

  c\_long **bufferlength**;  
length of buffer field

  char\* **contenttype**;  
Content-Type

  curl\_slist\* **contentheader**;  
list of extra headers for this form

  curl\_httppost\* **more**;  
if one field name has more than one file, this link should link to following files

  c\_long **flags**;  
as defined below

  char\* **showfilename**;  
The file name to show. If not set, the actual file name will be used (if this is a file part)

  void\* **userp**;  
custom pointer used for HTTPPOST\_CALLBACK posts

    enum int **HTTPPOST\_FILENAME**;  
specified content is a file name

  enum int **HTTPPOST\_READFILE**;  
specified content is a file name

  enum int **HTTPPOST\_PTRNAME**;  
name is only stored pointer do not free in formfree

  enum int **HTTPPOST\_PTRCONTENTS**;  
contents is only stored pointer do not free in formfree

  enum int **HTTPPOST\_BUFFER**;  
upload file from buffer

  enum int **HTTPPOST\_PTRBUFFER**;  
upload file from pointer contents

  enum int **HTTPPOST\_CALLBACK**;  
upload file contents by using the regular read callback to get the data and pass the given pointer as custom pointer

  alias **curl\_progress\_callback** = int function(void\* clientp, double dltotal, double dlnow, double ultotal, double ulnow);  enum int **CURL\_MAX\_WRITE\_SIZE**;  
Tests have proven that 20K is a very bad buffer size for uploads on Windows, while 16K for some odd reason performed a lot better. We do the ifndef check to allow this value to easier be changed at build time for those who feel adventurous. The practical minimum is about 400 bytes since libcurl uses a buffer of this size as a scratch area (unrelated to network send operations).

  enum int **CURL\_MAX\_HTTP\_HEADER**;  
The only reason to have a max limit for this is to avoid the risk of a bad server feeding libcurl with a never-ending header that will cause reallocs infinitely

  enum int **CURL\_WRITEFUNC\_PAUSE**;  
This is a magic return code for the write callback that, when returned, will signal libcurl to pause receiving on the current transfer.

  alias **curl\_write\_callback** = ulong function(char\* buffer, ulong size, ulong nitems, void\* outstream);  enum **CurlFileType**: int;  
enumeration of file types

 
**file** **directory** **symlink** **device\_block** **device\_char** **namedpipe** **socket** **door** **unknown** 
is possible only on Sun Solaris now

    alias **curlfiletype** = int;  enum **CurlFInfoFlagKnown**: int;   
**filename** **filetype** **time** **perm** **uid** **gid** **size** **hlinkcount**   struct **\_N2**;  
Content of this structure depends on information which is known and is achievable (e.g. by FTP LIST parsing). Please see the url\_easy\_setopt(3) man page for callbacks returning this structure -- some fields are mandatory, some others are optional. The FLAG field has special meaning. 


If some of these fields is not NULL, it is a pointer to b\_data.

 
char\* **time**;  char\* **perm**;  char\* **user**;  char\* **group**;  char\* **target**;  
pointer to the target filename of a symlink

    struct **curl\_fileinfo**;  
Content of this structure depends on information which is known and is achievable (e.g. by FTP LIST parsing). Please see the url\_easy\_setopt(3) man page for callbacks returning this structure -- some fields are mandatory, some others are optional. The FLAG field has special meaning.

 
char\* **filename**;  curlfiletype **filetype**;  time\_t **time**;  uint **perm**;  int **uid**;  int **gid**;  curl\_off\_t **size**;  c\_long **hardlinks**;  \_N2 **strings**;  uint **flags**;  char\* **b\_data**;  size\_t **b\_size**;  size\_t **b\_used**;    enum **CurlChunkBgnFunc**: int;  
return codes for CURLOPT\_CHUNK\_BGN\_FUNCTION

 
**ok** **fail** 
tell the lib to end the task

  **skip** 
skip this chunk over

    alias **curl\_chunk\_bgn\_callback** = long function(const(void)\* transfer\_info, void\* ptr, int remains);  
if splitting of data transfer is enabled, this callback is called before download of an individual chunk started. Note that parameter "remains" works only for FTP wildcard downloading (for now), otherwise is not used

  enum **CurlChunkEndFunc**: int;  
return codes for CURLOPT\_CHUNK\_END\_FUNCTION

 
**ok** **fail**   alias **curl\_chunk\_end\_callback** = long function(void\* ptr);  
If splitting of data transfer is enabled this callback is called after download of an individual chunk finished. Note! After this callback was set then it have to be called FOR ALL chunks. Even if downloading of this chunk was skipped in CHUNK\_BGN\_FUNC. This is the reason why we don't need "transfer\_info" parameter in this callback and we are not interested in "remains" parameter too.

  enum **CurlFnMAtchFunc**: int;  
return codes for FNMATCHFUNCTION

 
**match** **nomatch** **fail**   alias **curl\_fnmatch\_callback** = int function(void\* ptr, in char\* pattern, in char\* string);  
callback type for wildcard downloading pattern matching. If the string matches the pattern, return CURL\_FNMATCHFUNC\_MATCH value, etc.

  enum **CurlSeekPos**: int;  
seek whence...

 
**set** **current** **end**   enum **CurlSeek**: int;  
These are the return codes for the seek callbacks

 
**ok** **fail** 
fail the entire transfer

  **cantseek** 
tell libcurl seeking can't be done, so libcurl might try other means instead

    alias **curl\_seek\_callback** = int function(void\* instream, long offset, int origin);  enum **CurlReadFunc**: int;   
**abort** 
This is a return code for the read callback that, when returned, will signal libcurl to immediately abort the current transfer.

  **pause** 
This is a return code for the read callback that, when returned, will const signal libcurl to pause sending data on the current transfer.

    alias **curl\_read\_callback** = ulong function(char\* buffer, ulong size, ulong nitems, void\* instream);  enum **CurlSockType**: int;   
**ipcxn** 
socket created for a specific IP connection

  **last** 
never use

    alias **curlsocktype** = int;  alias **curl\_sockopt\_callback** = int function(void\* clientp, socket\_t curlfd, int purpose);  struct **curl\_sockaddr**;  
addrlen was a socklen\_t type before 7.18.0 but it turned really ugly and painful on the systems that lack this type

 
int **family**;  int **socktype**;  int **protocol**;  uint **addrlen**;  
addrlen was a socklen\_t type before 7.18.0 but it turned really ugly and painful on the systems that lack this type

  sockaddr **addr**;    alias **curl\_opensocket\_callback** = socket\_t function(void\* clientp, int purpose, curl\_sockaddr\* address);  enum **CurlIoError**: int;   
**ok** 
I/O operation successful

  **unknowncmd** 
command was unknown to callback

  **failrestart** 
failed to restart the read

  **last** 
never use

    alias **curlioerr** = int;  enum **CurlIoCmd**: int;   
**nop** 
command was unknown to callback

  **restartread** 
failed to restart the read

  **last** 
never use

    alias **curliocmd** = int;  alias **curl\_ioctl\_callback** = int function(void\* handle, int cmd, void\* clientp);  alias **curl\_malloc\_callback** = void\* function(ulong size);   
  
alias **curl\_free\_callback** = void function(void\* ptr);   
  
alias **curl\_realloc\_callback** = void\* function(void\* ptr, ulong size);   
  
alias **curl\_strdup\_callback** = char\* function(in char\* str);   
  
alias **curl\_calloc\_callback** = void\* function(ulong nmemb, ulong size);  
The following typedef's are signatures of malloc, free, realloc, strdup and calloc respectively. Function pointers of these types can be passed to the curl\_global\_init\_mem() function to set user defined memory management callback routines.

  enum **CurlCallbackInfo**: int;  
the kind of data that is passed to information\_callback

 
**text** **header\_in** **header\_out** **data\_in** **data\_out** **ssl\_data\_in** **ssl\_data\_out** **end**   alias **curl\_infotype** = int;  alias **curl\_debug\_callback** = int function(void\* handle, int type, char\* data, ulong size, void\* userptr);  enum **CurlError**: int;  
All possible error codes from all sorts of curl functions. Future versions may return other values, stay prepared. 


Always add new return codes last. Never *EVER* remove any. The return codes must remain the same!

 
**ok** **unsupported\_protocol** 
1

  **failed\_init** 
2

  **url\_malformat** 
3

  **not\_built\_in** 
4 - [was obsoleted in August 2007 for 7.17.0, reused in April 2011 for 7.21.5]

  **couldnt\_resolve\_proxy** 
5

  **couldnt\_resolve\_host** 
6

  **couldnt\_connect** 
7

  **ftp\_weird\_server\_reply** 
8

  **remote\_access\_denied** 
9 a service was denied by the server due to lack of access - when login fails this is not returned.

  **obsolete10** 
10 - NOT USED

  **ftp\_weird\_pass\_reply** 
11

  **obsolete12** 
12 - NOT USED

  **ftp\_weird\_pasv\_reply** 
13

  **ftp\_weird\_227\_format** 
14

  **ftp\_cant\_get\_host** 
15

  **obsolete16** 
16 - NOT USED

  **ftp\_couldnt\_set\_type** 
17

  **partial\_file** 
18

  **ftp\_couldnt\_retr\_file** 
19

  **obsolete20** 
20 - NOT USED

  **quote\_error** 
21 - quote command failure

  **http\_returned\_error** 
22

  **write\_error** 
23

  **obsolete24** 
24 - NOT USED

  **upload\_failed** 
25 - failed upload "command"

  **read\_error** 
26 - couldn't open/read from file

  **out\_of\_memory** 
27

  **operation\_timedout** 

Note
 CURLE\_OUT\_OF\_MEMORY may sometimes indicate a conversion error instead of a memory allocation error if CURL\_DOES\_CONVERSIONS is defined 
 28 - the timeout time was reached  **obsolete29** 
29 - NOT USED

  **ftp\_port\_failed** 
30 - FTP PORT operation failed

  **ftp\_couldnt\_use\_rest** 
31 - the REST command failed

  **obsolete32** 
32 - NOT USED

  **range\_error** 
33 - RANGE "command" didn't work

  **http\_post\_error** 
34

  **ssl\_connect\_error** 
35 - wrong when connecting with SSL

  **bad\_download\_resume** 
36 - couldn't resume download

  **file\_couldnt\_read\_file** 
37

  **ldap\_cannot\_bind** 
38

  **ldap\_search\_failed** 
39

  **obsolete40** 
40 - NOT USED

  **function\_not\_found** 
41

  **aborted\_by\_callback** 
42

  **bad\_function\_argument** 
43

  **obsolete44** 
44 - NOT USED

  **interface\_failed** 
45 - CURLOPT\_INTERFACE failed

  **obsolete46** 
46 - NOT USED

  **too\_many\_redirects** 
47 - catch endless re-direct loops

  **unknown\_option** 
48 - User specified an unknown option

  **telnet\_option\_syntax** 
49 - Malformed telnet option

  **obsolete50** 
50 - NOT USED

  **peer\_failed\_verification** 
51 - peer's certificate or fingerprint wasn't verified fine

  **got\_nothing** 
52 - when this is a specific error

  **ssl\_engine\_notfound** 
53 - SSL crypto engine not found

  **ssl\_engine\_setfailed** 
54 - can not set SSL crypto engine as default

  **send\_error** 
55 - failed sending network data

  **recv\_error** 
56 - failure in receiving network data

  **obsolete57** 
57 - NOT IN USE

  **ssl\_certproblem** 
58 - problem with the local certificate

  **ssl\_cipher** 
59 - couldn't use specified cipher

  **ssl\_cacert** 
60 - problem with the CA cert (path?)

  **bad\_content\_encoding** 
61 - Unrecognized transfer encoding

  **ldap\_invalid\_url** 
62 - Invalid LDAP URL

  **filesize\_exceeded** 
63 - Maximum file size exceeded

  **use\_ssl\_failed** 
64 - Requested FTP SSL level failed

  **send\_fail\_rewind** 
65 - Sending the data requires a rewind that failed

  **ssl\_engine\_initfailed** 
66 - failed to initialise ENGINE

  **login\_denied** 
67 - user, password or similar was not accepted and we failed to login

  **tftp\_notfound** 
68 - file not found on server

  **tftp\_perm** 
69 - permission problem on server

  **remote\_disk\_full** 
70 - out of disk space on server

  **tftp\_illegal** 
71 - Illegal TFTP operation

  **tftp\_unknownid** 
72 - Unknown transfer ID

  **remote\_file\_exists** 
73 - File already exists

  **tftp\_nosuchuser** 
74 - No such user

  **conv\_failed** 
75 - conversion failed

  **conv\_reqd** 
76 - caller must register conversion callbacks using curl\_easy\_setopt options CURLOPT\_CONV\_FROM\_NETWORK\_FUNCTION, CURLOPT\_CONV\_TO\_NETWORK\_FUNCTION, and CURLOPT\_CONV\_FROM\_UTF8\_FUNCTION

  **ssl\_cacert\_badfile** 
77 - could not load CACERT file, missing or wrong format

  **remote\_file\_not\_found** 
78 - remote file not found

  **ssh** 
79 - error from the SSH layer, somewhat generic so the error message will be of interest when this has happened

  **ssl\_shutdown\_failed** 
80 - Failed to shut down the SSL connection

  **again** 
81 - socket is not ready for send/recv, wait till it's ready and try again (Added in 7.18.2)

  **ssl\_crl\_badfile** 
82 - could not load CRL file, missing or wrong format (Added in 7.19.0)

  **ssl\_issuer\_error** 
83 - Issuer check failed. (Added in 7.19.0)

  **ftp\_pret\_failed** 
84 - a PRET command failed

  **rtsp\_cseq\_error** 
85 - mismatch of RTSP CSeq numbers

  **rtsp\_session\_error** 
86 - mismatch of RTSP Session Identifiers

  **ftp\_bad\_file\_list** 
87 - unable to parse FTP file list

  **chunk\_failed** 
88 - chunk callback reported error

  **curl\_last** 
never use!

    alias **CURLcode** = int;  alias **curl\_conv\_callback** = int function(char\* buffer, ulong length);  
This prototype applies to all conversion callbacks

  alias **curl\_ssl\_ctx\_callback** = int function(void\* curl, void\* ssl\_ctx, void\* userptr);  
actually an OpenSSL SSL\_CTX

  enum **CurlProxy**: int;   
**http** 
added in 7.10, new in 7.19.4 default is to use CONNECT HTTP/1.1

  **http\_1\_0** 
added in 7.19.4, force to use CONNECT HTTP/1.0

  **socks4** 
support added in 7.15.2, enum existed already in 7.10

  **socks5** 
added in 7.10

  **socks4a** 
added in 7.18.0

  **socks5\_hostname** 
Use the SOCKS5 protocol but pass along the host name rather than the IP address. added in 7.18.0

    alias **curl\_proxytype** = int;  enum **CurlAuth**: long;   
**basic** 
Basic (default)

  **digest** 
Digest

  **gssnegotiate** 
GSS-Negotiate

  **ntlm** 
NTLM

  **digest\_ie** 
Digest with IE flavour

  **only** 
used together with a single other type to force no auth or just that single type

  **any** 
all fine types set

  **anysafe**   enum **CurlSshAuth**: int;   
**any** 
all types supported by the server

  **none** 
none allowed, silly but complete

  **publickey** 
public/private key files

  **password** 
password

  **host** 
host key files

  **keyboard** 
keyboard interactive

    enum int **CURL\_ERROR\_SIZE**;  enum **CurlKHType**: int;  
points to a zero-terminated string encoded with base64 if len is zero, otherwise to the "raw" data

 
**unknown** **rsa1** **rsa** **dss**   struct **curl\_khkey**;   
const(char)\* **key**;  
points to a zero-terminated string encoded with base64 if len is zero, otherwise to the "raw" data

  size\_t **len**;  CurlKHType **keytype**;    enum **CurlKHStat**: int;  
this is the set of return values expected from the curl\_sshkeycallback callback

 
**fine\_add\_to\_file** **fine** **reject** 
reject the connection, return an error

  **defer** 
do not accept it, but we can't answer right now so this causes a CURLE\_DEFER error but otherwise the connection will be left intact etc

  **last** 
not for use, only a marker for last-in-list

    enum **CurlKHMatch**: int;  
this is the set of status codes pass in to the callback

 
**ok** 
match

  **mismatch** 
host found, key mismatch!

  **missing** 
no matching host/key found

  **last** 
not for use, only a marker for last-in-list

    alias **curl\_sshkeycallback** = int function(void\* easy, const(curl\_khkey)\* knownkey, const(curl\_khkey)\* foundkey, CurlKHMatch m, void\* clientp);  enum **CurlUseSSL**: int;  
parameter for the CURLOPT\_USE\_SSL option

 
**none** 
do not attempt to use SSL

  **tryssl** 
try using SSL, proceed anyway otherwise

  **control** 
SSL for the control connection or fail

  **all** 
SSL for all communication or fail

  **last** 
not an option, never use

    alias **curl\_usessl** = int;  enum **CurlFtpSSL**: int;  
parameter for the CURLOPT\_FTP\_SSL\_CCC option

 
**ccc\_none** 
do not send CCC

  **ccc\_passive** 
Let the server initiate the shutdown

  **ccc\_active** 
Initiate the shutdown

  **ccc\_last** 
not an option, never use

    alias **curl\_ftpccc** = int;  enum **CurlFtpAuth**: int;  
parameter for the CURLOPT\_FTPSSLAUTH option

 
**defaultauth** 
let libcurl decide

  **ssl** 
use "AUTH SSL"

  **tls** 
use "AUTH TLS"

  **last** 
not an option, never use

    alias **curl\_ftpauth** = int;  enum **CurlFtp**: int;  
parameter for the CURLOPT\_FTP\_CREATE\_MISSING\_DIRS option

 
**create\_dir\_none** 
do NOT create missing dirs!

  **create\_dir** 
(FTP/SFTP) if CWD fails, try MKD and then CWD again if MKD succeeded, for SFTP this does similar magic

  **create\_dir\_retry** 
(FTP only) if CWD fails, try MKD and then CWD again even if MKD failed!

  **create\_dir\_last** 
not an option, never use

    alias **curl\_ftpcreatedir** = int;  enum **CurlFtpMethod**: int;  
parameter for the CURLOPT\_FTP\_FILEMETHOD option

 
**defaultmethod** 
let libcurl pick

  **multicwd** 
single CWD operation for each path part

  **nocwd** 
no CWD at all

  **singlecwd** 
one CWD to full dir, then work on file

  **last** 
not an option, never use

    alias **curl\_ftpmethod** = int;  enum **CurlProto**: int;  
CURLPROTO\_ defines are for the CURLOPT\_\*PROTOCOLS options

 
**http** **https** **ftp** **ftps** **scp** **sftp** **telnet** **ldap** **ldaps** **dict** **file** **tftp** **imap** **imaps** **pop3** **pop3s** **smtp** **smtps** **rtsp** **rtmp** **rtmpt** **rtmpe** **rtmpte** **rtmps** **rtmpts** **gopher** **all** 
enable everything

    enum int **CURLOPTTYPE\_LONG**;   
  
enum int **CURLOPTTYPE\_OBJECTPOINT**;   
  
enum int **CURLOPTTYPE\_FUNCTIONPOINT**;   
  
enum int **CURLOPTTYPE\_OFF\_T**;  
long may be 32 or 64 bits, but we should never depend on anything else but 32

  alias **LONG** = CURLOPTTYPE\_LONG;   
  
alias **OBJECTPOINT** = CURLOPTTYPE\_OBJECTPOINT;   
  
alias **FUNCTIONPOINT** = CURLOPTTYPE\_FUNCTIONPOINT;   
  
alias **OFF\_T** = CURLOPTTYPE\_OFF\_T;  
name is uppercase CURLOPT\_<name>, type is one of the defined CURLOPTTYPE\_<type> number is unique identifier 


The macro "##" is ISO C, we assume pre-ISO C doesn't support it.

  enum **CurlOption**: int;   
**file** 
This is the FILE \* or void \* the regular output should be written to.

  **url** 
The full URL to get/put

  **port** 
Port number to connect to, if other than default.

  **proxy** 
Name of proxy to use.

  **userpwd** 
"name:password" to use when fetching.

  **proxyuserpwd** 
"name:password" to use with proxy.

  **range** 
Range to get, specified as an ASCII string.

  **infile** 
not used 


Specified file stream to upload from (use as input):

  **errorbuffer** 
Buffer to receive error messages in, must be at least CURL\_ERROR\_SIZE bytes big. If this is not used, error messages go to stderr instead:

  **writefunction** 
Function that will be called to store the output (instead of fwrite). The parameters will use fwrite() syntax, make sure to follow them.

  **readfunction** 
Function that will be called to read the input (instead of fread). The parameters will use fread() syntax, make sure to follow them.

  **timeout** 
Time-out the read operation after this amount of seconds

  **infilesize** 
If the CURLOPT\_INFILE is used, this can be used to inform libcurl about how large the file being sent really is. That allows better error checking and better verifies that the upload was successful. -1 means unknown size. 


For large file support, there is also a LARGE version of the key which takes an off\_t type, allowing platforms with larger off\_t sizes to handle larger files. See below for INFILESIZE\_LARGE.

  **postfields** 
POST static input fields.

  **referer** 
Set the referrer page (needed by some CGIs)

  **ftpport** 
Set the FTP PORT string (interface name, named or numerical IP address) Use i.e '-' to use default address.

  **useragent** 
Set the User-Agent string (examined by some CGIs)

  **low\_speed\_limit** 
If the download receives less than "low speed limit" bytes/second during "low speed time" seconds, the operations is aborted. You could i.e if you have a pretty high speed connection, abort if it is less than 2000 bytes/sec during 20 seconds. 


Set the "low speed limit"

  **low\_speed\_time** 
Set the "low speed time"

  **resume\_from** 
Set the continuation offset. 


Note there is also a LARGE version of this key which uses off\_t types, allowing for large file offsets on platforms which use larger-than-32-bit off\_t's. Look below for RESUME\_FROM\_LARGE.

  **cookie** 
Set cookie in request:

  **httpheader** 
This points to a linked list of headers, struct curl\_slist kind

  **httppost** 
This points to a linked list of post entries, struct curl\_httppost

  **sslcert** 
name of the file keeping your private SSL-certificate

  **keypasswd** 
password for the SSL or SSH private key

  **crlf** 
send TYPE parameter?

  **quote** 
send linked-list of QUOTE commands

  **writeheader** 
send FILE \* or void \* to store headers to, if you use a callback it is simply passed to the callback unmodified

  **cookiefile** 
point to a file to read the initial cookies from, also enables "cookie awareness"

  **sslversion** 
What version to specifically try to use. See CURL\_SSLVERSION defines below.

  **timecondition** 
What kind of HTTP time condition to use, see defines

  **timevalue** 
Time to use with the above condition. Specified in number of seconds since 1 Jan 1970

  **customrequest** 
Custom request, for customizing the get command like 



HTTP
 DELETE, TRACE and others 
 
FTP
 to use a different list command
  **stderr** 
HTTP request, for odd commands like DELETE, TRACE and others

  **postquote** 
send linked-list of post-transfer QUOTE commands

  **writeinfo** 
Pass a pointer to string of the output using full variable-replacement as described elsewhere.

  **verbose** 
talk a lot

  **header** 
throw the header out too

  **noprogress** 
shut off the progress meter

  **nobody** 
use HEAD to get http document

  **failonerror** 
no output on http error codes >= 300

  **upload** 
this is an upload

  **post** 
HTTP POST method

  **dirlistonly** 
return bare names when listing directories

  **append** 
Append instead of overwrite on upload!

  **netrc** 
Specify whether to read the user+password from the .netrc or the URL. This must be one of the CURL\_NETRC\_\* enums below.

  **followlocation** 
use Location: Luke!

  **transfertext** 
transfer data in text/ASCII format

  **put** 
HTTP PUT

  **progressfunction** 
Function that will be called instead of the internal progress display function. This function should be defined as the curl\_progress\_callback prototype defines.

  **progressdata** 
Data passed to the progress callback

  **autoreferer** 
We want the referrer field set automatically when following locations

  **proxyport** 
Port of the proxy, can be set in the proxy string as well with: `[host]:[port]`

  **postfieldsize** 
size of the POST input data, if strlen() is not good to use

  **httpproxytunnel** 
tunnel non-http operations through a HTTP proxy

  **intrface** 
Set the interface string to use as outgoing network interface

  **krblevel** 
Set the krb4/5 security level, this also enables krb4/5 awareness. This is a string, 'clear', 'safe', 'confidential' or 'private'. If the string is set but doesn't match one of these, 'private' will be used.

  **ssl\_verifypeer** 
Set if we should verify the peer in ssl handshake, set 1 to verify.

  **cainfo** 
The CApath or CAfile used to validate the peer certificate this option is used only if SSL\_VERIFYPEER is true

  **maxredirs** 
Maximum number of http redirects to follow

  **filetime** 
Pass a long set to 1 to get the date of the requested document (if possible)! Pass a zero to shut it off.

  **telnetoptions** 
This points to a linked list of telnet options

  **maxconnects** 
Max amount of cached alive connections

  **closepolicy** 
What policy to use when closing connections when the cache is filled up

  **fresh\_connect** 
Set to explicitly use a new connection for the upcoming transfer. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network.

  **forbid\_reuse** 
Set to explicitly forbid the upcoming transfer's connection to be re-used when done. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network.

  **random\_file** 
Set to a file name that contains random data for libcurl to use to seed the random engine when doing SSL connects.

  **egdsocket** 
Set to the Entropy Gathering Daemon socket pathname

  **connecttimeout** 
Time-out connect operations after this amount of seconds, if connects are OK within this time, then fine... This only aborts the connect phase. [Only works on unix-style/SIGALRM operating systems]

  **headerfunction** 
Function that will be called to store headers (instead of fwrite). The parameters will use fwrite() syntax, make sure to follow them.

  **httpget** 
Set this to force the HTTP request to get back to GET. Only really usable if POST, PUT or a custom request have been used first.

  **ssl\_verifyhost** 
Set if we should verify the Common name from the peer certificate in ssl handshake, set 1 to check existence, 2 to ensure that it matches the provided hostname.

  **cookiejar** 
Specify which file name to write all known cookies in after completed operation. Set file name to "-" (dash) to make it go to stdout.

  **ssl\_cipher\_list** 
Specify which SSL ciphers to use

  **http\_version** 
Specify which HTTP version to use! This must be set to one of the CURL\_HTTP\_VERSION\* enums set below.

  **ftp\_use\_epsv** 
Specifically switch on or off the FTP engine's use of the EPSV command. By default, that one will always be attempted before the more traditional PASV command.

  **sslcerttype** 
type of the file keeping your SSL-certificate ("DER", "PEM", "ENG")

  **sslkey** 
name of the file keeping your private SSL-key

  **sslkeytype** 
type of the file keeping your private SSL-key ("DER", "PEM", "ENG")

  **sslengine** 
crypto engine for the SSL-sub system

  **sslengine\_default** 
set the crypto engine for the SSL-sub system as default the param has no meaning...

  **dns\_use\_global\_cache** 
Non-zero value means to use the global dns cache

  **dns\_cache\_timeout** 
DNS cache timeout

  **prequote** 
send linked-list of pre-transfer QUOTE commands

  **debugfunction** 
set the debug function

  **debugdata** 
set the data for the debug function

  **cookiesession** 
mark this as start of a cookie session

  **capath** 
The CApath directory used to validate the peer certificate this option is used only if SSL\_VERIFYPEER is true

  **buffersize** 
Instruct libcurl to use a smaller receive buffer

  **nosignal** 
Instruct libcurl to not use any signal/alarm handlers, even when using timeouts. This option is useful for multi-threaded applications. See libcurl-the-guide for more background information.

  **share** 
Provide a CURLShare for mutexing non-ts data

  **proxytype** 
indicates type of proxy. accepted values are CURLPROXY\_HTTP (default), CURLPROXY\_SOCKS4, CURLPROXY\_SOCKS4A and CURLPROXY\_SOCKS5.

  **encoding** 
Set the Accept-Encoding string. Use this to tell a server you would like the response to be compressed.

  **private\_opt** 
Set pointer to private data

  **http200aliases** 
Set aliases for HTTP 200 in the HTTP Response header

  **unrestricted\_auth** 
Continue to send authentication (user+password) when following locations, even when hostname changed. This can potentially send off the name and password to whatever host the server decides.

  **ftp\_use\_eprt** 
Specifically switch on or off the FTP engine's use of the EPRT command ( it also disables the LPRT attempt). By default, those ones will always be attempted before the good old traditional PORT command.

  **httpauth** 
Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT\_USERPWD. Note that setting multiple bits may cause extra network round-trips.

  **ssl\_ctx\_function** 
Set the ssl context callback function, currently only for OpenSSL ssl\_ctx in second argument. The function must be matching the curl\_ssl\_ctx\_callback proto.

  **ssl\_ctx\_data** 
Set the userdata for the ssl context callback function's third argument

  **ftp\_create\_missing\_dirs** 
FTP Option that causes missing dirs to be created on the remote server. In 7.19.4 we introduced the convenience enums for this option using the CURLFTP\_CREATE\_DIR prefix.

  **proxyauth** 
Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT\_PROXYUSERPWD. Note that setting multiple bits may cause extra network round-trips.

  **ftp\_response\_timeout** 
FTP option that changes the timeout, in seconds, associated with getting a response. This is different from transfer timeout time and essentially places a demand on the FTP server to acknowledge commands in a timely manner.

  **ipresolve** 
Set this option to one of the CURL\_IPRESOLVE\_\* defines (see below) to tell libcurl to resolve names to those IP versions only. This only has affect on systems with support for more than one, i.e IPv4 and\_ IPv6.

  **maxfilesize** 
Set this option to limit the size of a file that will be downloaded from an HTTP or FTP server. 


Note there is also LARGE version which adds large file support for platforms which have larger off\_t sizes. See MAXFILESIZE\_LARGE below.

  **infilesize\_large** 
See the comment for INFILESIZE above, but in short, specifies the size of the file being uploaded. -1 means unknown.

  **resume\_from\_large** 
Sets the continuation offset. There is also a LONG version of this; look above for RESUME\_FROM.

  **maxfilesize\_large** 
Sets the maximum size of data that will be downloaded from an HTTP or FTP server. See MAXFILESIZE above for the LONG version.

  **netrc\_file** 
Set this option to the file name of your .netrc file you want libcurl to parse (using the CURLOPT\_NETRC option). If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there.

  **use\_ssl** 
Enable SSL/TLS for FTP, pick one of: CURLFTPSSL\_TRY - try using SSL, proceed anyway otherwise CURLFTPSSL\_CONTROL - SSL for the control connection or fail CURLFTPSSL\_ALL - SSL for all communication or fail

  **postfieldsize\_large** 
The LARGE version of the standard POSTFIELDSIZE option

  **tcp\_nodelay** 
Enable/disable the TCP Nagle algorithm

  **ftpsslauth** 
When FTP over SSL/TLS is selected (with CURLOPT\_USE\_SSL), this option can be used to change libcurl's default action which is to first try "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK response has been received. 


Available parameters are: CURLFTPAUTH\_DEFAULT - let libcurl decide CURLFTPAUTH\_SSL - try "AUTH SSL" first, then TLS CURLFTPAUTH\_TLS - try "AUTH TLS" first, then SSL

  **ioctlfunction** **ioctldata** **ftp\_account** 
zero terminated string for pass on to the FTP server when asked for "account" info

  **cookielist** 
feed cookies into cookie engine

  **ignore\_content\_length** 
ignore Content-Length

  **ftp\_skip\_pasv\_ip** 
Set to non-zero to skip the IP address received in a 227 PASV FTP server response. Typically used for FTP-SSL purposes but is not restricted to that. libcurl will then instead use the same IP address it used for the control connection.

  **ftp\_filemethod** 
Select "file method" to use when doing FTP, see the curl\_ftpmethod above.

  **localport** 
Local port number to bind the socket to

  **localportrange** 
Number of ports to try, including the first one set with LOCALPORT. Thus, setting it to 1 will make no additional attempts but the first.

  **connect\_only** 
no transfer, set up connection and let application use the socket by extracting it with CURLINFO\_LASTSOCKET

  **conv\_from\_network\_function** 
Function that will be called to convert from the network encoding (instead of using the iconv calls in libcurl)

  **conv\_to\_network\_function** 
Function that will be called to convert to the network encoding (instead of using the iconv calls in libcurl)

  **conv\_from\_utf8\_function** 
Function that will be called to convert from UTF8 (instead of using the iconv calls in libcurl) Note that this is used only for SSL certificate processing

  
**max\_send\_speed\_large**  
  
**max\_recv\_speed\_large**
 
If the connection proceeds too quickly then need to slow it down 


limit-rate: maximum number of bytes per second to send or receive

  **ftp\_alternative\_to\_user** 
Pointer to command string to send if USER/PASS fails.

  **sockoptfunction** 
callback function for setting socket options

  **ssl\_sessionid\_cache** 
set to 0 to disable session ID re-use for this transfer, default is enabled (== 1)

  **ssh\_auth\_types** 
allowed SSH authentication methods

  **ssh\_public\_keyfile** 
Used by scp/sftp to do public/private key authentication

  **ftp\_ssl\_ccc** 
Send CCC (Clear Command Channel) after authentication

  
**timeout\_ms**  
  
**connecttimeout\_ms**
 
Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution

  
**http\_transfer\_decoding**  
  
**http\_content\_decoding**
 
set to zero to disable the libcurl's decoding and thus pass the raw body data to the application even when it is encoded/compressed

  
**new\_file\_perms**  
  
**new\_directory\_perms**
 
Permission used when creating new files and directories on the remote server for protocols that support it, SFTP/SCP/FILE

  **postredir** 
Set the behaviour of POST when redirecting. Values must be set to one of CURL\_REDIR\* defines below. This used to be called CURLOPT\_POST301

  **ssh\_host\_public\_key\_md5** 
used by scp/sftp to verify the host's public key

  
**opensocketfunction**  
  
**opensocketdata**
 
Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or refuse to connect returning CURL\_SOCKET\_BAD. The callback should have type curl\_opensocket\_callback

  **copypostfields** 
POST volatile input fields.

  **proxy\_transfer\_mode** 
set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy

  
**seekfunction**  
  
**seekdata**
 
Callback function for seeking in the input stream

  **crlfile** 
CRL file

  **issuercert** 
Issuer certificate

  **address\_scope** 
(IPv6) Address scope

  **certinfo** 
Collect certificate chain info and allow it to get retrievable with CURLINFO\_CERTINFO after the transfer is complete. (Unfortunately) only working with OpenSSL-powered builds.

  
**username**  
  
**password**
 
"name" and "pwd" to use when fetching.

  
**proxyusername**  
  
**proxypassword**
 
"name" and "pwd" to use with Proxy when fetching.

  **noproxy** 
Comma separated list of hostnames defining no-proxy zones. These should match both hostnames directly, and hostnames within a domain. For example, local.com will match local.com and www.local.com, but NOT notlocal.com or www.notlocal.com. For compatibility with other implementations of this, .local.com will be considered to be the same as local.com. A single \* is the only valid wildcard, and effectively disables the use of proxy.

  **tftp\_blksize** 
block size for TFTP transfers

  **socks5\_gssapi\_service** 
Socks Service

  **socks5\_gssapi\_nec** 
Socks Service

  **protocols** 
set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO\_ALL.

  **redir\_protocols** 
set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT\_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. Defaults to all protocols except FILE and SCP.

  **ssh\_knownhosts** 
set the SSH knownhost file name to use

  **ssh\_keyfunction** 
set the SSH host key callback, must point to a curl\_sshkeycallback function

  **ssh\_keydata** 
set the SSH host key callback custom pointer

  **mail\_from** 
set the SMTP mail originator

  **mail\_rcpt** 
set the SMTP mail receiver(s)

  **ftp\_use\_pret** 

FTP
 send PRET before PASV
  **rtsp\_request** 
RTSP request method (OPTIONS, SETUP, PLAY, etc...)

  **rtsp\_session\_id** 
The RTSP session identifier

  **rtsp\_stream\_uri** 
The RTSP stream URI

  **rtsp\_transport** 
The Transport: header to use in RTSP requests

  **rtsp\_client\_cseq** 
Manually initialize the client RTSP CSeq for this handle

  **rtsp\_server\_cseq** 
Manually initialize the server RTSP CSeq for this handle

  **interleavedata** 
The stream to pass to INTERLEAVEFUNCTION.

  **interleavefunction** 
Let the application define a custom write method for RTP data

  **wildcardmatch** 
Turn on wildcard matching

  **chunk\_bgn\_function** 
Directory matching callback called before downloading of an individual file (chunk) started

  **chunk\_end\_function** 
Directory matching callback called after the file (chunk) was downloaded, or skipped

  **fnmatch\_function** 
Change match (fnmatch-like) callback for wildcard matching

  **chunk\_data** 
Let the application define custom chunk data pointer

  **fnmatch\_data** 
FNMATCH\_FUNCTION user pointer

  **resolve** 
send linked-list of name:port:address sets

  **tlsauth\_username** 
Set a username for authenticated TLS

  **tlsauth\_password** 
Set a password for authenticated TLS

  **tlsauth\_type** 
Set authentication type for authenticated TLS

  **lastentry** 
the last unused

  
**writedata**  
  
**readdata**  
  
**headerdata**  
  
**rtspheader**
 
convenient alias

    alias **CURLoption** = int;  enum CurlOption **CURLOPT\_SERVER\_RESPONSE\_TIMEOUT**;  enum **CurlIpResolve**: int;  
Below here follows defines for the CURLOPT\_IPRESOLVE option. If a host name resolves addresses using more than one IP protocol version, this option might be handy to force libcurl to use a specific IP version.

 
**whatever** 
default, resolves addresses to all IP versions that your system allows

  **v4** 
resolve to ipv4 addresses

  **v6** 
resolve to ipv6 addresses

    enum CurlOption **CURLOPT\_WRITEDATA**;   
  
enum CurlOption **CURLOPT\_READDATA**;   
  
enum CurlOption **CURLOPT\_HEADERDATA**;   
  
enum CurlOption **CURLOPT\_RTSPHEADER**;  
three convenient "aliases" that follow the name scheme better

  enum **CurlHttpVersion**: int;  
These enums are for use with the CURLOPT\_HTTP\_VERSION option.

 
**none** 
setting this means we don't care, and that we'd like the library to choose the best possible for us!

  **v1\_0** 
please use HTTP 1.0 in the request

  **v1\_1** 
please use HTTP 1.1 in the request

  **last** 
*ILLEGAL* http version

    enum **CurlRtspReq**: int;  
Public API enums for RTSP requests

 
**none** **options** **describe** **announce** **setup** **play** **pause** **teardown** **get\_parameter** **set\_parameter** **record** **receive** **last**   enum **CurlNetRcOption**: int;  
These enums are for use with the CURLOPT\_NETRC option.

 
**ignored** 
The .netrc will never be read. This is the default.

  **optional** 
A user:password in the URL will be preferred to one in the .netrc.

  **required** 
A user:password in the URL will be ignored. Unless one is set programmatically, the .netrc will be queried.

  **last**   enum **CurlSslVersion**: int;   
**default\_version** **tlsv1** **sslv2** **sslv3** **last** 
never use

    enum **CurlTlsAuth**: int;   
**none** **srp** **last** 
never use

    enum **CurlRedir**: int;  
symbols to use with CURLOPT\_POSTREDIR. CURL\_REDIR\_POST\_301 and CURL\_REDIR\_POST\_302 can be bitwise ORed so that CURL\_REDIR\_POST\_301 | CURL\_REDIR\_POST\_302 == CURL\_REDIR\_POST\_ALL

 
**get\_all** **post\_301** **post\_302** **post\_all**   enum **CurlTimeCond**: int;   
**none** **ifmodsince** **ifunmodsince** **lastmod** **last**   alias **curl\_TimeCond** = int;  int **curl\_strequal**(in const(char)\* s1, in const(char)\* s2);  
curl\_strequal() and curl\_strnequal() are subject for removal in a future libcurl, see lib/README.curlx for details

  int **curl\_strnequal**(in const(char)\* s1, in const(char)\* s2, size\_t n);  
ditto 


curl\_strequal() and curl\_strnequal() are subject for removal in a future libcurl, see lib/README.curlx for details

  struct **curl\_forms**;  
structure to be used as parameter for CURLFORM\_ARRAY

 
CURLformoption **option**;  const(char)\* **value**;    enum **CurlFormAdd**: int;  
Use this for multipart formpost building 


Returns code for curl\_formadd() 

 
Returns:
* CURL\_FORMADD\_OK on success
* CURL\_FORMADD\_MEMORY if the FormInfo allocation fails
* CURL\_FORMADD\_OPTION\_TWICE if one option is given twice for one Form
* CURL\_FORMADD\_NULL if a null pointer was given for a char
* CURL\_FORMADD\_MEMORY if the allocation of a FormInfo struct failed
* CURL\_FORMADD\_UNKNOWN\_OPTION if an unknown option was used
* CURL\_FORMADD\_INCOMPLETE if the some FormInfo is not complete (or error)
* CURL\_FORMADD\_MEMORY if a curl\_httppost struct cannot be allocated
* CURL\_FORMADD\_MEMORY if some allocation for string copying failed.
* CURL\_FORMADD\_ILLEGAL\_ARRAY if an illegal option is used in an array

 
**ok** 
first, no error

  **memory** **option\_twice** **null\_ptr** **unknown\_option** **incomplete** **illegal\_array** **disabled** 
libcurl was built with this disabled

  **last**   alias **CURLFORMcode** = int;  CURLFORMcode **curl\_formadd**(curl\_httppost\*\* httppost, curl\_httppost\*\* last\_post, ...);  

Name
 curl\_formadd() 
 
Description
 Pretty advanced function for building multi-part formposts. Each invoke adds one part that together construct a full post. Then use CURLOPT\_HTTPPOST to send it off to libcurl.
  alias **curl\_formget\_callback** = extern (C) ulong function(void\* arg, in char\* buf, ulong len);  
callback function for curl\_formget() The void \*arg pointer will be the one passed as second argument to curl\_formget(). The character buffer passed to it must not be freed. Should return the buffer length passed to it as the argument "len" on success.

  int **curl\_formget**(curl\_httppost\* form, void\* arg, curl\_formget\_callback append);  

Name
 curl\_formget() 
 
Description
 Serialize a curl\_httppost struct built with curl\_formadd(). Accepts a void pointer as second argument which will be passed to the curl\_formget\_callback function. Returns 0 on success.
  void **curl\_formfree**(curl\_httppost\* form);  

Name
 curl\_formfree() 
 
Description
 Free a multipart formpost previously built with curl\_formadd().
  char\* **curl\_getenv**(in const(char)\* variable);  

Name
 curl\_getenv() 
 
Description
 Returns a malloc()'ed string that MUST be curl\_free()ed after usage is complete. DEPRECATED - see lib/README.curlx
  char\* **curl\_version**();  

Name
 curl\_version() 
 
Description
 Returns a static ascii string of the libcurl version.
  char\* **curl\_easy\_escape**(CURL\* handle, in const(char)\* string, int length);  

Name
 curl\_easy\_escape() 
 
Description
 Escapes URL strings (converts all letters consider illegal in URLs to their %XX versions). This function returns a new allocated string or NULL if an error occurred.
  char\* **curl\_escape**(in const(char)\* string, int length);  
the previous version:

  char\* **curl\_easy\_unescape**(CURL\* handle, in const(char)\* string, int length, int\* outlength);  

Name
 curl\_easy\_unescape() 
 
Description
 Unescapes URL encoding in strings (converts all %XX codes to their 8bit versions). This function returns a new allocated string or NULL if an error occurred. Conversion Note: On non-ASCII platforms the ASCII %XX codes are converted into the host encoding.
  char\* **curl\_unescape**(in const(char)\* string, int length);  
the previous version

  void **curl\_free**(void\* p);  

Name
 curl\_free() 
 
Description
 Provided for de-allocation in the same translation unit that did the allocation. Added in libcurl 7.10
  CURLcode **curl\_global\_init**(c\_long flags);  

Name
 curl\_global\_init() 
 
Description
 curl\_global\_init() should be invoked exactly once for each application that uses libcurl and before any call of other libcurl functions. 
 This function is not thread-safe!  CURLcode **curl\_global\_init\_mem**(c\_long flags, curl\_malloc\_callback m, curl\_free\_callback f, curl\_realloc\_callback r, curl\_strdup\_callback s, curl\_calloc\_callback c);  

Name
 curl\_global\_init\_mem() 
 
Description
 curl\_global\_init() or curl\_global\_init\_mem() should be invoked exactly once for each application that uses libcurl. This function can be used to initialize libcurl and set user defined memory management callback functions. Users can implement memory management routines to check for memory leaks, check for mis-use of the curl library etc. User registered callback routines with be invoked by this library instead of the system memory management routines like malloc, free etc.
  void **curl\_global\_cleanup**();  

Name
 curl\_global\_cleanup() 
 
Description
 curl\_global\_cleanup() should be invoked exactly once for each application that uses libcurl
  struct **curl\_slist**;  
linked-list structure for the CURLOPT\_QUOTE option (and other)

  curl\_slist\* **curl\_slist\_append**(curl\_slist\*, in const(char)\*);  

Name
 curl\_slist\_append() 
 
Description
 Appends a string to a linked list. If no list exists, it will be created first. Returns the new list, after appending. 
 linked-list structure for the CURLOPT\_QUOTE option (and other)  void **curl\_slist\_free\_all**(curl\_slist\*);  

Name
 curl\_slist\_free\_all() 
 
Description
 free a previously built curl\_slist. 
 linked-list structure for the CURLOPT\_QUOTE option (and other)  time\_t **curl\_getdate**(const(char)\* p, const(time\_t)\* unused);  

Name
 curl\_getdate() 
 
Description
 Returns the time, in seconds since 1 Jan 1970 of the time string given in the first argument. The time argument in the second parameter is unused and should be set to NULL. 
 linked-list structure for the CURLOPT\_QUOTE option (and other)  struct **curl\_certinfo**;  
info about the certificate chain, only for OpenSSL builds. Asked for with CURLOPT\_CERTINFO / CURLINFO\_CERTINFO 


linked-list structure for the CURLOPT\_QUOTE option (and other)

 
int **num\_of\_certs**;  
number of certificates with information

  curl\_slist\*\* **certinfo**;  
for each index in this array, there's a linked list with textual information in the format "name: value"

    enum int **CURLINFO\_STRING**;  enum int **CURLINFO\_LONG**;  enum int **CURLINFO\_DOUBLE**;  enum int **CURLINFO\_SLIST**;  enum int **CURLINFO\_MASK**;  enum int **CURLINFO\_TYPEMASK**;  enum **CurlInfo**: int;   
**none** **effective\_url** **response\_code** **total\_time** **namelookup\_time** **connect\_time** **pretransfer\_time** **size\_upload** **size\_download** **speed\_download** **speed\_upload** **header\_size** **request\_size** **ssl\_verifyresult** **filetime** **content\_length\_download** **content\_length\_upload** **starttransfer\_time** **content\_type** **redirect\_time** **redirect\_count** **private\_info** **http\_connectcode** **httpauth\_avail** **proxyauth\_avail** **os\_errno** **num\_connects** **ssl\_engines** **cookielist** **lastsocket** **ftp\_entry\_path** **redirect\_url** **primary\_ip** **appconnect\_time** **certinfo** **condition\_unmet** **rtsp\_session\_id** **rtsp\_client\_cseq** **rtsp\_server\_cseq** **rtsp\_cseq\_recv** **primary\_port** **local\_ip** **local\_port** **lastone** 
Fill in new entries below here!

    alias **CURLINFO** = int;  enum CurlInfo **CURLINFO\_HTTP\_CODE**;  
CURLINFO\_RESPONSE\_CODE is the new name for the option previously known as CURLINFO\_HTTP\_CODE

  enum **CurlClosePolicy**: int;   
**none** **oldest** **least\_recently\_used** **least\_traffic** **slowest** **callback** **last**   alias **curl\_closepolicy** = int;  enum **CurlGlobal**: int;   
**ssl** **win32** **all** **nothing** **default\_** 
all

    enum **CurlLockData**: int;  
Setup defines, protos etc for the sharing stuff. 


Different data locks for a single share

 
**none** **share** 
CURL\_LOCK\_DATA\_SHARE is used internally to say that the locking is just made to change the internal state of the share itself.

  **cookie** **dns** **ssl\_session** **connect** **last**   alias **curl\_lock\_data** = int;  enum **CurlLockAccess**: int;  
Different lock access types

 
**none** 
unspecified action

  **shared\_access** 
for read perhaps

  **single** 
for write perhaps

  **last** 
never use

    alias **curl\_lock\_access** = int;  alias **curl\_lock\_function** = void function(void\* handle, int data, int locktype, void\* userptr);  alias **curl\_unlock\_function** = void function(void\* handle, int data, void\* userptr);  alias **CURLSH** = void;  enum **CurlShError**: int;   
**ok** 
all is fine

  **bad\_option** 
1

  **in\_use** 
2

  **invalid** 
3

  **nomem** 
out of memory

  **last** 
never use

    alias **CURLSHcode** = int;  enum **CurlShOption**: int;  
pass in a user data pointer used in the lock/unlock callback functions

 
**none** 
don't use

  **share** 
specify a data type to share

  **unshare** 
specify which data type to stop sharing

  **lockfunc** 
pass in a 'curl\_lock\_function' pointer

  **unlockfunc** 
pass in a 'curl\_unlock\_function' pointer

  **userdata** 
pass in a user data pointer used in the lock/unlock callback functions

  **last** 
never use

    alias **CURLSHoption** = int;  CURLSH\* **curl\_share\_init**();  CURLSHcode **curl\_share\_setopt**(CURLSH\*, CURLSHoption option, ...);  CURLSHcode **curl\_share\_cleanup**(CURLSH\*);  enum **CurlVer**: int;  
Structures for querying information about the curl library at runtime.

 
**first** **second** **third** **fourth** **last**   alias **CURLversion** = int;  enum CurlVer **CURLVERSION\_NOW**;  
The 'CURLVERSION\_NOW' is the symbolic name meant to be used by basically all programs ever that want to get version information. It is meant to be a built-in version number for what kind of struct the caller expects. If the struct ever changes, we redefine the NOW to another enum from above.

  struct **\_N28**;   
CURLversion **age**;  
age of the returned struct

  const(char)\* **version\_**;  
LIBCURL\_VERSION

  uint **version\_num**;  
LIBCURL\_VERSION\_NUM

  const(char)\* **host**;  
OS/host/cpu/machine when configured

  int **features**;  
bitmask, see defines below

  const(char)\* **ssl\_version**;  
human readable string

  c\_long **ssl\_version\_num**;  
not used anymore, always 0

  const(char)\* **libz\_version**;  
human readable string

  const(char)\*\* **protocols**;  
protocols is terminated by an entry with a NULL protoname

  const(char)\* **ares**;  
The fields below this were added in CURLVERSION\_SECOND

  const(char)\* **libidn**;  
This field was added in CURLVERSION\_THIRD

  int **iconv\_ver\_num**;  
These field were added in CURLVERSION\_FOURTH. Same as 'libiconv\_version' if built with HAVE\_ICONV

  const(char)\* **libssh\_version**;  
human readable string

    alias **curl\_version\_info\_data** = \_N28;  enum **CurlVersion**: int;   
**ipv6** 
IPv6-enabled

  **kerberos4** 
kerberos auth is supported

  **ssl** 
SSL options are present

  **libz** 
libz features are present

  **ntlm** 
NTLM auth is supported

  **gssnegotiate** 
Negotiate auth support

  **dbg** 
built with debug capabilities

  **asynchdns** 
asynchronous dns resolves

  **spnego** 
SPNEGO auth

  **largefile** 
supports files bigger than 2GB

  **idn** 
International Domain Names support

  **sspi** 
SSPI is supported

  **conv** 
character conversions supported

  **curldebug** 
debug memory tracking supported

  **tlsauth\_srp** 
TLS-SRP auth is supported

    curl\_version\_info\_data\* **curl\_version\_info**(CURLversion);  

Name
 curl\_version\_info() 
 
Description
 This function returns a pointer to a static copy of the version info struct. See above.
  const(char)\* **curl\_easy\_strerror**(CURLcode);  

Name
 curl\_easy\_strerror() 
 
Description
 The curl\_easy\_strerror function may be used to turn a CURLcode value into the equivalent human readable error string. This is useful for printing meaningful error messages.
  const(char)\* **curl\_share\_strerror**(CURLSHcode);  

Name
 curl\_share\_strerror() 
 
Description
 The curl\_share\_strerror function may be used to turn a CURLSHcode value into the equivalent human readable error string. This is useful for printing meaningful error messages.
  CURLcode **curl\_easy\_pause**(CURL\* handle, int bitmask);  

Name
 curl\_easy\_pause() 
 
Description
 The curl\_easy\_pause function pauses or unpauses transfers. Select the new state by setting the bitmask, use the convenience defines below.
  enum **CurlPause**: int;   
**recv** **recv\_cont** **send** **send\_cont** **all** **cont**   CURL\* **curl\_easy\_init**();  CURLcode **curl\_easy\_setopt**(CURL\* curl, CURLoption option, ...);  CURLcode **curl\_easy\_perform**(CURL\* curl);  void **curl\_easy\_cleanup**(CURL\* curl);  CURLcode **curl\_easy\_getinfo**(CURL\* curl, CURLINFO info, ...);  

Name
 curl\_easy\_getinfo() 
 
Description
 Request internal information from the curl session with this function. The third argument MUST be a pointer to a long, a pointer to a char \* or a pointer to a double (as the documentation describes elsewhere). The data pointed to will be filled in accordingly and can be relied upon only if the function returns CURLE\_OK. This function is intended to get used *AFTER* a performed transfer, all results from this function are undefined until the transfer is completed.
  CURL\* **curl\_easy\_duphandle**(CURL\* curl);  

Name
 curl\_easy\_duphandle() 
 
Description
 Creates a new curl session handle with the same options set for the handle passed in. Duplicating a handle could only be a matter of cloning data and options, internal state info and things like persistant connections cannot be transfered. It is useful in multithreaded applications when you can run curl\_easy\_duphandle() for each new thread to avoid a series of identical curl\_easy\_setopt() invokes in every thread.
  void **curl\_easy\_reset**(CURL\* curl);  

Name
 curl\_easy\_reset() 
 
Description
 Re-initializes a CURL handle to the default values. This puts back the handle to the same state as it was in when it was just created. 
 It does keep: live connections, the Session ID cache, the DNS cache and the cookies.  CURLcode **curl\_easy\_recv**(CURL\* curl, void\* buffer, size\_t buflen, size\_t\* n);  

Name
 curl\_easy\_recv() 
 
Description
 Receives data from the connected socket. Use after successful curl\_easy\_perform() with CURLOPT\_CONNECT\_ONLY option.
  CURLcode **curl\_easy\_send**(CURL\* curl, void\* buffer, size\_t buflen, size\_t\* n);  

Name
 curl\_easy\_send() 
 
Description
 Sends data over the connected socket. Use after successful curl\_easy\_perform() with CURLOPT\_CONNECT\_ONLY option.
  alias **CURLM** = void;  enum **CurlM**: int;   
**call\_multi\_perform** 
please call curl\_multi\_perform() or curl\_multi\_socket\*() soon

  **ok** **bad\_handle** 
the passed-in handle is not a valid CURLM handle

  **bad\_easy\_handle** 
an easy handle was not good/valid

  **out\_of\_memory** 
if you ever get this, you're in deep sh\*t

  **internal\_error** 
this is a libcurl bug

  **bad\_socket** 
the passed in socket argument did not match

  **unknown\_option** 
curl\_multi\_setopt() with unsupported option

  **last**   alias **CURLMcode** = int;  enum CurlM **CURLM\_CALL\_MULTI\_SOCKET**;  
just to make code nicer when using curl\_multi\_socket() you can now check for CURLM\_CALL\_MULTI\_SOCKET too in the same style it works for curl\_multi\_perform() and CURLM\_CALL\_MULTI\_PERFORM

  enum **CurlMsg**: int;   
**none** **done** 
This easy handle has completed. 'result' contains the CURLcode of the transfer

  **last** 
no used

    alias **CURLMSG** = int;  union **\_N31**;   
void\* **whatever**;  
message-specific data

  CURLcode **result**;  
return code for transfer

    struct **CURLMsg**;   
CURLMSG **msg**;  
what this message means

  CURL\* **easy\_handle**;  
the handle it concerns

  \_N31 **data**;    CURLM\* **curl\_multi\_init**();  

Name
 curl\_multi\_init() 
 
Desc
 inititalize multi-style curl usage 
 
Returns:
a new CURLM handle to use in all 'curl\_multi' functions.
  CURLMcode **curl\_multi\_add\_handle**(CURLM\* multi\_handle, CURL\* curl\_handle);  

Name
 curl\_multi\_add\_handle() 
 
Desc
 add a standard curl handle to the multi stack 
 
Returns:
CURLMcode type, general multi error code.
  CURLMcode **curl\_multi\_remove\_handle**(CURLM\* multi\_handle, CURL\* curl\_handle);  

Name
 curl\_multi\_remove\_handle() 
 
Desc
 removes a curl handle from the multi stack again 
 
Returns:
CURLMcode type, general multi error code.
  alias **fd\_set** = int;  

Name
 curl\_multi\_fdset() 
 
Desc
 Ask curl for its fd\_set sets. The app can use these to select() or poll() on. We want curl\_multi\_perform() called as soon as one of them are ready. 
 
Returns:
CURLMcode type, general multi error code. tmp decl
  CURLMcode **curl\_multi\_fdset**(CURLM\* multi\_handle, fd\_set\* read\_fd\_set, fd\_set\* write\_fd\_set, fd\_set\* exc\_fd\_set, int\* max\_fd);  CURLMcode **curl\_multi\_perform**(CURLM\* multi\_handle, int\* running\_handles);  

Name
 curl\_multi\_perform() 
 
Desc
 When the app thinks there's data available for curl it calls this function to read/write whatever there is right now. This returns as soon as the reads and writes are done. This function does not require that there actually is data available for reading or that data can be written, it can be called just in case. It returns the number of handles that still transfer data in the second argument's integer-pointer. 
 
Returns:
CURLMcode type, general multi error code. *NOTE* that this only returns errors etc regarding the whole multi stack. There might still have occurred problems on invidual transfers even when this returns OK.
  CURLMcode **curl\_multi\_cleanup**(CURLM\* multi\_handle);  

Name
 curl\_multi\_cleanup() 
 
Desc
 Cleans up and removes a whole multi stack. It does not free or touch any individual easy handles in any way. We need to define in what state those handles will be if this function is called in the middle of a transfer. 
 
Returns:
CURLMcode type, general multi error code.
  CURLMsg\* **curl\_multi\_info\_read**(CURLM\* multi\_handle, int\* msgs\_in\_queue);  

Name
 curl\_multi\_info\_read() 
 
Desc
 Ask the multi handle if there's any messages/informationals from the individual transfers. Messages include informationals such as error code from the transfer or just the fact that a transfer is completed. More details on these should be written down as well. 
 Repeated calls to this function will return a new struct each time, until a special "end of msgs" struct is returned as a signal that there is no more to get at this point. The data the returned pointer points to will not survive calling curl\_multi\_cleanup(). The 'CURLMsg' struct is meant to be very simple and only contain very basic informations. If more involved information is wanted, we will provide the particular "transfer handle" in that struct and that should/could/would be used in subsequent curl\_easy\_getinfo() calls (or similar). The point being that we must never expose complex structs to applications, as then we'll undoubtably get backwards compatibility problems in the future. 
Returns:
A pointer to a filled-in struct, or NULL if it failed or ran out of structs. It also writes the number of messages left in the queue (after this read) in the integer the second argument points to.
  const(char)\* **curl\_multi\_strerror**(CURLMcode);  

Name
 curl\_multi\_strerror() 
 
Desc
 The curl\_multi\_strerror function may be used to turn a CURLMcode value into the equivalent human readable error string. This is useful for printing meaningful error messages. 
 
Returns:
A pointer to a zero-terminated error message.
  enum **CurlPoll**: int;  

Name
 curl\_multi\_socket() and curl\_multi\_socket\_all() 
 
Desc
 An alternative version of curl\_multi\_perform() that allows the application to pass in one of the file descriptors that have been detected to have "action" on them and let libcurl perform. See man page for details.
 
**none\_** 
jdrewsen - underscored in order not to clash with reserved D symbols

  **in\_** **out\_** **inout\_** **remove\_**   alias **CURL\_SOCKET\_TIMEOUT** = CURL\_SOCKET\_BAD;  enum **CurlCSelect**: int;   
**in\_** 
jdrewsen - underscored in order not to clash with reserved D symbols

  **out\_** **err\_**   alias **curl\_socket\_callback** = extern (C) int function(void\* easy, socket\_t s, int what, void\* userp, void\* socketp);  
private socket pointer

  alias **curl\_multi\_timer\_callback** = extern (C) int function(void\* multi, long timeout\_ms, void\* userp);  
private callback pointer 



Name
 curl\_multi\_timer\_callback 
 
Desc
 Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). 
 
Returns:
The callback should return zero.
  CURLMcode **curl\_multi\_socket**(CURLM\* multi\_handle, curl\_socket\_t s, int\* running\_handles);  
ditto 



Name
 curl\_multi\_timer\_callback 
 
Desc
 Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). 
 
Returns:
The callback should return zero.
  CURLMcode **curl\_multi\_socket\_action**(CURLM\* multi\_handle, curl\_socket\_t s, int ev\_bitmask, int\* running\_handles);  
ditto 



Name
 curl\_multi\_timer\_callback 
 
Desc
 Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). 
 
Returns:
The callback should return zero.
  CURLMcode **curl\_multi\_socket\_all**(CURLM\* multi\_handle, int\* running\_handles);  
ditto 



Name
 curl\_multi\_timer\_callback 
 
Desc
 Called by libcurl whenever the library detects a change in the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). 
 
Returns:
The callback should return zero.
  CURLMcode **curl\_multi\_timeout**(CURLM\* multi\_handle, c\_long\* milliseconds);  
This macro below was added in 7.16.3 to push users who recompile to use the new curl\_multi\_socket\_action() instead of the old curl\_multi\_socket() 



Name
 curl\_multi\_timeout() 
 
Desc
 Returns the maximum number of milliseconds the app is allowed to wait before curl\_multi\_socket() or curl\_multi\_perform() must be called (to allow libcurl's timed events to take place). 
 
Returns:
CURLM error code.
  enum **CurlMOption**: int;   
**socketfunction** 
This is the socket callback function pointer

  **socketdata** 
This is the argument passed to the socket callback

  **pipelining** 
set to 1 to enable pipelining for this multi handle

  **timerfunction** 
This is the timer callback function pointer

  **timerdata** 
This is the argument passed to the timer callback

  **maxconnects** 
maximum number of entries in the connection cache

  **lastentry**   alias **CURLMoption** = int;  CURLMcode **curl\_multi\_setopt**(CURLM\* multi\_handle, CURLMoption option, ...);  

Name
 curl\_multi\_setopt() 
 
Desc
 Sets options for the multi handle. 
 
Returns:
CURLM error code.
  CURLMcode **curl\_multi\_assign**(CURLM\* multi\_handle, curl\_socket\_t sockfd, void\* sockp);  

Name
 curl\_multi\_assign() 
 
Desc
 This function sets an association in the multi handle between the given socket and a private pointer of the application. This is (only) useful for curl\_multi\_socket uses. 
 
Returns:
CURLM error code.
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/etc_c_curl.html>

core.stdc.inttypes
==================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<inttypes.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/inttypes.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/inttypes.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/inttypes.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
struct **imaxdiv\_t**;  enum \_cstr **PRId8**;  enum \_cstr **PRId16**;  enum \_cstr **PRId32**;  enum \_cstr **PRId64**;  enum \_cstr **PRIdLEAST8**;  enum \_cstr **PRIdLEAST16**;  enum \_cstr **PRIdLEAST32**;  enum \_cstr **PRIdLEAST64**;  enum \_cstr **PRIdFAST8**;  enum \_cstr **PRIdFAST16**;  enum \_cstr **PRIdFAST32**;  enum \_cstr **PRIdFAST64**;  enum \_cstr **PRIi8**;  enum \_cstr **PRIi16**;  enum \_cstr **PRIi32**;  enum \_cstr **PRIi64**;  enum \_cstr **PRIiLEAST8**;  enum \_cstr **PRIiLEAST16**;  enum \_cstr **PRIiLEAST32**;  enum \_cstr **PRIiLEAST64**;  enum \_cstr **PRIiFAST8**;  enum \_cstr **PRIiFAST16**;  enum \_cstr **PRIiFAST32**;  enum \_cstr **PRIiFAST64**;  enum \_cstr **PRIo8**;  enum \_cstr **PRIo16**;  enum \_cstr **PRIo32**;  enum \_cstr **PRIo64**;  enum \_cstr **PRIoLEAST8**;  enum \_cstr **PRIoLEAST16**;  enum \_cstr **PRIoLEAST32**;  enum \_cstr **PRIoLEAST64**;  enum \_cstr **PRIoFAST8**;  enum \_cstr **PRIoFAST16**;  enum \_cstr **PRIoFAST32**;  enum \_cstr **PRIoFAST64**;  enum \_cstr **PRIu8**;  enum \_cstr **PRIu16**;  enum \_cstr **PRIu32**;  enum \_cstr **PRIu64**;  enum \_cstr **PRIuLEAST8**;  enum \_cstr **PRIuLEAST16**;  enum \_cstr **PRIuLEAST32**;  enum \_cstr **PRIuLEAST64**;  enum \_cstr **PRIuFAST8**;  enum \_cstr **PRIuFAST16**;  enum \_cstr **PRIuFAST32**;  enum \_cstr **PRIuFAST64**;  enum \_cstr **PRIx8**;  enum \_cstr **PRIx16**;  enum \_cstr **PRIx32**;  enum \_cstr **PRIx64**;  enum \_cstr **PRIxLEAST8**;  enum \_cstr **PRIxLEAST16**;  enum \_cstr **PRIxLEAST32**;  enum \_cstr **PRIxLEAST64**;  enum \_cstr **PRIxFAST8**;  enum \_cstr **PRIxFAST16**;  enum \_cstr **PRIxFAST32**;  enum \_cstr **PRIxFAST64**;  enum \_cstr **PRIX8**;  enum \_cstr **PRIX16**;  enum \_cstr **PRIX32**;  enum \_cstr **PRIX64**;  enum \_cstr **PRIXLEAST8**;  enum \_cstr **PRIXLEAST16**;  enum \_cstr **PRIXLEAST32**;  enum \_cstr **PRIXLEAST64**;  enum \_cstr **PRIXFAST8**;  enum \_cstr **PRIXFAST16**;  enum \_cstr **PRIXFAST32**;  enum \_cstr **PRIXFAST64**;  enum \_cstr **SCNd8**;  enum \_cstr **SCNd16**;  enum \_cstr **SCNd32**;  enum \_cstr **SCNd64**;  enum \_cstr **SCNdLEAST8**;  enum \_cstr **SCNdLEAST16**;  enum \_cstr **SCNdLEAST32**;  enum \_cstr **SCNdLEAST64**;  enum \_cstr **SCNdFAST8**;  enum \_cstr **SCNdFAST16**;  enum \_cstr **SCNdFAST32**;  enum \_cstr **SCNdFAST64**;  enum \_cstr **SCNi8**;  enum \_cstr **SCNi16**;  enum \_cstr **SCNi32**;  enum \_cstr **SCNi64**;  enum \_cstr **SCNiLEAST8**;  enum \_cstr **SCNiLEAST16**;  enum \_cstr **SCNiLEAST32**;  enum \_cstr **SCNiLEAST64**;  enum \_cstr **SCNiFAST8**;  enum \_cstr **SCNiFAST16**;  enum \_cstr **SCNiFAST32**;  enum \_cstr **SCNiFAST64**;  enum \_cstr **SCNo8**;  enum \_cstr **SCNo16**;  enum \_cstr **SCNo32**;  enum \_cstr **SCNo64**;  enum \_cstr **SCNoLEAST8**;  enum \_cstr **SCNoLEAST16**;  enum \_cstr **SCNoLEAST32**;  enum \_cstr **SCNoLEAST64**;  enum \_cstr **SCNoFAST8**;  enum \_cstr **SCNoFAST16**;  enum \_cstr **SCNoFAST32**;  enum \_cstr **SCNoFAST64**;  enum \_cstr **SCNu8**;  enum \_cstr **SCNu16**;  enum \_cstr **SCNu32**;  enum \_cstr **SCNu64**;  enum \_cstr **SCNuLEAST8**;  enum \_cstr **SCNuLEAST16**;  enum \_cstr **SCNuLEAST32**;  enum \_cstr **SCNuLEAST64**;  enum \_cstr **SCNuFAST8**;  enum \_cstr **SCNuFAST16**;  enum \_cstr **SCNuFAST32**;  enum \_cstr **SCNuFAST64**;  enum \_cstr **SCNx8**;  enum \_cstr **SCNx16**;  enum \_cstr **SCNx32**;  enum \_cstr **SCNx64**;  enum \_cstr **SCNxLEAST8**;  enum \_cstr **SCNxLEAST16**;  enum \_cstr **SCNxLEAST32**;  enum \_cstr **SCNxLEAST64**;  enum \_cstr **SCNxFAST8**;  enum \_cstr **SCNxFAST16**;  enum \_cstr **SCNxFAST32**;  enum \_cstr **SCNxFAST64**;  enum \_cstr **PRIdMAX**;  enum \_cstr **PRIiMAX**;  enum \_cstr **PRIoMAX**;  enum \_cstr **PRIuMAX**;  enum \_cstr **PRIxMAX**;  enum \_cstr **PRIXMAX**;  enum \_cstr **SCNdMAX**;  enum \_cstr **SCNiMAX**;  enum \_cstr **SCNoMAX**;  enum \_cstr **SCNuMAX**;  enum \_cstr **SCNxMAX**;  enum \_cstr **PRIdPTR**;  enum \_cstr **PRIiPTR**;  enum \_cstr **PRIoPTR**;  enum \_cstr **PRIuPTR**;  enum \_cstr **PRIxPTR**;  enum \_cstr **PRIXPTR**;  enum \_cstr **SCNdPTR**;  enum \_cstr **SCNiPTR**;  enum \_cstr **SCNoPTR**;  enum \_cstr **SCNuPTR**;  enum \_cstr **SCNxPTR**;  nothrow @nogc @trusted intmax\_t **imaxabs**(intmax\_t j);  nothrow @nogc @trusted imaxdiv\_t **imaxdiv**(intmax\_t numer, intmax\_t denom);  nothrow @nogc @trusted intmax\_t **strtoimax**(scope const char\* nptr, char\*\* endptr, int base);  nothrow @nogc @trusted uintmax\_t **strtoumax**(scope const char\* nptr, char\*\* endptr, int base);  nothrow @nogc @trusted intmax\_t **wcstoimax**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  nothrow @nogc @trusted uintmax\_t **wcstoumax**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_inttypes.html>

core.stdc.signal
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<signal.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/signal.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/signal.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **sig\_atomic\_t** = int;  enum void function(int) nothrow @nogc @system **SIG\_ERR**;  enum void function(int) nothrow @nogc @system **SIG\_DFL**;  enum void function(int) nothrow @nogc @system **SIG\_IGN**;  enum int **SIGABRT**;  enum int **SIGFPE**;  enum int **SIGILL**;  enum int **SIGINT**;  enum int **SIGSEGV**;  enum int **SIGTERM**;  nothrow @nogc @system sigfn\_t **signal**(int sig, sigfn\_t func);  nothrow @nogc @system int **raise**(int sig);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_signal.html>

core.stdc.stddef
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<stddef.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stddef.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/stddef.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/stddef.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **nullptr\_t** = typeof(null);  alias **wchar\_t** = dchar;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_stddef.html>

core.stdc.math
==============

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<math.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/math.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/math.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/math.d)

 
alias **float\_t** = float;  alias **double\_t** = double;  enum double **HUGE\_VAL**;  enum double **HUGE\_VALF**;  enum double **HUGE\_VALL**;  enum float **INFINITY**;  enum float **NAN**;  enum int **FP\_ILOGB0**;  enum int **FP\_ILOGBNAN**;  enum int **MATH\_ERRNO**;  enum int **MATH\_ERREXCEPT**;  enum int **math\_errhandling**;  **FP\_NAN** **FP\_INFINITE** **FP\_ZERO** **FP\_SUBNORMAL** **FP\_NORMAL** **FP\_FAST\_FMA** **FP\_FAST\_FMAF** **FP\_FAST\_FMAL** pure nothrow @nogc @trusted int **fpclassify**(float x);  pure nothrow @nogc @trusted int **fpclassify**(double x);  pure nothrow @nogc @trusted int **fpclassify**(real x);  pure nothrow @nogc @trusted int **isfinite**(float x);  pure nothrow @nogc @trusted int **isfinite**(double x);  pure nothrow @nogc @trusted int **isfinite**(real x);  pure nothrow @nogc @trusted int **isinf**(float x);  pure nothrow @nogc @trusted int **isinf**(double x);  pure nothrow @nogc @trusted int **isinf**(real x);  pure nothrow @nogc @trusted int **isnan**(float x);  pure nothrow @nogc @trusted int **isnan**(double x);  pure nothrow @nogc @trusted int **isnan**(real x);  pure nothrow @nogc @trusted int **isnormal**(float x);  pure nothrow @nogc @trusted int **isnormal**(double x);  pure nothrow @nogc @trusted int **isnormal**(real x);  pure nothrow @nogc @trusted int **signbit**(float x);  pure nothrow @nogc @trusted int **signbit**(double x);  pure nothrow @nogc @trusted int **signbit**(real x);  pure nothrow @nogc @trusted int **isgreater**(float x, float y);  pure nothrow @nogc @trusted int **isgreater**(double x, double y);  pure nothrow @nogc @trusted int **isgreater**(real x, real y);  pure nothrow @nogc @trusted int **isgreaterequal**(float x, float y);  pure nothrow @nogc @trusted int **isgreaterequal**(double x, double y);  pure nothrow @nogc @trusted int **isgreaterequal**(real x, real y);  pure nothrow @nogc @trusted int **isless**(float x, float y);  pure nothrow @nogc @trusted int **isless**(double x, double y);  pure nothrow @nogc @trusted int **isless**(real x, real y);  pure nothrow @nogc @trusted int **islessequal**(float x, float y);  pure nothrow @nogc @trusted int **islessequal**(double x, double y);  pure nothrow @nogc @trusted int **islessequal**(real x, real y);  pure nothrow @nogc @trusted int **islessgreater**(float x, float y);  pure nothrow @nogc @trusted int **islessgreater**(double x, double y);  pure nothrow @nogc @trusted int **islessgreater**(real x, real y);  pure nothrow @nogc @trusted int **isunordered**(float x, float y);  pure nothrow @nogc @trusted int **isunordered**(double x, double y);  pure nothrow @nogc @trusted int **isunordered**(real x, real y);  nothrow @nogc @trusted double **acos**(double x);  nothrow @nogc @trusted float **acosf**(float x);  nothrow @nogc @trusted real **acosl**(real x);  nothrow @nogc @trusted double **asin**(double x);  nothrow @nogc @trusted float **asinf**(float x);  nothrow @nogc @trusted real **asinl**(real x);  pure nothrow @nogc @trusted double **atan**(double x);  pure nothrow @nogc @trusted float **atanf**(float x);  pure nothrow @nogc @trusted real **atanl**(real x);  nothrow @nogc @trusted double **atan2**(double y, double x);  nothrow @nogc @trusted float **atan2f**(float y, float x);  nothrow @nogc @trusted real **atan2l**(real y, real x);  pure nothrow @nogc @trusted double **cos**(double x);  pure nothrow @nogc @trusted float **cosf**(float x);  pure nothrow @nogc @trusted real **cosl**(real x);  pure nothrow @nogc @trusted double **sin**(double x);  pure nothrow @nogc @trusted float **sinf**(float x);  pure nothrow @nogc @trusted real **sinl**(real x);  pure nothrow @nogc @trusted double **tan**(double x);  pure nothrow @nogc @trusted float **tanf**(float x);  pure nothrow @nogc @trusted real **tanl**(real x);  nothrow @nogc @trusted double **acosh**(double x);  nothrow @nogc @trusted float **acoshf**(float x);  nothrow @nogc @trusted real **acoshl**(real x);  pure nothrow @nogc @trusted double **asinh**(double x);  pure nothrow @nogc @trusted float **asinhf**(float x);  pure nothrow @nogc @trusted real **asinhl**(real x);  nothrow @nogc @trusted double **atanh**(double x);  nothrow @nogc @trusted float **atanhf**(float x);  nothrow @nogc @trusted real **atanhl**(real x);  nothrow @nogc @trusted double **cosh**(double x);  nothrow @nogc @trusted float **coshf**(float x);  nothrow @nogc @trusted real **coshl**(real x);  nothrow @nogc @trusted double **sinh**(double x);  nothrow @nogc @trusted float **sinhf**(float x);  nothrow @nogc @trusted real **sinhl**(real x);  pure nothrow @nogc @trusted double **tanh**(double x);  pure nothrow @nogc @trusted float **tanhf**(float x);  pure nothrow @nogc @trusted real **tanhl**(real x);  nothrow @nogc @trusted double **exp**(double x);  nothrow @nogc @trusted float **expf**(float x);  nothrow @nogc @trusted real **expl**(real x);  nothrow @nogc @trusted double **exp2**(double x);  nothrow @nogc @trusted float **exp2f**(float x);  nothrow @nogc @trusted real **exp2l**(real x);  nothrow @nogc @trusted double **expm1**(double x);  nothrow @nogc @trusted float **expm1f**(float x);  nothrow @nogc @trusted real **expm1l**(real x);  pure nothrow @nogc @trusted double **frexp**(double value, int\* exp);  pure nothrow @nogc @trusted float **frexpf**(float value, int\* exp);  pure nothrow @nogc @trusted real **frexpl**(real value, int\* exp);  nothrow @nogc @trusted int **ilogb**(double x);  nothrow @nogc @trusted int **ilogbf**(float x);  nothrow @nogc @trusted int **ilogbl**(real x);  nothrow @nogc @trusted double **ldexp**(double x, int exp);  nothrow @nogc @trusted float **ldexpf**(float x, int exp);  nothrow @nogc @trusted real **ldexpl**(real x, int exp);  nothrow @nogc @trusted double **log**(double x);  nothrow @nogc @trusted float **logf**(float x);  nothrow @nogc @trusted real **logl**(real x);  nothrow @nogc @trusted double **log10**(double x);  nothrow @nogc @trusted float **log10f**(float x);  nothrow @nogc @trusted real **log10l**(real x);  nothrow @nogc @trusted double **log1p**(double x);  nothrow @nogc @trusted float **log1pf**(float x);  nothrow @nogc @trusted real **log1pl**(real x);  nothrow @nogc @trusted double **log2**(double x);  nothrow @nogc @trusted float **log2f**(float x);  nothrow @nogc @trusted real **log2l**(real x);  nothrow @nogc @trusted double **logb**(double x);  nothrow @nogc @trusted float **logbf**(float x);  nothrow @nogc @trusted real **logbl**(real x);  pure nothrow @nogc @trusted double **modf**(double value, double\* iptr);  pure nothrow @nogc @trusted float **modff**(float value, float\* iptr);  pure nothrow @nogc @trusted real **modfl**(real value, real\* iptr);  nothrow @nogc @trusted double **scalbn**(double x, int n);  nothrow @nogc @trusted float **scalbnf**(float x, int n);  nothrow @nogc @trusted real **scalbnl**(real x, int n);  nothrow @nogc @trusted double **scalbln**(double x, c\_long n);  nothrow @nogc @trusted float **scalblnf**(float x, c\_long n);  nothrow @nogc @trusted real **scalblnl**(real x, c\_long n);  pure nothrow @nogc @trusted double **cbrt**(double x);  pure nothrow @nogc @trusted float **cbrtf**(float x);  pure nothrow @nogc @trusted real **cbrtl**(real x);  pure nothrow @nogc @trusted double **fabs**(double x);  pure nothrow @nogc @trusted float **fabsf**(float x);  pure nothrow @nogc @trusted real **fabsl**(real x);  nothrow @nogc @trusted double **hypot**(double x, double y);  nothrow @nogc @trusted float **hypotf**(float x, float y);  nothrow @nogc @trusted real **hypotl**(real x, real y);  nothrow @nogc @trusted double **pow**(double x, double y);  nothrow @nogc @trusted float **powf**(float x, float y);  nothrow @nogc @trusted real **powl**(real x, real y);  nothrow @nogc @trusted double **sqrt**(double x);  nothrow @nogc @trusted float **sqrtf**(float x);  nothrow @nogc @trusted real **sqrtl**(real x);  pure nothrow @nogc @trusted double **erf**(double x);  pure nothrow @nogc @trusted float **erff**(float x);  pure nothrow @nogc @trusted real **erfl**(real x);  nothrow @nogc @trusted double **erfc**(double x);  nothrow @nogc @trusted float **erfcf**(float x);  nothrow @nogc @trusted real **erfcl**(real x);  nothrow @nogc @trusted double **lgamma**(double x);  nothrow @nogc @trusted float **lgammaf**(float x);  nothrow @nogc @trusted real **lgammal**(real x);  nothrow @nogc @trusted double **tgamma**(double x);  nothrow @nogc @trusted float **tgammaf**(float x);  nothrow @nogc @trusted real **tgammal**(real x);  pure nothrow @nogc @trusted double **ceil**(double x);  pure nothrow @nogc @trusted float **ceilf**(float x);  pure nothrow @nogc @trusted real **ceill**(real x);  pure nothrow @nogc @trusted double **floor**(double x);  pure nothrow @nogc @trusted float **floorf**(float x);  pure nothrow @nogc @trusted real **floorl**(real x);  pure nothrow @nogc @trusted double **nearbyint**(double x);  pure nothrow @nogc @trusted float **nearbyintf**(float x);  pure nothrow @nogc @trusted real **nearbyintl**(real x);  pure nothrow @nogc @trusted double **rint**(double x);  pure nothrow @nogc @trusted float **rintf**(float x);  pure nothrow @nogc @trusted real **rintl**(real x);  nothrow @nogc @trusted c\_long **lrint**(double x);  nothrow @nogc @trusted c\_long **lrintf**(float x);  nothrow @nogc @trusted c\_long **lrintl**(real x);  nothrow @nogc @trusted long **llrint**(double x);  nothrow @nogc @trusted long **llrintf**(float x);  nothrow @nogc @trusted long **llrintl**(real x);  pure nothrow @nogc @trusted double **round**(double x);  pure nothrow @nogc @trusted float **roundf**(float x);  pure nothrow @nogc @trusted real **roundl**(real x);  nothrow @nogc @trusted c\_long **lround**(double x);  nothrow @nogc @trusted c\_long **lroundf**(float x);  nothrow @nogc @trusted c\_long **lroundl**(real x);  nothrow @nogc @trusted long **llround**(double x);  nothrow @nogc @trusted long **llroundf**(float x);  nothrow @nogc @trusted long **llroundl**(real x);  pure nothrow @nogc @trusted double **trunc**(double x);  pure nothrow @nogc @trusted float **truncf**(float x);  pure nothrow @nogc @trusted real **truncl**(real x);  nothrow @nogc @trusted double **fmod**(double x, double y);  nothrow @nogc @trusted float **fmodf**(float x, float y);  nothrow @nogc @trusted real **fmodl**(real x, real y);  nothrow @nogc @trusted double **remainder**(double x, double y);  nothrow @nogc @trusted float **remainderf**(float x, float y);  nothrow @nogc @trusted real **remainderl**(real x, real y);  nothrow @nogc @trusted double **remquo**(double x, double y, int\* quo);  nothrow @nogc @trusted float **remquof**(float x, float y, int\* quo);  nothrow @nogc @trusted real **remquol**(real x, real y, int\* quo);  pure nothrow @nogc @trusted double **copysign**(double x, double y);  pure nothrow @nogc @trusted float **copysignf**(float x, float y);  pure nothrow @nogc @trusted real **copysignl**(real x, real y);  pure nothrow @nogc @trusted double **nan**(char\* tagp);  pure nothrow @nogc @trusted float **nanf**(char\* tagp);  pure nothrow @nogc @trusted real **nanl**(char\* tagp);  nothrow @nogc @trusted double **nextafter**(double x, double y);  nothrow @nogc @trusted float **nextafterf**(float x, float y);  nothrow @nogc @trusted real **nextafterl**(real x, real y);  nothrow @nogc @trusted double **nexttoward**(double x, real y);  nothrow @nogc @trusted float **nexttowardf**(float x, real y);  nothrow @nogc @trusted real **nexttowardl**(real x, real y);  nothrow @nogc @trusted double **fdim**(double x, double y);  nothrow @nogc @trusted float **fdimf**(float x, float y);  nothrow @nogc @trusted real **fdiml**(real x, real y);  pure nothrow @nogc @trusted double **fmax**(double x, double y);  pure nothrow @nogc @trusted float **fmaxf**(float x, float y);  pure nothrow @nogc @trusted real **fmaxl**(real x, real y);  pure nothrow @nogc @trusted double **fmin**(double x, double y);  pure nothrow @nogc @trusted float **fminf**(float x, float y);  pure nothrow @nogc @trusted real **fminl**(real x, real y);  pure nothrow @nogc @trusted double **fma**(double x, double y, double z);  pure nothrow @nogc @trusted float **fmaf**(float x, float y, float z);  pure nothrow @nogc @trusted real **fmal**(real x, real y, real z);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_math.html>

core.stdc.stdint
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<stdint.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/stdint.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/stdint.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **int8\_t** = byte;  alias **int16\_t** = short;  alias **uint8\_t** = ubyte;  alias **uint16\_t** = ushort;  alias **int32\_t** = int;  alias **uint32\_t** = uint;  alias **int64\_t** = long;  alias **uint64\_t** = ulong;  alias **int\_least8\_t** = byte;  alias **uint\_least8\_t** = ubyte;  alias **int\_least16\_t** = short;  alias **uint\_least16\_t** = ushort;  alias **int\_least32\_t** = int;  alias **uint\_least32\_t** = uint;  alias **int\_least64\_t** = long;  alias **uint\_least64\_t** = ulong;  alias **int\_fast8\_t** = byte;  alias **uint\_fast8\_t** = ubyte;  alias **int\_fast16\_t** = long;  alias **uint\_fast16\_t** = ulong;  alias **int\_fast32\_t** = long;  alias **uint\_fast32\_t** = ulong;  alias **int\_fast64\_t** = long;  alias **uint\_fast64\_t** = ulong;  alias **intptr\_t** = long;  alias **uintptr\_t** = ulong;  alias **intmax\_t** = long;  alias **uintmax\_t** = ulong;  enum int8\_t **INT8\_MIN**;  enum int8\_t **INT8\_MAX**;  enum int16\_t **INT16\_MIN**;  enum int16\_t **INT16\_MAX**;  enum int32\_t **INT32\_MIN**;  enum int32\_t **INT32\_MAX**;  enum int64\_t **INT64\_MIN**;  enum int64\_t **INT64\_MAX**;  enum uint8\_t **UINT8\_MAX**;  enum uint16\_t **UINT16\_MAX**;  enum uint32\_t **UINT32\_MAX**;  enum uint64\_t **UINT64\_MAX**;  enum int\_least8\_t **INT\_LEAST8\_MIN**;  enum int\_least8\_t **INT\_LEAST8\_MAX**;  enum int\_least16\_t **INT\_LEAST16\_MIN**;  enum int\_least16\_t **INT\_LEAST16\_MAX**;  enum int\_least32\_t **INT\_LEAST32\_MIN**;  enum int\_least32\_t **INT\_LEAST32\_MAX**;  enum int\_least64\_t **INT\_LEAST64\_MIN**;  enum int\_least64\_t **INT\_LEAST64\_MAX**;  enum uint\_least8\_t **UINT\_LEAST8\_MAX**;  enum uint\_least16\_t **UINT\_LEAST16\_MAX**;  enum uint\_least32\_t **UINT\_LEAST32\_MAX**;  enum uint\_least64\_t **UINT\_LEAST64\_MAX**;  enum int\_fast8\_t **INT\_FAST8\_MIN**;  enum int\_fast8\_t **INT\_FAST8\_MAX**;  enum int\_fast16\_t **INT\_FAST16\_MIN**;  enum int\_fast16\_t **INT\_FAST16\_MAX**;  enum int\_fast32\_t **INT\_FAST32\_MIN**;  enum int\_fast32\_t **INT\_FAST32\_MAX**;  enum int\_fast64\_t **INT\_FAST64\_MIN**;  enum int\_fast64\_t **INT\_FAST64\_MAX**;  enum uint\_fast8\_t **UINT\_FAST8\_MAX**;  enum uint\_fast16\_t **UINT\_FAST16\_MAX**;  enum uint\_fast32\_t **UINT\_FAST32\_MAX**;  enum uint\_fast64\_t **UINT\_FAST64\_MAX**;  enum intptr\_t **INTPTR\_MIN**;  enum intptr\_t **INTPTR\_MAX**;  enum uintptr\_t **UINTPTR\_MIN**;  enum uintptr\_t **UINTPTR\_MAX**;  enum intmax\_t **INTMAX\_MIN**;  enum intmax\_t **INTMAX\_MAX**;  enum uintmax\_t **UINTMAX\_MAX**;  enum ptrdiff\_t **PTRDIFF\_MIN**;  enum ptrdiff\_t **PTRDIFF\_MAX**;  enum sig\_atomic\_t **SIG\_ATOMIC\_MIN**;  enum sig\_atomic\_t **SIG\_ATOMIC\_MAX**;  enum size\_t **SIZE\_MAX**;  enum wchar\_t **WCHAR\_MIN**;  enum wchar\_t **WCHAR\_MAX**;  enum wint\_t **WINT\_MIN**;  enum wint\_t **WINT\_MAX**;  alias **INT8\_C** = \_typify!byte.\_typify;  alias **INT16\_C** = \_typify!short.\_typify;  alias **INT32\_C** = \_typify!int.\_typify;  alias **INT64\_C** = \_typify!long.\_typify;  alias **UINT8\_C** = \_typify!ubyte.\_typify;  alias **UINT16\_C** = \_typify!ushort.\_typify;  alias **UINT32\_C** = \_typify!uint.\_typify;  alias **UINT64\_C** = \_typify!ulong.\_typify;  alias **INTMAX\_C** = \_typify!long.\_typify;  alias **UINTMAX\_C** = \_typify!ulong.\_typify;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_stdint.html>

core.stdc.stdio
===============

 D header file for C99  


This module contains bindings to selected types and functions from the standard C header [`<stdio.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdio.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Alex Rønne Petersen 
 
Source
 <https://github.com/dlang/druntime/blob/master/src/core/stdc/stdio.d> 
 
Standards:
ISO/IEC 9899:1999 (E)
 
**BUFSIZ** **EOF** **FOPEN\_MAX** **FILENAME\_MAX** **TMP\_MAX** **L\_tmpnam** **SEEK\_SET** 
Offset is relative to the beginning

  **SEEK\_CUR** 
Offset is relative to the current position

  **SEEK\_END** 
Offset is relative to the end

  struct **fpos\_t**;  struct **\_IO\_FILE**;  alias **\_iobuf** = \_IO\_FILE;  alias **FILE** = \_IO\_FILE;  **\_F\_RDWR** **\_F\_READ** **\_F\_WRIT** **\_F\_BUF** **\_F\_LBUF** **\_F\_ERR** **\_F\_EOF** **\_F\_BIN** **\_F\_IN** **\_F\_OUT** **\_F\_TERM** **\_IOFBF** **\_IOLBF** **\_IONBF** shared FILE\* **stdin**;  shared FILE\* **stdout**;  shared FILE\* **stderr**;  nothrow @nogc @system int **remove**(scope const char\* filename);  nothrow @nogc @system int **rename**(scope const char\* from, scope const char\* to);  nothrow @nogc @trusted FILE\* **tmpfile**();  nothrow @nogc @system char\* **tmpnam**(char\* s);  nothrow @nogc @system int **fclose**(FILE\* stream);  nothrow @nogc @trusted int **fflush**(FILE\* stream);  nothrow @nogc @system FILE\* **fopen**(scope const char\* filename, scope const char\* mode);  nothrow @nogc @system FILE\* **freopen**(scope const char\* filename, scope const char\* mode, FILE\* stream);  nothrow @nogc @system void **setbuf**(FILE\* stream, char\* buf);  nothrow @nogc @system int **setvbuf**(FILE\* stream, char\* buf, int mode, size\_t size);  nothrow @nogc @system int **fprintf**(FILE\* stream, scope const char\* format, ...);  nothrow @nogc @system int **fscanf**(FILE\* stream, scope const char\* format, ...);  nothrow @nogc @system int **sprintf**(scope char\* s, scope const char\* format, ...);  nothrow @nogc @system int **sscanf**(scope const char\* s, scope const char\* format, ...);  nothrow @nogc @system int **vfprintf**(FILE\* stream, scope const char\* format, va\_list arg);  nothrow @nogc @system int **vfscanf**(FILE\* stream, scope const char\* format, va\_list arg);  nothrow @nogc @system int **vsprintf**(scope char\* s, scope const char\* format, va\_list arg);  nothrow @nogc @system int **vsscanf**(scope const char\* s, scope const char\* format, va\_list arg);  nothrow @nogc @system int **vprintf**(scope const char\* format, va\_list arg);  nothrow @nogc @system int **vscanf**(scope const char\* format, va\_list arg);  nothrow @nogc @system int **printf**(scope const char\* format, ...);  nothrow @nogc @system int **scanf**(scope const char\* format, ...);  nothrow @nogc @trusted int **fgetc**(FILE\* stream);  nothrow @nogc @trusted int **fputc**(int c, FILE\* stream);  nothrow @nogc @system char\* **fgets**(char\* s, int n, FILE\* stream);  nothrow @nogc @system int **fputs**(scope const char\* s, FILE\* stream);  nothrow @nogc @system char\* **gets**(char\* s);  nothrow @nogc @system int **puts**(scope const char\* s);  int **getchar**()();  int **putchar**()(int c);  int **getc**()(FILE\* stream);  int **putc**()(int c, FILE\* stream);  nothrow @nogc @trusted int **ungetc**(int c, FILE\* stream);  nothrow @nogc @system size\_t **fread**(scope void\* ptr, size\_t size, size\_t nmemb, FILE\* stream);  nothrow @nogc @system size\_t **fwrite**(scope const void\* ptr, size\_t size, size\_t nmemb, FILE\* stream);  nothrow @nogc @trusted int **fgetpos**(FILE\* stream, scope fpos\_t\* pos);  nothrow @nogc @trusted int **fsetpos**(FILE\* stream, scope const fpos\_t\* pos);  nothrow @nogc @trusted int **fseek**(FILE\* stream, c\_long offset, int whence);  nothrow @nogc @trusted c\_long **ftell**(FILE\* stream);  nothrow @nogc @trusted void **rewind**(FILE\* stream);  pure nothrow @nogc @trusted void **clearerr**(FILE\* stream);  pure nothrow @nogc @trusted int **feof**(FILE\* stream);  pure nothrow @nogc @trusted int **ferror**(FILE\* stream);  nothrow @nogc @trusted int **fileno**(FILE\*);  nothrow @nogc @system int **snprintf**(scope char\* s, size\_t n, scope const char\* format, ...);  nothrow @nogc @system int **vsnprintf**(scope char\* s, size\_t n, scope const char\* format, va\_list arg);  nothrow @nogc @system void **perror**(scope const char\* s);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_stdio.html>

core.stdc.stdlib
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<stdlib.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Standards:
ISO/IEC 9899:1999 (E) 
 
Source
 [src/core/stdc/stdlib.d](https://github.com/dlang/druntime/blob/master/src/src/core/stdc/stdlib.d)

 
alias **\_compare\_fp\_t** = extern (C) int function(const(void\*), const(void\*)) @system;  nothrow @nogc @system inout(void)\* **bsearch**(const void\* key, inout(void)\* base, size\_t nmemb, size\_t size, \_compare\_fp\_t compar);  nothrow @nogc @system void **qsort**(void\* base, size\_t nmemb, size\_t size, \_compare\_fp\_t compar);  struct **div\_t**;  struct **ldiv\_t**;  struct **lldiv\_t**;  enum int **EXIT\_SUCCESS**;  enum int **EXIT\_FAILURE**;  enum int **MB\_CUR\_MAX**;  enum int **RAND\_MAX**;  nothrow @nogc @system double **atof**(scope const char\* nptr);  nothrow @nogc @system int **atoi**(scope const char\* nptr);  nothrow @nogc @system c\_long **atol**(scope const char\* nptr);  nothrow @nogc @system long **atoll**(scope const char\* nptr);  nothrow @nogc @system double **strtod**(scope inout(char)\* nptr, scope inout(char)\*\* endptr);  nothrow @nogc @system float **strtof**(scope inout(char)\* nptr, scope inout(char)\*\* endptr);  nothrow @nogc @system c\_long **strtol**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base);  nothrow @nogc @system long **strtoll**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base);  nothrow @nogc @system c\_ulong **strtoul**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base);  nothrow @nogc @system ulong **strtoull**(scope inout(char)\* nptr, scope inout(char)\*\* endptr, int base);  nothrow @nogc @system real **strtold**(scope inout(char)\* nptr, scope inout(char)\*\* endptr);  
Added to Bionic since Lollipop.

  nothrow @nogc @trusted int **rand**();  
These two were added to Bionic in Lollipop.

  nothrow @nogc @trusted void **srand**(uint seed);  nothrow @nogc @system void\* **malloc**(size\_t size);  nothrow @nogc @system void\* **calloc**(size\_t nmemb, size\_t size);  nothrow @nogc @system void\* **realloc**(void\* ptr, size\_t size);  nothrow @nogc @system void **free**(void\* ptr);  nothrow @nogc @safe void **abort**();  nothrow @nogc @system void **exit**(int status);  nothrow @nogc @system int **atexit**(void function() func);  nothrow @nogc @system void **\_Exit**(int status);  nothrow @nogc @system char\* **getenv**(scope const char\* name);  nothrow @nogc @**system** int **system**(scope const char\* string);  pure nothrow @nogc @trusted int **abs**(int j);  pure nothrow @nogc @trusted c\_long **labs**(c\_long j);  pure nothrow @nogc @trusted long **llabs**(long j);  nothrow @nogc @trusted div\_t **div**(int numer, int denom);  nothrow @nogc @trusted ldiv\_t **ldiv**(c\_long numer, c\_long denom);  nothrow @nogc @trusted lldiv\_t **lldiv**(long numer, long denom);  nothrow @nogc @system int **mblen**(scope const char\* s, size\_t n);  nothrow @nogc @system int **mbtowc**(scope wchar\_t\* pwc, scope const char\* s, size\_t n);  nothrow @nogc @system int **wctomb**(scope char\* s, wchar\_t wc);  nothrow @nogc @system size\_t **mbstowcs**(scope wchar\_t\* pwcs, scope const char\* s, size\_t n);  nothrow @nogc @system size\_t **wcstombs**(scope char\* s, scope const wchar\_t\* pwcs, size\_t n);  pure nothrow @nogc @system void\* **alloca**(size\_t size);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_stdlib.html>

core.stdc.time
==============

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<time.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/time.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Alex Rønne Petersen 
 
Source
 [core/stdc/time.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/time.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
pure nothrow @nogc @trusted double **difftime**(time\_t time1, time\_t time0);  nothrow @nogc @system time\_t **mktime**(scope tm\* timeptr);  nothrow @nogc @trusted time\_t **time**(scope time\_t\* timer);  nothrow @nogc @system char\* **asctime**(scope const tm\* timeptr);  nothrow @nogc @system char\* **ctime**(scope const time\_t\* timer);  nothrow @nogc @system tm\* **gmtime**(scope const time\_t\* timer);  nothrow @nogc @system tm\* **localtime**(scope const time\_t\* timer);  nothrow @nogc @system size\_t **strftime**(scope char\* s, size\_t maxsize, scope const char\* format, scope const tm\* timeptr);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_time.html>

core.stdc.string
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<string.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/string.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/string.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/string.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
pure nothrow @nogc @system inout(void)\* **memchr**(return inout void\* s, int c, size\_t n);  pure nothrow @nogc @system int **memcmp**(scope const void\* s1, scope const void\* s2, size\_t n);  pure nothrow @nogc @system void\* **memcpy**(return void\* s1, scope const void\* s2, size\_t n);  pure nothrow @nogc @system void\* **memmove**(return void\* s1, scope const void\* s2, size\_t n);  pure nothrow @nogc @system void\* **memset**(return void\* s, int c, size\_t n);  pure nothrow @nogc @system char\* **strcat**(return char\* s1, scope const char\* s2);  pure nothrow @nogc @system inout(char)\* **strchr**(return inout(char)\* s, int c);  pure nothrow @nogc @system int **strcmp**(scope const char\* s1, scope const char\* s2);  nothrow @nogc @system int **strcoll**(scope const char\* s1, scope const char\* s2);  pure nothrow @nogc @system char\* **strcpy**(return char\* s1, scope const char\* s2);  pure nothrow @nogc @system size\_t **strcspn**(scope const char\* s1, scope const char\* s2);  nothrow @nogc @system char\* **strdup**(scope const char\* s);  nothrow @nogc @system char\* **strerror**(int errnum);  nothrow @nogc @system const(char)\* **strerror\_r**(int errnum, return char\* buf, size\_t buflen);  pure nothrow @nogc @system size\_t **strlen**(scope const char\* s);  pure nothrow @nogc @system char\* **strncat**(return char\* s1, scope const char\* s2, size\_t n);  pure nothrow @nogc @system int **strncmp**(scope const char\* s1, scope const char\* s2, size\_t n);  pure nothrow @nogc @system char\* **strncpy**(return char\* s1, scope const char\* s2, size\_t n);  pure nothrow @nogc @system inout(char)\* **strpbrk**(return inout(char)\* s1, scope const char\* s2);  pure nothrow @nogc @system inout(char)\* **strrchr**(return inout(char)\* s, int c);  pure nothrow @nogc @system size\_t **strspn**(scope const char\* s1, scope const char\* s2);  pure nothrow @nogc @system inout(char)\* **strstr**(return inout(char)\* s1, scope const char\* s2);  nothrow @nogc @system char\* **strtok**(return char\* s1, scope const char\* s2);  nothrow @nogc @system size\_t **strxfrm**(scope char\* s1, scope const char\* s2, size\_t n);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_string.html>

core.stdc.wctype
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<wctype.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/wctype.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/wctype.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/wctype.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **wctrans\_t** = dchar;  alias **wctype\_t** = dchar;  pure nothrow @nogc @trusted int **iswalnum**(wint\_t wc);  pure nothrow @nogc @trusted int **iswalpha**(wint\_t wc);  pure nothrow @nogc @trusted int **iswblank**(wint\_t wc);  pure nothrow @nogc @trusted int **iswcntrl**(wint\_t wc);  pure nothrow @nogc @trusted int **iswdigit**(wint\_t wc);  pure nothrow @nogc @trusted int **iswgraph**(wint\_t wc);  pure nothrow @nogc @trusted int **iswlower**(wint\_t wc);  pure nothrow @nogc @trusted int **iswprint**(wint\_t wc);  pure nothrow @nogc @trusted int **iswpunct**(wint\_t wc);  pure nothrow @nogc @trusted int **iswspace**(wint\_t wc);  pure nothrow @nogc @trusted int **iswupper**(wint\_t wc);  pure nothrow @nogc @trusted int **iswxdigit**(wint\_t wc);  nothrow @nogc @trusted int **iswctype**(wint\_t wc, wctype\_t desc);  nothrow @nogc @system wctype\_t **wctype**(scope const char\* property);  pure nothrow @nogc @trusted wint\_t **towlower**(wint\_t wc);  pure nothrow @nogc @trusted wint\_t **towupper**(wint\_t wc);  nothrow @nogc @trusted wint\_t **towctrans**(wint\_t wc, wctrans\_t desc);  nothrow @nogc @system wctrans\_t **wctrans**(scope const char\* property);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_wctype.html>

core.stdcpp.allocator
=====================

 D binding to C++ std::allocator. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Manu Evans 
 
Source
 [core/stdcpp/allocator.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/allocator.d)

 
struct **allocator**(T);  
Allocators are classes that define memory models to be used by some parts of the C++ Standard Library, and most specifically, by STL containers.

 
this(U)(ref allocator!U);  alias **size\_type** = size\_t;  alias **difference\_type** = ptrdiff\_t;  alias **pointer** = T\*;  alias **value\_type** = T;  enum auto **propagate\_on\_container\_move\_assignment**;  enum auto **is\_always\_equal**;  template **rebind**(U) @nogc T\* **allocate**(size\_t count);  @nogc void **deallocate**(T\* ptr, size\_t count);  enum size\_t **max\_size**;    struct **allocator\_traits**(Alloc);   
alias **allocator\_type** = Alloc;  alias **value\_type** = allocator\_type.**value\_type**;  alias **size\_type** = allocator\_type.**size\_type**;  alias **difference\_type** = allocator\_type.**difference\_type**;  alias **pointer** = allocator\_type.**pointer**;  enum auto **propagate\_on\_container\_copy\_assignment**;  enum auto **propagate\_on\_container\_move\_assignment**;  enum auto **propagate\_on\_container\_swap**;  enum auto **is\_always\_equal**;  template **rebind\_alloc**(U) template **rebind\_traits**(U) size\_type **max\_size**()(auto ref allocator\_type a);  allocator\_type **select\_on\_container\_copy\_construction**()(auto ref allocator\_type a);    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_allocator.html>

core.stdcpp.array
=================

 D header file for interaction with C++ std::array. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Manu Evans 
 
Source
 [core/stdcpp/array.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/array.d)

 
struct **array**(T, size\_t N);  
D language counterpart to C++ std::array. 


C++ reference: 

 
alias **size\_type** = size\_t;  alias **difference\_type** = ptrdiff\_t;  alias **value\_type** = T;  alias **pointer** = T\*;  alias **const\_pointer** = const(T)\*;  this(T[N] args...);  
Variadic constructor

  void **fill**()(auto ref const(T) value);  const @safe size\_type **size**();  alias **length** = size;  alias **opDollar** = length;  const @safe size\_type **max\_size**();  const @safe bool **empty**();  inout ref @safe inout(T) **front**();  inout ref @safe inout(T) **back**();  inout @safe inout(T)\* **data**();  inout ref @safe inout(T)[N] **as\_array**();  inout ref @safe inout(T) **at**(size\_type i);    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_array.html>

core.stdcpp.exception
=====================

 Interface to C++ 



License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) Manu Evans 
 
Source
 [core/stdcpp/exception.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/exception.d)

 
alias **terminate\_handler** = extern (C++) void function() nothrow @nogc;  nothrow @nogc terminate\_handler **set\_terminate**(terminate\_handler f);  nothrow @nogc terminate\_handler **get\_terminate**();  nothrow @nogc void **terminate**();  alias **unexpected\_handler** = extern (C++) void function() @nogc;  deprecated nothrow @nogc unexpected\_handler **set\_unexpected**(unexpected\_handler f);  deprecated nothrow @nogc unexpected\_handler **get\_unexpected**();  deprecated @nogc void **unexpected**();  nothrow @nogc bool **uncaught\_exception**();  class **exception**;   
nothrow @nogc this();  const nothrow @nogc const(char)\* **what**();    class **bad\_exception**: core.stdcpp.exception.exception;   
@nogc this(const(char)\* message = "bad exception");    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_exception.html>

core.stdc.wchar\_
=================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<wchar.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/wchar.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/wchar\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/wchar_.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
struct **mbstate\_t**;  alias **wint\_t** = dchar;  enum wchar\_t **WEOF**;  nothrow @nogc @system int **fwprintf**(FILE\* stream, scope const wchar\_t\* format, ...);  nothrow @nogc @system int **fwscanf**(FILE\* stream, scope const wchar\_t\* format, ...);  nothrow @nogc @system int **swprintf**(wchar\_t\* s, size\_t n, scope const wchar\_t\* format, ...);  nothrow @nogc @system int **swscanf**(scope const wchar\_t\* s, scope const wchar\_t\* format, ...);  nothrow @nogc @system int **vfwprintf**(FILE\* stream, scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **vfwscanf**(FILE\* stream, scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **vswprintf**(wchar\_t\* s, size\_t n, scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **vswscanf**(scope const wchar\_t\* s, scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **vwprintf**(scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **vwscanf**(scope const wchar\_t\* format, va\_list arg);  nothrow @nogc @system int **wprintf**(scope const wchar\_t\* format, ...);  nothrow @nogc @system int **wscanf**(scope const wchar\_t\* format, ...);  nothrow @nogc @trusted wint\_t **fgetwc**(FILE\* stream);  nothrow @nogc @trusted wint\_t **fputwc**(wchar\_t c, FILE\* stream);  nothrow @nogc @system wchar\_t\* **fgetws**(wchar\_t\* s, int n, FILE\* stream);  nothrow @nogc @system int **fputws**(scope const wchar\_t\* s, FILE\* stream);  nothrow @nogc @trusted wint\_t **getwchar**();  nothrow @nogc @trusted wint\_t **putwchar**(wchar\_t c);  nothrow @nogc @trusted wint\_t **getwc**(FILE\* stream);  nothrow @nogc @trusted wint\_t **putwc**(wchar\_t c, FILE\* stream);  nothrow @nogc @trusted wint\_t **ungetwc**(wint\_t c, FILE\* stream);  nothrow @nogc @trusted int **fwide**(FILE\* stream, int mode);  nothrow @nogc @system double **wcstod**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr);  nothrow @nogc @system float **wcstof**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr);  nothrow @nogc @system real **wcstold**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr);  nothrow @nogc @system c\_long **wcstol**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  nothrow @nogc @system long **wcstoll**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  nothrow @nogc @system c\_ulong **wcstoul**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  nothrow @nogc @system ulong **wcstoull**(scope const wchar\_t\* nptr, wchar\_t\*\* endptr, int base);  pure nothrow @nogc @system wchar\_t\* **wcscpy**(return wchar\_t\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system wchar\_t\* **wcsncpy**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system wchar\_t\* **wcscat**(return wchar\_t\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system wchar\_t\* **wcsncat**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system int **wcscmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2);  nothrow @nogc @system int **wcscoll**(scope const wchar\_t\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system int **wcsncmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  nothrow @nogc @system size\_t **wcsxfrm**(scope wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system inout(wchar\_t)\* **wcschr**(return inout(wchar\_t)\* s, wchar\_t c);  pure nothrow @nogc @system size\_t **wcscspn**(scope const wchar\_t\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system inout(wchar\_t)\* **wcspbrk**(return inout(wchar\_t)\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system inout(wchar\_t)\* **wcsrchr**(return inout(wchar\_t)\* s, wchar\_t c);  pure nothrow @nogc @system size\_t **wcsspn**(scope const wchar\_t\* s1, scope const wchar\_t\* s2);  pure nothrow @nogc @system inout(wchar\_t)\* **wcsstr**(return inout(wchar\_t)\* s1, scope const wchar\_t\* s2);  nothrow @nogc @system wchar\_t\* **wcstok**(return wchar\_t\* s1, scope const wchar\_t\* s2, wchar\_t\*\* ptr);  pure nothrow @nogc @system size\_t **wcslen**(scope const wchar\_t\* s);  pure nothrow @nogc @system inout(wchar\_t)\* **wmemchr**(return inout wchar\_t\* s, wchar\_t c, size\_t n);  pure nothrow @nogc @system int **wmemcmp**(scope const wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system wchar\_t\* **wmemcpy**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system wchar\_t\* **wmemmove**(return wchar\_t\* s1, scope const wchar\_t\* s2, size\_t n);  pure nothrow @nogc @system wchar\_t\* **wmemset**(return wchar\_t\* s, wchar\_t c, size\_t n);  nothrow @nogc @system size\_t **wcsftime**(wchar\_t\* s, size\_t maxsize, scope const wchar\_t\* format, scope const tm\* timeptr);  nothrow @nogc @trusted wint\_t **btowc**(int c);  nothrow @nogc @trusted int **wctob**(wint\_t c);  nothrow @nogc @system int **mbsinit**(scope const mbstate\_t\* ps);  nothrow @nogc @system size\_t **mbrlen**(scope const char\* s, size\_t n, mbstate\_t\* ps);  nothrow @nogc @system size\_t **mbrtowc**(wchar\_t\* pwc, scope const char\* s, size\_t n, mbstate\_t\* ps);  nothrow @nogc @system size\_t **wcrtomb**(char\* s, wchar\_t wc, mbstate\_t\* ps);  nothrow @nogc @system size\_t **mbsrtowcs**(wchar\_t\* dst, scope const char\*\* src, size\_t len, mbstate\_t\* ps);  nothrow @nogc @system size\_t **wcsrtombs**(char\* dst, scope const wchar\_t\*\* src, size\_t len, mbstate\_t\* ps);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_wchar_.html>

core.stdcpp.new\_
=================

 D binding to C++ 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Manu Evans 
 
Source
 [core/stdcpp/new\_.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/new_.d)

 
struct **nothrow\_t**;  enum **align\_val\_t**: ulong;  class **bad\_alloc**: core.stdcpp.exception.exception;   
@nogc this();    T\* **cpp\_new**(T, Args...)(auto ref Args args)  
 Constraints: if (!is(T == class)); 
 T **cpp\_new**(T, Args...)(auto ref Args args)  
 Constraints: if (is(T == class)); 
 void **cpp\_delete**(T)(T\* ptr)  
 Constraints: if (!is(T == class)); 
 void **cpp\_delete**(T)(T instance)  
 Constraints: if (is(T == class)); 
 @nogc void\* **\_\_cpp\_new**(size\_t count);  
Binding for ::operator new(std::size\_t count)

  nothrow @nogc void\* **\_\_cpp\_new\_nothrow**(size\_t count, ref const(nothrow\_t) = std\_nothrow);  
Binding for ::operator new(std::size\_t count, const std::nothrow\_t&)

  @nogc void **\_\_cpp\_delete**(void\* ptr);  
Binding for ::operator delete(void\* ptr)

  nothrow @nogc void **\_\_cpp\_delete\_nothrow**(void\* ptr, ref const(nothrow\_t) = std\_nothrow);  
Binding for ::operator delete(void\* ptr, const std::nothrow\_t& tag)

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_new_.html>

core.stdcpp.string\_view
========================

 D header file for interaction with C++ std::string\_view. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Manu Evans 
 
Source
 [core/stdcpp/string\_view.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/string_view.d)

 
alias **string\_view** = basic\_string\_view!(char, char\_traits!char).basic\_string\_view;  alias **u16string\_view** = basic\_string\_view!(wchar, char\_traits!wchar).basic\_string\_view;  alias **u32string\_view** = basic\_string\_view!(dchar, char\_traits!dchar).basic\_string\_view;  alias **wstring\_view** = basic\_string\_view!(dchar, char\_traits!dchar).basic\_string\_view;  struct **char\_traits**(CharT);  
Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters.

  struct **basic\_string\_view**(T, Traits = char\_traits!T);  
D language counterpart to C++ std::basic\_string\_view. 


C++ reference: 

 
enum size\_type **npos**;  alias **size\_type** = size\_t;  alias **difference\_type** = ptrdiff\_t;  alias **value\_type** = T;  alias **pointer** = T\*;  alias **const\_pointer** = const(T)\*;  alias **toString** = as\_array;  @trusted this(const(T)[] str);  alias **length** = size;  alias **opDollar** = length;  const @safe size\_type **size**();  const @safe bool **empty**();  const @safe const(T)\* **data**();  const @trusted const(T)[] **as\_array**();  const ref @trusted const(T) **at**(size\_type i);  const ref @safe const(T) **front**();  const ref @safe const(T) **back**();    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_string_view.html>

core.stdcpp.string
==================

 D header file for interaction with C++ std::string. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Guillaume Chatelet Manu Evans 
 
Source
 [core/stdcpp/string.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/string.d)

 
enum DefaultConstruct **Default**;  
Constructor argument for default construction

  struct **char\_traits**(CharT);  
Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters.

  struct **basic\_string**(T, Traits = char\_traits!T, Alloc = allocator!T);  
D language counterpart to C++ std::basic\_string. 


C++ reference: 

 
enum size\_type **npos**;  alias **size\_type** = size\_t;  alias **difference\_type** = ptrdiff\_t;  alias **value\_type** = T;  alias **traits\_type** = Traits;  alias **allocator\_type** = Alloc;  alias **pointer** = value\_type\*;  alias **const\_pointer** = const(value\_type)\*;  alias **toString** = as\_array;  this();  
MSVC allocates on default initialisation in debug, which can't be modelled by D `struct`

  alias **length** = size;  alias **opDollar** = length;  const nothrow @safe bool **empty**();  const pure nothrow @nogc @safe size\_t[2] **opSlice**(size\_t dim : 0)(size\_t start, size\_t end);  inout pure nothrow @nogc ref @safe inout(T) **opIndex**(size\_t index);  inout pure nothrow @nogc @safe inout(T)[] **opIndex**(size\_t[2] slice);  inout pure nothrow @nogc @safe inout(T)[] **opIndex**();  const pure nothrow @safe bool **opEquals**(ref scope const basic\_string s);   
  
const pure nothrow @safe bool **opEquals**(scope const T[] s);  
Two `basic_string`s are equal if they represent the same sequence of code units.

  const pure nothrow @safe int **opCmp**(ref scope const basic\_string rhs);   
  
const pure nothrow @safe int **opCmp**(scope const T[] rhs);  
Performs lexicographical comparison.

  const pure nothrow @nogc @safe size\_t **toHash**();  
Hash to allow `basic_string`s to be used as keys for built-in associative arrays. **The result will generally not be the same as C++ `std::hash<std::basic_string<T>>`.**

  void **clear**();  @trusted void **resize**(size\_type n, T c = T(0));  inout nothrow ref @safe inout(T) **front**();  inout nothrow ref @safe inout(T) **back**();  const nothrow @safe const(T)\* **c\_str**();  ref basic\_string **opAssign**()(auto ref basic\_string str);  ref basic\_string **opAssign**(const(T)[] str);  ref basic\_string **opAssign**(T c);  ref basic\_string **opIndexAssign**(T c, size\_t index);  ref basic\_string **opIndexAssign**(T c, size\_t[2] slice);  ref basic\_string **opIndexAssign**(const(T)[] str, size\_t[2] slice);  ref basic\_string **opIndexAssign**(T c);  ref basic\_string **opIndexAssign**(const(T)[] str);  ref basic\_string **opIndexOpAssign**(string op)(T c, size\_t index);  ref basic\_string **opIndexOpAssign**(string op)(T c, size\_t[2] slice);  ref basic\_string **opIndexOpAssign**(string op)(const(T)[] str, size\_t[2] slice);  ref basic\_string **opIndexOpAssign**(string op)(T c);  ref basic\_string **opIndexOpAssign**(string op)(const(T)[] str);  ref basic\_string **append**(T c);  ref basic\_string **opOpAssign**(string op : "~")(const(T)[] str);  ref basic\_string **opOpAssign**(string op : "~")(T c);  ref basic\_string **insert**(size\_type pos, ref const(basic\_string) str);  ref @trusted basic\_string **insert**(size\_type pos, ref const(basic\_string) str, size\_type subpos, size\_type sublen);  ref basic\_string **insert**(S : size\_type)(S pos, const(T)\* s);  ref basic\_string **insert**(size\_type pos, const(T)[] s);  ref basic\_string **erase**(size\_type pos = 0);  ref basic\_string **erase**(size\_type pos, size\_type len);  ref basic\_string **replace**()(size\_type pos, size\_type len, auto ref basic\_string str);  ref basic\_string **replace**()(size\_type pos, size\_type len, auto ref basic\_string str, size\_type subpos, size\_type sublen = npos);  ref basic\_string **replace**(size\_type pos, size\_type len, const(value\_type)[] s);  ref basic\_string **replace**(S : size\_type)(S pos, size\_type len, const(value\_type)\* s);  @trusted void **push\_back**(T c);  void **pop\_back**();  this(DefaultConstruct);  this(const(T)[] str);  this(const(T)[] str, ref const(allocator\_type) al);  inout ref inout(Alloc) **get\_allocator**();  const nothrow @safe size\_type **max\_size**();  const nothrow @safe size\_type **size**();  const nothrow @safe size\_type **capacity**();  inout @safe inout(T)\* **data**();  inout nothrow @trusted inout(T)[] **as\_array**();  inout nothrow ref @trusted inout(T) **at**(size\_type i);  ref basic\_string **assign**(const(T)[] str);  ref basic\_string **assign**(ref const basic\_string str);  ref basic\_string **append**(const(T)[] str);  ref basic\_string **append**(size\_type n, T c);  void **reserve**(size\_type \_Newcap = 0);  void **shrink\_to\_fit**();  ref basic\_string **insert**(size\_type pos, const(T)\* s, size\_type n);  ref basic\_string **insert**(size\_type pos, size\_type n, T c);  ref basic\_string **replace**(size\_type pos, size\_type len, const(T)\* s, size\_type slen);  ref basic\_string **replace**(size\_type \_Off, size\_type \_N0, size\_type \_Count, T \_Ch);  void **swap**(ref basic\_string \_Right);    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_string.html>

core.stdc.tgmath
================

 D header file for C99. 


This module contains bindings to selected types and functions from the standard C header [`<tgmath.h>`](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/tgmath.h.html). Note that this is not automatically generated, and may omit some types/functions from the original C header. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly 
 
Source
 [core/stdc/tgmath.d](https://github.com/dlang/druntime/blob/master/src/core/stdc/tgmath.d) 
 
Standards:
ISO/IEC 9899:1999 (E)
 
alias **acos** = **acos**;  alias **acos** = **acos**;  alias **acos** = **acos**;  alias **acos** = **acos**;  alias **acos** = **acos**;  alias **acos** = core.stdc.complex.cacosl;  alias **asin** = **asin**;  alias **asin** = **asin**;  alias **asin** = **asin**;  alias **asin** = **asin**;  alias **asin** = **asin**;  alias **asin** = core.stdc.complex.casinl;  alias **atan** = **atan**;  alias **atan** = **atan**;  alias **atan** = **atan**;  alias **atan** = **atan**;  alias **atan** = **atan**;  alias **atan** = core.stdc.complex.catanl;  alias **atan2** = **atan2**;  alias **atan2** = **atan2**;  alias **atan2** = core.stdc.math.atan2l;  alias **cos** = **cos**;  alias **cos** = **cos**;  alias **cos** = **cos**;  alias **cos** = **cos**;  alias **cos** = **cos**;  alias **cos** = core.stdc.complex.ccosl;  alias **sin** = **sin**;  alias **sin** = **sin**;  alias **sin** = core.stdc.math.sinl;  alias **csin** = **csin**;  alias **csin** = **csin**;  alias **csin** = core.stdc.complex.csinl;  alias **tan** = **tan**;  alias **tan** = **tan**;  alias **tan** = **tan**;  alias **tan** = **tan**;  alias **tan** = **tan**;  alias **tan** = core.stdc.complex.ctanl;  alias **acosh** = **acosh**;  alias **acosh** = **acosh**;  alias **acosh** = **acosh**;  alias **acosh** = **acosh**;  alias **acosh** = **acosh**;  alias **acosh** = core.stdc.complex.cacoshl;  alias **asinh** = **asinh**;  alias **asinh** = **asinh**;  alias **asinh** = **asinh**;  alias **asinh** = **asinh**;  alias **asinh** = **asinh**;  alias **asinh** = core.stdc.complex.casinhl;  alias **atanh** = **atanh**;  alias **atanh** = **atanh**;  alias **atanh** = **atanh**;  alias **atanh** = **atanh**;  alias **atanh** = **atanh**;  alias **atanh** = core.stdc.complex.catanhl;  alias **cosh** = **cosh**;  alias **cosh** = **cosh**;  alias **cosh** = **cosh**;  alias **cosh** = **cosh**;  alias **cosh** = **cosh**;  alias **cosh** = core.stdc.complex.ccoshl;  alias **sinh** = **sinh**;  alias **sinh** = **sinh**;  alias **sinh** = **sinh**;  alias **sinh** = **sinh**;  alias **sinh** = **sinh**;  alias **sinh** = core.stdc.complex.csinhl;  alias **tanh** = **tanh**;  alias **tanh** = **tanh**;  alias **tanh** = **tanh**;  alias **tanh** = **tanh**;  alias **tanh** = **tanh**;  alias **tanh** = core.stdc.complex.ctanhl;  alias **exp** = **exp**;  alias **exp** = **exp**;  alias **exp** = **exp**;  alias **exp** = **exp**;  alias **exp** = **exp**;  alias **exp** = core.stdc.complex.cexpl;  alias **exp2** = **exp2**;  alias **exp2** = **exp2**;  alias **exp2** = core.stdc.math.exp2l;  alias **expm1** = **expm1**;  alias **expm1** = **expm1**;  alias **expm1** = core.stdc.math.expm1l;  alias **frexp** = **frexp**;  alias **frexp** = **frexp**;  alias **frexp** = core.stdc.math.frexpl;  alias **ilogb** = **ilogb**;  alias **ilogb** = **ilogb**;  alias **ilogb** = core.stdc.math.ilogbl;  alias **ldexp** = **ldexp**;  alias **ldexp** = **ldexp**;  alias **ldexp** = core.stdc.math.ldexpl;  alias **log** = **log**;  alias **log** = **log**;  alias **log** = **log**;  alias **log** = **log**;  alias **log** = **log**;  alias **log** = core.stdc.complex.clogl;  alias **log10** = **log10**;  alias **log10** = **log10**;  alias **log10** = core.stdc.math.log10l;  alias **log1p** = **log1p**;  alias **log1p** = **log1p**;  alias **log1p** = core.stdc.math.log1pl;  alias **log2** = **log2**;  alias **log2** = **log2**;  alias **log2** = core.stdc.math.log2l;  alias **logb** = **logb**;  alias **logb** = **logb**;  alias **logb** = core.stdc.math.logbl;  alias **modf** = **modf**;  alias **modf** = **modf**;  alias **modf** = core.stdc.math.modfl;  alias **scalbn** = **scalbn**;  alias **scalbn** = **scalbn**;  alias **scalbn** = core.stdc.math.scalbnl;  alias **scalbln** = **scalbln**;  alias **scalbln** = **scalbln**;  alias **scalbln** = core.stdc.math.scalblnl;  alias **cbrt** = **cbrt**;  alias **cbrt** = **cbrt**;  alias **cbrt** = core.stdc.math.cbrtl;  alias **fabs** = **fabs**;  alias **fabs** = **fabs**;  alias **fabs** = **fabs**;  alias **fabs** = **fabs**;  alias **fabs** = **fabs**;  alias **fabs** = core.stdc.complex.cabsl;  alias **hypot** = **hypot**;  alias **hypot** = **hypot**;  alias **hypot** = core.stdc.math.hypotl;  alias **pow** = **pow**;  alias **pow** = **pow**;  alias **pow** = **pow**;  alias **pow** = **pow**;  alias **pow** = **pow**;  alias **pow** = core.stdc.complex.cpowl;  alias **sqrt** = **sqrt**;  alias **sqrt** = **sqrt**;  alias **sqrt** = **sqrt**;  alias **sqrt** = **sqrt**;  alias **sqrt** = **sqrt**;  alias **sqrt** = core.stdc.complex.csqrtl;  alias **erf** = **erf**;  alias **erf** = **erf**;  alias **erf** = core.stdc.math.erfl;  alias **erfc** = **erfc**;  alias **erfc** = **erfc**;  alias **erfc** = core.stdc.math.erfcl;  alias **lgamma** = **lgamma**;  alias **lgamma** = **lgamma**;  alias **lgamma** = core.stdc.math.lgammal;  alias **tgamma** = **tgamma**;  alias **tgamma** = **tgamma**;  alias **tgamma** = core.stdc.math.tgammal;  alias **ceil** = **ceil**;  alias **ceil** = **ceil**;  alias **ceil** = core.stdc.math.ceill;  alias **floor** = **floor**;  alias **floor** = **floor**;  alias **floor** = core.stdc.math.floorl;  alias **nearbyint** = **nearbyint**;  alias **nearbyint** = **nearbyint**;  alias **nearbyint** = core.stdc.math.nearbyintl;  alias **rint** = **rint**;  alias **rint** = **rint**;  alias **rint** = core.stdc.math.rintl;  alias **lrint** = **lrint**;  alias **lrint** = **lrint**;  alias **lrint** = core.stdc.math.lrintl;  alias **llrint** = **llrint**;  alias **llrint** = **llrint**;  alias **llrint** = core.stdc.math.llrintl;  alias **round** = **round**;  alias **round** = **round**;  alias **round** = core.stdc.math.roundl;  alias **lround** = **lround**;  alias **lround** = **lround**;  alias **lround** = core.stdc.math.lroundl;  alias **llround** = **llround**;  alias **llround** = **llround**;  alias **llround** = core.stdc.math.llroundl;  alias **trunc** = **trunc**;  alias **trunc** = **trunc**;  alias **trunc** = core.stdc.math.truncl;  alias **fmod** = **fmod**;  alias **fmod** = **fmod**;  alias **fmod** = core.stdc.math.fmodl;  alias **remainder** = **remainder**;  alias **remainder** = **remainder**;  alias **remainder** = core.stdc.math.remainderl;  alias **remquo** = **remquo**;  alias **remquo** = **remquo**;  alias **remquo** = core.stdc.math.remquol;  alias **copysign** = **copysign**;  alias **copysign** = **copysign**;  alias **copysign** = core.stdc.math.copysignl;  alias **nan** = **nan**;  alias **nan** = **nan**;  alias **nan** = core.stdc.math.nanl;  alias **nextafter** = **nextafter**;  alias **nextafter** = **nextafter**;  alias **nextafter** = core.stdc.math.nextafterl;  alias **nexttoward** = **nexttoward**;  alias **nexttoward** = **nexttoward**;  alias **nexttoward** = core.stdc.math.nexttowardl;  alias **fdim** = **fdim**;  alias **fdim** = **fdim**;  alias **fdim** = core.stdc.math.fdiml;  alias **fmax** = **fmax**;  alias **fmax** = **fmax**;  alias **fmax** = core.stdc.math.fmaxl;  alias **fmin** = **fmin**;  alias **fmin** = **fmin**;  alias **fmin** = core.stdc.math.fminl;  alias **fma** = **fma**;  alias **fma** = **fma**;  alias **fma** = core.stdc.math.fmal;  alias **carg** = **carg**;  alias **carg** = **carg**;  alias **carg** = core.stdc.complex.cargl;  alias **cimag** = **cimag**;  alias **cimag** = **cimag**;  alias **cimag** = core.stdc.complex.cimagl;  alias **conj** = **conj**;  alias **conj** = **conj**;  alias **conj** = core.stdc.complex.conjl;  alias **cproj** = **cproj**;  alias **cproj** = **cproj**;  alias **cproj** = core.stdc.complex.cprojl;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdc_tgmath.html>

core.stdcpp.type\_traits
========================

 D header file for interaction with C++ std::type\_traits. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Manu Evans 
 
Source
 [core/stdcpp/type\_traits.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/type_traits.d)

 
struct **integral\_constant**(T, T Val);   
enum T **value**;  alias **value\_type** = T;  alias **type** = typeof(this);    template **bool\_constant**(bool b) alias **true\_type** = integral\_constant!(bool, true).integral\_constant;  alias **false\_type** = integral\_constant!(bool, false).integral\_constant;  struct **is\_empty**(T);   
enum bool **value**;  alias **value\_type** = bool;  alias **type** = integral\_constant!(bool, value);    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_type_traits.html>

core.sync.barrier
=================

 The barrier module provides a primitive for synchronizing the progress of a group of threads. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/barrier.d](https://github.com/dlang/druntime/blob/master/src/core/sync/barrier.d)

 
class **Barrier**;  
This class represents a barrier across which threads may only travel in groups of a specific size.



Examples:


```
import core.thread;

int  numThreads = 10;
auto barrier    = new Barrier( numThreads );
auto synInfo    = new Object;
int  numReady   = 0;
int  numPassed  = 0;

void threadFn()
{
    synchronized( synInfo )
    {
        ++numReady;
    }
    barrier.wait();
    synchronized( synInfo )
    {
        ++numPassed;
    }
}

auto group = new ThreadGroup;

for ( int i = 0; i < numThreads; ++i )
{
    group.create( &threadFn );
}
group.joinAll();
assert( numReady == numThreads && numPassed == numThreads );

```
 
 
this(uint limit);  
Initializes a barrier object which releases threads in groups of limit in size. 



Parameters:


|  |  |
| --- | --- |
| uint `limit` | The number of waiting threads to release in unison. |


 
Throws:
SyncError on error.
  void **wait**();  
Wait for the pre-determined number of threads and then proceed. 



Throws:
SyncError on error.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_barrier.html>

core.stdcpp.typeinfo
====================

 Interface to C++ 



License:

[Boost License 1.0](http://boost.org/LICENSE_1_0.txt). 
 
Authors:

[Walter Bright](http://digitalmars.com) 
 
Source
 [core/stdcpp/typeinfo.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/typeinfo.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_typeinfo.html>

core.stdcpp.vector
==================

 D header file for interaction with C++ std::vector. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Guillaume Chatelet Manu Evans 
 
Source
 [core/stdcpp/vector.d](https://github.com/dlang/druntime/blob/master/src/core/stdcpp/vector.d)

 
enum DefaultConstruct **Default**;  
Constructor argument for default construction

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_stdcpp_vector.html>

core.sync.condition
===================

 The condition module provides a primitive for synchronized condition checking. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/condition.d](https://github.com/dlang/druntime/blob/master/src/core/sync/condition.d)

 
class **Condition**;  
This class represents a condition variable as conceived by C.A.R. Hoare. As per Mesa type monitors however, "signal" has been replaced with "notify" to indicate that control is not transferred to the waiter when a notification is sent.



Examples:


```
import core.thread;
import core.sync.mutex;
import core.sync.semaphore;


void testNotify()
{
    auto mutex      = new Mutex;
    auto condReady  = new Condition( mutex );
    auto semDone    = new Semaphore;
    auto synLoop    = new Object;
    int  numWaiters = 10;
    int  numTries   = 10;
    int  numReady   = 0;
    int  numTotal   = 0;
    int  numDone    = 0;
    int  numPost    = 0;

    void waiter()
    {
        for ( int i = 0; i < numTries; ++i )
        {
            synchronized( mutex )
            {
                while ( numReady < 1 )
                {
                    condReady.wait();
                }
                --numReady;
                ++numTotal;
            }

            synchronized( synLoop )
            {
                ++numDone;
            }
            semDone.wait();
        }
    }

    auto group = new ThreadGroup;

    for ( int i = 0; i < numWaiters; ++i )
        group.create( &waiter );

    for ( int i = 0; i < numTries; ++i )
    {
        for ( int j = 0; j < numWaiters; ++j )
        {
            synchronized( mutex )
            {
                ++numReady;
                condReady.notify();
            }
        }
        while ( true )
        {
            synchronized( synLoop )
            {
                if ( numDone >= numWaiters )
                    break;
            }
            Thread.yield();
        }
        for ( int j = 0; j < numWaiters; ++j )
        {
            semDone.notify();
        }
    }

    group.joinAll();
    assert( numTotal == numWaiters * numTries );
}


void testNotifyAll()
{
    auto mutex      = new Mutex;
    auto condReady  = new Condition( mutex );
    int  numWaiters = 10;
    int  numReady   = 0;
    int  numDone    = 0;
    bool alert      = false;

    void waiter()
    {
        synchronized( mutex )
        {
            ++numReady;
            while ( !alert )
                condReady.wait();
            ++numDone;
        }
    }

    auto group = new ThreadGroup;

    for ( int i = 0; i < numWaiters; ++i )
        group.create( &waiter );

    while ( true )
    {
        synchronized( mutex )
        {
            if ( numReady >= numWaiters )
            {
                alert = true;
                condReady.notifyAll();
                break;
            }
        }
        Thread.yield();
    }
    group.joinAll();
    assert( numReady == numWaiters && numDone == numWaiters );
}


void testWaitTimeout()
{
    auto mutex      = new Mutex;
    auto condReady  = new Condition( mutex );
    bool waiting    = false;
    bool alertedOne = true;
    bool alertedTwo = true;

    void waiter()
    {
        synchronized( mutex )
        {
            waiting    = true;
            // we never want to miss the notification (30s)
            alertedOne = condReady.wait( dur!"seconds"(30) );
            // but we don't want to wait long for the timeout (10ms)
            alertedTwo = condReady.wait( dur!"msecs"(10) );
        }
    }

    auto thread = new Thread( &waiter );
    thread.start();

    while ( true )
    {
        synchronized( mutex )
        {
            if ( waiting )
            {
                condReady.notify();
                break;
            }
        }
        Thread.yield();
    }
    thread.join();
    assert( waiting );
    assert( alertedOne );
    assert( !alertedTwo );
}

testNotify();
testNotifyAll();
testWaitTimeout();

```
 
 
nothrow @safe this(Mutex m);   
  
shared nothrow @safe this(shared Mutex m);  
Initializes a condition object which is associated with the supplied mutex object. 



Parameters:


|  |  |
| --- | --- |
| Mutex `m` | The mutex with which this condition will be associated. |


 
Throws:
SyncError on error.
  @property Mutex **mutex**();   
  
shared @property shared(Mutex) **mutex**();  
Gets the mutex associated with this condition. 



Returns:
The mutex associated with this condition.
  void **wait**();   
  
shared void **wait**();   
  
void **wait**(this Q)(bool \_unused\_)  
 Constraints: if (is(Q == Condition) || is(Q == shared(Condition))); 
 
Wait until notified. 



Throws:
SyncError on error.
  bool **wait**(Duration val);   
  
shared bool **wait**(Duration val);   
  
bool **wait**(this Q)(Duration val, bool \_unused\_)  
 Constraints: if (is(Q == Condition) || is(Q == shared(Condition))); 
 
Suspends the calling thread until a notification occurs or until the supplied time period has elapsed. 



Parameters:


|  |  |
| --- | --- |
| Duration `val` | The time to wait. |


 
In
 val must be non-negative. 
 
Throws:
SyncError on error. 
 
Returns:
true if notified before the timeout and false if not.
  void **notify**();   
  
shared void **notify**();   
  
void **notify**(this Q)(bool \_unused\_)  
 Constraints: if (is(Q == Condition) || is(Q == shared(Condition))); 
 
Notifies one waiter. 



Throws:
SyncError on error.
  void **notifyAll**();   
  
shared void **notifyAll**();   
  
void **notifyAll**(this Q)(bool \_unused\_)  
 Constraints: if (is(Q == Condition) || is(Q == shared(Condition))); 
 
Notifies all waiters. 



Throws:
SyncError on error.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_condition.html>

core.sync.config
================

 The config module contains utility routines and configuration information specific to this package. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/config.d](https://github.com/dlang/druntime/blob/master/src/core/sync/config.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_config.html>

core.sync.exception
===================

 Define base class for synchronization exceptions. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/exception.d](https://github.com/dlang/druntime/blob/master/src/core/sync/exception.d)

 
class **SyncError**: object.Error;  
Base class for synchronization errors.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_exception.html>

core.sync.event
===============

 The event module provides a primitive for lightweight signaling of other threads (emulating Windows events on Posix) 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Rainer Schuetze 
 
Source
 [core/sync/event.d](https://github.com/dlang/druntime/blob/master/src/core/sync/event.d)

 
struct **Event**;  
represents an event. Clients of an event are suspended while waiting for the event to be "signaled". 


 Implemented using `pthread_mutex` and `pthread_condition` on Posix and `CreateEvent` and `SetEvent` on Windows. 
```
import core.sync.event, core.thread, std.file;

struct ProcessFile
{
    ThreadGroup group;
    Event event;
    void[] buffer;

    void doProcess()
    {
        event.wait();
        // process buffer
    }

    void process(string filename)
    {
        event.initialize(true, false);
        group = new ThreadGroup;
        for (int i = 0; i < 10; ++i)
            group.create(&doProcess);

        buffer = std.file.read(filename);
        event.set();
        group.joinAll();
        event.terminate();
    }
}

```
 

 
nothrow @nogc this(bool manualReset, bool initialState);  
Creates an event object. 



Parameters:


|  |  |
| --- | --- |
| bool `manualReset` | the state of the event is not reset automatically after resuming waiting clients |
| bool `initialState` | initial state of the signal |


  nothrow @nogc void **initialize**(bool manualReset, bool initialState);  
Initializes an event object. Does nothing if the event is already initialized. 



Parameters:


|  |  |
| --- | --- |
| bool `manualReset` | the state of the event is not reset automatically after resuming waiting clients |
| bool `initialState` | initial state of the signal |


  nothrow @nogc void **terminate**();  
deinitialize event. Does nothing if the event is not initialized. There must not be threads currently waiting for the event to be signaled.

  nothrow @nogc void **set**();  
Set the event to "signaled", so that waiting clients are resumed

  nothrow @nogc void **reset**();  
Reset the event manually

  nothrow @nogc bool **wait**();  
Wait for the event to be signaled without timeout. 



Returns:

`true` if the event is in signaled state, `false` if the event is uninitialized or another error occured
  nothrow @nogc bool **wait**(Duration tmout);  
Wait for the event to be signaled with timeout. 



Parameters:


|  |  |
| --- | --- |
| Duration `tmout` | the maximum time to wait |


 
Returns:

`true` if the event is in signaled state, `false` if the event was nonsignaled for the given time or the event is uninitialized or another error occured
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_event.html>

core.sync.mutex
===============

 The mutex module provides a primitive for maintaining mutually exclusive access. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/mutex.d](https://github.com/dlang/druntime/blob/master/src/core/sync/mutex.d)

 
class **Mutex**: object.Object.Monitor;  
This class represents a general purpose, recursive mutex. 


Implemented using `pthread_mutex` on Posix and `CRITICAL_SECTION` on Windows.

 
Examples:


```
import core.thread : Thread;

class Resource
{
    Mutex mtx;
    int cargo;

    this() shared @safe nothrow
    {
        mtx = new shared Mutex();
        cargo = 42;
    }

    void useResource() shared @safe nothrow @nogc
    {
        mtx.lock_nothrow();
        (cast() cargo) += 1;
        mtx.unlock_nothrow();
    }
}

shared Resource res = new shared Resource();

auto otherThread = new Thread(
{
    foreach (i; 0 .. 10000)
        res.useResource();
}).start();

foreach (i; 0 .. 10000)
    res.useResource();

otherThread.join();

assert (res.cargo == 20042);

```
 
 
nothrow @nogc @trusted this();   
  
shared nothrow @nogc @trusted this();  
Initializes a mutex object. 

  nothrow @nogc @trusted this(Object obj);   
  
shared nothrow @nogc @trusted this(Object obj);  
Initializes a mutex object and sets it as the monitor for `obj`. 



In
 `obj` must not already have a monitor.
  @trusted void **lock**();   
  
shared @trusted void **lock**();   
  
final nothrow @nogc @trusted void **lock\_nothrow**(this Q)()  
 Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); 
 
If this lock is not already held by the caller, the lock is acquired, then the internal counter is incremented by one. 



Note
 `Mutex.lock` does not throw, but a class derived from Mutex can throw. Use `lock_nothrow` in `nothrow @nogc` code.
  @trusted void **unlock**();   
  
shared @trusted void **unlock**();   
  
final nothrow @nogc @trusted void **unlock\_nothrow**(this Q)()  
 Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); 
 
Decrements the internal lock count by one. If this brings the count to zero, the lock is released. 



Note
 `Mutex.unlock` does not throw, but a class derived from Mutex can throw. Use `unlock_nothrow` in `nothrow @nogc` code.
  @trusted bool **tryLock**();   
  
shared @trusted bool **tryLock**();   
  
final nothrow @nogc @trusted bool **tryLock\_nothrow**(this Q)()  
 Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); 
 
If the lock is held by another caller, the method returns. Otherwise, the lock is acquired if it is not already held, and then the internal counter is incremented by one. 



Returns:
true if the lock was acquired and false if not. 
 
Note
 `Mutex.tryLock` does not throw, but a class derived from Mutex can throw. Use `tryLock_nothrow` in `nothrow @nogc` code.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_mutex.html>

core.thread
===========

 The thread module provides support for thread creation and management. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak 
 
Source
 [core/thread/package.d](https://github.com/dlang/druntime/blob/master/src/core/thread/package.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_thread.html>

core.sync.rwmutex
=================

 The read/write mutex module provides a primitive for maintaining shared read access and mutually exclusive write access. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/rwmutex.d](https://github.com/dlang/druntime/blob/master/src/core/sync/rwmutex.d)

 
class **ReadWriteMutex**;  
This class represents a mutex that allows any number of readers to enter, but when a writer enters, all other readers and writers are blocked. 


Please note that this mutex is not recursive and is intended to guard access to data only. Also, no deadlock checking is in place because doing so would require dynamic memory allocation, which would reduce performance by an unacceptable amount. As a result, any attempt to recursively acquire this mutex may well deadlock the caller, particularly if a write lock is acquired while holding a read lock, or vice-versa. In practice, this should not be an issue however, because it is uncommon to call deeply into unknown code while holding a lock that simply protects data.

 
Examples:


```
import core.atomic, core.thread, core.sync.semaphore;

static void runTest(ReadWriteMutex.Policy policy)
{
    scope mutex = new ReadWriteMutex(policy);
    scope rdSemA = new Semaphore, rdSemB = new Semaphore,
          wrSemA = new Semaphore, wrSemB = new Semaphore;
    shared size_t numReaders, numWriters;

    void readerFn()
    {
        synchronized (mutex.reader)
        {
            atomicOp!"+="(numReaders, 1);
            rdSemA.notify();
            rdSemB.wait();
            atomicOp!"-="(numReaders, 1);
        }
    }

    void writerFn()
    {
        synchronized (mutex.writer)
        {
            atomicOp!"+="(numWriters, 1);
            wrSemA.notify();
            wrSemB.wait();
            atomicOp!"-="(numWriters, 1);
        }
    }

    void waitQueued(size_t queuedReaders, size_t queuedWriters)
    {
        for (;;)
        {
            synchronized (mutex.m_commonMutex)
            {
                if (mutex.m_numQueuedReaders == queuedReaders &&
                    mutex.m_numQueuedWriters == queuedWriters)
                    break;
            }
            Thread.yield();
        }
    }

    scope group = new ThreadGroup;

    // 2 simultaneous readers
    group.create(&readerFn); group.create(&readerFn);
    rdSemA.wait(); rdSemA.wait();
    assert(numReaders == 2);
    rdSemB.notify(); rdSemB.notify();
    group.joinAll();
    assert(numReaders == 0);
    foreach (t; group) group.remove(t);

    // 1 writer at a time
    group.create(&writerFn); group.create(&writerFn);
    wrSemA.wait();
    assert(!wrSemA.tryWait());
    assert(numWriters == 1);
    wrSemB.notify();
    wrSemA.wait();
    assert(numWriters == 1);
    wrSemB.notify();
    group.joinAll();
    assert(numWriters == 0);
    foreach (t; group) group.remove(t);

    // reader and writer are mutually exclusive
    group.create(&readerFn);
    rdSemA.wait();
    group.create(&writerFn);
    waitQueued(0, 1);
    assert(!wrSemA.tryWait());
    assert(numReaders == 1 && numWriters == 0);
    rdSemB.notify();
    wrSemA.wait();
    assert(numReaders == 0 && numWriters == 1);
    wrSemB.notify();
    group.joinAll();
    assert(numReaders == 0 && numWriters == 0);
    foreach (t; group) group.remove(t);

    // writer and reader are mutually exclusive
    group.create(&writerFn);
    wrSemA.wait();
    group.create(&readerFn);
    waitQueued(1, 0);
    assert(!rdSemA.tryWait());
    assert(numReaders == 0 && numWriters == 1);
    wrSemB.notify();
    rdSemA.wait();
    assert(numReaders == 1 && numWriters == 0);
    rdSemB.notify();
    group.joinAll();
    assert(numReaders == 0 && numWriters == 0);
    foreach (t; group) group.remove(t);

    // policy determines whether queued reader or writers progress first
    group.create(&writerFn);
    wrSemA.wait();
    group.create(&readerFn);
    group.create(&writerFn);
    waitQueued(1, 1);
    assert(numReaders == 0 && numWriters == 1);
    wrSemB.notify();

    if (policy == ReadWriteMutex.Policy.PREFER_READERS)
    {
        rdSemA.wait();
        assert(numReaders == 1 && numWriters == 0);
        rdSemB.notify();
        wrSemA.wait();
        assert(numReaders == 0 && numWriters == 1);
        wrSemB.notify();
    }
    else if (policy == ReadWriteMutex.Policy.PREFER_WRITERS)
    {
        wrSemA.wait();
        assert(numReaders == 0 && numWriters == 1);
        wrSemB.notify();
        rdSemA.wait();
        assert(numReaders == 1 && numWriters == 0);
        rdSemB.notify();
    }
    group.joinAll();
    assert(numReaders == 0 && numWriters == 0);
    foreach (t; group) group.remove(t);
}
runTest(ReadWriteMutex.Policy.PREFER_READERS);
runTest(ReadWriteMutex.Policy.PREFER_WRITERS);

```
 
 
enum **Policy**: int;  
Defines the policy used by this mutex. Currently, two policies are defined. 


The first will queue writers until no readers hold the mutex, then pass the writers through one at a time. If a reader acquires the mutex while there are still writers queued, the reader will take precedence.   
  
 The second will queue readers if there are any writers queued. Writers are passed through one at a time, and once there are no writers present, all queued readers will be alerted.   
  
 Future policies may offer a more even balance between reader and writer precedence.

 
**PREFER\_READERS** 
Readers get preference. This may starve writers.

  **PREFER\_WRITERS** 
Writers get preference. This may starve readers.

    this(Policy policy = Policy.PREFER\_WRITERS);  
Initializes a read/write mutex object with the supplied policy. 



Parameters:


|  |  |
| --- | --- |
| Policy `policy` | The policy to use. |


 
Throws:
SyncError on error.
  @property Policy **policy**();  
Gets the policy used by this mutex. 



Returns:
The policy used by this mutex.
  @property Reader **reader**();  
Gets an object representing the reader lock for the associated mutex. 



Returns:
A reader sub-mutex.
  @property Writer **writer**();  
Gets an object representing the writer lock for the associated mutex. 



Returns:
A writer sub-mutex.
  class **Reader**: object.Object.Monitor;  
This class can be considered a mutex in its own right, and is used to negotiate a read lock for the enclosing mutex.

 
this();  
Initializes a read/write mutex reader proxy object.

  @trusted void **lock**();  
Acquires a read lock on the enclosing mutex.

  @trusted void **unlock**();  
Releases a read lock on the enclosing mutex.

  bool **tryLock**();  
Attempts to acquire a read lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the lock is not acquired and false is returned. 



Returns:
true if the lock was acquired and false if not.
  bool **tryLock**(Duration timeout);  
Attempts to acquire a read lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the function blocks until either the lock can be obtained or the time elapsed exceeds timeout, returning true if the lock was acquired and false if the function timed out. 



Parameters:


|  |  |
| --- | --- |
| Duration `timeout` | maximum amount of time to wait for the lock |


 
Returns:
true if the lock was acquired and false if not.
    class **Writer**: object.Object.Monitor;  
This class can be considered a mutex in its own right, and is used to negotiate a write lock for the enclosing mutex.

 
this();  
Initializes a read/write mutex writer proxy object.

  @trusted void **lock**();  
Acquires a write lock on the enclosing mutex.

  @trusted void **unlock**();  
Releases a write lock on the enclosing mutex.

  bool **tryLock**();  
Attempts to acquire a write lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the lock is not acquired and false is returned. 



Returns:
true if the lock was acquired and false if not.
  bool **tryLock**(Duration timeout);  
Attempts to acquire a write lock on the enclosing mutex. If one can be obtained without blocking, the lock is acquired and true is returned. If not, the function blocks until either the lock can be obtained or the time elapsed exceeds timeout, returning true if the lock was acquired and false if the function timed out. 



Parameters:


|  |  |
| --- | --- |
| Duration `timeout` | maximum amount of time to wait for the lock |


 
Returns:
true if the lock was acquired and false if not.
      

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_rwmutex.html>

core.sync.semaphore
===================

 The semaphore module provides a general use semaphore for synchronization. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Sean Kelly 
 
Source
 [core/sync/semaphore.d](https://github.com/dlang/druntime/blob/master/src/core/sync/semaphore.d)

 
class **Semaphore**;  
This class represents a general counting semaphore as concieved by Edsger Dijkstra. As per Mesa type monitors however, "signal" has been replaced with "notify" to indicate that control is not transferred to the waiter when a notification is sent.



Examples:


```
import core.thread, core.atomic;

void testWait()
{
    auto semaphore = new Semaphore;
    shared bool stopConsumption = false;
    immutable numToProduce = 20;
    immutable numConsumers = 10;
    shared size_t numConsumed;
    shared size_t numComplete;

    void consumer()
    {
        while (true)
        {
            semaphore.wait();

            if (atomicLoad(stopConsumption))
                break;
            atomicOp!"+="(numConsumed, 1);
        }
        atomicOp!"+="(numComplete, 1);
    }

    void producer()
    {
        assert(!semaphore.tryWait());

        foreach (_; 0 .. numToProduce)
            semaphore.notify();

        // wait until all items are consumed
        while (atomicLoad(numConsumed) != numToProduce)
            Thread.yield();

        // mark consumption as finished
        atomicStore(stopConsumption, true);

        // wake all consumers
        foreach (_; 0 .. numConsumers)
            semaphore.notify();

        // wait until all consumers completed
        while (atomicLoad(numComplete) != numConsumers)
            Thread.yield();

        assert(!semaphore.tryWait());
        semaphore.notify();
        assert(semaphore.tryWait());
        assert(!semaphore.tryWait());
    }

    auto group = new ThreadGroup;

    for ( int i = 0; i < numConsumers; ++i )
        group.create(&consumer);
    group.create(&producer);
    group.joinAll();
}


void testWaitTimeout()
{
    auto sem = new Semaphore;
    shared bool semReady;
    bool alertedOne, alertedTwo;

    void waiter()
    {
        while (!atomicLoad(semReady))
            Thread.yield();
        alertedOne = sem.wait(dur!"msecs"(1));
        alertedTwo = sem.wait(dur!"msecs"(1));
        assert(alertedOne && !alertedTwo);
    }

    auto thread = new Thread(&waiter);
    thread.start();

    sem.notify();
    atomicStore(semReady, true);
    thread.join();
    assert(alertedOne && !alertedTwo);
}

testWait();
testWaitTimeout();

```
 
 
this(uint count = 0);  
Initializes a semaphore object with the specified initial count. 



Parameters:


|  |  |
| --- | --- |
| uint `count` | The initial count for the semaphore. |


 
Throws:
SyncError on error.
  void **wait**();  
Wait until the current count is above zero, then atomically decrement the count by one and return. 



Throws:
SyncError on error.
  bool **wait**(Duration period);  
Suspends the calling thread until the current count moves above zero or until the supplied time period has elapsed. If the count moves above zero in this interval, then atomically decrement the count by one and return true. Otherwise, return false. 



Parameters:


|  |  |
| --- | --- |
| Duration `period` | The time to wait. |


 
In
 period must be non-negative. 
 
Throws:
SyncError on error. 
 
Returns:
true if notified before the timeout and false if not.
  void **notify**();  
Atomically increment the current count by one. This will notify one waiter, if there are any in the queue. 



Throws:
SyncError on error.
  bool **tryWait**();  
If the current count is equal to zero, return. Otherwise, atomically decrement the count by one and return true. 



Throws:
SyncError on error. 
 
Returns:
true if the count was above zero and false if not.
  protected alias **Handle** = core.sys.posix.semaphore.sem\_t;  
Aliases the operating-system-specific semaphore type.

  protected Handle **m\_hndl**;  
Handle to the system-specific semaphore.

    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_sync_semaphore.html>

core.thread.fiber
=================

 The fiber module provides OS-indepedent lightweight threads aka fibers. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak 
 
Source
 [core/thread/fiber.d](https://github.com/dlang/druntime/blob/master/src/core/thread/fiber.d)

 
class **Fiber**;  
This class provides a cooperative concurrency mechanism integrated with the threading and garbage collection functionality. Calling a fiber may be considered a blocking operation that returns when the fiber yields (via Fiber.yield()). Execution occurs within the context of the calling thread so synchronization is not necessary to guarantee memory visibility so long as the same thread calls the fiber each time. Please note that there is no requirement that a fiber be bound to one specific thread. Rather, fibers may be freely passed between threads so long as they are not currently executing. Like threads, a new fiber thread may be created using either derivation or composition, as in the following example. 



Warning
 Status registers are not saved by the current implementations. This means floating point exception status bits (overflow, divide by 0), rounding mode and similar stuff is set per-thread, not per Fiber! 
 
Warning
 On ARM FPU registers are not saved if druntime was compiled as ARM\_SoftFloat. If such a build is used on a ARM\_SoftFP system which actually has got a FPU and other libraries are using the FPU registers (other code is compiled as ARM\_SoftFP) this can cause problems. Druntime must be compiled as ARM\_SoftFP in this case. 
 
Authors:
Based on a design by Mikola Lysenko.
 
Examples:


```
int counter;

class DerivedFiber : Fiber
{
    this()
    {
        super( &run );
    }

private :
    void run()
    {
        counter += 2;
    }
}

void fiberFunc()
{
    counter += 4;
    Fiber.yield();
    counter += 8;
}

// create instances of each type
Fiber derived = new DerivedFiber();
Fiber composed = new Fiber( &fiberFunc );

assert( counter == 0 );

derived.call();
assert( counter == 2, "Derived fiber increment." );

composed.call();
assert( counter == 6, "First composed fiber increment." );

counter += 16;
assert( counter == 22, "Calling context increment." );

composed.call();
assert( counter == 30, "Second composed fiber increment." );

// since each fiber has run to completion, each should have state TERM
assert( derived.state == Fiber.State.TERM );
assert( composed.state == Fiber.State.TERM );

```
 
 
enum int **defaultStackPages**;  nothrow this(void function() fn, size\_t sz = PAGESIZE \* defaultStackPages, size\_t guardPageSize = PAGESIZE);  
Initializes a fiber object which is associated with a static D function. 



Parameters:


|  |  |
| --- | --- |
| void function() `fn` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |
| size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. |


 
In
 fn must not be null.
  nothrow this(void delegate() dg, size\_t sz = PAGESIZE \* defaultStackPages, size\_t guardPageSize = PAGESIZE);  
Initializes a fiber object which is associated with a dynamic D function. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `dg` | The fiber function. |
| size\_t `sz` | The stack size for this fiber. |
| size\_t `guardPageSize` | size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. |


 
In
 dg must not be null.
  final Throwable **call**(Rethrow rethrow = Rethrow.yes);   
  
final Throwable **call**(Rethrow rethrow)();  
Transfers execution to this fiber object. The calling context will be suspended until the fiber calls Fiber.yield() or until it terminates via an unhandled exception. 



Parameters:


|  |  |
| --- | --- |
| Rethrow `rethrow` | Rethrow any unhandled exception which may have caused this fiber to terminate. |


 
In
 This fiber must be in state HOLD. 
 
Throws:
Any exception not handled by the joined thread. 
 
Returns:
Any exception not handled by this fiber if rethrow = false, null otherwise.
  enum **Rethrow**: bool;  
Flag to control rethrow behavior of `[call](#call)`

  final nothrow @nogc void **reset**();   
  
final nothrow @nogc void **reset**(void function() fn);   
  
final nothrow @nogc void **reset**(void delegate() dg);  
Resets this fiber so that it may be re-used, optionally with a new function/delegate. This routine should only be called for fibers that have terminated, as doing otherwise could result in scope-dependent functionality that is not executed. Stack-based classes, for example, may not be cleaned up properly if a fiber is reset before it has terminated. 



In
 This fiber must be in state TERM or HOLD.
  enum **State**: int;  
A fiber may occupy one of three states: HOLD, EXEC, and TERM.

 
**HOLD** 
The HOLD state applies to any fiber that is suspended and ready to be called.

  **EXEC** 
The EXEC state will be set for any fiber that is currently executing.

  **TERM** 
The TERM state is set when a fiber terminates. Once a fiber terminates, it must be reset before it may be called again.

    final const pure nothrow @nogc @property @safe State **state**();  
Gets the current state of this fiber. 



Returns:
The state of this fiber as an enumerated value.
  static nothrow @nogc void **yield**();  
Forces a context switch to occur away from the calling fiber.

  static nothrow @nogc void **yieldAndThrow**(Throwable t);  
Forces a context switch to occur away from the calling fiber and then throws obj in the calling fiber. 



Parameters:


|  |  |
| --- | --- |
| Throwable `t` | The object to throw. |


 
In
 t must not be null.
  static nothrow @nogc @safe Fiber **getThis**();  
Provides a reference to the calling fiber or null if no fiber is currently active. 



Returns:
The fiber object representing the calling fiber or null if no fiber is currently active within this thread. The result of deleting this object is undefined.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_thread_fiber.html>

core.thread.osthread
====================

 The osthread module provides low-level, OS-dependent code for thread creation and management. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak 
 
Source
 [core/thread/osthread.d](https://github.com/dlang/druntime/blob/master/src/core/thread/osthread.d)

 
class **Thread**: core.thread.threadbase.ThreadBase;  
This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

 
pure nothrow @nogc @safe this(void function() fn, size\_t sz = 0);  
Initializes a thread object which is associated with a static D function. 



Parameters:


|  |  |
| --- | --- |
| void function() `fn` | The thread function. |
| size\_t `sz` | The stack size for this thread. |


 
In
 fn must not be null.
  pure nothrow @nogc @safe this(void delegate() dg, size\_t sz = 0);  
Initializes a thread object which is associated with a dynamic D function. 



Parameters:


|  |  |
| --- | --- |
| void delegate() `dg` | The thread function. |
| size\_t `sz` | The stack size for this thread. |


 
In
 dg must not be null.
  static nothrow @nogc @safe Thread **getThis**();  
Provides a reference to the calling thread. 



Returns:
The thread object representing the calling thread. The result of deleting this object is undefined. If the current thread is not attached to the runtime, a null reference is returned.
  final nothrow Thread **start**();  
Starts the thread and invokes the function or delegate passed upon construction. 



In
 This routine may only be called once per thread instance. 
 
Throws:
ThreadException if the thread fails to start.
  final Throwable **join**(bool rethrow = true);  
Waits for this thread to complete. If the thread terminated as the result of an unhandled exception, this exception will be rethrown. 



Parameters:


|  |  |
| --- | --- |
| bool `rethrow` | Rethrow any unhandled exception which may have caused this thread to terminate. |


 
Throws:
ThreadException if the operation fails. Any exception not handled by the joined thread. 
 
Returns:
Any exception not handled by this thread if rethrow = false, null otherwise.
  static pure nothrow @nogc @property @trusted int **PRIORITY\_MIN**();  
The minimum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the minimum valid priority for the scheduling policy of the process. 

  static pure nothrow @nogc @property @trusted const(int) **PRIORITY\_MAX**();  
The maximum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the maximum valid priority for the scheduling policy of the process. 

  static pure nothrow @nogc @property @trusted int **PRIORITY\_DEFAULT**();  
The default scheduling priority that is set for a thread. On systems where multiple scheduling policies are defined, this value represents the default priority for the scheduling policy of the process. 

  final @property int **priority**();  
Gets the scheduling priority for the associated thread. 



Note
 Getting the priority of a thread that already terminated might return the default priority. 
 
Returns:
The scheduling priority of this thread.
  final @property void **priority**(int val);  
Sets the scheduling priority for the associated thread. 



Note
 Setting the priority of a thread that already terminated might have no effect. 
 
Parameters:


|  |  |
| --- | --- |
| int `val` | The new scheduling priority of this thread. |


  final nothrow @nogc @property bool **isRunning**();  
Tests whether this thread is running. 



Returns:
true if the thread is running, false if not.
  static nothrow @nogc void **sleep**(Duration val);  
Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system. 



Parameters:


|  |  |
| --- | --- |
| Duration `val` | The minimum duration the calling thread should be suspended. |


 
In
 period must be non-negative. 
 
Example


```

Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds


```
  static nothrow @nogc void **yield**();  
Forces a context switch to occur away from the calling thread.

    nothrow @nogc void **thread\_setGCSignals**(int suspendSignalNo, int resumeSignalNo);  
Instruct the thread module, when initialized, to use a different set of signals besides SIGUSR1 and SIGUSR2 for suspension and resumption of threads. This function should be called at most once, prior to thread\_init(). This function is Posix-only. 

  Thread **thread\_attachThis**();  
Registers the calling thread for use with the D Runtime. If this routine is called for a thread which is already registered, no action is performed. 



NOTE
 This routine does not run thread-local static constructors when called. If full functionality as a D thread is desired, the following function must be called after thread\_attachThis: 
 extern (C) void rt\_moduleTlsCtor();  alias **getpid** = core.sys.posix.unistd.**getpid**;  
Returns the process ID of the calling process, which is guaranteed to be unique on the system. This call is always successful. 



Example


```
writefln("Current process id: %s", getpid());

```
  nothrow void **thread\_suspendAll**();  
Suspend all threads but the calling thread for "stop the world" garbage collection runs. This function may be called multiple times, and must be followed by a matching number of calls to thread\_resumeAll before processing is resumed. 



Throws:
ThreadError if the suspend operation fails for a running thread.
  @nogc void **thread\_init**();  
Initializes the thread module. This function must be called by the garbage collector on startup and before any other thread routines are called.

  @nogc void **thread\_term**();  
Terminates the thread module. No other thread routine may be called afterwards.

  nothrow @nogc ThreadID **createLowLevelThread**(void delegate() nothrow dg, uint stacksize = 0, void delegate() nothrow cbDllUnload = null);  
Create a thread not under control of the runtime, i.e. TLS module constructors are not run and the GC does not suspend it during a collection. 



Parameters:


|  |  |
| --- | --- |
| void delegate() nothrow `dg` | delegate to execute in the created thread. |
| uint `stacksize` | size of the stack of the created thread. The default of 0 will select the platform-specific default size. |
| void delegate() nothrow `cbDllUnload` | Windows only: if running in a dynamically loaded DLL, this delegate will be called if the DLL is supposed to be unloaded, but the thread is still running. The thread must be terminated via `joinLowLevelThread` by the callback. |


 
Returns:
the platform specific thread ID of the new thread. If an error occurs, `ThreadID.init` is returned.
  nothrow @nogc void **joinLowLevelThread**(ThreadID tid);  
Wait for a thread created with `createLowLevelThread` to terminate. 



Note
 In a Windows DLL, if this function is called via DllMain with argument DLL\_PROCESS\_DETACH, the thread is terminated forcefully without proper cleanup as a deadlock would happen otherwise. 
 
Parameters:


|  |  |
| --- | --- |
| ThreadID `tid` | the thread ID returned by `createLowLevelThread`. |


  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_thread_osthread.html>

core.vararg
===========

 The vararg module is intended to facilitate vararg manipulation in D. It should be interface compatible with the C module "stdarg," and the two modules may share a common implementation if possible (as is done here). 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Walter Bright, Hauke Duden 
 
Source
 [core/vararg.d](https://github.com/dlang/druntime/blob/master/src/core/vararg.d)

 
alias **va\_arg** = **va\_arg**;  void **va\_arg**()(ref va\_list ap, TypeInfo ti, void\* parmn);  
Retrieve and store through parmn the next value that is of TypeInfo ti. Used when the static type is not known.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_vararg.html>

core.volatile
=============

 This module declares intrinsics for volatile operations. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt) 
 
Authors:
Walter Bright, Ernesto Castellotti 
 
Source
 [core/volatile.d](https://github.com/dlang/druntime/blob/master/src/core/volatile.d)

 
nothrow @nogc @safe ubyte **volatileLoad**(ubyte\* ptr);   
  
nothrow @nogc @safe ushort **volatileLoad**(ushort\* ptr);   
  
nothrow @nogc @safe uint **volatileLoad**(uint\* ptr);   
  
nothrow @nogc @safe ulong **volatileLoad**(ulong\* ptr);   
  
nothrow @nogc @safe void **volatileStore**(ubyte\* ptr, ubyte value);   
  
nothrow @nogc @safe void **volatileStore**(ushort\* ptr, ushort value);   
  
nothrow @nogc @safe void **volatileStore**(uint\* ptr, uint value);   
  
nothrow @nogc @safe void **volatileStore**(ulong\* ptr, ulong value);  
Read/write value from/to the memory location indicated by ptr. 


These functions are recognized by the compiler, and calls to them are guaranteed to not be removed (as dead assignment elimination or presumed to have no effect) or reordered in the same thread.   
  
 These reordering guarantees are only made with regards to other operations done through these functions; the compiler is free to reorder regular loads/stores with regards to loads/stores done through these functions.   
  
 This is useful when dealing with memory-mapped I/O (MMIO) where a store can have an effect other than just writing a value, or where sequential loads with no intervening stores can retrieve different values from the same location due to external stores to the location.   
  
 These functions will, when possible, do the load/store as a single operation. In general, this is possible when the size of the operation is less than or equal to `(void*).sizeof`, although some targets may support larger operations. If the load/store cannot be done as a single operation, multiple smaller operations will be used.   
  
 These are not to be conflated with atomic operations. They do not guarantee any atomicity. This may be provided by coincidence as a result of the instructions used on the target, but this should not be relied on for portable programs. Further, no memory fences are implied by these functions. They should not be used for communication between threads. They may be used to guarantee a write or read cycle occurs at a specified address.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_volatile.html>

core.time
=========

 Module containing core time functionality, such as [`Duration`](#Duration) (which represents a duration of time) or [`MonoTime`](#MonoTime) (which represents a timestamp of the system's monotonic clock). 


Various functions take a string (or strings) to represent a unit of time (e.g. `convert!("days", "hours")(numDays)`). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There are a few functions that also allow "nsecs", but very little actually has precision greater than hnsecs.   
  
 

Cheat Sheet| Symbol | Description |
|  *Types* |
| [`Duration`](#Duration) | Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). |
| [`TickDuration`](#TickDuration) | Represents a duration of time in system clock ticks, using the highest precision that the system provides. |
| [`MonoTime`](#MonoTime) | Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. |
|  *Functions* |
| [`convert`](#convert) | Generic way of converting between two time units. |
| [`dur`](#dur) | Allows constructing a [`Duration`](#Duration) from the given time units with the given length. |
| [`weeks`](#weeks) [`days`](#days) [`hours`](#hours) [`minutes`](#minutes) [`seconds`](#seconds) [`msecs`](#msecs) [`usecs`](#usecs) [`hnsecs`](#hnsecs) [`nsecs`](#nsecs) | Convenience aliases for [`dur`](#dur). |
| [`abs`](#abs) | Returns the absolute value of a duration. |

   
  
 

Conversions|  | From [`Duration`](#Duration) | From [`TickDuration`](#TickDuration) | From units |
| To [`Duration`](#Duration) | - | `tickDuration.`[`to`](std_conv#to)`!Duration()` | `dur!"msecs"(5)` or `5.msecs()` |
| To [`TickDuration`](#TickDuration) | `duration.`[`to`](std_conv#to)`!TickDuration()` | - | `TickDuration.from!"msecs"(msecs)` |
| To units | `duration.total!"days"` | `tickDuration.msecs` | `convert!("days", "msecs")(msecs)` |

 

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:

[Jonathan M Davis](http://jmdavisprog.com) and Kato Shoichi 
 
Source
 [core/time.d](https://github.com/dlang/druntime/blob/master/src/core/time.d) 
 
enum **ClockType**: int;  
What type of clock to use with [`MonoTime`](#MonoTime) / [`MonoTimeImpl`](#MonoTimeImpl) or `std.datetime.Clock.currTime`. They default to `ClockType.normal`, and most programs do not need to ever deal with the others. 


The other `ClockType`s are provided so that other clocks provided by the underlying C, system calls can be used with [`MonoTimeImpl`](#MonoTimeImpl) or `std.datetime.Clock.currTime` without having to use the C API directly.   
  
 In the case of the monotonic time, [`MonoTimeImpl`](#MonoTimeImpl) is templatized on `ClockType`, whereas with `std.datetime.Clock.currTime`, its a runtime argument, since in the case of the monotonic time, the type of the clock affects the resolution of a [`MonoTimeImpl`](#MonoTimeImpl) object, whereas with [`std.datetime.SysTime`](std_datetime#SysTime), its resolution is always hecto-nanoseconds regardless of the source of the time.   
  
 `ClockType.normal`, `ClockType.coarse`, and `ClockType.precise` work with both `Clock.currTime` and [`MonoTimeImpl`](#MonoTimeImpl). `ClockType.second` only works with `Clock.currTime`. The others only work with [`MonoTimeImpl`](#MonoTimeImpl).

 
**normal** 
Use the normal clock.

  **bootTime** 
Linux,OpenBSD-Only 


Uses `CLOCK_BOOTTIME`.

  **coarse** 
Use the coarse clock, not the normal one (e.g. on Linux, that would be `CLOCK_REALTIME_COARSE` instead of `CLOCK_REALTIME` for `clock_gettime` if a function is using the realtime clock). It's generally faster to get the time with the coarse clock than the normal clock, but it's less precise (e.g. 1 msec instead of 1 usec or 1 nsec). Howeover, it *is* guaranteed to still have sub-second precision (just not as high as with `ClockType.normal`). 


On systems which do not support a coarser clock, `MonoTimeImpl!(ClockType.coarse)` will internally use the same clock as `Monotime` does, and `Clock.currTime!(ClockType.coarse)` will use the same clock as `Clock.currTime`. This is because the coarse clock is doing the same thing as the normal clock (just at lower precision), whereas some of the other clock types (e.g. `ClockType.processCPUTime`) mean something fundamentally different. So, treating those as `ClockType.normal` on systems where they weren't natively supported would give misleading results.   
  
 Most programs should not use the coarse clock, exactly because it's less precise, and most programs don't need to get the time often enough to care, but for those rare programs that need to get the time extremely frequently (e.g. hundreds of thousands of times a second) but don't care about high precision, the coarse clock might be appropriate.   
  
 Currently, only Linux and FreeBSD/DragonFlyBSD support a coarser clock, and on other platforms, it's treated as `ClockType.normal`.

  **precise** 
Uses a more precise clock than the normal one (which is already very precise), but it takes longer to get the time. Similarly to `ClockType.coarse`, if it's used on a system that does not support a more precise clock than the normal one, it's treated as equivalent to `ClockType.normal`. 


Currently, only FreeBSD/DragonFlyBSD supports a more precise clock, where it uses `CLOCK_MONOTONIC_PRECISE` for the monotonic time and `CLOCK_REALTIME_PRECISE` for the wall clock time.

  **processCPUTime** 
Linux,OpenBSD,Solaris-Only 


Uses `CLOCK_PROCESS_CPUTIME_ID`.

  **raw** 
Linux-Only 


Uses `CLOCK_MONOTONIC_RAW`.

  **second** 
Uses a clock that has a precision of one second (contrast to the coarse clock, which has sub-second precision like the normal clock does). 


FreeBSD/DragonFlyBSD are the only systems which specifically have a clock set up for this (it has `CLOCK_SECOND` to use with `clock_gettime` which takes advantage of an in-kernel cached value), but on other systems, the fastest function available will be used, and the resulting `SysTime` will be rounded down to the second if the clock that was used gave the time at a more precise resolution. So, it's guaranteed that the time will be given at a precision of one second and it's likely the case that will be faster than `ClockType.normal`, since there tend to be several options on a system to get the time at low resolutions, and they tend to be faster than getting the time at high resolutions.   
  
 So, the primary difference between `ClockType.coarse` and `ClockType.second` is that `ClockType.coarse` sacrifices some precision in order to get speed but is still fairly precise, whereas `ClockType.second` tries to be as fast as possible at the expense of all sub-second precision.

  **threadCPUTime** 
Linux,OpenBSD,Solaris-Only 


Uses `CLOCK_THREAD_CPUTIME_ID`.

  **uptime** 
DragonFlyBSD,FreeBSD,OpenBSD-Only 


Uses `CLOCK_UPTIME`.

  **uptimeCoarse** 
FreeBSD-Only 


Uses `CLOCK_UPTIME_FAST`.

  **uptimePrecise** 
FreeBSD-Only 


Uses `CLOCK_UPTIME_PRECISE`.

    struct **Duration**;  
Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). 


It is used when representing a duration of time - such as how long to sleep with [`core.thread.Thread.sleep`](core_thread#Thread.sleep).   
  
 In std.datetime, it is also used as the result of various arithmetic operations on time points.   
  
 Use the [`dur`](#dur) function or one of its non-generic aliases to create `Duration`s.   
  
 It's not possible to create a Duration of months or years, because the variable number of days in a month or year makes it impossible to convert between months or years and smaller units without a specific date. So, nothing uses `Duration`s when dealing with months or years. Rather, functions specific to months and years are defined. For instance, [`std.datetime.Date`](std_datetime#Date) has `add!"years"` and `add!"months"` for adding years and months rather than creating a Duration of years or months and adding that to a [`std.datetime.Date`](std_datetime#Date). But Duration is used when dealing with weeks or smaller. 

 
Examples:


```
import std.datetime;

assert(dur!"days"(12) == dur!"hnsecs"(10_368_000_000_000L));
assert(dur!"hnsecs"(27) == dur!"hnsecs"(27));
assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) ==
       std.datetime.Date(2010, 9, 12));

assert(days(-12) == dur!"hnsecs"(-10_368_000_000_000L));
assert(hnsecs(-27) == dur!"hnsecs"(-27));
assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) ==
       days(-26));

```
 
 
Examples:


```
import core.time;

// using the dur template
auto numDays = dur!"days"(12);

// using the days function
numDays = days(12);

// alternatively using UFCS syntax
numDays = 12.days;

auto myTime = 100.msecs + 20_000.usecs + 30_000.hnsecs;
assert(myTime == 123.msecs);

```
 
 
static pure nothrow @nogc @property @safe Duration **zero**();  
A `Duration` of `0`. It's shorter than doing something like `dur!"seconds"(0)` and more explicit than `Duration.init`.

  static pure nothrow @nogc @property @safe Duration **max**();  
Largest `Duration` possible.

  static pure nothrow @nogc @property @safe Duration **min**();  
Most negative `Duration` possible.

  const pure nothrow @nogc @safe int **opCmp**(Duration rhs);  
Compares this `Duration` with the given `Duration`. 



Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const nothrow @nogc Duration **opBinary**(string op, D)(D rhs)  
 Constraints: if ((op == "+" || op == "-" || op == "%") && is(immutable(D) == immutable(Duration)) || (op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); 
 
Adds, subtracts or calculates the modulo of two durations. 


The legal types of arithmetic for `Duration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Duration | + | Duration | --> | Duration |
| Duration | - | Duration | --> | Duration |
| Duration | % | Duration | --> | Duration |
| Duration | + | TickDuration | --> | Duration |
| Duration | - | TickDuration | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| D `rhs` | The duration to add to or subtract from this `Duration`. |


  const nothrow @nogc Duration **opBinaryRight**(string op, D)(D lhs)  
 Constraints: if ((op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); 
 
Adds or subtracts two durations. 


The legal types of arithmetic for `Duration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | + | Duration | --> | Duration |
| TickDuration | - | Duration | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| D `lhs` | The `TickDuration` to add to this `Duration` or to subtract this `Duration` from. |


  nothrow @nogc ref Duration **opOpAssign**(string op, D)(scope const D rhs)  
 Constraints: if ((op == "+" || op == "-" || op == "%") && is(immutable(D) == immutable(Duration)) || (op == "+" || op == "-") && is(immutable(D) == immutable(TickDuration))); 
 
Adds, subtracts or calculates the modulo of two durations as well as assigning the result to this `Duration`. 


The legal types of arithmetic for `Duration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Duration | + | Duration | --> | Duration |
| Duration | - | Duration | --> | Duration |
| Duration | % | Duration | --> | Duration |
| Duration | + | TickDuration | --> | Duration |
| Duration | - | TickDuration | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| D `rhs` | The duration to add to or subtract from this `Duration`. |


  const nothrow @nogc Duration **opBinary**(string op)(long value)  
 Constraints: if (op == "\*" || op == "/"); 
 
Multiplies or divides the duration by an integer value. 


The legal types of arithmetic for `Duration` using this operator overload are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Duration | \* | long | --> | Duration |
| Duration | / | long | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| long `value` | The value to multiply this `Duration` by. |


  nothrow @nogc ref Duration **opOpAssign**(string op)(long value)  
 Constraints: if (op == "\*" || op == "/"); 
 
Multiplies/Divides the duration by an integer value as well as assigning the result to this `Duration`. 


The legal types of arithmetic for `Duration` using this operator overload are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Duration | \* | long | --> | Duration |
| Duration | / | long | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| long `value` | The value to multiply/divide this `Duration` by. |


  const nothrow @nogc long **opBinary**(string op)(Duration rhs)  
 Constraints: if (op == "/"); 
 
Divides two durations. 


The legal types of arithmetic for `Duration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| Duration | / | Duration | --> | long |

 

 
Parameters:


|  |  |
| --- | --- |
| Duration `rhs` | The duration to divide this `Duration` by. |


  const nothrow @nogc Duration **opBinaryRight**(string op)(long value)  
 Constraints: if (op == "\*"); 
 
Multiplies an integral value and a `Duration`. 


The legal types of arithmetic for `Duration` using this operator overload are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| long | \* | Duration | --> | Duration |

 

 
Parameters:


|  |  |
| --- | --- |
| long `value` | The number of units to multiply this `Duration` by. |


  const nothrow @nogc Duration **opUnary**(string op)()  
 Constraints: if (op == "-"); 
 
Returns the negation of this `Duration`.

  const nothrow @nogc TickDuration **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(TickDuration))); 
 
Returns a [`TickDuration`](#TickDuration) with the same number of hnsecs as this `Duration`. Note that the conventional way to convert between `Duration` and `TickDuration` is using [`std.conv.to`](std_conv#to), e.g.: `duration.to!TickDuration()`

  const nothrow @nogc bool **opCast**(T : bool)();  
Allow Duration to be used as a boolean. 



Returns:

`true` if this duration is non-zero.
  template **split**(units...) if (allAreAcceptedUnits!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs", "nsecs")(units) && unitsAreInDescendingOrder(units)) 
Splits out the Duration into the given units. 


split takes the list of time units to split out as template arguments. The time unit strings must be given in decreasing order. How it returns the values for those units depends on the overload used.   
  
 The overload which accepts function arguments takes integral types in the order that the time unit strings were given, and those integers are passed by `ref`. split assigns the values for the units to each corresponding integer. Any integral type may be used, but no attempt is made to prevent integer overflow, so don't use small integral types in circumstances where the values for those units aren't likely to fit in an integral type that small.   
  
 The overload with no arguments returns the values for the units in a struct with members whose names are the same as the given time unit strings. The members are all `long`s. This overload will also work with no time strings being given, in which case *all* of the time units from weeks through hnsecs will be provided (but no nsecs, since it would always be `0`).   
  
 For both overloads, the entire value of the Duration is split among the units (rather than splitting the Duration across all units and then only providing the values for the requested units), so if only one unit is given, the result is equivalent to [`total`](#total).   
  
 `"nsecs"` is accepted by split, but `"years"` and `"months"` are not.   
  
 For negative durations, all of the split values will be negative.

 
Examples:


```
{
    auto d = dur!"days"(12) + dur!"minutes"(7) + dur!"usecs"(501223);
    long days;
    int seconds;
    short msecs;
    d.split!("days", "seconds", "msecs")(days, seconds, msecs);
    assert(days == 12);
    assert(seconds == 7 * 60);
    assert(msecs == 501);

    auto splitStruct = d.split!("days", "seconds", "msecs")();
    assert(splitStruct.days == 12);
    assert(splitStruct.seconds == 7 * 60);
    assert(splitStruct.msecs == 501);

    auto fullSplitStruct = d.split();
    assert(fullSplitStruct.weeks == 1);
    assert(fullSplitStruct.days == 5);
    assert(fullSplitStruct.hours == 0);
    assert(fullSplitStruct.minutes == 7);
    assert(fullSplitStruct.seconds == 0);
    assert(fullSplitStruct.msecs == 501);
    assert(fullSplitStruct.usecs == 223);
    assert(fullSplitStruct.hnsecs == 0);

    assert(d.split!"minutes"().minutes == d.total!"minutes");
}

{
    auto d = dur!"days"(12);
    assert(d.split!"weeks"().weeks == 1);
    assert(d.split!"days"().days == 12);

    assert(d.split().weeks == 1);
    assert(d.split().days == 5);
}

{
    auto d = dur!"days"(7) + dur!"hnsecs"(42);
    assert(d.split!("seconds", "nsecs")().nsecs == 4200);
}

{
    auto d = dur!"days"(-7) + dur!"hours"(-9);
    auto result = d.split!("days", "hours")();
    assert(result.days == -7);
    assert(result.hours == -9);
}

```
 
 
const nothrow @nogc void **split**(Args...)(out Args args)  
 Constraints: if (units.length != 0 && (args.length == units.length) && allAreMutableIntegralTypes!Args);   
  
const nothrow @nogc auto **split**();  
Ditto

    const nothrow @nogc @property long **total**(string units)()  
 Constraints: if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"); 
 
Returns the total number of the given units in this `Duration`. So, unlike `split`, it does not strip out the larger units.



Examples:


```
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);

assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);

assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);

assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);

```
 
  const pure nothrow @safe string **toString**();  
Converts this `Duration` to a `string`. 


The string is meant to be human readable, not machine parseable (e.g. whether there is an `'s'` on the end of the unit name usually depends on whether it's plural or not, and empty units are not included unless the Duration is `zero`). Any code needing a specific string format should use `total` or `split` to get the units needed to create the desired string format and create the string itself.   
  
 The format returned by toString may or may not change in the future.

 
Examples:


```
assert(Duration.zero.toString() == "0 hnsecs");
assert(weeks(5).toString() == "5 weeks");
assert(days(2).toString() == "2 days");
assert(hours(1).toString() == "1 hour");
assert(minutes(19).toString() == "19 minutes");
assert(seconds(42).toString() == "42 secs");
assert(msecs(42).toString() == "42 ms");
assert(usecs(27).toString() == "27 μs");
assert(hnsecs(5).toString() == "5 hnsecs");

assert(seconds(121).toString() == "2 minutes and 1 sec");
assert((minutes(5) + seconds(3) + usecs(4)).toString() ==
       "5 minutes, 3 secs, and 4 μs");

assert(seconds(-42).toString() == "-42 secs");
assert(usecs(-5239492).toString() == "-5 secs, -239 ms, and -492 μs");

```
 
  const pure nothrow @nogc @property @safe bool **isNegative**();  
Returns whether this `Duration` is negative.

    pure nothrow @nogc @safe T **to**(string units, T, D)(D td)  
 Constraints: if (is(immutable(D) == immutable(TickDuration)) && (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs")); 
 
Converts a `TickDuration` to the given units as either an integral value or a floating point value. 



Parameters:


|  |  |
| --- | --- |
| units | The units to convert to. Accepts `"seconds"` and smaller only. |
| T | The type to convert to (either an integral type or a floating point type). |
| D `td` | The TickDuration to convert |


 
Examples:


```
auto t = TickDuration.from!"seconds"(1000);

long tl = to!("seconds",long)(t);
assert(tl == 1000);

import core.stdc.math : fabs;
double td = to!("seconds",double)(t);
assert(fabs(td - 1000) < 0.001);

```
 
  pure nothrow @nogc @safe Duration **dur**(string units)(long length)  
 Constraints: if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs");   
  
alias **weeks** = dur!"**weeks**".dur;   
  
alias **days** = dur!"**days**".dur;   
  
alias **hours** = dur!"**hours**".dur;   
  
alias **minutes** = dur!"**minutes**".dur;   
  
alias **seconds** = dur!"**seconds**".dur;   
  
alias **msecs** = dur!"**msecs**".dur;   
  
alias **usecs** = dur!"**usecs**".dur;   
  
alias **hnsecs** = dur!"**hnsecs**".dur;   
  
alias **nsecs** = dur!"**nsecs**".dur;  
These allow you to construct a `Duration` from the given time units with the given length. 


You can either use the generic function `dur` and give it the units as a `string` or use the named aliases.   
  
 The possible values for units are `"weeks"`, `"days"`, `"hours"`, `"minutes"`, `"seconds"`, `"msecs"` (milliseconds), `"usecs"`, (microseconds), `"hnsecs"` (hecto-nanoseconds, i.e. 100 ns), and `"nsecs"`. 

 
Parameters:


|  |  |
| --- | --- |
| units | The time units of the `Duration` (e.g. `"days"`). |
| long `length` | The number of units in the `Duration`. |


 
Examples:


```
// Generic
assert(dur!"weeks"(142).total!"weeks" == 142);
assert(dur!"days"(142).total!"days" == 142);
assert(dur!"hours"(142).total!"hours" == 142);
assert(dur!"minutes"(142).total!"minutes" == 142);
assert(dur!"seconds"(142).total!"seconds" == 142);
assert(dur!"msecs"(142).total!"msecs" == 142);
assert(dur!"usecs"(142).total!"usecs" == 142);
assert(dur!"hnsecs"(142).total!"hnsecs" == 142);
assert(dur!"nsecs"(142).total!"nsecs" == 100);

// Non-generic
assert(weeks(142).total!"weeks" == 142);
assert(days(142).total!"days" == 142);
assert(hours(142).total!"hours" == 142);
assert(minutes(142).total!"minutes" == 142);
assert(seconds(142).total!"seconds" == 142);
assert(msecs(142).total!"msecs" == 142);
assert(usecs(142).total!"usecs" == 142);
assert(hnsecs(142).total!"hnsecs" == 142);
assert(nsecs(142).total!"nsecs" == 100);

```
 
  alias **MonoTime** = MonoTimeImpl!ClockType.normal.MonoTimeImpl;  
alias for `MonoTimeImpl` instantiated with `ClockType.normal`. This is what most programs should use. It's also what much of `MonoTimeImpl` uses in its documentation (particularly in the examples), because that's what's going to be used in most code.

  struct **MonoTimeImpl**(ClockType clockType);  
Represents a timestamp of the system's monotonic clock. 


 A monotonic clock is one which always goes forward and never moves backwards, unlike the system's wall clock time (as represented by [`std.datetime.SysTime`](std_datetime#SysTime)). The system's wall clock time can be adjusted by the user or by the system itself via services such as NTP, so it is unreliable to use the wall clock time for timing. Timers which use the wall clock time could easily end up never going off due to changes made to the wall clock time or otherwise waiting for a different period of time than that specified by the programmer. However, because the monotonic clock always increases at a fixed rate and is not affected by adjustments to the wall clock time, it is ideal for use with timers or anything which requires high precision timing.   
  
 So, MonoTime should be used for anything involving timers and timing, whereas [`std.datetime.SysTime`](std_datetime#SysTime) should be used when the wall clock time is required.   
  
 The monotonic clock has no relation to wall clock time. Rather, it holds its time as the number of ticks of the clock which have occurred since the clock started (typically when the system booted up). So, to determine how much time has passed between two points in time, one monotonic time is subtracted from the other to determine the number of ticks which occurred between the two points of time, and those ticks are divided by the number of ticks that occur every second (as represented by MonoTime.ticksPerSecond) to get a meaningful duration of time. Normally, MonoTime does these calculations for the programmer, but the `ticks` and `ticksPerSecond` properties are provided for those who require direct access to the system ticks. The normal way that MonoTime would be used is   
  
 
```
    MonoTime before = MonoTime.currTime;
    // do stuff...
    MonoTime after = MonoTime.currTime;
    Duration timeElapsed = after - before;

```
   
  
 [`MonoTime`](#MonoTime) is an alias to `MonoTimeImpl!(ClockType.normal)` and is what most programs should use for the monotonic clock, so that's what is used in most of `MonoTimeImpl`'s documentation. But `MonoTimeImpl` can be instantiated with other clock types for those rare programs that need it. 

 
See Also:
[`ClockType`](#ClockType)
 
static nothrow @nogc @property @trusted MonoTimeImpl **currTime**();  
The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific. 


On Windows, `QueryPerformanceCounter` is used. On Mac OS X, `mach_absolute_time` is used, while on other POSIX systems, `clock_gettime` is used.   
  
 Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

  MonoTimeImpl **zero**();  
A `MonoTime` of `0` ticks. It's provided to be consistent with `Duration.zero`, and it's more explicit than `MonoTime.init`.

  MonoTimeImpl **max**();  
Largest `MonoTime` possible.

  MonoTimeImpl **min**();  
Most negative `MonoTime` possible.

  const pure nothrow @nogc int **opCmp**(MonoTimeImpl rhs);  
Compares this MonoTime with the given MonoTime. 



Returns:


|  |  |
| --- | --- |
| this < rhs | < 0 |
| this == rhs | 0 |
| this > rhs | > 0 |


  const pure nothrow @nogc Duration **opBinary**(string op)(MonoTimeImpl rhs)  
 Constraints: if (op == "-"); 
 
Subtracting two MonoTimes results in a [`Duration`](#Duration) representing the amount of time which elapsed between them. 


 The primary way that programs should time how long something takes is to do 
```
MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

```
 or to use a wrapper (such as a stop watch type) which does that.   
  
 Warning: Because [`Duration`](#Duration) is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail 
```
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

```
   
  
 This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's `ticks` property and keep all calculations in ticks rather than using [`Duration`](#Duration).

  const pure nothrow @nogc MonoTimeImpl **opBinary**(string op)(Duration rhs)  
 Constraints: if (op == "+" || op == "-");   
  
pure nothrow @nogc ref MonoTimeImpl **opOpAssign**(string op)(Duration rhs)  
 Constraints: if (op == "+" || op == "-"); 
 
Adding or subtracting a [`Duration`](#Duration) to/from a MonoTime results in a MonoTime which is adjusted by that amount.

  const pure nothrow @nogc @property long **ticks**();  
The number of ticks in the monotonic time. 


Most programs should not use this directly, but it's exposed for those few programs that need it.   
  
 The main reasons that a program might need to use ticks directly is if the system clock has higher precision than hnsecs, and the program needs that higher precision, or if the program needs to avoid the rounding errors caused by converting to hnsecs.

  static pure nothrow @nogc @property long **ticksPerSecond**();  
The number of ticks that MonoTime has per second - i.e. the resolution or frequency of the system's monotonic clock. 


e.g. if the system clock had a resolution of microseconds, then ticksPerSecond would be `1_000_000`.

  const pure nothrow string **toString**();    pure nothrow @nogc @safe long **convClockFreq**(long ticks, long srcTicksPerSecond, long dstTicksPerSecond);  
Converts the given time from one clock frequency/resolution to another. 



See Also:
[`ticksToNSecs`](#ticksToNSecs)
 
Examples:


```
// one tick is one second -> one tick is a hecto-nanosecond
assert(convClockFreq(45, 1, 10_000_000) == 450_000_000);

// one tick is one microsecond -> one tick is a millisecond
assert(convClockFreq(9029, 1_000_000, 1_000) == 9);

// one tick is 1/3_515_654 of a second -> 1/1_001_010 of a second
assert(convClockFreq(912_319, 3_515_654, 1_001_010) == 259_764);

// one tick is 1/MonoTime.ticksPerSecond -> one tick is a nanosecond
// Equivalent to ticksToNSecs
auto nsecs = convClockFreq(1982, MonoTime.ticksPerSecond, 1_000_000_000);

```
 
  pure nothrow @nogc @safe long **ticksToNSecs**(long ticks);  
Convenience wrapper around [`convClockFreq`](#convClockFreq) which converts ticks at a clock frequency of `MonoTime.ticksPerSecond` to nanoseconds. 


It's primarily of use when `MonoTime.ticksPerSecond` is greater than hecto-nanosecond resolution, and an application needs a higher precision than hecto-nanoceconds. 

 
See Also:
[`convClockFreq`](#convClockFreq)
 
Examples:


```
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto diffInTicks = after.ticks - before.ticks;
auto diffInNSecs = ticksToNSecs(diffInTicks);
assert(diffInNSecs == convClockFreq(diffInTicks, MonoTime.ticksPerSecond, 1_000_000_000));

```
 
  pure nothrow @nogc @safe long **nsecsToTicks**(long ticks);  
The reverse of [`ticksToNSecs`](#ticksToNSecs).

  struct **TickDuration**;  
Warning: TickDuration will be deprecated in the near future (once all uses of it in Phobos have been deprecated). Please use [`MonoTime`](#MonoTime) for the cases where a monotonic timestamp is needed and [`Duration`](#Duration) when a duration is needed, rather than using TickDuration. It has been decided that TickDuration is too confusing (e.g. it conflates a monotonic timestamp and a duration in monotonic clock ticks) and that having multiple duration types is too awkward and confusing. 


Represents a duration of time in system clock ticks.   
  
 The system clock ticks are the ticks of the system clock at the highest precision that the system provides.

 
static immutable long **ticksPerSec**;  
The number of ticks that the system clock has in one second. 


If `ticksPerSec` is `0`, then then `TickDuration` failed to get the value of `ticksPerSec` on the current system, and `TickDuration` is not going to work. That would be highly abnormal though.

  static immutable TickDuration **appOrigin**;  
The tick of the system clock (as a `TickDuration`) when the application started.

  static pure nothrow @nogc @property @safe TickDuration **zero**();  
It's the same as `TickDuration(0)`, but it's provided to be consistent with `Duration`, which provides a `zero` property.

  static pure nothrow @nogc @property @safe TickDuration **max**();  
Largest `TickDuration` possible.

  static pure nothrow @nogc @property @safe TickDuration **min**();  
Most negative `TickDuration` possible.

  long **length**;  
The number of system ticks in this `TickDuration`. 


You can convert this `length` into the number of seconds by dividing it by `ticksPerSec` (or using one the appropriate property function to do it).

  const pure nothrow @nogc @property @safe long **seconds**();  
Returns the total number of seconds in this `TickDuration`.

  const pure nothrow @nogc @property @safe long **msecs**();  
Returns the total number of milliseconds in this `TickDuration`.

  const pure nothrow @nogc @property @safe long **usecs**();  
Returns the total number of microseconds in this `TickDuration`.

  const pure nothrow @nogc @property @safe long **hnsecs**();  
Returns the total number of hecto-nanoseconds in this `TickDuration`.

  const pure nothrow @nogc @property @safe long **nsecs**();  
Returns the total number of nanoseconds in this `TickDuration`.

  pure nothrow @nogc @safe TickDuration **from**(string units)(long length)  
 Constraints: if (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"); 
 
This allows you to construct a `TickDuration` from the given time units with the given length. 



Parameters:


|  |  |
| --- | --- |
| units | The time units of the `TickDuration` (e.g. `"msecs"`). |
| long `length` | The number of units in the `TickDuration`. |


  const pure nothrow @nogc @safe Duration **opCast**(T)()  
 Constraints: if (is(immutable(T) == immutable(Duration))); 
 
Returns a [`Duration`](#Duration) with the same number of hnsecs as this `TickDuration`. Note that the conventional way to convert between `TickDuration` and `Duration` is using [`std.conv.to`](std_conv#to), e.g.: `tickDuration.to!Duration()`

  pure nothrow @nogc ref @safe TickDuration **opOpAssign**(string op)(TickDuration rhs)  
 Constraints: if (op == "+" || op == "-"); 
 
Adds or subtracts two `TickDuration`s as well as assigning the result to this `TickDuration`. 


The legal types of arithmetic for `TickDuration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | += | TickDuration | --> | TickDuration |
| TickDuration | -= | TickDuration | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| TickDuration `rhs` | The `TickDuration` to add to or subtract from this `TickDuration`. |


  const pure nothrow @nogc @safe TickDuration **opBinary**(string op)(TickDuration rhs)  
 Constraints: if (op == "+" || op == "-"); 
 
Adds or subtracts two `TickDuration`s. 


The legal types of arithmetic for `TickDuration` using this operator are   
  
 

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | + | TickDuration | --> | TickDuration |
| TickDuration | - | TickDuration | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| TickDuration `rhs` | The `TickDuration` to add to or subtract from this `TickDuration`. |


  const pure nothrow @nogc @safe TickDuration **opUnary**(string op)()  
 Constraints: if (op == "-"); 
 
Returns the negation of this `TickDuration`.

  const pure nothrow @nogc @safe int **opCmp**(TickDuration rhs);  
operator overloading "<, >, <=, >="

  pure nothrow @nogc @safe void **opOpAssign**(string op, T)(T value)  
 Constraints: if (op == "\*" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); 
 
The legal types of arithmetic for `TickDuration` using this operator overload are 




|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | \* | long | --> | TickDuration |
| TickDuration | \* | floating point | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| T `value` | The value to divide from this duration. |


  pure @safe void **opOpAssign**(string op, T)(T value)  
 Constraints: if (op == "/" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); 
 
The legal types of arithmetic for `TickDuration` using this operator overload are 




|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | / | long | --> | TickDuration |
| TickDuration | / | floating point | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| T `value` | The value to divide from this `TickDuration`. |


 
Throws:

`TimeException` if an attempt to divide by `0` is made.
  const pure nothrow @nogc @safe TickDuration **opBinary**(string op, T)(T value)  
 Constraints: if (op == "\*" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); 
 
The legal types of arithmetic for `TickDuration` using this operator overload are 




|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | \* | long | --> | TickDuration |
| TickDuration | \* | floating point | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| T `value` | The value to divide from this `TickDuration`. |


  const pure @safe TickDuration **opBinary**(string op, T)(T value)  
 Constraints: if (op == "/" && (\_\_traits(isIntegral, T) || \_\_traits(isFloating, T))); 
 
The legal types of arithmetic for `TickDuration` using this operator overload are 




|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| TickDuration | / | long | --> | TickDuration |
| TickDuration | / | floating point | --> | TickDuration |

 

 
Parameters:


|  |  |
| --- | --- |
| T `value` | The value to divide from this `TickDuration`. |


 
Throws:

`TimeException` if an attempt to divide by `0` is made.
  pure nothrow @nogc @safe this(long ticks);  

Parameters:


|  |  |
| --- | --- |
| long `ticks` | The number of ticks in the TickDuration. |


  static nothrow @nogc @property @trusted TickDuration **currSystemTick**();  
The current system tick. The number of ticks per second varies from system to system. `currSystemTick` uses a monotonic clock, so it's intended for precision timing by comparing relative time values, not for getting the current system time. 


On Windows, `QueryPerformanceCounter` is used. On Mac OS X, `mach_absolute_time` is used, while on other Posix systems, `clock_gettime` is used. If `mach_absolute_time` or `clock_gettime` is unavailable, then Posix systems use `gettimeofday` (the decision is made when `TickDuration` is compiled), which unfortunately, is not monotonic, but if `mach_absolute_time` and `clock_gettime` aren't available, then `gettimeofday` is the the best that there is.   
  
 Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock could be off if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or on Linux. 

 
Throws:

`TimeException` if it fails to get the time.
    pure nothrow @nogc @safe long **convert**(string from, string to)(long value)  
 Constraints: if ((from == "weeks" || from == "days" || from == "hours" || from == "minutes" || from == "seconds" || from == "msecs" || from == "usecs" || from == "hnsecs" || from == "nsecs") && (to == "weeks" || to == "days" || to == "hours" || to == "minutes" || to == "seconds" || to == "msecs" || to == "usecs" || to == "hnsecs" || to == "nsecs") || (from == "years" || from == "months") && (to == "years" || to == "months")); 
 
Generic way of converting between two time units. Conversions to smaller units use truncating division. Years and months can be converted to each other, small units can be converted to each other, but years and months cannot be converted to or from smaller units (due to the varying number of days in a month or year). 



Parameters:


|  |  |
| --- | --- |
| from | The units of time to convert from. |
| to | The units of time to convert to. |
| long `value` | The value to convert. |


 
Examples:


```
assert(convert!("years", "months")(1) == 12);
assert(convert!("months", "years")(12) == 1);

assert(convert!("weeks", "days")(1) == 7);
assert(convert!("hours", "seconds")(1) == 3600);
assert(convert!("seconds", "days")(1) == 0);
assert(convert!("seconds", "days")(86_400) == 1);

assert(convert!("nsecs", "nsecs")(1) == 1);
assert(convert!("nsecs", "hnsecs")(1) == 0);
assert(convert!("hnsecs", "nsecs")(1) == 100);
assert(convert!("nsecs", "seconds")(1) == 0);
assert(convert!("seconds", "nsecs")(1) == 1_000_000_000);

```
 
  class **TimeException**: object.Exception;  
Exception type used by core.time.

 
pure nothrow @safe this(string msg, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_, Throwable next = null);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |
| Throwable `next` | The previous exception in the chain of exceptions, if any. |


  pure nothrow @safe this(string msg, Throwable next, string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  

Parameters:


|  |  |
| --- | --- |
| string `msg` | The message for the exception. |
| Throwable `next` | The previous exception in the chain of exceptions. |
| string `file` | The file where the exception occurred. |
| size\_t `line` | The line number where the exception occurred. |


    pure nothrow @nogc @safe Duration **abs**(Duration duration);   
  
pure nothrow @nogc @safe TickDuration **abs**(TickDuration duration);  
Returns the absolute value of a duration.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/core_time.html>

rt.aApplyR
==========

 This code handles decoding UTF strings for foreach\_reverse loops. There are 6 combinations of conversions between char, wchar, and dchar, and 2 of each of those. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly
 
alias **dg\_t** = int delegate(void\*);  int **\_aApplyRwd1**(in wchar[] aa, dg\_t dg);  int **\_aApplyRcw1**(in char[] aa, dg\_t dg);  int **\_aApplyRwc1**(in wchar[] aa, dg\_t dg);  int **\_aApplyRdc1**(in dchar[] aa, dg\_t dg);  int **\_aApplyRdw1**(in dchar[] aa, dg\_t dg);  alias **dg2\_t** = int delegate(void\*, void\*);  int **\_aApplyRwd2**(in wchar[] aa, dg2\_t dg);  int **\_aApplyRcw2**(in char[] aa, dg2\_t dg);  int **\_aApplyRwc2**(in wchar[] aa, dg2\_t dg);  int **\_aApplyRdc2**(in dchar[] aa, dg2\_t dg);  int **\_aApplyRdw2**(in dchar[] aa, dg2\_t dg);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_aApplyR.html>

rt.aApply
=========

 This code handles decoding UTF strings for foreach loops. There are 6 combinations of conversions between char, wchar, and dchar, and 2 of each of those. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright 
 
Source
 [rt/aApply.d](https://github.com/dlang/druntime/blob/master/src/rt/aApply.d)

 
alias **dg\_t** = int delegate(void\*);  int **\_aApplywd1**(in wchar[] aa, dg\_t dg);  int **\_aApplycw1**(in char[] aa, dg\_t dg);  int **\_aApplywc1**(in wchar[] aa, dg\_t dg);  int **\_aApplydc1**(in dchar[] aa, dg\_t dg);  int **\_aApplydw1**(in dchar[] aa, dg\_t dg);  alias **dg2\_t** = int delegate(void\*, void\*);  int **\_aApplywd2**(in wchar[] aa, dg2\_t dg);  int **\_aApplycw2**(in char[] aa, dg2\_t dg);  int **\_aApplywc2**(in wchar[] aa, dg2\_t dg);  int **\_aApplydc2**(in dchar[] aa, dg2\_t dg);  int **\_aApplydw2**(in dchar[] aa, dg2\_t dg);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_aApply.html>

rt.adi
======

 Implementation of dynamic array property support routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/adi.d](https://github.com/dlang/druntime/blob/master/src/rt/adi.d)

 
int **\_adEq2**(void[] a1, void[] a2, TypeInfo ti);  
Support for array equality test. 



Returns:
1 equal 0 not equal
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_adi.html>

rt.alloca
=========

 Implementation of alloca() standard C routine. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/alloca.d](https://github.com/dlang/druntime/blob/master/src/rt/alloca.d)

 
void\* **\_\_alloca**(int nbytes);  
Allocate data from the caller's stack frame. This is a 'magic' function that needs help from the compiler to work right, do not change its name, do not call it from other compilers. 



Input
 nbytes number of bytes to allocate ECX address of variable with # of bytes in locals This is adjusted upon return to reflect the additional size of the stack frame. 
 
Returns:
EAX allocated data, null if stack overflows
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_alloca.html>

rt.arraycat
===========

 Implementation of array copy support routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/arraycat.d](https://github.com/dlang/druntime/blob/master/src/rt/arraycat.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_arraycat.html>

rt.cast\_
=========

 Implementation of array assignment support routines. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly
 
pure nothrow @nogc Object **\_d\_toObject**(return void\* p);  
Given a pointer: If it is an Object, return that Object. If it is an interface, return the Object implementing the interface. If it is null, return null. Else, undefined crash

  pure nothrow @nogc void\* **\_d\_interface\_cast**(void\* p, ClassInfo c);  
Attempts to cast Object o to class c. Returns o if successful, null if not.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_cast_.html>

rt.cmath2
=========

 Runtime support for complex arithmetic code generation (for Posix). 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly
 
void **\_Cmul**();  
Multiply two complex floating point numbers, x and y. 



Input
 x.re ST3 x.im ST2 y.re ST1 y.im ST0 
 
Output
 ST1 real part ST0 imaginary part
  void **\_Cdiv**();  
Divide two complex floating point numbers, x / y. 



Input
 x.re ST3 x.im ST2 y.re ST1 y.im ST0 
 
Output
 ST1 real part ST0 imaginary part
  void **\_Ccmp**();  
Compare two complex floating point numbers, x and y. 



Input
 x.re ST3 x.im ST2 y.re ST1 y.im ST0 
 
Output
 8087 stack is cleared flags set
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_cmath2.html>

rt.config
=========

 Configuration options for druntime. 


The default way to configure the runtime is by passing command line arguments starting with `--DRT-` and followed by the option name, e.g. `--DRT-gcopt` to configure the GC. When command line parsing is enabled, command line options starting with `--DRT-` are filtered out before calling main, so the program will not see them. They are still available via `rt_args()`.   
  
 Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using it's default from the runtime:   
  
 
```
extern(C) __gshared bool rt_cmdline_enabled = false;

```
   
  
 Likewise, declare a boolean rt\_envvars\_enabled to enable configuration via the environment variable `DRT_` followed by the option name, e.g. `DRT_GCOPT`:   
  
 
```
extern(C) __gshared bool rt_envvars_enabled = true;

```
   
  
 Setting default configuration properties in the executable can be done by specifying an array of options named `rt_options`:   
  
 
```
extern(C) __gshared string[] rt_options = [ "gcopt=precise:1 profile:1"];

```
   
  
 Evaluation order of options is `rt_options`, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Rainer Schuetze 
 
Source
 [rt/config.d](https://github.com/dlang/druntime/blob/master/src/rt/config.d)

 
nothrow @nogc string **rt\_configOption**(string opt, scope rt\_configCallBack dg = null, bool reverse = false);  
get a druntime config option using standard configuration options opt name of the option to retrieve dg if non-null, passes the option through this delegate and only returns its return value if non-null reverse reverse the default processing order cmdline/envvar/rt\_options to allow overwriting settings in the delegate with values from higher priority 


returns the options' value if * set on the command line as "--DRT-=value" (rt\_cmdline\_enabled enabled)
* the environment variable "DRT\_" is set (rt\_envvars\_enabled enabled)
* rt\_options[] contains an entry "=value"
* null otherwise


  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_config.html>

rt.cover
========

 Implementation of code coverage analyzer. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/cover.d](https://github.com/dlang/druntime/blob/master/src/rt/cover.d)

 
void **dmd\_coverSourcePath**(string pathname);  
Set path to where source files are located. 



Parameters:


|  |  |
| --- | --- |
| string `pathname` | The new path name. |


  void **dmd\_coverDestPath**(string pathname);  
Set path to where listing files are to be written. 



Parameters:


|  |  |
| --- | --- |
| string `pathname` | The new path name. |


  void **dmd\_coverSetMerge**(bool flag);  
Set merge mode. 



Parameters:


|  |  |
| --- | --- |
| bool `flag` | true means new data is summed with existing data in the listing file; false means a new listing file is always created. |


  void **\_d\_cover\_register2**(string filename, size\_t[] valid, uint[] data, ubyte minPercent);  
The coverage callback. 



Parameters:


|  |  |
| --- | --- |
| string `filename` | The name of the coverage file. |
| size\_t[] `valid` | ??? |
| uint[] `data` | ??? |
| ubyte `minPercent` | minimal coverage of the module |


  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_cover.html>

rt.critical\_
=============

 Implementation of support routines for synchronized blocks. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_critical_.html>

rt.deh
======

 Entry point for exception handling support routines. 


There are three style of exception handling being supported by DMD: DWARF, Win32, and Win64. The Win64 code also supports POSIX. Support for those scheme is in `rt.dwarfeh`, `rt.deh_win32`, and `rt.deh_win64_posix`, respectively, and publicly imported here.   
  
 When an exception is thrown by the user, the compiler translates code like `throw e;` into either `_d_throwdwarf` (for DWARF exceptions) or `_d_throwc` (Win32 / Win64), with the `Exception` object as argument.   
  
 During those functions' handling, they eventually call `_d_createTrace`, which will store inside the `Exception` object the return of `_d_traceContext`, which is an object implementing `Throwable.TraceInfo`. `_d_traceContext` is a configurable hook, and by default will call `core.runtime : defaultTraceHandler`, which itself will call `backtrace` or something similar to store an array of stack frames (`void*` pointers) in the object it returns. Note that `defaultTraceHandler` returns a GC-allocated instance, hence a GC allocation can happen in the middle of throwing an `Exception`.   
  
 The `Throwable.TraceInfo`-implementing should not resolves function names, file and line number until its `opApply` function is called, avoiding the overhead of reading the debug infos until the user call `toString`. If the user only calls `Throwable.message` (or use `Throwable.msg` directly), only the overhead of `backtrace` will be paid, which is minimal enouh. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/deh.d](https://github.com/dlang/druntime/blob/master/src/rt/deh.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_deh.html>

rt.deh\_win32
=============

 Implementation of exception handling support routines for Win32. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/deh\_win32.d](https://github.com/dlang/druntime/blob/master/src/rt/deh_win32.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_deh_win32.html>

rt.deh\_win64\_posix
====================

 Implementation of exception handling support routines for Win64. 


Note that this code also support POSIX, however since v2.070.0, DWARF exception handling is used instead when possible, as it provides better compatibility with C++. 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/deh\_win64\_posix.d](https://github.com/dlang/druntime/blob/master/src/rt/deh_win64_posix.d) 
 
See Also:
<https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=vs-2019>
 
immutable(FuncTable)\* **\_\_eh\_finddata**(void\* address);  
Given address that is inside a function, figure out which function it is in. Return DHandlerTable if there is one, NULL if not.

  size\_t **\_\_eh\_find\_caller**(size\_t regbp, size\_t\* pretaddr);  
Given EBP, find return address to caller, and caller's EBP. 



Input
 regbp Value of EBP for current function \*pretaddr Return address 
 
Output
 \*pretaddr return address to caller 
 
Returns:
caller's EBP
  void **\_d\_throwc**(Throwable h);  
Throw a D object.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_deh_win64_posix.html>

rt.ehalloc
==========

 Exception allocation, cloning, and release compiler support routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/dwarfeh.d](https://github.com/dlang/druntime/blob/master/src/rt/dwarfeh.d)

 
Throwable **\_d\_newThrowable**(const TypeInfo\_Class ci);  
Allocate an exception of type `ci` from the exception pool. It has the same interface as `rt.lifetime._d_newclass()`. The class type must be Throwable or derived from it, and cannot be a COM or C++ class. The compiler must enforce this. 



Returns:
default initialized instance of the type
  nothrow void **\_d\_delThrowable**(Throwable t);  
Delete exception instance `t` from the exception pool. Must have been allocated with `_d_newThrowable()`. This is meant to be called at the close of a catch block. It's nothrow because otherwise any function with a catch block could not be nothrow. 



Input
 t = Throwable
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_ehalloc.html>

rt.aaA
======

 Implementation of associative arrays. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak
 
immutable int **\_aaVersion**;  
AA version for debuggers, bump whenever changing the layout

  struct **AA**;  
Opaque AA wrapper

  pure nothrow @nogc size\_t **\_aaLen**(scope const AA aa);  
Determine number of entries in associative array.

  void\* **\_aaGetY**(AA\* paa, const TypeInfo\_AssociativeArray ti, const size\_t valsz, scope const void\* pkey);  
Lookup \*pkey in aa. Called only from implementation of (aa[key]) expressions when value is mutable. 



Parameters:


|  |  |
| --- | --- |
| AA\* `paa` | associative array opaque pointer |
| TypeInfo\_AssociativeArray `ti` | TypeInfo for the associative array |
| size\_t `valsz` | ignored |
| void\* `pkey` | pointer to the key value |


 
Returns:
if 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 all zeros
  void\* **\_aaGetX**(AA\* paa, const TypeInfo\_AssociativeArray ti, const size\_t valsz, scope const void\* pkey, out bool found);  
Lookup \*pkey in aa. Called only from implementation of require 



Parameters:


|  |  |
| --- | --- |
| AA\* `paa` | associative array opaque pointer |
| TypeInfo\_AssociativeArray `ti` | TypeInfo for the associative array |
| size\_t `valsz` | ignored |
| void\* `pkey` | pointer to the key value |
| bool `found` | true if the value was found |


 
Returns:
if 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 all zeros
  inout(void)\* **\_aaGetRvalueX**(inout AA aa, scope const TypeInfo keyti, const size\_t valsz, scope const void\* pkey);  
Lookup \*pkey in aa. Called only from implementation of (aa[key]) expressions when value is not mutable. 



Parameters:


|  |  |
| --- | --- |
| AA `aa` | associative array opaque pointer |
| TypeInfo `keyti` | TypeInfo for the key |
| size\_t `valsz` | ignored |
| void\* `pkey` | pointer to the key value |


 
Returns:
pointer to value if present, null otherwise
  inout(void)\* **\_aaInX**(inout AA aa, scope const TypeInfo keyti, scope const void\* pkey);  
Lookup \*pkey in aa. Called only from implementation of (key in aa) expressions. 



Parameters:


|  |  |
| --- | --- |
| AA `aa` | associative array opaque pointer |
| TypeInfo `keyti` | TypeInfo for the key |
| void\* `pkey` | pointer to the key value |


 
Returns:
pointer to value if present, null otherwise
  bool **\_aaDelX**(AA aa, scope const TypeInfo keyti, scope const void\* pkey);  
Delete entry scope const AA, return true if it was present

  pure nothrow void **\_aaClear**(AA aa);  
Remove all elements from AA.

  pure nothrow void\* **\_aaRehash**(AA\* paa, scope const TypeInfo keyti);  
Rehash AA

  pure nothrow inout(void[]) **\_aaValues**(inout AA aa, const size\_t keysz, const size\_t valsz, const TypeInfo tiValueArray);  
Return a GC allocated array of all values

  pure nothrow inout(void[]) **\_aaKeys**(inout AA aa, const size\_t keysz, const TypeInfo tiKeyArray);  
Return a GC allocated array of all keys

  int **\_aaApply**(AA aa, const size\_t keysz, dg\_t dg);  
foreach opApply over all values

  int **\_aaApply2**(AA aa, const size\_t keysz, dg2\_t dg);  
foreach opApply over all key/value pairs

  Impl\* **\_d\_assocarrayliteralTX**(const TypeInfo\_AssociativeArray ti, void[] keys, void[] vals);  
Construct an associative array of type ti from keys and value

  int **\_aaEqual**(scope const TypeInfo tiRaw, scope const AA aa1, scope const AA aa2);  
compares 2 AAs for equality

  nothrow hash\_t **\_aaGetHash**(scope const AA\* paa, scope const TypeInfo tiRaw);  
compute a hash

  struct **Range**;  
aaRange implements a ForwardRange

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_aaA.html>

rt.arrayassign
==============

 Implementation of array assignment support routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Kenji Hara 
 
Source
 [rt/arrayassign.d](https://github.com/dlang/druntime/blob/master/src/rt/arrayassign.d)

 
void[] **\_d\_arrayassign**(TypeInfo ti, void[] from, void[] to);  
Keep for backward binary compatibility. This function can be removed in the future.

  void[] **\_d\_arrayassign\_l**(TypeInfo ti, void[] src, void[] dst, void\* ptmp);  
Does array assignment (not construction) from another lvalue array of the same element type. Handles overlapping copies. 



Input
 ti TypeInfo of the element type. dst Points target memory. Its .length is equal to the element count, not byte length. src Points source memory. Its .length is equal to the element count, not byte length. ptmp Temporary memory for element swapping.
  void[] **\_d\_arrayassign\_r**(TypeInfo ti, void[] src, void[] dst, void\* ptmp);  
Does array assignment (not construction) from another rvalue array of the same element type. 



Input
 ti TypeInfo of the element type. dst Points target memory. Its .length is equal to the element count, not byte length. src Points source memory. Its .length is equal to the element count, not byte length. It is always allocated on stack and never overlapping with dst. ptmp Temporary memory for element swapping.
  void[] **\_d\_arrayctor**(TypeInfo ti, void[] from, void[] to);  
Does array initialization (not assignment) from another array of the same element type. ti is the element type.

  void\* **\_d\_arraysetassign**(void\* p, void\* value, int count, TypeInfo ti);  
Do assignment to an array. p[0 .. count] = value;

  void\* **\_d\_arraysetctor**(void\* p, void\* value, int count, TypeInfo ti);  
Do construction of an array. ti[count] p = value;

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_arrayassign.html>

rt.dmain2
=========

 Contains druntime startup and shutdown routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/dmain2.d](https://github.com/dlang/druntime/blob/master/src/rt/dmain2.d)

 
void\* **gc\_getProxy**();  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  void **gc\_setProxy**(void\* p);  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  void **gc\_clrProxy**();  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  alias **gcGetFn** = extern (C) void\* function();  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  alias **gcSetFn** = extern (C) void function(void\*);  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  alias **gcClrFn** = extern (C) void function();  
These are a temporary means of providing a GC hook for DLL use. They may be replaced with some other similar functionality later.

  shared size\_t **\_initCount**;  
Keep track of how often rt\_init/rt\_term were called.

  int **rt\_init**();  
Initialize druntime. If a C program wishes to call D code, and there's no D main(), then it must call rt\_init() and rt\_term().

  int **rt\_term**();  
Terminate use of druntime.

  alias **TraceHandler** = TraceInfo function(void\* ptr);  
Trace handler

  void **rt\_setTraceHandler**(TraceHandler h);  
Overrides the default trace hander with a user-supplied version. 



Parameters:


|  |  |
| --- | --- |
| TraceHandler `h` | The new trace handler. Set to null to use the default handler. |


  TraceHandler **rt\_getTraceHandler**();  
Return the current trace handler

  Throwable.TraceInfo **\_d\_traceContext**(void\* ptr = null);  
This function will be called when an exception is constructed. The user-supplied trace handler will be called if one has been supplied, otherwise no trace will be generated. 



Parameters:


|  |  |
| --- | --- |
| void\* `ptr` | A pointer to the location from which to generate the trace, or null if the trace should be generated from within the trace handler itself. |


 
Returns:
An object describing the current calling context or null if no handler is supplied.
  struct **CArgs**;  
Provide out-of-band access to the original C argc/argv passed to this program via main(argc,argv).

  int **\_d\_run\_main**(int argc, char\*\* argv, MainFunc mainFunc);  
Sets up the D char[][] command-line args, initializes druntime, runs embedded unittests and then runs the given D main() function, optionally catching and printing any unhandled exceptions.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_dmain2.html>

invariant
=========

 
void **\_d\_invariant**(Object o);  
Implementation of invariant support routines. 



Copyright:
Copyright Digital Mars 2007 - 2010. 
 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_invariant.html>

rt.llmath
=========

 Support for 64-bit longs. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/llmath.d](https://github.com/dlang/druntime/blob/master/src/rt/llmath.d)

 
void **\_\_ULDIV2\_\_**();  
Unsigned long divide. 



Input
 [EDX,EAX],[ECX,EBX] 
 
Output
 [EDX,EAX] = [EDX,EAX] / [ECX,EBX] [ECX,EBX] = [EDX,EAX] % [ECX,EBX]
  void **\_\_LDIV2\_\_**();  
Signed long divide. 



Input
 [EDX,EAX],[ECX,EBX] 
 
Output
 [EDX,EAX] = [EDX,EAX] / [ECX,EBX] [ECX,EBX] = [EDX,EAX] % [ECX,EBX] ESI,EDI destroyed
  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_llmath.html>

rt.dwarfeh
==========

 Exception handling support for Dwarf-style portable exceptions. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [rt/dwarfeh.d](https://github.com/dlang/druntime/blob/master/src/rt/dwarfeh.d)

 
struct **ExceptionHeader**;  
Wrap the unwinder's data with our own compiler specific struct with our own data.

 
static @nogc ExceptionHeader\* **create**(Throwable o);  
Allocate and initialize an ExceptionHeader. 



Parameters:


|  |  |
| --- | --- |
| Throwable `o` | thrown object |


 
Returns:
allocated and initalized ExceptionHeader
  static void **free**(ExceptionHeader\* eh);  
Free ExceptionHeader that was created by create(). 



Parameters:


|  |  |
| --- | --- |
| ExceptionHeader\* `eh` | ExceptionHeader to free |


  void **push**();  
Push this onto stack of chained exceptions.

  static ExceptionHeader\* **pop**();  
Pop and return top of chained exception stack.

  static ExceptionHeader\* **toExceptionHeader**(\_Unwind\_Exception\* eo);  
Convert from pointer to exception\_object to pointer to ExceptionHeader that it is embedded inside of. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `eo` | pointer to exception\_object field |


 
Returns:
pointer to ExceptionHeader that eo points into.
    Throwable **\_\_dmd\_begin\_catch**(\_Unwind\_Exception\* exceptionObject);  
The first thing a catch handler does is call this. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `exceptionObject` | value passed to catch handler by unwinder |


 
Returns:
object that was caught
  nothrow @nogc void\* **\_d\_eh\_swapContextDwarf**(void\* newContext);  
Called when fibers switch contexts. 



Parameters:


|  |  |
| --- | --- |
| void\* `newContext` | stack to switch to |


 
Returns:
previous value of stack
  void **\_d\_throwdwarf**(Throwable o);  
 Called by D code to throw an exception via 
```
throw o;

```
 



Parameters:


|  |  |
| --- | --- |
| Throwable `o` | Object to throw |


 
Returns:
doesn't return
  \_Unwind\_Reason\_Code **\_\_dmd\_personality\_v0**(int ver, \_Unwind\_Action actions, \_Unwind\_Exception\_Class exceptionClass, \_Unwind\_Exception\* exceptionObject, \_Unwind\_Context\* context);  
"personality" function, specific to each language. This one, of course, is specific to DMD. 



Parameters:


|  |  |
| --- | --- |
| int `ver` | version must be 1 |
| \_Unwind\_Action `actions` | bitwise OR of the 4 actions UA\_xxx. UA\_SEARCH\_PHASE means return URC\_HANDLER\_FOUND if current frame has a handler, URC\_CONTINUE\_UNWIND if not. Cannot be used with UA\_CLEANUP\_PHASE. UA\_CLEANUP\_PHASE means perform cleanup for current frame by calling nested functions and returning URC\_CONTINUE\_UNWIND. Or, set up registers and IP for Landing Pad and return URC\_INSTALL\_CONTEXT. UA\_HANDLER\_FRAME means this frame was the one with the handler in Phase 1, and now it is Phase 2 and the handler must be run. UA\_FORCE\_UNWIND means unwinding the stack for longjmp or thread cancellation. Run finally clauses, not catch clauses, finallys must end with call to Uwind\_Resume(). |
| \_Unwind\_Exception\_Class `exceptionClass` | 8 byte value indicating type of thrown exception. If the low 4 bytes are "C++\0", it's a C++ exception. |
| \_Unwind\_Exception\* `exceptionObject` | language specific exception information |
| \_Unwind\_Context\* `context` | opaque type of unwinder state information |


 
Returns:
reason code 
 
See Also:
<http://www.ucw.cz/~hubicka/papers/abi/node25.html>
  ClassInfo **getClassInfo**(\_Unwind\_Exception\* exceptionObject, const(ubyte)\* currentLsd);  
Look at the chain of inflight exceptions and pick the class type that'll be looked for in catch clauses. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `exceptionObject` | language specific exception information |
| const(ubyte)\* `currentLsd` | pointer to LSDA table |


 
Returns:
class type to look for
  \_uleb128\_t **uLEB128**(const(ubyte)\*\* p);  
Decode Unsigned LEB128. 



Parameters:


|  |  |
| --- | --- |
| const(ubyte)\*\* `p` | pointer to data pointer, \*p is updated to point past decoded value |


 
Returns:
decoded value 
 
See Also:
<https://en.wikipedia.org/wiki/LEB128>
  \_sleb128\_t **sLEB128**(const(ubyte)\*\* p);  
Decode Signed LEB128. 



Parameters:


|  |  |
| --- | --- |
| const(ubyte)\*\* `p` | pointer to data pointer, \*p is updated to point past decoded value |


 
Returns:
decoded value 
 
See Also:
<https://en.wikipedia.org/wiki/LEB128>
  LsdaResult **scanLSDA**(const(ubyte)\* lsda, \_Unwind\_Ptr ip, \_Unwind\_Exception\_Class exceptionClass, bool cleanupsOnly, bool preferHandler, \_Unwind\_Exception\* exceptionObject, out \_Unwind\_Ptr landingPad, out int handler);  
Read and extract information from the LSDA (aka gcc\_except\_table section). The dmd Call Site Table is structurally different from other implementations. It is organized as nested ranges, and one ip can map to multiple ranges. The most nested candidate is selected when searched. Other implementations have one candidate per ip. 



Parameters:


|  |  |
| --- | --- |
| const(ubyte)\* `lsda` | pointer to LSDA table |
| \_Unwind\_Ptr `ip` | offset from start of function at which exception happened |
| \_Unwind\_Exception\_Class `exceptionClass` | which language threw the exception |
| bool `cleanupsOnly` | only look for cleanups |
| bool `preferHandler` | if a handler encloses a cleanup, prefer the handler |
| \_Unwind\_Exception\* `exceptionObject` | language specific exception information |
| \_Unwind\_Ptr `landingPad` | set to landing pad |
| int `handler` | set to index of which catch clause was matched |


 
Returns:
LsdaResult 
 
See Also:

<http://reverseengineering.stackexchange.com/questions/6311/how-to-recover-the-exception-info-from-gcc-except-table-and-eh-handle-sections> <http://www.airs.com/blog/archives/464> <https://anarcheuz.github.io/2015/02/15/ELF%20internals%20part%202%20-%20exception%20handling/>

  int **actionTableLookup**(\_Unwind\_Exception\* exceptionObject, uint actionRecordPtr, const(ubyte)\* pActionTable, const(ubyte)\* tt, ubyte TType, \_Unwind\_Exception\_Class exceptionClass, const(ubyte)\* lsda);  
Look up classType in Action Table. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `exceptionObject` | language specific exception information |
| uint `actionRecordPtr` | starting index in Action Table + 1 |
| const(ubyte)\* `pActionTable` | pointer to start of Action Table |
| const(ubyte)\* `tt` | pointer past end of Type Table |
| ubyte `TType` | encoding of entries in Type Table |
| \_Unwind\_Exception\_Class `exceptionClass` | which language threw the exception |
| const(ubyte)\* `lsda` | pointer to LSDA table |


 
Returns:
 * >=1 means the handler index of the classType
* 0 means classType is not in the Action Table
* <0 means corrupt



  enum \_Unwind\_Exception\_Class **cppExceptionClass**;  
C++ Support

  void\* **getCppPtrToThrownObject**(\_Unwind\_Exception\* exceptionObject, CppTypeInfo sti);  
Get Pointer to Thrown Object if type of thrown object is implicitly convertible to the catch type. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `exceptionObject` | language specific exception information |
| CppTypeInfo `sti` | type of catch clause |


 
Returns:
null if not caught, pointer to thrown object if caught
  interface **CppTypeInfo**;  
Access C++ std::type\_info's virtual functions from D, being careful to not require linking with libstd++ or interfere with core.stdcpp.typeinfo. So, give it a different name.

  struct **CppExceptionHeader**;  
The C++ version of D's ExceptionHeader wrapper

 
static CppExceptionHeader\* **toExceptionHeader**(\_Unwind\_Exception\* eo);  
Convert from pointer to exception\_object field to pointer to CppExceptionHeader that it is embedded inside of. 



Parameters:


|  |  |
| --- | --- |
| \_Unwind\_Exception\* `eo` | pointer to exception\_object field |


 
Returns:
pointer to CppExceptionHeader that eo points into.
    

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_dwarfeh.html>

rt.lifetime
===========

 This module contains all functions related to an object's lifetime: allocation, resizing, deallocation, and finalization. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Steven Schveighoffer 
 
Source
 [rt/lifetime.d](https://github.com/dlang/druntime/blob/master/src/rt/lifetime.d)

 
void\* **\_d\_allocmemory**(size\_t sz);  Object **\_d\_newclass**(const ClassInfo ci);  void **\_d\_delinterface**(void\*\* p);  void **\_d\_delclass**(Object\* p);  void **\_d\_delstruct**(void\*\* p, TypeInfo\_Struct inf);  
This is called for a delete statement where the value being deleted is a pointer to a struct with a destructor but doesn't have an overloaded delete operator.

  pure nothrow bool **\_\_setArrayAllocLength**(ref BlkInfo info, size\_t newlength, bool isshared, const TypeInfo tinext, size\_t oldlength = ~0);  
Set the allocated length of the array block. This is called any time an array is appended to or its length is set. 


The allocated block looks like this for blocks < PAGESIZE:   
  
 |elem0|elem1|elem2|...|elemN-1|emptyspace|N\*elemsize|   
  
   
  
 The size of the allocated length at the end depends on the block size:   
  
 a block of 16 to 256 bytes has an 8-bit length.   
  
 a block with 512 to pagesize/2 bytes has a 16-bit length.   
  
 For blocks >= pagesize, the length is a size\_t and is at the beginning of the block. The reason we have to do this is because the block can extend into more pages, so we cannot trust the block length if it sits at the end of the block, because it might have just been extended. If we can prove in the future that the block is unshared, we may be able to change this, but I'm not sure it's important.   
  
 In order to do put the length at the front, we have to provide 16 bytes buffer space in case the block has to be aligned properly. In x86, certain SSE instructions will only work if the data is 16-byte aligned. In addition, we need the sentinel byte to prevent accidental pointers to the next block. Because of the extra overhead, we only do this for page size and above, where the overhead is minimal compared to the block size.   
  
 So for those blocks, it looks like:   
  
 |N\*elemsize|padding|elem0|elem1|...|elemN-1|emptyspace|sentinelbyte|   
  
 where elem0 starts 16 bytes after the first byte.

  pure nothrow size\_t **\_\_arrayAllocLength**(ref BlkInfo info, const TypeInfo tinext);  
get the allocation size of the array for the given block (without padding or type info)

  pure nothrow void\* **\_\_arrayStart**(return BlkInfo info);  
get the start of the array for the given block

  pure nothrow @trusted size\_t **\_\_arrayPad**(size\_t size, const TypeInfo tinext);  
get the padding required to allocate size bytes. Note that the padding is NOT included in the passed in size. Therefore, do NOT call this function with the size of an allocated block.

  pure nothrow BlkInfo **\_\_arrayAlloc**(size\_t arrsize, const TypeInfo ti, const TypeInfo tinext);  
allocate an array memory block by applying the proper padding and assigning block attributes if not inherited from the existing block

  enum int **N\_CACHE\_BLOCKS**;  
cache for the lookup of the block info

  nothrow BlkInfo\* **\_\_getBlkInfo**(void\* interior);  
Get the cached block info of an interior pointer. Returns null if the interior pointer's block is not cached. 



NOTE
 The base ptr in this struct can be cleared asynchronously by the GC, so any use of the returned BlkInfo should copy it and then check the base ptr of the copy before actually using it. 
 
TODO
 Change this function so the caller doesn't have to be aware of this issue. Either return by value and expect the caller to always check the base ptr as an indication of whether the struct is valid, or set the BlkInfo as a side-effect and return a bool to indicate success.
  void **\_d\_arrayshrinkfit**(const TypeInfo ti, void[] arr);  
Shrink the "allocated" length of an array to be the exact size of the array. It doesn't matter what the current allocated length of the array is, the user is telling the runtime that he knows what he is doing.

  size\_t **\_d\_arraysetcapacity**(const TypeInfo ti, size\_t newcapacity, void[]\* p);  
set the array capacity. If the array capacity isn't currently large enough to hold the requested capacity (in number of elements), then the array is resized/reallocated to the appropriate size. Pass in a requested capacity of 0 to get the current capacity. Returns the number of elements that can actually be stored once the resizing is done.

  pure nothrow void[] **\_d\_newarrayU**(const TypeInfo ti, size\_t length);  
Allocate a new uninitialized array of length elements. ti is the type of the resulting array, or pointer to element.

  pure nothrow void[] **\_d\_newarrayT**(const TypeInfo ti, size\_t length);  
Allocate a new array of length elements. ti is the type of the resulting array, or pointer to element. (For when the array is initialized to 0)

  pure nothrow void[] **\_d\_newarrayiT**(const TypeInfo ti, size\_t length);  
For when the array has a non-zero initializer.

  void[] **\_d\_newarrayOpT**(alias op)(const TypeInfo ti, size\_t[] dims);  void[] **\_d\_newarraymTX**(const TypeInfo ti, size\_t[] dims);  void[] **\_d\_newarraymiTX**(const TypeInfo ti, size\_t[] dims);  void\* **\_d\_newitemU**(in TypeInfo \_ti);  
Allocate an uninitialized non-array item. This is an optimization to avoid things needed for arrays like the \_arrayPad(size).

  void\* **\_d\_newitemT**(in TypeInfo \_ti);  
Same as above, zero initializes the item.

  void\* **\_d\_newitemiT**(in TypeInfo \_ti);  
Same as above, for item with non-zero initializer.

  struct **Array**;  void **\_d\_delarray\_t**(void[]\* p, const TypeInfo\_Struct ti);  void **\_d\_delmemory**(void\*\* p);  void **\_d\_callinterfacefinalizer**(void\* p);  void **\_d\_callfinalizer**(void\* p);  void **rt\_setCollectHandler**(CollectHandler h);  CollectHandler **rt\_getCollectHandler**();  nothrow int **rt\_hasFinalizerInSegment**(void\* p, size\_t size, uint attr, in void[] segment);  nothrow void **rt\_finalize2**(void\* p, bool det = true, bool resetMemory = true);  void[] **\_d\_arraysetlengthT**(const TypeInfo ti, size\_t newlength, void[]\* p);  
Resize dynamic arrays with 0 initializers.

  void[] **\_d\_arraysetlengthiT**(const TypeInfo ti, size\_t newlength, void[]\* p);  
Resize arrays for non-zero initializers. p pointer to array lvalue to be updated newlength new .length property of array sizeelem size of each element of array initsize size of initializer ... initializer

  void[] **\_d\_arrayappendT**(const TypeInfo ti, ref byte[] x, byte[] y);  
Append y[] to array x[]

  size\_t **newCapacity**(size\_t newlength, size\_t size);  byte[] **\_d\_arrayappendcTX**(const TypeInfo ti, ref byte[] px, size\_t n);  
Extend an array by n elements. Caller must initialize those elements.

  void[] **\_d\_arrayappendcd**(ref byte[] x, dchar c);  
Append dchar to char[]

  void[] **\_d\_arrayappendwd**(ref byte[] x, dchar c);  
Append dchar to wchar[]

  byte[] **\_d\_arraycatT**(const TypeInfo ti, byte[] x, byte[] y);  void[] **\_d\_arraycatnTX**(const TypeInfo ti, byte[][] arrs);  void\* **\_d\_arrayliteralTX**(const TypeInfo ti, size\_t length);  
Allocate the array, rely on the caller to do the initialization of the array.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_lifetime.html>

rt.memory
=========

 This module tells the garbage collector about the static data and bss segments, so the GC can scan them for roots. It does not deal with thread local static data. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/memory.d](https://github.com/dlang/druntime/blob/master/src/rt/memory.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_memory.html>

rt.memset
=========

 Contains a memset implementation used by compiler-generated code. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_memset.html>

rt.monitor\_
============

 Contains the implementation for object monitors. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak


 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_monitor_.html>

rt.sections
===========

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak 
 
Source
 [rt/sections.d](https://github.com/dlang/druntime/blob/master/src/rt/sections.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections.html>

rt.sections\_android
====================

 Written in the D programming language. This module provides bionic-specific support for sections. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak 
 
Source
 [rt/sections\_android.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_android.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_android.html>

rt.sections\_elf\_shared
========================

 Written in the D programming language. This module provides ELF-specific support for sections with shared libraries. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak 
 
Source
 [rt/sections\_linux.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_linux.d)

 
bool **\_isRuntimeInitialized**;  
Boolean flag set to true while the runtime is initialized.

  nothrow @nogc void **initSections**();  
Gets called on program startup just before GC is initialized.

  nothrow @nogc void **finiSections**();  
Gets called on program shutdown just after GC is terminated.

  nothrow @nogc Array!(void[])\* **initTLSRanges**();  
Called once per thread; returns array of thread local storage ranges

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_elf_shared.html>

rt.sections\_osx\_x86\_64
=========================

 Written in the D programming language. This module provides OS X x86-64 specific support for sections. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak, Jacob Carlborg 
 
Source
 [rt/sections\_osx\_x86\_64.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_osx_x86_64.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_osx_x86_64.html>

rt.minfo
========

 Written in the D programming language. Module initialization routines. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly 
 
Source
 [rt/minfo.d](https://github.com/dlang/druntime/blob/master/src/rt/minfo.d)

 
struct **ModuleGroup**;  
A ModuleGroup is an unordered collection of modules. There is exactly one for: 1. all statically linked in D modules, either directely or as shared libraries
2. each call to rt\_loadLibrary()


 
void **sortCtors**(string cycleHandling);   
  
void **sortCtors**();  
Allocate and fill in ctors[] and tlsctors[]. Modules are inserted into the arrays in the order in which the constructors need to be run. 



Parameters:
 
Throws:
Exception if it fails.
  bool **sortCtorsOld**(int[][] edges);  
This is the old ctor sorting algorithm that does not find all cycles. 


It is here to allow the deprecated behavior from the original algorithm until people have fixed their code.   
  
 If no cycles are found, the ctors and tlsctors are replaced with the ones generated by this algorithm to preserve the old incorrect ordering behavior. 

 
Parameters:


|  |  |
| --- | --- |
| int[][] `edges` | The module edges as found in the `importedModules` member of each ModuleInfo. Generated in sortCtors. |


 
Returns:
true if no cycle is found, false if one was.
    int **moduleinfos\_apply**(scope int delegate(immutable(ModuleInfo\*)) dg);  
Iterate over all module infos.

  void **rt\_moduleCtor**();  
Module constructor and destructor routines.

  void **rt\_moduleTlsCtor**();  
Module constructor and destructor routines.

  void **rt\_moduleTlsDtor**();  
Module constructor and destructor routines.

  void **rt\_moduleDtor**();  
Module constructor and destructor routines.

  void **runModuleFuncs**(alias getfp)(const(immutable(ModuleInfo)\*)[] modules);  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_minfo.html>

rt.sections\_solaris
====================

 Written in the D programming language. This module provides Solaris-specific support for sections. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak 
 
Source
 [rt/sections\_solaris.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_solaris.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_solaris.html>

rt.sections\_win32
==================

 Written in the D programming language. This module provides Win32-specific support for sections. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak 
 
Source
 [rt/sections\_win32.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_win32.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_win32.html>

rt.sections\_win64
==================

 Written in the D programming language. This module provides Win32-specific support for sections. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak 
 
Source
 [rt/sections\_win64.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_win64.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_win64.html>

rt.tlsgc
========

 
License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Martin Nowak
 
struct **Data**;  
Per thread record to store thread associated data for garbage collection.

  nothrow @nogc void\* **init**();  
Initialization hook, called FROM each thread. No assumptions about module initialization state should be made.

  nothrow @nogc void **destroy**(void\* data);  
Finalization hook, called FOR each thread. No assumptions about module initialization state should be made.

  nothrow void **scan**(void\* data, scope ScanDg dg);  
GC scan hook, called FOR each thread. Can be used to scan additional thread local memory.

  nothrow void **processGCMarks**(void\* data, scope IsMarkedDg dg);  
GC sweep hook, called FOR each thread. Can be used to free additional thread local memory or associated data structures. Note that only memory allocated from the GC can have marks.

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_tlsgc.html>

rt.trace
========

 Contains support code for code profiling. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, the LDC team 
 
Source
 [rt/trace.d](https://github.com/dlang/druntime/blob/master/src/rt/trace.d)

 
void **trace\_setlogfilename**(string name);  
Set the file path for profile reports (`-profile`) 


This function is a public API, exposed in `core.runtime`.   
  
 Since we are calling C functions under the hood, and we might need to open and close files during the runtime tear-down we copy the parameter via malloc to ensure NUL-termination. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | Path to the output file. Empty means stdout. |


  void **trace\_setdeffilename**(string name);  
Set the file path for the optimized profile linker DEF file (`-profile`) 


This function is a public API, exposed in `core.runtime`.   
  
 Since we are calling C functions under the hood, and we might need to open and close files during the runtime tear-down we copy the parameter via malloc to ensure NUL-termination. 

 
Parameters:


|  |  |
| --- | --- |
| string `name` | Path to the output file. Empty means stdout. |


  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_trace.html>

rt.profilegc
============



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_profilegc.html>

rt.sections\_osx\_x86
=====================

 Written in the D programming language. This module provides OS X x86 specific support for sections. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright, Sean Kelly, Martin Nowak, Jacob Carlborg 
 
Source
 [rt/sections\_osx\_x86.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_osx_x86.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_osx_x86.html>

Introduction
============

 D is a general-purpose systems programming language with a C-like syntax that compiles to native code. It is statically typed and supports both automatic (garbage collected) and manual memory management. D programs are structured as modules that can be compiled separately and linked with external libraries to create native libraries or executables.

 This document is the reference manual for the D Programming Language. For more information and other documents, see [The D Language Website](https://dlang.org/).

 Phases of Compilation
---------------------

 The process of compiling is divided into multiple phases. Each phase is independent of subsequent phases. For example, the scanner is not affected by the semantic analyzer. This separation of passes makes language tools like syntax-directed editors relatively easy to create. It is also possible to compress D source by storing it in ‘tokenized’ form.

 1. **source character set**  
 The source file is checked to determine its encoding and the appropriate scanner is loaded. 7-bit ASCII and UTF encodings are accepted.
2. **script line**   
 If the first line starts with "#!", then that line is ignored.
3. **lexical analysis**  
 The source file is divided into a sequence of tokens. [Special tokens](lex#specialtokens) are replaced with other tokens. [*SpecialTokenSequence*](lex#SpecialTokenSequence)s are processed and removed.
4. **syntax analysis**  
 The sequence of tokens is parsed to form syntax trees.
5. **semantic analysis**  
 The syntax trees are traversed to declare variables, load symbol tables, assign types, and determine the meaning of the program.
6. **optimization**  
 Optimization is an optional pass that attempts to rewrite the program in a semantically equivalent, more performant, version.
7. **code generation**  
 Instructions are selected from the target architecture to implement the semantics of the program. The typical result will be an object file suitable for input to a linker.

 Memory Model
------------

 The *byte* is the fundamental unit of storage. Each byte has 8 bits and is stored at a unique address. A *memory location* is a sequence of one or more bytes of the exact size required to hold a scalar type. Multiple threads can access separate memory locations without interference. 

 Memory locations come in three groups:

 1. *Thread-local memory locations* are accessible from only one thread at a time.
2. *Immutable memory locations* cannot be written to during their lifetime. Immutable memory locations can be read from by multiple threads without synchronization.
3. *Shared memory locations* are accessible from multiple threads.

 **Undefined Behavior:** Allowing multiple threads to access a thread-local memory location results in undefined behavior. **Undefined Behavior:** Writing to an immutable memory location during its lifetime results in undefined behavior. **Undefined Behavior:** Writing to a shared memory location in one thread while one or more additional threads read from or write to the same location is undefined behavior unless all of the reads and writes are synchronized. Execution of a single thread on thread-local and immutable memory locations is *sequentially consistent*. This means the collective result of the operations is the same as if they were executed in the same order that the operations appear in the program. 

 A memory location can be transferred from thread-local to immutable or shared if there is only one reference to the location.

 A memory location can be transferred from shared to immutable or thread-local if there is only one reference to the location.

 A memory location can be temporarily transferred from shared to local if synchronization is used to prevent any other threads from accessing the memory location during the operation.

 Object Model
------------

 An *object* is created in the following circumstances: 

 * a definition
* a [*NewExpression*](expression#NewExpression)
* a temporary is created
* changing which field of a union is active

 An object spans a sequence of memory locations which may or may not be contiguous. Its lifetime encompasses construction, destruction, and the period in between. Each object has a type which is determined either statically or by runtime type information. The object's memory locations may include any combination of thread-local, immutable, or shared. 

 Objects can be composed into a *composed object*. Objects that make up a composed object are *subobjects*. An object that is not the subobject of another object is a *complete object*. The lifetime of a subobject is always within the lifetime of the complete object to which it belongs. 

 An object's address is the address of the first byte of the first memory location for that object. Object addresses are distinct unless one object is nested within the other. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/intro.html>

rt.tracegc
==========

 Contains implementations of functions called when the -profile=gc switch is thrown. 


Tests for this functionality can be found in test/profile/src/profilegc.d 

 
License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Walter Bright 
 
Source
 [src/rt/tracegc.d](https://github.com/dlang/druntime/blob/master/src/src/rt/tracegc.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_tracegc.html>

rt.unwind
=========

 Written in the D programming language. Equivalent to unwind.h 



See Also:
Itanium C++ ABI: Exception Handling ($Revision: 1.22 $) 
 
Source
 [rt/unwind.d](https://github.com/dlang/druntime/blob/master/src/rt/unwind.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_unwind.html>

rt.util.typeinfo
================

 This module contains utilities for TypeInfo implementation. 



License:

[Boost License 1.0](http://www.boost.org/LICENSE_1_0.txt). 
 
Authors:
Kenji Hara
 
class **TypeInfo\_v**: rt.util.typeinfo.TypeInfoGeneric!(ubyte, ubyte).TypeInfoGeneric;  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_util_typeinfo.html>

rt.util.utility
===============

 Contains various utility functions used by the runtime implementation. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Jacob Carlborg 
 
Source
 [rt/util/utility.d](https://github.com/dlang/druntime/blob/master/src/rt/util/utility.d)

 
package(rt) nothrow @nogc @safe void **safeAssert**(bool condition, scope string msg, scope string file = \_\_FILE\_\_, size\_t line = \_\_LINE\_\_);  
Asserts that the given condition is `true`. 


The assertion is independent from -release, by abort()ing. Regular assertions throw an AssertError and thus require an initialized GC, which might not be the case (yet or anymore) for the startup/shutdown code in this package (called by CRT ctors/dtors etc.).

  

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_util_utility.html>

rt.sections\_darwin\_64
=======================

 Written in the D programming language. This module provides Darwin 64 bit specific support for sections. 



License:
Distributed under the [Boost Software License 1.0](http://www.boost.org/LICENSE_1_0.txt). (See accompanying file LICENSE) 
 
Authors:
Jacob Carlborg 
 
Source
 [rt/sections\_darwin\_64.d](https://github.com/dlang/druntime/blob/master/src/rt/sections_darwin_64.d)



 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/phobos/rt_sections_darwin_64.html>

Properties
==========

 **Contents** 1. [.init Property](#init)
2. [.stringof Property](#stringof)
3. [.sizeof Property](#sizeof)
4. [.alignof Property](#alignof)
5. [.mangleof Property](#mangleof)
6. [.classinfo Property](#classinfo)
7. [User-Defined Properties](#classproperties)

 Every symbol, type, and expression has properties that can be queried:

 

Property Examples| **Expression** |  **Value** |
| `int.sizeof` | yields 4 |
| `float.nan` |  yields the floating point nan (Not A Number) value |
| `(float).nan` |  yields the floating point nan value |
| `(3).sizeof` | yields 4 (because 3 is an int) |
| `int.init` |  default initializer for ints |
| `int.mangleof` |  yields the string "i" |
| `int.stringof` |  yields the string "int" |
| `(1+2).stringof` |  yields the string "1 + 2" |

   
 

Properties for All Types|  **Property** | **Description** |
| [`.init`](#init) |  initializer |
| [`.sizeof`](#sizeof) | size in bytes |
| [`.alignof`](#alignof) | alignment size |
| [`.mangleof`](#mangleof) | string representing the ‘mangled’ representation of the type |
| [`.stringof`](#stringof) | string representing the source representation of the type |

   
 

Properties for Integral Types| **Property** | **Description** |
| `.init` |  initializer |
| `.max` | maximum value |
| `.min` | minimum value |

   
 

Properties for Floating Point Types| **Property** | **Description** |
| `.init` | initializer (NaN) |
| `.infinity` | infinity value |
| `.nan` | NaN value |
| `.dig` | number of decimal digits of precision |
| `.epsilon` | smallest increment to the value 1 |
| `.mant_dig` | number of bits in mantissa |
| `.max_10_exp` | maximum int value such that 10`max_10_exp` is representable |
| `.max_exp` | maximum int value such that 2`max_exp-1` is representable |
| `.min_10_exp` | minimum int value such that 10`min_10_exp` is representable as a normalized value |
| `.min_exp` | minimum int value such that 2`min_exp-1` is representable as a normalized value |
| `.max` | largest representable value that's not infinity |
| `.min_normal` | smallest representable normalized value that's not 0 |
| `.re` | real part |
| `.im` | imaginary part |

   
 

Properties for Class Types| **Property** | **Description** |
| [`.classinfo`](#classinfo) | Information about the dynamic type of the class |

 .init Property
--------------

 `.init` produces a constant expression that is the default initializer. If applied to a type, it is the default initializer for that type. If applied to a variable or field, it is the default initializer for that variable or field's type. 

 
```
int a;
int b = 1;

int.init // is 0
a.init   // is 0
b.init   // is 0

struct Foo
{
    int a;
    int b = 7;
}

Foo.init.a  // is 0
Foo.init.b  // is 7

```
 **Note:** `.init` produces a default initialized object, not default constructed. If there is a default constructor for an object, it may produce a different value.

 1. If `T` is a nested struct, the context pointer in `T.init` is `null`.

```
void main()
{
    int x;
    struct S
    {
        void foo() { x = 1; }  // access x in enclosing scope via context pointer
    }
    S s1;           // OK. S() correctly initialize its context pointer.
    S s2 = S();     // OK. same as s1
    S s3 = S.init;  // Bad. the context pointer in s3 is null
    s3.foo();       // Access violation
}

```
3. If `T` is a struct which has `@disable this();`, `T.init` might return a logically incorrect object.

```
struct S
{
    int x;
    @disable this();
    this(int n) { x = n; }
    invariant { assert(x > 0); }
    void check() {}
}

void main()
{
  //S s1;           // Error: variable s1 initializer required for type S
  //S s2 = S();     // Error: constructor S.this is not callable
                    // because it is annotated with @disable
    S s3 = S.init;  // Bad. s3.x == 0, and it violates the invariant of S
    s3.check();     // Assertion failure
}

```

 .stringof Property
------------------

 `.stringof` produces a constant string that is the source representation of its prefix. If applied to a type, it is the string for that type. If applied to an expression, it is the source representation of that expression. The expression will not be evaluated. 

 
```
module test;
import std.stdio;

struct Dog { }

enum Color { Red }

int i = 4;

void main()
{
    writeln((1+2).stringof);       // "1 + 2"
    writeln(Dog.stringof);         // "Dog"
    writeln(test.Dog.stringof);    // "Dog"
    writeln(int.stringof);         // "int"
    writeln((int*[5][]).stringof); // "int*[5][]"
    writeln(Color.Red.stringof);   // "Red"
    writeln((5).stringof);         // "5"

    writeln((++i).stringof);       // "i += 1"
    writeln(i);                    // 4
}

```
 **Implementation Defined:** The string representation for a type or expression can vary. **Best Practices:** Do not use `.stringof` for code generation. Instead use the [identifier](traits#identifier) trait, or one of the Phobos helper functions such as [`std.traits.fullyQualifiedName`](https://dlang.org/phobos/std_traits.html#fullyQualifiedName). .sizeof Property
----------------

 `e.sizeof` gives the size in bytes of the expression `e`. 

 When getting the size of a member, it is not necessary for there to be a *this* object: 

 
```
struct S
{
    int a;
    static int foo()
    {
        return a.sizeof; // returns 4
    }
}

void test()
{
    int x = S.a.sizeof; // sets x to 4
}

```
 `.sizeof` applied to a class object returns the size of the class reference, not the class instantiation.

 .alignof Property
-----------------

 `.alignof` gives the aligned size of an expression or type. For example, an aligned size of 1 means that it is aligned on a byte boundary, 4 means it is aligned on a 32 bit boundary. 

 **Implementation Defined:** the actual aligned size. **Best Practices:** Be particularly careful when laying out an object that must line up with an externally imposed layout. Data misalignment can result in particularly pernicious bugs. It's often worth putting in an `assert` to assure it is correct. .mangleof Property
------------------

 Mangling refers to how a symbol is represented in text form in the generated object file. `.mangleof` returns a string literal of the representation of the type or symbol it is applied to. The mangling of types and symbols with D linkage is defined by [Name Mangling](abi#name_mangling). 

 **Implementation Defined:** 1. whether a leading underscore is added to a symbol
2. the mangling of types and symbols with non-D linkage. For C and C++ linkage, this will typically match what the associated C or C++ compiler does.

 .classinfo Property
-------------------

 `.classinfo` provides information about the dynamic type of a class object. It returns a reference to type [`object.TypeInfo_Class`](https://dlang.org/phobos/object.html).

 `.classinfo` applied to an interface gives the information for the interface, not the class it might be an instance of.

 User-Defined Properties
-----------------------

 User-defined properties can be created using [Property Functions](function#property-functions).

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/property.html>

Pragmas
=======

 **Contents** 1. [Predefined Pragmas](#predefined-pragmas)
	1. [`pragma crt_constructor`](#crtctor)
	2. [`pragma crt_destructor`](#crtdtor)
	3. [`pragma inline`](#inline)
	4. [`pragma lib`](#lib)
	5. [`pragma linkerDirective`](#linkerDirective)
	6. [`pragma mangle`](#mangle)
	7. [`pragma msg`](#msg)
	8. [`pragma printf`](#printf)
	9. [`pragma scanf`](#scanf)
	10. [`pragma startaddress`](#startaddress)
2. [Vendor Specific Pragmas](#vendor_specific_pragmas)

 
```
PragmaDeclaration:
    Pragma;
    Pragma DeclarationBlock

PragmaStatement:
    Pragma;
    Pragma NoScopeStatement

Pragma:
    pragma ( Identifier )
    pragma ( Identifier , ArgumentList )

```
 Pragmas pass special information to the implementation and can add vendor specific extensions. Pragmas can be used by themselves terminated with a *;*, and can apply to a statement, a block of statements, a declaration, or a block of declarations. 

 Pragmas can be either a [*PragmaDeclaration*](#PragmaDeclaration) or a [*PragmaStatement*](#PragmaStatement). 

 
```
pragma(ident);        // just by itself

pragma(ident) declaration; // influence one declaration

pragma(ident): // influence subsequent declarations
    declaration;
    declaration;

pragma(ident)   // influence block of declarations
{
    declaration;
    declaration;
}

pragma(ident) statement; // influence one statement

pragma(ident)   // influence block of statements
{
    statement;
    statement;
}

```
 The kind of pragma it is determined by the *Identifier*. [*ArgumentList*](expression#ArgumentList) is a comma-separated list of [*AssignExpression*](expression#AssignExpression)s. The [*AssignExpression*](expression#AssignExpression)s must be parsable as expressions, but their meaning is up to the individual pragma semantics. 

 Predefined Pragmas
------------------

 All implementations must support these, even if by just ignoring them:

 * [pragma crt\_constructor](#crtctor)
* [pragma crt\_destructor](#crtdtor)
* [pragma inline](#inline)
* [pragma lib](#lib)
* [pragma linkerDirective](#linkerDirective)
* [pragma mangle](#mangle)
* [pragma msg](#msg)
* [pragma printf](#printf)
* [pragma scanf](#scanf)
* [pragma startaddress](#startaddress)

 **Implementation Defined:** An implementation may ignore these pragmas. ### `pragma crt_constructor`

 Annotates a function so it is run after the C runtime library is initialized and before the D runtime library is initialized. 

 The function must:

 1. be `extern (C)`
2. not have any parameters
3. not be a non-static member function
4. be a function definition, not a declaration (i.e. it must have a function body)
5. not return a type that has a destructor
6. not be a nested function

 
```
__gshared int initCount;

pragma(crt_constructor)
extern(C) void initializer() { initCount += 1; }

```
 No arguments to the pragma are allowed.

 A function may be annotated with both `pragma(crt_constructor)` and `pragma(crt_destructor)`. 

 Annotating declarations other than function definitions has no effect.

 Annotating a struct or class definition does not affect the members of the aggregate.

 **Best Practices:** Use for system programming and interfacing with C/C++, for example to allow for initialization of the runtime when loading a DSO, or as a simple replacement for `shared static this` in [betterC mode](betterc). **Implementation Defined:** The order in which functions annotated with `pragma(crt_constructor)` are run is implementation defined. **Best Practices:** to control the order in which the functions are called within one module, write a single function that calls them in the desired order, and only annotate that function. **Implementation Defined:** This uses the mechanism C compilers use to run code before `main()` is called. C++ compilers use it to run static constructors and destructors. For example, GCC's [`__attribute__((constructor))`](https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) is equivalent. Digital Mars C uses *\_STI* and *\_STD* identifier prefixes to mark crt\_constructor and crt\_destructor functions. **Implementation Defined:** A reference to the annotated function will be inserted in the *.init\_array* section for Elf systems, the *XI* section for Win32 OMF systems, the *.CRT$XCU* section for Windows MSCOFF systems, and the *\_\_mod\_init\_func* section for OSX systems. **Note:** `crt_constructor` and `crt_destructor` were implemented in [v2.078.0 (2018-01-01)](https://dlang.org/changelog/2.078.0.html). Some compilers exposed non-standard, compiler-specific mechanism before. ### `pragma crt_destructor`

 `pragma(crt_destructor)` works the same as `pragma(crt_destructor)` except:

 Annotates a function so it is run after the D runtime library is terminated and before the C runtime library is terminated. Calling C's `exit()` function also causes the annotated functions to run. 

 The order in which the annotated functions are run is the reverse of those functions annotated with `pragma(crt_constructor)`.

 **Implementation Defined:** This uses the mechanism C compilers use to run code after `main()` returns or `exit()` is called. C++ compilers use it to run static destructors. For example, GCC's [`__attribute__((destructor))`](https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) is equivalent. Digital Mars C uses *\_STI* and *\_STD* identifier prefixes to mark crt\_constructor and crt\_destructor functions. **Implementation Defined:** A reference to the annotated function will be inserted in the *.fini\_array* section for Elf systems, the *XC* section for Win32 OMF systems, the *.CRT$XPU* section for Windows MSCOFF systems, and the *\_\_mod\_term\_func* section for OSX systems. 
```
__gshared int initCount;

pragma(crt_constructor)
extern(C) void initialize() { initCount += 1; }

pragma(crt_destructor)
extern(C) void deinitialize() { initCount -= 1; }

pragma(crt_constructor)
pragma(crt_destructor)
extern(C) void innuendo() { printf("Inside a constructor... Or destructor?\n"); }

```
 ### `pragma inline`

 Affects whether functions are inlined or not. If at the declaration level, it affects the functions declared in the block it controls. If inside a function, it affects the function it is enclosed by.

 It takes two forms:

 1. ```
pragma(inline)

```
 Sets the behavior to match the implementation's default behavior.
2. ```
pragma(inline, AssignExpression)

```
 The [*AssignExpression*](expression#AssignExpression) is evaluated and must have a type that can be converted to a boolean. If the result is false the functions are never inlined, otherwise they are always inlined.

 More than one *AssignExpression* is not allowed.

 If there are multiple pragma inlines in a function, the lexically last one takes effect.

 
```
pragma(inline):
int foo(int x) // foo() is never inlined
{
    pragma(inline, true);
    ++x;
    pragma(inline, false); // supercedes the others
    return x + 3;
}

```
 **Implementation Defined:** 1. The default inline behavior is typically selectable with a compiler switch such as [*-inline*.](https://dlang.org/dmd.html#switch-inline)
2. Whether a particular function can be inlined or not is implementation defined.
3. What happens for `pragma(inline, true)` if the function cannot be inlined. An error message is typical.

 ### `pragma lib`

 There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. 

 
```
pragma(lib, "foo.lib");

```
 **Implementation Defined:** The string literal specifies the file name of a library file. This name is inserted into the generated object file, or otherwise passed to the linker, so the linker automatically links in that library. ### `pragma linkerDirective`

 There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. 

 
```
pragma(linkerDirective, "/FAILIFMISMATCH:_ITERATOR_DEBUG_LEVEL=2");

```
 **Implementation Defined:** The string literal specifies a linker directive to be embedded in the generated object file. Linker directives are only supported for MS-COFF output. ### `pragma mangle`

 Overrides the default mangling for a symbol.

 There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a string literal. 

 It only applies to function and variable symbols. Other symbols are ignored.

 **Implementation Defined:** On macOS and Win32, an extra underscore (`_`) is prepended to the string since 2.079, as is done by the C/C++ toolchain. This allows using the same `pragma(mangle)` for all compatible (POSIX in one case, win64 in another) platforms instead of having to special-case. **Rationale:** * Enables linking to symbol names that D cannot represent.
* Enables linking to a symbol which is a D keyword, since an [*Identifier*](lex#Identifier) cannot be a keyword.

 
```
pragma(mangle, "body")
extern(C) void body_func();

```
 ### `pragma msg`

 Each [*AssignExpression*](expression#AssignExpression) is evaluated at compile time and then all are combined into a message.

 
```
pragma(msg, "compiling...", 6, 1.0); // prints "compiling...61.0" at compile time

```
 **Implementation Defined:** The form the message takes and how it is presented to the user. One way is by printing them to the standard error stream. **Rationale:** Analogously to how `writeln()` performs a role of writing informational messages during runtime, `pragma(msg)` performs the equivalent role at compile time. For example, 
```
static if (kilroy)
    pragma(msg, "Kilroy was here");
else
    pragma(msg, "Kilroy got lost");

```
 ### `pragma printf`

 `pragma(printf)` specifies that a function declaration is a printf-like function, meaning it is an `extern (C)` or `extern (C++)` function with a `format` parameter accepting a pointer to a 0-terminated `char` string conforming to the C99 Standard 7.19.6.1, immediately followed by either a `...` variadic argument list or a parameter of type `va_list` as the last parameter. 

 If the `format` argument is a string literal, it is verified to be a valid format string per the C99 Standard. If the `format` parameter is followed by `...`, the number and types of the variadic arguments are checked against the format string.

 Diagnosed incompatibilities are:

 * incompatible sizes which may cause argument misalignment
* deferencing arguments that are not pointers
* insufficient number of arguments
* struct arguments
* array and slice arguments
* non-pointer arguments to `s` specifier
* non-standard formats
* undefined behavior per C99

 Per the C99 Standard, extra arguments are ignored.

 Ignored mismatches are:

 * sign mismatches, such as printing an `int` with a `%u` format
* integral promotion mismatches, where the format specifies a smaller integral type than `int` or `uint`, such as printing a `short` with the `%d` format rather than `%hd`

 
```
printf("%k\n", value); // error: non-Standard format k
printf("%d\n");        // error: not enough arguments
printf("%d\n", 1, 2);  // ok, extra arguments ignored

```
 **Best Practices:** In order to use non-Standard printf/scanf formats, an easy workaround is: 
```
const format = "%k\n";
printf(format.ptr, value);  // no error

```
 **Best Practices:** Most of the errors detected are portability issues. For instance, 
```
string s;
printf("%.*s\n", s.length, s.ptr);
printf("%d\n", s.sizeof);
ulong u;
scanf("%lld%*c\n", &u);

```
 should be replaced with: 
```
string s;
printf("%.*s\n", cast(int) s.length, s.ptr);
printf("%zd\n", s.sizeof);
ulong u;
scanf("%llu%*c\n", &u);

```
 `pragma(printf)` applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type. 

 ### `pragma scanf`

 `pragma(scanf)` specifies that a function declaration is a scanf-like function, meaning it is an `extern (C)` or `extern (C++)` function with a `format` parameter accepting a pointer to a 0-terminated `char` string conforming to the C99 Standard 7.19.6.2, immediately followed by either a `...` variadic argument list or a parameter of type `va_list` as the last parameter. 

 If the `format` argument is a string literal, it is verified to be a valid format string per the C99 Standard. If the `format` parameter is followed by `...`, the number and types of the variadic arguments are checked against the format string.

 Diagnosed incompatibilities are:

 * argument is not a pointer to the format specified type
* insufficient number of arguments
* non-standard formats
* undefined behavior per C99

 Per the C99 Standard, extra arguments are ignored.

 `pragma(scanf)` applied to declarations that are not functions are ignored. In particular, it has no effect on the declaration of a pointer to function type. 

 ### `pragma startaddress`

 There must be one [*AssignExpression*](expression#AssignExpression) and it must evaluate at compile time to a function symbol.

 **Implementation Defined:** The function symbol specifies the start address for the program. The symbol is inserted into the object file or is otherwise presented to the linker to set the start address. This is not normally used for application level programming, but is for specialized systems work. For applications code, the start address is taken care of by the runtime library. 
```
void foo() { ... }
pragma(startaddress, foo);

```
 Vendor Specific Pragmas
-----------------------

 Vendor specific pragma *Identifier*s can be defined if they are prefixed by the vendor's trademarked name, in a similar manner to version identifiers: 

 
```
pragma(DigitalMars_extension) { ... }

```
 Implementations must diagnose an error for unrecognized *Pragma*s, even if they are vendor specific ones. 

 **Implementation Defined:** Vendor specific pragmas. **Best Practices:** vendor specific pragmas should be wrapped in version statements 
```
version (DigitalMars)
{
    pragma(DigitalMars_extension)
    {   ... }
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/pragma.html>

Modules
=======

 **Contents** 1. [Module Declaration](#module_declaration)
2. [Import Declaration](#import-declaration)
3. [Symbol Name Lookup](#name_lookup)
4. [Public Imports](#public_imports)
5. [Static Imports](#static_imports)
6. [Renamed Imports](#renamed_imports)
7. [Selective Imports](#selective_imports)
8. [Renamed and Selective Imports](#renamed_selective_imports)
9. [Scoped Imports](#scoped_imports)
10. [Module Scope Operator](#module_scope_operators)
11. [Static Construction and Destruction](#staticorder)
12. [Order of Static Construction](#order_of_static_ctor)
13. [Order of Static Construction within a Module](#order_of_static_ctors)
14. [Order of Static Destruction](#order_static_dtor)
15. [Order of Unit tests](#order_of_unittests)
16. [Mixin Declaration](#mixin-declaration)
17. [Package Module](#package-module)

 
```
Module:
    ModuleDeclaration DeclDefs
    DeclDefs

DeclDefs:
    DeclDef
    DeclDef DeclDefs

DeclDef:
    AttributeSpecifier
    Declaration
    Constructor
    Destructor
    Postblit
    Allocator
    Deallocator
    ClassInvariant
    StructInvariant
    UnitTest
    AliasThis
    StaticConstructor
    StaticDestructor
    SharedStaticConstructor
    SharedStaticDestructor
    ConditionalDeclaration
    DebugSpecification
    VersionSpecification
    StaticAssert
    TemplateDeclaration
    TemplateMixinDeclaration
    TemplateMixin
    MixinDeclaration
    ;

```
 Modules have a one-to-one correspondence with source files. The module name is, by default, the file name with the path and extension stripped off, and can be set explicitly with the module declaration.

 Modules automatically provide a namespace scope for their contents. Modules superficially resemble classes, but differ in that:

 * There's only one instance of each module, and it is statically allocated.
* There is no virtual table.
* Modules do not inherit, they have no super modules, etc.
* A file may contain only one module.
* Module symbols can be imported.
* Modules are always compiled at global scope, and are unaffected by surrounding attributes or other modifiers.

 Modules can be grouped together in hierarchies called *packages*.

 Modules offer several guarantees:

 * The order in which modules are imported does not affect the semantics.
* The semantics of a module are not affected by what imports it.
* If a module C imports modules A and B, any modifications to B will not silently change code in C that is dependent on A.

 Module Declaration
------------------

 The *ModuleDeclaration* sets the name of the module and what package it belongs to. If absent, the module name is taken to be the same name (stripped of path and extension) of the source file name.

 
```
ModuleDeclaration:
    ModuleAttributesopt module ModuleFullyQualifiedName ;

ModuleAttributes:
    ModuleAttribute
    ModuleAttribute ModuleAttributes

ModuleAttribute:
    DeprecatedAttribute
    UserDefinedAttribute

ModuleFullyQualifiedName:
    ModuleName
    Packages . ModuleName

ModuleName:
    Identifier

Packages:
    PackageName
    Packages . PackageName

PackageName:
    Identifier

```
 The *Identifier*s preceding the rightmost *Identifier* are the *Packages* that the module is in. The packages correspond to directory names in the source file path. Package and module names cannot be [*Keyword*](lex#Keyword)s.

 If present, the *ModuleDeclaration* must be the first and only such declaration in the source file, and may be preceded only by comments and `#line` directives.

 Example:

 
```
module c.stdio; // module stdio in the c package

```
 By convention, package and module names are all lower case. This is because these names have a one-to-one correspondence with the operating system's directory and file names, and many file systems are not case sensitive. Using all lower case package and module names will avoid or minimize problems when moving projects between dissimilar file systems.

 If the file name of a module is an invalid module name (e.g. `foo-bar.d`), use a module declaration to set a valid module name:

 
```
module foo_bar;

```
 A *ModuleDeclaration* can have an optional [*DeprecatedAttribute*](attribute#DeprecatedAttribute). The compiler will produce a message when the deprecated module is imported.

 
```
deprecated module foo;

```
 
```
module bar;
import foo;  // Deprecated: module foo is deprecated

```
 A *DeprecatedAttribute* can have an optional [*AssignExpression*](expression#AssignExpression) argument to provide a more informative message. An *AssignExpression* must evaluate to a string at compile time. 

 
```
deprecated("Please use foo2 instead.")
module foo;

```
 
```
module bar;
import foo;  // Deprecated: module foo is deprecated - Please use foo2 instead.

```
 **Implementation Defined:** 1. The mapping of package and module identifiers to directory and file names.
2. How the deprecation messages are presented to the user.

 **Best Practices:** 1. [*PackageName*](#PackageName)s and [*ModuleName*](#ModuleName)s should be composed of the ASCII characters lower case letters, digits or `_` to ensure maximum portability and compatibility with various file systems.
2. The file names for packages and modules should be composed only of the ASCII lower case letters, digits, and `_`s, and should not be a [*Keyword*](lex#Keyword).

 Import Declaration
------------------

 Symbols from one module are made available in another module by using the *ImportDeclaration*:

 
```
ImportDeclaration:
    import ImportList ;
    static import ImportList ;

ImportList:
    Import
    ImportBindings
    Import , ImportList

Import:
    ModuleFullyQualifiedName
    ModuleAliasIdentifier = ModuleFullyQualifiedName

ImportBindings:
    Import : ImportBindList

ImportBindList:
    ImportBind
    ImportBind , ImportBindList

ImportBind:
    Identifier
    Identifier = Identifier

ModuleAliasIdentifier:
    Identifier

```
 There are several forms of the *ImportDeclaration*, from generalized to fine-grained importing.

 The order in which *ImportDeclaration*s occur has no significance.

 *ModuleFullyQualifiedName*s in the *ImportDeclaration* must be fully qualified with whatever packages they are in. They are not considered to be relative to the module that imports them.

 Symbol Name Lookup
------------------

 The simplest form of importing is to just list the modules being imported:

 
```
module myapp.main;

import std.stdio; // import module stdio from package std

class Foo : BaseClass
{
    import myapp.foo;  // import module myapp.foo in this class' scope
    void bar ()
    {
        import myapp.bar;  // import module myapp.bar in this function' scope
        writeln("hello!");  // calls std.stdio.writeln
    }
}

```
 When a symbol name is used unqualified, a two-phase lookup is used. First, the module scope is searched, starting from the innermost scope. For example, in the previous example, while looking for `writeln`, the order will be:

 * Declarations inside `bar`.
* Declarations inside `Foo`.
* Declarations inside `BaseClass`.
* Declarations at module scope.

 If the first lookup isn't successful, a second one is performed on imports. In the second lookup phase inherited scopes are ignored. This includes the scope of base classes and interfaces (in this example, `BaseClass`'s imports would be ignored), as well as imports in mixed-in `template`.

 Symbol lookup stops as soon as a matching symbol is found. If two symbols with the same name are found at the same lookup phase, this ambiguity will result in a compilation error.

 
```
module A;
void foo();
void bar();

```
 
```
module B;
void foo();
void bar();

```
 
```
module C;
import A;
void foo();
void test()
{
    foo(); // C.foo() is called, it is found before imports are searched
    bar(); // A.bar() is called, since imports are searched
}

```
 
```
module D;
import A;
import B;
void test()
{
    foo();   // error, A.foo() or B.foo() ?
    A.foo(); // ok, call A.foo()
    B.foo(); // ok, call B.foo()
}

```
 
```
module E;
import A;
import B;
alias foo = B.foo;
void test()
{
    foo();   // call B.foo()
    A.foo(); // call A.foo()
    B.foo(); // call B.foo()
}

```
 Public Imports
--------------

 By default, imports are *private*. This means that if module A imports module B, and module B imports module C, then names inside C are visible only inside B and not inside A.

 An import can be explicitly declared *public*, which will cause names from the imported module to be visible to further imports. So in the above example where module A imports module B, if module B *publicly* imports module C, names from C will be visible in A as well.

 All symbols from a publicly imported module are also aliased in the importing module. Thus in the above example if C contains the name foo, it will be accessible in A as `foo`, `B.foo` and `C.foo`.

 For another example:

 
```
module W;
void foo() { }

```
 
```
module X;
void bar() { }

```
 
```
module Y;
import W;
public import X;
...
foo();  // calls W.foo()
bar();  // calls X.bar()

```
 
```
module Z;
import Y;
...
foo();   // error, foo() is undefined
bar();   // ok, calls X.bar()
X.bar(); // ditto
Y.bar(); // ok, Y.bar() is an alias to X.bar()

```
 Static Imports
--------------

 A static import requires the use of a fully qualified name to reference the module's names:

 
```
static import std.stdio;

void main()
{
    writeln("hello!");           // error, writeln is undefined
    std.stdio.writeln("hello!"); // ok, writeln is fully qualified
}

```
 Renamed Imports
---------------

 A local name for an import can be given, through which all references to the module's symbols must be qualified with:

 
```
import io = std.stdio;

void main()
{
    io.writeln("hello!");        // ok, calls std.stdio.writeln
    std.stdio.writeln("hello!"); // error, std is undefined
    writeln("hello!");           // error, writeln is undefined
}

```
 **Best Practices:** Renamed imports are handy when dealing with very long import names. Selective Imports
-----------------

 Specific symbols can be exclusively imported from a module and bound into the current namespace:

 
```
import std.stdio : writeln, foo = write;

void main()
{
    std.stdio.writeln("hello!"); // error, std is undefined
    writeln("hello!");           // ok, writeln bound into current namespace
    write("world");              // error, write is undefined
    foo("world");                // ok, calls std.stdio.write()
    fwritefln(stdout, "abc");    // error, fwritefln undefined
}

```
 `static` cannot be used with selective imports.

 Renamed and Selective Imports
-----------------------------

 When renaming and selective importing are combined:

 
```
import io = std.stdio : foo = writeln;

void main()
{
    writeln("bar");           // error, writeln is undefined
    std.stdio.foo("bar");     // error, foo is bound into current namespace
    std.stdio.writeln("bar"); // error, std is undefined
    foo("bar");               // ok, foo is bound into current namespace,
                              // FQN not required
    io.writeln("bar");        // ok, io=std.stdio bound the name io in
                              // the current namespace to refer to the entire
                              //   module
    io.foo("bar");            // error, foo is bound into current namespace,
                              // foo is not a member of io
}

```
 Scoped Imports
--------------

 Import declarations may be used at any scope. For example:

 
```
void main()
{
    import std.stdio;
    writeln("bar");
}

```
 The imports are looked up to satisfy any unresolved symbols at that scope. Imported symbols may hide symbols from outer scopes.

 In function scopes, imported symbols only become visible after the import declaration lexically appears in the function body. In other words, imported symbols at function scope cannot be forward referenced.

 
```
void main()
{
    void writeln(string) {}
    void foo()
    {
        writeln("bar"); // calls main.writeln
        import std.stdio;
        writeln("bar"); // calls std.stdio.writeln
        void writeln(string) {}
        writeln("bar"); // calls main.foo.writeln
    }
    writeln("bar"); // calls main.writeln
    std.stdio.writeln("bar");  // error, std is undefined
}

```
 Module Scope Operator
---------------------

 A leading `.` causes the identifier to be looked up in the module scope.

 
```
int x;

int foo(int x)
{
    if (y)
        return x;  // returns foo.x, not global x
    else
        return .x; // returns global x
}

```
 Static Construction and Destruction
-----------------------------------

 Static constructors are executed to initialize a module's state. Static destructors terminate a module's state. 

 A module may have multiple static constructors and static destructors. The static constructors are run in lexical order, the static destructors are run in reverse lexical order.

 Non-shared static constructors and destructors are run whenever threads are created or destroyed, including the main thread.

 Shared static constructors are run once before `main()` is called. Shared static destructors are run after the `main()` function returns. 

 
```
import resource;

Resource x;
shared Resource y;
__gshared Resource z;

static this()  // non-shared static constructor
{
    x = acquireResource();
}

shared static this()  // shared static constructor
{
    y = acquireSharedResource();
    z = acquireSharedResource();
}

static ~this()  // non-shared static destructor
{
    releaseResource(x);
}

shared static ~this()   // shared static destructor
{
    releaseSharedResource(y);
    releaseSharedResource(z);
}

```
 **Best Practices:** 1. Shared static constructors and destructors are used to initialize and terminate shared global data.
2. Non-shared static constructors and destructors are used to initialize and terminate thread local data.

 Order of Static Construction
----------------------------

 Shared static constructors on all modules are run before any non-shared static constructors.

 The order of static initialization is implicitly determined by the *import* declarations in each module. Each module is assumed to depend on any imported modules being statically constructed first. There is no other order imposed on the execution of module static constructors.

 Cycles (circular dependencies) in the import declarations are allowed so long as neither, or one, but not both, of the modules, contains static constructors or static destructors. Violation of this rule will result in a runtime exception.

 **Implementation Defined:** 1. An implementation may provide a means of overriding the cycle detection abort. A typical method uses the D Runtime switch `--DRT-oncycle=...` where the following behaviors are supported:
	1. `abort` The default behavior. The normal behavior as described in the previous section.
	2. `deprecate` This works just like `abort`, but upon cycle detection the runtime will use a flawed pre-2.072 algorithm to determine if the cycle was previously detected. If no cycles are detected in the old algorithm, execution continues, but a deprecation message is printed.
	3. `print` Print all cycles detected, but do not abort execution. When cycles are present, the order of static construction is implementation defined, and not guaranteed to be valid.
	4. `ignore` Do not abort execution or print any cycles. When cycles are present, the order of static construction is implementation defined, and not guaranteed to be valid.

 **Best Practices:** 1. Avoid cyclical imports where practical. They can be an indication of poor decomposition of a program's structure into independent modules. Two modules that import each other can often be reorganized into three modules without cycles, where the third contains the declarations needed by the other two.

 Order of Static Construction within a Module
--------------------------------------------

 Within a module, static construction occurs in the lexical order in which they appear.

 Order of Static Destruction
---------------------------

 This is defined to be in exactly the reverse order of static construction. Static destructors for individual modules will only be run if the corresponding static constructor successfully completed.

 Shared static destructors are executed after static destructors.

 Order of Unit tests
-------------------

 Unit tests are run in the lexical order in which they appear within a module.

 Mixin Declaration
-----------------

 
```
MixinDeclaration:
    mixin ( ArgumentList ) ;

```
 Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*DeclDefs*](#DeclDefs), and is compiled as such. 

 Package Module
--------------

 A package module can be used to publicly import other modules, while providing a simpler import syntax. This enables the conversion of a module into a package of modules, without breaking existing code which uses that module. Example of a set of library modules:

 **libweb/client.d:** 
```
module libweb.client;

void runClient() { }

```
 **libweb/server.d:** 
```
module libweb.server;

void runServer() { }

```
 **libweb/package.d:** 
```
module libweb;

public import libweb.client;
public import libweb.server;

```
 The package module's file name must be `package.d`. The module name is declared to be the fully qualified name of the package. Package modules can be imported just like any other modules:

 **test.d:** 
```
module test;

// import the package module
import libweb;

void main()
{
    runClient();
    runServer();
}

```
 A package module can be nested inside of a sub-package:

 **libweb/utils/package.d:** 
```
// must be declared as the fully qualified name of the package, not just 'utils'
module libweb.utils;

// publicly import modules from within the 'libweb.utils' package.
public import libweb.utils.conv;
public import libweb.utils.text;

```
 The package module can then be imported with the standard module import declaration:

 **test.d:** 
```
module test;

// import the package module
import libweb.utils;

void main() { }

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/module.html>

Declarations
============

 **Contents** 1. [Declaration Syntax](#declaration_syntax)
	1. [Pointers to Functions](#pointers-to-functions)
	2. [C-Style Declarations](#c-style-declarations)
	3. [Declaring Multiple Symbols](#declaring-multiple-symbols)
2. [Implicit Type Inference](#auto-declaration)
3. [Alias Declarations](#alias)
4. [Extern Declarations](#extern)
5. [Void Initializations](#void_init)
6. [Global and Static Initializers](#global_static_init)
7. [Type Qualifiers vs. Storage Classes](#typequal_vs_storageclass)

 
```
Declaration:
    FuncDeclaration
    VarDeclarations
    AliasDeclaration
    AggregateDeclaration
    EnumDeclaration
    ImportDeclaration
    ConditionalDeclaration
    StaticForeachDeclaration
    StaticAssert

```
 
```
VarDeclarations:
    StorageClassesopt BasicType Declarators ;
    AutoDeclaration

Declarators:
    DeclaratorInitializer
    DeclaratorInitializer , DeclaratorIdentifierList

DeclaratorInitializer:
    VarDeclarator
    VarDeclarator TemplateParametersopt = Initializer
    AltDeclarator
    AltDeclarator = Initializer

DeclaratorIdentifierList:
    DeclaratorIdentifier
    DeclaratorIdentifier , DeclaratorIdentifierList

DeclaratorIdentifier:
    VarDeclaratorIdentifier
    AltDeclaratorIdentifier

VarDeclaratorIdentifier:
    Identifier
    Identifier TemplateParametersopt = Initializer

AltDeclaratorIdentifier:
    TypeSuffixes Identifier AltDeclaratorSuffixesopt
    TypeSuffixes Identifier AltDeclaratorSuffixesopt = Initializer
    TypeSuffixesopt Identifier AltDeclaratorSuffixes
    TypeSuffixesopt Identifier AltDeclaratorSuffixes = Initializer

Declarator:
    VarDeclarator
    AltDeclarator

VarDeclarator:
    TypeSuffixesopt Identifier

AltDeclarator:
    TypeSuffixesopt Identifier AltDeclaratorSuffixes
    TypeSuffixesopt ( AltDeclaratorInner )
    TypeSuffixesopt ( AltDeclaratorInner ) AltFuncDeclaratorSuffix
    TypeSuffixesopt ( AltDeclaratorInner ) AltDeclaratorSuffixes

AltDeclaratorInner:
    TypeSuffixesopt Identifier
    TypeSuffixesopt Identifier AltFuncDeclaratorSuffix
    AltDeclarator

AltDeclaratorSuffixes:
    AltDeclaratorSuffix
    AltDeclaratorSuffix AltDeclaratorSuffixes

AltDeclaratorSuffix:
    [ ]
    [ AssignExpression ]
    [ Type ]

AltFuncDeclaratorSuffix:
    Parameters MemberFunctionAttributesopt

```
 
```
StorageClasses:
    StorageClass
    StorageClass StorageClasses

StorageClass:
    LinkageAttribute
    AlignAttribute
    deprecated
    enum
    static
    extern
    abstract
    final
    override
    synchronized
    auto
    scope
    const
    immutable
    inout
    shared
    __gshared
    Property
    nothrow
    pure
    ref

```
 
```
Initializer:
    VoidInitializer
    NonVoidInitializer

NonVoidInitializer:
    ExpInitializer
    ArrayInitializer
    StructInitializer

ExpInitializer:
    AssignExpression

ArrayInitializer:
    [ ArrayMemberInitializationsopt ]

ArrayMemberInitializations:
    ArrayMemberInitialization
    ArrayMemberInitialization ,
    ArrayMemberInitialization , ArrayMemberInitializations

ArrayMemberInitialization:
    NonVoidInitializer
    AssignExpression : NonVoidInitializer

StructInitializer:
    { StructMemberInitializersopt }

StructMemberInitializers:
    StructMemberInitializer
    StructMemberInitializer ,
    StructMemberInitializer , StructMemberInitializers

StructMemberInitializer:
    NonVoidInitializer
    Identifier : NonVoidInitializer

```
 Declaration Syntax
------------------

 Declaration syntax generally reads right to left, including arrays:

 
```
int x;    // x is an int
int* x;   // x is a pointer to int
int** x;  // x is a pointer to a pointer to int

int[] x;  // x is an array of ints
int*[] x; // x is an array of pointers to ints
int[]* x; // x is a pointer to an array of ints

int[3] x;     // x is a static array of 3 ints
int[3][5] x;  // x is a static array of 5 static arrays of 3 ints
int[3]*[5] x; // x is a static array of 5 pointers to static arrays of 3 ints

```
 ### Pointers to Functions

 Pointers to functions are declared using the `function` keyword: 

 
```
int function(char) x; // x is a pointer to
                     // a function taking a char argument
                     // and returning an int
int function(char)[] x; // x is an array of
                     // pointers to functions
                     // taking a char argument
                     // and returning an int

```
 ### C-Style Declarations

 C-style array, function pointer and pointer to array declarations are deprecated: 

 
```
int x[3];          // x is a static array of 3 ints
int x[3][5];       // x is a static array of 3 arrays of 5 ints

int (*x[5])[3];    // x is a static array of 5 pointers to static arrays of 3 ints
int (*x)(char);    // x is a pointer to a function taking a char argument
                   // and returning an int
int (*[] x)(char); // x is an array of pointers to functions
                   // taking a char argument and returning an int

```
 ### Declaring Multiple Symbols

 In a declaration declaring multiple symbols, all the declarations must be of the same type: 

 
```
int x,y;   // x and y are ints
int* x,y;  // x and y are pointers to ints
int[] x,y; // x and y are arrays of ints

// invalid C-style declarations
int x,*y;  // error, multiple types
int x[],y; // error, multiple types

```
 Implicit Type Inference
-----------------------

 
```
AutoDeclaration:
    StorageClasses AutoAssignments ;

AutoAssignments:
    AutoAssignment
    AutoAssignments , AutoAssignment

AutoAssignment:
    Identifier TemplateParametersopt = Initializer

```
 If a declaration starts with a *StorageClass* and has a *NonVoidInitializer* from which the type can be inferred, the type on the declaration can be omitted. 

 
```
static x = 3;      // x is type int
auto y = 4u;       // y is type uint

auto s = "Apollo"; // s is type immutable(char)[] i.e., string

class C { ... }

auto c = new C();  // c is a handle to an instance of class C

```
 The *NonVoidInitializer* cannot contain forward references (this restriction may be removed in the future). The implicitly inferred type is statically bound to the declaration at compile time, not run time. 

 An [*ArrayLiteral*](expression#ArrayLiteral) is inferred to be a dynamic array type rather than a static array:

 
```
auto v = ["resistance", "is", "useless"]; // type is string[], not string[3]

```
 Alias Declarations
------------------

 
```
AliasDeclaration:
    alias StorageClassesopt BasicType Declarators ;
    alias StorageClassesopt BasicType FuncDeclarator ;
    alias AliasAssignments ;

AliasAssignments:
    AliasAssignment
    AliasAssignments , AliasAssignment

AliasAssignment:
    Identifier TemplateParametersopt = StorageClassesopt Type
    Identifier TemplateParametersopt = FunctionLiteral
    Identifier TemplateParametersopt = StorageClassesopt BasicType Parameters MemberFunctionAttributesopt

```
 *AliasDeclaration*s create a symbol that is an alias for another type, and can be used anywhere that other type may appear. 

 
```
alias myint = abc.Foo.bar;

```
  Aliased types are semantically identical to the types they are aliased to. The debugger cannot distinguish between them, and there is no difference as far as function overloading is concerned. For example: 

 
```
alias myint = int;

void foo(int x) { ... }
void foo(myint m) { ... } // error, multiply defined function foo

```
 A symbol can be declared as an *alias* of another symbol. For example: 

 
```
import planets;

alias myAlbedo = planets.albedo;
...
int len = myAlbedo("Saturn"); // actually calls planets.albedo()

```
  The following alias declarations are valid: 

 
```
template Foo2(T) { alias t = T; }
alias t1 = Foo2!(int);
alias t2 = Foo2!(int).t;
alias t3 = t1.t;
alias t4 = t2;

t1.t v1;  // v1 is type int
t2 v2;    // v2 is type int
t3 v3;    // v3 is type int
t4 v4;    // v4 is type int

alias Fun = int(string p);
int fun(string){return 0;}
static assert(is(typeof(fun) == Fun));

alias MemberFun1 = int() const;
alias MemberFun2 = const int();
// leading attributes apply to the func, not the return type
static assert(is(MemberFun1 == MemberFun2));

```
  Aliased symbols are useful as a shorthand for a long qualified symbol name, or as a way to redirect references from one symbol to another: 

 
```
version (Win32)
{
    alias myfoo = win32.foo;
}
version (linux)
{
    alias myfoo = linux.bar;
}

```
  Aliasing can be used to `import` a symbol from an import into the current scope: 

 
```
alias strlen = string.strlen;

```
  Aliases can also `import` a set of overloaded functions, that can be overloaded with functions in the current scope: 

 
```
class A
{
    int foo(int a) { return 1; }
}

class B : A
{
    int foo( int a, uint b ) { return 2; }
}

class C : B
{
    int foo( int a ) { return 3; }
    alias foo = B.foo;
}

class D : C
{
}

void test()
{
    D b = new D();
    int i;

    i = b.foo(1, 2u);   // calls B.foo
    i = b.foo(1);       // calls C.foo
}

```
  **Note:** Type aliases can sometimes look indistinguishable from alias declarations: 

 
```
alias abc = foo.bar; // is it a type or a symbol?

```
  The distinction is made in the semantic analysis pass. 

 Aliases cannot be used for expressions:

 
```
struct S
{
    static int i;
    static int j;
}

alias a = S.i; // OK, `S.i` is a symbol
alias b = S.j; // OK. `S.j` is also a symbol
alias c = a + b; // illegal, `a + b` is an expression
a = 2;         // sets `S.i` to `2`
b = 4;         // sets `S.j` to `4`

```
 Extern Declarations
-------------------

 Variable declarations with the storage class `extern` are not allocated storage within the module. They must be defined in some other object file with a matching name which is then linked in.

 An `extern` declaration can optionally be followed by an `extern` [linkage attribute](attribute#linkage). If there is no linkage attribute it defaults to `extern(D)`:

 
```
// variable allocated and initialized in this module with C linkage
extern(C) int foo;
// variable allocated outside this module with C linkage
// (e.g. in a statically linked C library or another module)
extern extern(C) int bar;

```
 **Best Practices:** 1. The primary usefulness of *Extern Declarations* is to connect with global variables declarations and functions in C or C++ files.

 Void Initializations
--------------------

 
```
VoidInitializer:
    void

```
 Normally, variables are initialized either with an explicit [*Initializer*](#Initializer) or are set to the default value for the type of the variable. If the *Initializer* is `void`, however, the variable is not initialized. If its value is used before it is set, undefined program behavior will result. 

 **Undefined Behavior:** If a void initialized variable's value is used before it is set, the behavior is undefined. 
```
void foo()
{
    int x = void;
    writeln(x);  // will print garbage
}

```
 **Best Practices:** 1. Void initializers are useful when a static array is on the stack, but may only be partially used, such as as a temporary buffer. Void initializers will potentially speed up the code, but they introduce risk, since one must ensure that array elements are always set before read.
2. The same is true for structs.
3. Use of void initializers is rarely useful for individual local variables, as a modern optimizer will remove the dead store of its initialization if it is initialized later.
4. For hot code paths, it is worth profiling to see if the void initializer actually improves results.

 Global and Static Initializers
------------------------------

 The [*Initializer*](#Initializer) for a global or static variable must be evaluatable at compile time. Runtime initialization is done with static constructors. 

 **Implementation Defined:** 1. Whether some pointers can be initialized with the addresses of other functions or data.

 Type Qualifiers vs. Storage Classes
-----------------------------------

 Type qualifer and storage classes are distinct.

 A *type qualifier* creates a derived type from an existing base type, and the resulting type may be used to create multiple instances of that type.

 For example, the `immutable` type qualifier can be used to create variables of immutable type, such as:

 
```
immutable(int)   x; // typeof(x) == immutable(int)
immutable(int)[] y; // typeof(y) == immutable(int)[]
                    // typeof(y[0]) == immutable(int)

// Type constructors create new types that can be aliased:
alias ImmutableInt = immutable(int);
ImmutableInt z;     // typeof(z) == immutable(int)

```
 A *storage class*, on the other hand, does not create a new type, but describes only the kind of storage used by the variable or function being declared. For example, a member function can be declared with the `const` storage class to indicate that it does not modify its implicit `this` argument:

 
```
struct S
{
    int x;
    int method() const
    {
        //x++;    // Error: this method is const and cannot modify this.x
        return x; // OK: we can still read this.x
    }
}

```
 Although some keywords can be used both as a type qualifier and a storage class, there are some storage classes that cannot be used to construct new types, such as `ref`:

 
```
// ref declares the parameter x to be passed by reference
void func(ref int x)
{
    x++; // so modifications to x will be visible in the caller
}

void main()
{
    auto x = 1;
    func(x);
    assert(x == 2);

    // However, ref is not a type qualifier, so the following is illegal:
    ref(int) y; // Error: ref is not a type qualifier.
}

```
 Functions can also be declared as `ref`, meaning their return value is passed by reference:

 
```
ref int func2()
{
    static int y = 0;
    return y;
}

void main()
{
    func2() = 2; // The return value of func2() can be modified.
    assert(func2() == 2);

    // However, the reference returned by func2() does not propagate to
    // variables, because the 'ref' only applies to the return value itself,
    // not to any subsequent variable created from it:
    auto x = func2();
    static assert(is(typeof(x) == int)); // N.B.: *not* ref(int);
                                     // there is no such type as ref(int).
    x++;
    assert(x == 3);
    assert(func2() == 2); // x is not a reference to what func2() returned; it
                          // does not inherit the ref storage class from func2().
}

```
 Some keywords, such as `const`, can be used both as a type qualifier and a storage class. The distinction is determined by the syntax where it appears.

 
```
struct S
{
    /* Is const here a type qualifier or a storage class?
     * Is the return value const(int), or is this a const function that returns
     * (mutable) int?
     */
    const int* func() // a const function
    {
        ++p;          // error, this.p is const
        return p;     // error, cannot convert const(int)* to int*
    }

    const(int)* func() // a function returning a pointer to a const int
    {
        ++p;          // ok, this.p is mutable
        return p;     // ok, int* can be implicitly converted to const(int)*
    }

    int* p;
}

```
 **Best Practices:** To avoid confusion, the type qualifier syntax with parentheses should be used for return types, and function storage classes should be written on the right-hand side of the declaration instead of the left-hand side where it may be visually confused with the return type: 
```
struct S
{
    // Now it is clear that the 'const' here applies to the return type:
    const(int) func1() { return 1; }

    // And it is clear that the 'const' here applies to the function:
    int func2() const { return 1; }
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/declaration.html>

Types
=====

 **Contents** 1. [Basic Data Types](#basic-data-types)
2. [Derived Data Types](#derived-data-types)
3. [User-Defined Types](#user-defined-types)
4. [Type Conversions](#type-conversions)
	1. [Pointer Conversions](#pointer-conversions)
	2. [Implicit Conversions](#implicit-conversions)
	3. [Integer Promotions](#integer-promotions)
	4. [Usual Arithmetic Conversions](#usual-arithmetic-conversions)
5. [`bool`](#bool)
6. [Delegates](#delegates)
7. [`typeof`](#typeof)
8. [Mixin Types](#mixin_types)
9. [Aliased Types](#aliased-types)
	1. [`size_t`](#size_t)
	2. [`ptrdiff_t`](#ptrdiff_t)
	3. [`string`](#string)

 D is statically typed. Every expression has a type. Types constrain the values an expression can hold, and determine the semantics of operations on those values. 

 
```
Type:
    TypeCtorsopt BasicType TypeSuffixesopt

TypeCtors:
    TypeCtor
    TypeCtor TypeCtors

TypeCtor:
    const
    immutable
    inout
    shared

BasicType:
    FundamentalType
    . QualifiedIdentifier
    QualifiedIdentifier
    Typeof
    Typeof . QualifiedIdentifier
    TypeCtor ( Type )
    Vector
    Traits
    MixinType

Vector:
    __vector ( VectorBaseType )

VectorBaseType:
    Type

FundamentalType:
    bool
    byte
    ubyte
    short
    ushort
    int
    uint
    long
    ulong
    cent
    ucent
    char
    wchar
    dchar
    float
    double
    real
    ifloat
    idouble
    ireal
    cfloat
    cdouble
    creal
    void

TypeSuffixes:
    TypeSuffix TypeSuffixesopt

TypeSuffix:
    *
    [ ]
    [ AssignExpression ]
    [ AssignExpression .. AssignExpression ]
    [ Type ]
    delegate Parameters MemberFunctionAttributesopt
    function Parameters FunctionAttributesopt

QualifiedIdentifier:
    Identifier
    Identifier . QualifiedIdentifier
    TemplateInstance
    TemplateInstance . QualifiedIdentifier
    Identifier [ AssignExpression ]
    Identifier [ AssignExpression ]. QualifiedIdentifier

```
 [Basic Data Types](#basic_data_types) are leaf types. [Derived Data Types](#derived-data_types) build on leaf types. [User-Defined Types](#user-defined-types) are aggregates of basic and derived types. 

 Basic Data Types
----------------

 

Basic Data Types| **Keyword** | **Default Initializer (`.init`)** | **Description** |
| `void` | no default initializer | `void` has no value |
| [`bool`](#bool) | `false` | boolean value |
| `byte` | `0` | signed 8 bits |
| `ubyte` | `0u` | unsigned 8 bits |
| `short` | `0` | signed 16 bits |
| `ushort` | `0u` | unsigned 16 bits |
| `int` | `0` | signed 32 bits |
| `uint` | `0u` | unsigned 32 bits |
| `long` | `0L` | signed 64 bits |
| `ulong` | `0uL` | unsigned 64 bits |
| `cent` | `0` | signed 128 bits (reserved for future use) |
| `ucent` | `0u` | unsigned 128 bits (reserved for future use) |
| `float` | `float.nan` | 32 bit floating point |
| `double` | `double.nan` | 64 bit floating point |
| `real` | `real.nan` | largest floating point size available |
| `ifloat` | `float.nan*1.0i` | imaginary float |
| `idouble` | `double.nan*1.0i` | imaginary double |
| `ireal` | `real.nan*1.0i` | imaginary real |
| `cfloat` | `float.nan+float.nan*1.0i` | a complex number of two float values |
| `cdouble` | `double.nan+double.nan*1.0i` | complex double |
| `creal` | `real.nan+real.nan*1.0i` | complex real |
| `char` | `'xFF'` | unsigned 8 bit (UTF-8 code unit) |
| `wchar` | `'uFFFF'` | unsigned 16 bit (UTF-16 code unit) |
| `dchar` | `'U0000FFFF'` | unsigned 32 bit (UTF-32 code unit) |

 **Implementation Defined:** The real floating point type has at least the range and precision of the `double` type. On x86 CPUs it is often implemented as the 80 bit Extended Real type supported by the x86 FPU. Derived Data Types
------------------

 * [Pointer](https://dlang.org/arrays.html#pointers)
* [Static Array](https://dlang.org/arrays.html#static-arrays)
* [Dynamic Array](https://dlang.org/arrays.html#dynamic-arrays)
* [Associative Array](hash-map)
* [Functions](function)
* [Delegates](#delegates)

 User-Defined Types
------------------

 * [Enums](enum)
* [Structs and Unions](struct)
* [Classes](class)
* [Interfaces](interface)

 Type Conversions
----------------

 See also: [*CastExpression*](expression#CastExpression). ### Pointer Conversions

 Casting pointers to non-pointers and vice versa is allowed.

 **Best Practices:** do not do this for any pointers that point to data allocated by the garbage collector. ### Implicit Conversions

 Implicit conversions are used to automatically convert types as required. 

 An enum can be implicitly converted to its base type, but going the other way requires an explicit conversion. For example:

 
```
int i;

enum Foo { E }
Foo f;
i = f;           // OK
f = i;           // error
f = cast(Foo)i;  // OK
f = 0;           // error
f = Foo.E;       // OK

```
 A derived class can be implicitly converted to its base class, but going the other way requires an explicit cast. For example:

 
```
class Base {}
class Derived : Base {}
Base bd = new Derived();              // implicit conversion
Derived db = cast(Derived)new Base(); // explicit conversion

```
 A dynamic array, say `x`, of a derived class can be implicitly converted to a dynamic array, say `y`, of a base class iff elements of `x` and `y` are qualified as being either both `const` or `both` `immutable`.

 
```
class Base {}
class Derived : Base {}
const(Base)[] ca = (const(Derived)[]).init; // `const` elements
immutable(Base)[] ia = (immutable(Derived)[]).init; // `immutable` elements

```
 A static array, say `x`, of a derived class can be implicitly converted to a static array, say `y`, of a base class iff elements of `x` and `y` are qualified as being either both `const` or `both` `immutable` or both mutable (neither `const` nor `immutable`).

 
```
class Base {}
class Derived : Base {}
Base[3] ma = (Derived[3]).init; // mutable elements
const(Base)[3] ca = (const(Derived)[3]).init; // `const` elements
immutable(Base)[3] ia = (immutable(Derived)[3]).init; // `immutable` elements

```
 ### Integer Promotions

 Integer Promotions are conversions of the following types: 

 

Integer Promotions| **from** | **to** |
| `bool` | `int` |
| `byte` | `int` |
| `ubyte` | `int` |
| `short` | `int` |
| `ushort` | `int` |
| `char` | `int` |
| `wchar` | `int` |
| `dchar` | `uint` |

 If an enum has as a base type one of the types in the left column, it is converted to the type in the right column. 

 ### Usual Arithmetic Conversions

 The usual arithmetic conversions convert operands of binary operators to a common type. The operands must already be of arithmetic types. The following rules are applied in order, looking at the base type: 

 1. If either operand is `real`, the other operand is converted to `real`.
2. Else if either operand is `double`, the other operand is converted to `double`.
3. Else if either operand is `float`, the other operand is converted to `float`.
4. Else the integer promotions are done on each operand, followed by:
	1. If both are the same type, no more conversions are done.
	2. If both are signed or both are unsigned, the smaller type is converted to the larger.
	3. If the signed type is larger than the unsigned type, the unsigned type is converted to the signed type.
	4. The signed type is converted to the unsigned type.

 If one or both of the operand types is an enum after undergoing the above conversions, the result type is:

 1. If the operands are the same type, the result will be of that type.
2. If one operand is an enum and the other is the base type of that enum, the result is the base type.
3. If the two operands are different enums, the result is the closest base type common to both. A base type being closer means there is a shorter sequence of conversions to base type to get there from the original type.

 Integer values cannot be implicitly converted to another type that cannot represent the integer bit pattern after integral promotion. For example:

 
```
ubyte  u1 = -1;       // error, -1 cannot be represented in a ubyte
ushort u2 = -1;       // error, -1 cannot be represented in a ushort
uint   u3 = int(-1);  // ok, -1 can be represented in a uint
ulong  u4 = long(-1); // ok, -1 can be represented in a ulong

```
 Floating point types cannot be implicitly converted to integral types. Complex or imaginary floating point types cannot be implicitly converted to non-complex floating point types. Non-complex floating point types cannot be implicitly converted to imaginary floating point types. 

 `bool`
------

 The bool type is a byte-size type that can only hold the value `true` or `false`.

 The only operators that can accept operands of type bool are: `&` `|`, `^`, `&``=`, `|``=`, `^=`, !, `&``&`, `|``|`, and `?:`.

 A `bool` value can be implicitly converted to any integral type, with `false` becoming 0 and `true` becoming 1.

 The numeric literals `0` and `1` can be implicitly converted to the `bool` values `false` and `true`, respectively. Casting an expression to `bool` means testing for `0` or `!=0` for arithmetic types, and `null` or `!=null` for pointers or references.

 Delegates
---------

 Delegates are an aggregate of two pieces of data: an object reference and a pointer to a non-static member function, or a pointer to a closure and a pointer to a nested function. The object reference forms the `this` pointer when the function is called.

 Delegates are declared similarly to function pointers:

 
```
int function(int) fp; // fp is pointer to a function
int delegate(int) dg; // dg is a delegate to a function

```
 A delegate is initialized analogously to function pointers: 

 
```
int func(int);
fp = &func;   // fp points to func
class OB
{
    int member(int);
}
OB o;
dg = &o.member; // dg is a delegate to object o and
                // member function member

```
 Delegates cannot be initialized with static member functions or non-member functions. 

 Delegates are called analogously to function pointers: 

 
```
fp(3);   // call func(3)
dg(3);   // call o.member(3)

```
 The equivalent of member function pointers can be constructed using [anonymous lambda functions](expression#function_literals):

 
```
class C
{
    int a;
    int foo(int i) { return i + a; }
}

// mfp is the member function pointer
auto mfp = function(C self, int i) { return self.foo(i); };
auto c = new C();  // create an instance of C
mfp(c, 1);  // and call c.foo(1)

```
 The C style syntax for declaring pointers to functions is deprecated:

 
```
int (*fp)(int);  // fp is pointer to a function

```
 `typeof`
--------

 
```
Typeof:
    typeof ( Expression )
    typeof ( return )

```
  `typeof` is a way to specify a type based on the type of an expression. For example: 

 
```
void func(int i)
{
    typeof(i) j;       // j is of type int
    typeof(3 + 6.0) x; // x is of type double
    typeof(1)* p;      // p is of type pointer to int
    int[typeof(p)] a;  // a is of type int[int*]

    writeln(typeof('c').sizeof); // prints 1
    double c = cast(typeof(1.0))j; // cast j to double
}

```
  *Expression* is not evaluated, it is used purely to generate the type: 

 
```
void func()
{
    int i = 1;
    typeof(++i) j; // j is declared to be an int, i is not incremented
    writeln(i);  // prints 1
}

```
 Special cases: 

 1. `typeof(this)` will generate the type of what `this` would be in a non-static member function, even if not in a member function.
2. Analogously, `typeof(super)` will generate the type of what `super` would be in a non-static member function.
3. `typeof(return)` will, when inside a function scope, give the return type of that function.

 
```
class A { }

class B : A
{
    typeof(this) x;  // x is declared to be a B
    typeof(super) y; // y is declared to be an A
}

struct C
{
    static typeof(this) z;  // z is declared to be a C

    typeof(super) q; // error, no super struct for C
}

typeof(this) r;   // error, no enclosing struct or class

```
 If the expression is a  [Property Function](function#property-functions), `typeof` gives its return type. 

 
```
struct S
{
    @property int foo() { return 1; }
}
typeof(S.foo) n;  // n is declared to be an int

```
 **Best Practices:** 1. *Typeof* is most useful in writing generic template code.

 Mixin Types
-----------

 
```
MixinType:
    mixin ( ArgumentList )

```
 Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*Type*](type#Type), and is compiled as such.

 
```
void test(mixin("int")* p) // int* p
{
    mixin("int")[] a;      // int[] a;
    mixin("int[]") b;      // int[] b;
}

```
 Aliased Types
-------------

 ### `size_t`

 `size_t` is an alias to one of the unsigned integral basic types, and represents a type that is large enough to represent an offset into all addressable memory.

 ### `ptrdiff_t`

 `ptrdiff_t` is an alias to the signed integral basic type the same size as `size_t`.

 ### `string`

 A [*string* is a special case of an array.](arrays#strings)

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/type.html>

Attributes
==========

 **Contents** 1. [Linkage Attribute](#linkage)
2. [`align` Attribute](#align)
3. [`deprecated` Attribute](#deprecated)
4. [Visibility Attribute](#visibility_attributes)
5. [`const` Attribute](#const)
6. [`immutable` Attribute](#immutable)
7. [`inout` Attribute](#inout)
8. [`shared` Attribute](#shared)
9. [`__gshared` Attribute](#gshared)
10. [`@disable` Attribute](#disable)
11. [`@safe`, `@trusted`, and `@system` Attribute](#safe)
12. [`@nogc` Attribute](#nogc)
13. [`@property` Attribute](#property)
14. [`nothrow` Attribute](#nothrow)
15. [`pure` Attribute](#pure)
16. [`ref` Attribute](#ref)
17. [`return` Attribute](#return)
18. [`override` Attribute](#override)
19. [`static` Attribute](#static)
20. [`auto` Attribute](#auto)
21. [`scope` Attribute](#scope)
22. [`abstract` Attribute](#abstract)
23. [User-Defined Attributes](#uda)

 
```
AttributeSpecifier:
    Attribute :
    Attribute DeclarationBlock

Attribute:
    LinkageAttribute
    AlignAttribute
    DeprecatedAttribute
    VisibilityAttribute
    Pragma
    static
    extern
    abstract
    final
    override
    synchronized
    auto
    scope
    const
    immutable
    inout
    shared
    __gshared
    AtAttribute
    FunctionAttributeKwd
    ref
    return

FunctionAttributeKwd:
    nothrow
    pure

AtAttribute:
    @ disable
    @ nogc
    @ live
    Property
    @ safe
    @ system
    @ trusted
    UserDefinedAttribute

Property:
    @ property

DeclarationBlock:
    DeclDef
    { DeclDefsopt }

```
 Attributes are a way to modify one or more declarations. The general forms are: 

 
```
attribute declaration; // affects the declaration

attribute:     // affects all declarations until the end of
               // the current scope
  declaration;
  declaration;
  ...

attribute {    // affects all declarations in the block
  declaration;
  declaration;
  ...
}

```
 Linkage Attribute
-----------------

 
```
LinkageAttribute:
    extern ( LinkageType )
    extern ( C++, QualifiedIdentifier )
    extern ( C++, NamespaceList )

LinkageType:
    C
    C++
    D
    Windows
    System
    Objective-C

NamespaceList:
    ConditionalExpression
    ConditionalExpression,
    ConditionalExpression, NamespaceList

```
 D provides an easy way to call C functions and operating system API functions, as compatibility with both is essential. The *LinkageType* is case sensitive, and is meant to be extensible by the implementation (`they are not keywords`). `C` and `D` must be supplied, the others are what makes sense for the implementation. `C++` offers limited compatibility with C++. `Objective-C` offers compatibility with Objective-C, see the [Interfacing to Objective-C](objc_interface) documentation for more information. `System` is the same as `Windows` on Windows platforms, and `C` on other platforms. `Implementation Note:` for Win32 platforms, `Windows` should exist. 

 C function calling conventions are specified by: 

 
```
extern (C):
    int foo(); // call foo() with C conventions

```
 Note that `extern(C)` can be provided for all types of declarations, including `struct` or `class`, even though there is no corresponding match on the `C` side. In that case, the attribute is ignored. This behavior applies for nested functions and nested variables as well. However, for `static` member methods and `static` nested functions, adding `extern(C)` will change the calling convention, but not the mangling. D conventions are:

 
```
extern (D):

```
 Windows API conventions are:

 
```
extern (Windows):
    void *VirtualAlloc(
        void *lpAddress,
        uint dwSize,
        uint flAllocationType,
        uint flProtect
    );

```
 The Windows convention is distinct from the C convention only on Win32 platforms, where it is equivalent to the [stdcall](https://en.wikipedia.org/wiki/X86_calling_conventions) convention.

 Note that a lone `extern` declaration is used as a [storage class](declaration#extern).

 ### C++ Namespaces

 The linkage form `extern (C++,` *QualifiedIdentifier*`)` creates C++ declarations that reside in C++ namespaces. The *QualifiedIdentifier* specifies the namespaces. 

 
```
extern (C++, N) { void foo(); }

```
 refers to the C++ declaration:

 
```
namespace N { void foo(); }
```
 and can be referred to with or without qualification:

 
```
foo();
N.foo();

```
 Namespaces create a new named scope that is imported into its enclosing scope.

 
```
extern (C++, N) { void foo(); void bar(); }
extern (C++, M) { void foo(); }

bar();   // ok
foo();   // error - N.foo() or M.foo() ?
M.foo(); // ok

```
 Multiple identifiers in the *QualifiedIdentifier* create nested namespaces:

 
```
extern (C++, N.M) { extern (C++) { extern (C++, R) { void foo(); } } }
N.M.R.foo();

```
 refers to the C++ declaration:

 
```
namespace N { namespace M { namespace R { void foo(); } } }
```
 
`align` Attribute
------------------

 
```
AlignAttribute:
    align
    align ( AssignExpression )

```
 Specifies the alignment of:

 1. variables
2. struct fields
3. union fields
4. class fields
5. struct, union, and class types

 `align` by itself sets it to the default, which matches the default member alignment of the companion C compiler.

 
```
struct S
{
  align:
    byte a;   // placed at offset 0
    int b;    // placed at offset 4
    long c;   // placed at offset 8
}
static assert(S.alignof == 8);
static assert(S.sizeof == 16);

```
 *AssignExpression* specifies the alignment which matches the behavior of the companion C compiler when non-default alignments are used. It must be a positive power of 2. 

 A value of 1 means that no alignment is done; fields are packed together. 

 
```
struct S
{
  align (1):
    byte a;   // placed at offset 0
    int b;    // placed at offset 1
    long c;   // placed at offset 5
}
static assert(S.alignof == 1);
static assert(S.sizeof == 13);

```
 The natural alignment of an aggregate is the maximum alignment of its fields. It can be overridden by setting the alignment outside of the aggregate.

 
```
align (2) struct S
{
  align (1):
    byte a;   // placed at offset 0
    int b;    // placed at offset 1
    long c;   // placed at offset 5
}
static assert(S.alignof == 2);
static assert(S.sizeof == 14);

```
 Setting the alignment of a field aligns it to that power of 2, regardless of the size of the field.

 
```
struct S
{
               byte a;  // placed at offset 0
    align (4)  byte b;  // placed at offset 4
    align (16) short c; // placed at offset 16
}
static assert(S.alignof == 16);
static assert(S.sizeof == 32);

```
 Do not align references or pointers that were allocated using [*NewExpression*](expression#NewExpression) on boundaries that are not a multiple of `size_t`. The garbage collector assumes that pointers and references to GC allocated objects will be on `size_t` byte boundaries. 

 **Undefined Behavior:** If any pointers and references to GC allocated objects are not aligned on `size_t` byte boundaries. The *AlignAttribute* is reset to the default when entering a function scope or a non-anonymous struct, union, class, and restored when exiting that scope. It is not inherited from a base class. 

 
`deprecated` Attribute
-----------------------

 
```
DeprecatedAttribute:
    deprecated
    deprecated ( AssignExpression )

```
 It is often necessary to deprecate a feature in a library, yet retain it for backwards compatibility. Such declarations can be marked as `deprecated`, which means that the compiler can be instructed to produce an error if any code refers to deprecated declarations: 

 
```
deprecated
{
    void oldFoo();
}

oldFoo();   // Deprecated: function test.oldFoo is deprecated

```
 Optionally a string literal or manifest constant can be used to provide additional information in the deprecation message. 

 
```
deprecated("Don't use bar") void oldBar();
oldBar();   // Deprecated: function test.oldBar is deprecated - Don't use bar

```
 Calling CTFE-able functions or using manifest constants is also possible. 

 
```
import std.format;
enum Message = format("%s and all its members are obsolete", Foobar.stringof);
deprecated(Message) class Foobar {}
auto f = new Foobar();   // Deprecated: class test.Foobar is deprecated - Foobar
     // and all its members are obsolete
deprecated(format("%s is also obsolete", "This class")) class BarFoo {}
auto bf = new BarFoo();  // Deprecated: class test.BarFoo is deprecated - This
     // class is also obsolete

```
 `Implementation Note:` The compiler should have a switch specifying if `deprecated` should be ignored, cause a warning, or cause an error during compilation. 

 Visibility Attribute
--------------------

 
```
VisibilityAttribute:
    private
    package
    package ( QualifiedIdentifier )
    protected
    public
    export

```
 Visibility is an attribute that is one of `private`, `package`, `protected`, `public`, or `export`. They may be referred to as protection attributes in documents predating [DIP22](http://wiki.dlang.org/DIP22).

 Symbols with `private` visibility can only be accessed from within the same module. Private member functions are implicitly final and cannot be overridden. 

 `package` extends private so that package members can be accessed from code in other modules that are in the same package. If no identifier is provided, this applies to the innermost package only, or defaults to `private` if a module is not nested in a package. 

 `package` may have an optional parameter in the form of a dot-separated identifier list which is resolved as the qualified package name. The package must be either the module's parent package or one of its anscestors. If this optional parameter is present, the symbol will be visible in the specified package and all of its descendants. 

 `protected` only applies inside classes (and templates as they can be mixed in) and means that a symbol can only be seen by members of the same module, or by a derived class. If accessing a protected instance member through a derived class member function, that member can only be accessed for the object instance which can be implicitly cast to the same type as ‘this’. `protected` module members are illegal. 

 `public` means that any code within the executable can see the member. It is the default visibility attribute. 

 `export` means that any code outside the executable can access the member. `export` is analogous to exporting definitions from a DLL. 

 Visibility participates in [symbol name lookup](module#name_lookup). 

 
`const` Attribute
------------------

 The `const` attribute changes the type of the declared symbol from `T` to `const(T)`, where `T` is the type specified (or inferred) for the introduced symbol in the absence of `const`. 

 
```
const int foo = 7;
static assert(is(typeof(foo) == const(int)));

const
{
    double bar = foo + 6;
}
static assert(is(typeof(bar) == const(double)));

class C
{
    const void foo();
    const
    {
        void bar();
    }
    void baz() const;
}
pragma(msg, typeof(C.foo)); // const void()
pragma(msg, typeof(C.bar)); // const void()
pragma(msg, typeof(C.baz)); // const void()
static assert(is(typeof(C.foo) == typeof(C.bar)) &&
              is(typeof(C.bar) == typeof(C.baz)));

```
 
`immutable` Attribute
----------------------

 The `immutable` attribute modifies the type from `T` to `immutable(T)`, the same way as `const` does. 

 
`inout` Attribute
------------------

 The `inout` attribute modifies the type from `T` to `inout(T)`, the same way as `const` does. 

 
`shared` Attribute
-------------------

 The `shared` attribute modifies the type from `T` to `shared(T)`, the same way as `const` does. 

 
`__gshared` Attribute
----------------------

 By default, non-immutable global declarations reside in thread local storage. When a global variable is marked with the `__gshared` attribute, its value is shared across all threads.

 
```
int foo;            // Each thread has its own exclusive copy of foo.
__gshared int bar;  // bar is shared by all threads.

```
 `__gshared` may also be applied to member variables and local variables. In these cases, `__gshared` is equivalent to `static`, except that the variable is shared by all threads rather than being thread local.

 
```
class Foo
{
    __gshared int bar;
}

int foo()
{
    __gshared int bar = 0;
    return bar++; // Not thread safe.
}

```
 Unlike the `shared` attribute, `__gshared` provides no safe-guards against data races or other multi-threaded synchronization issues. It is the responsibility of the programmer to ensure that access to variables marked `__gshared` is synchronized correctly.

 `__gshared` is disallowed in safe mode.

 
`@disable` Attribute
---------------------

 A reference to a declaration marked with the `@disable` attribute causes a compile time error. This can be used to explicitly disallow certain operations or overloads at compile time rather than relying on generating a runtime error.

 
```
@disable void foo() { }

```
 
```
void main() { foo(); /* error, foo is disabled */ }

```
 [Disabling struct no-arg constructor](struct#Struct-Constructor) disallows default construction of the struct. 

 [Disabling struct postblit](struct#StructPostblit) makes the struct not copyable. 

 
`@safe`, `@trusted`, and `@system` Attribute
---------------------------------------------

 See [Function Safety](https://dlang.org/function.html#function-safety).

 
`@nogc` Attribute
------------------

 See [No-GC Functions](https://dlang.org/function.html#nogc-functions).

 
`@property` Attribute
----------------------

 See [Property Functions](function#property-functions).

 
`nothrow` Attribute
--------------------

 See [Nothrow Functions](function#nothrow-functions).

 
`pure` Attribute
-----------------

 See [Pure Functions](function#pure-functions).

 
`ref` Attribute
----------------

 See [Ref Functions](function#ref-functions).

 
`return` Attribute
-------------------

 See [Return Ref Parameters](function#return-ref-parameters).

 
`override` Attribute
---------------------

 The `override` attribute applies to virtual functions. It means that the function must override a function with the same name and parameters in a base class. The override attribute is useful for catching errors when a base class's member function gets its parameters changed, and all derived classes need to have their overriding functions updated. 

 
```
class Foo
{
    int bar();
    int abc(int x);
}

class Foo2 : Foo
{
    override
    {
        int bar(char c); // error, no bar(char) in Foo
        int abc(int x);  // ok
    }
}

```
 
`static` Attribute
-------------------

 The `static` attribute applies to functions and data. It means that the declaration does not apply to a particular instance of an object, but to the type of the object. In other words, it means there is no `this` reference. `static` is ignored when applied to other declarations. 

 
```
class Foo
{
    static int bar() { return 6; }
    int foobar() { return 7; }
}

...

Foo f = new Foo;
Foo.bar();      // produces 6
Foo.foobar();   // error, no instance of Foo
f.bar();        // produces 6;
f.foobar();     // produces 7;

```
  Static functions are never virtual. 

  Static data has one instance per thread, not one per object. 

  Static does not have the additional C meaning of being local to a file. Use the `private` attribute in D to achieve that. For example: 

 
```
module foo;
int x = 3;         // x is global
private int y = 4; // y is local to module foo

```
 
`auto` Attribute
-----------------

 The `auto` attribute is used when there are no other attributes and type inference is desired. 

 
```
auto i = 6.8;   // declare i as a double

```
 For functions, the `auto` attribute means return type inference. See [Auto Functions](https://dlang.org/function.html#auto-functions). 

 
`scope` Attribute
------------------

  The `scope` attribute is used for local variables and for class declarations. For class declarations, the `scope` attribute creates a *scope* class. For local declarations, `scope` implements the RAII (Resource Acquisition Is Initialization) protocol. This means that the destructor for an object is automatically called when the reference to it goes out of scope. The destructor is called even if the scope is exited via a thrown exception, thus `scope` is used to guarantee cleanup. 

  If there is more than one `scope` variable going out of scope at the same point, then the destructors are called in the reverse order that the variables were constructed. 

  `scope` cannot be applied to globals, statics, data members, ref or out parameters. Arrays of `scope`s are not allowed, and `scope` function return values are not allowed. Assignment to a `scope`, other than initialization, is not allowed. `Rationale:` These restrictions may get relaxed in the future if a compelling reason to appears. 

 
`abstract` Attribute
---------------------

  An abstract member function must be overridden by a derived class. Only virtual member functions may be declared abstract; non-virtual member functions and free-standing functions cannot be declared abstract. 

  Classes become abstract if any of its virtual member functions are declared abstract or if they are defined within an abstract attribute. Note that an abstract class may also contain non-virtual member functions. 

  Classes defined within an abstract attribute or with abstract member functions cannot be instantiated directly. They can only be instantiated as a base class of another, non-abstract, class. 

  Member functions declared as abstract can still have function bodies. This is so that even though they must be overridden, they can still provide ‘base class functionality’, e.g. through `super.foo()` in a derived class. Note that the class is still abstract and cannot be instantiated directly. 

 User-Defined Attributes
-----------------------

 
```
UserDefinedAttribute:
    @ ( ArgumentList )
    @ Identifier
    @ Identifier ( ArgumentListopt )
    @ TemplateInstance
    @ TemplateInstance ( ArgumentListopt )

```
  User-Defined Attributes (UDA) are compile-time expressions that can be attached to a declaration. These attributes can then be queried, extracted, and manipulated at compile time. There is no runtime component to them. 

 A user-defined attribute looks like: 
```
@(3) int a;

```
 
```
@("string", 7) int b;

enum Foo;
@Foo int c;

struct Bar
{
    int x;
}

@Bar(3) int d;

```
  If there are multiple UDAs in scope for a declaration, they are concatenated: 

 
```
@(1)
{
    @(2) int a;         // has UDAs (1, 2)
    @("string") int b;  // has UDAs (1, "string")
}

```
  UDAs can be extracted into an expression tuple using `__traits`: 

 
```
@('c') string s;
pragma(msg, __traits(getAttributes, s)); // prints tuple('c')

```
  If there are no user-defined attributes for the symbol, an empty tuple is returned. The expression tuple can be turned into a manipulatable tuple: 

 
```
enum EEE = 7;
@("hello") struct SSS { }
@(3) { @(4) @EEE @SSS int foo; }

alias TP = __traits(getAttributes, foo);

pragma(msg, TP); // prints tuple(3, 4, 7, (SSS))
pragma(msg, TP[2]); // prints 7

```
  Of course the tuple types can be used to declare things: 

 
```
TP[3] a; // a is declared as an SSS

```
  The attribute of the type name is not the same as the attribute of the variable: 

 
```
pragma(msg, __traits(getAttributes, typeof(a))); // prints tuple("hello")

```
  Of course, the real value of UDAs is to be able to create user-defined types with specific values. Having attribute values of basic types does not scale. The attribute tuples can be manipulated like any other tuple, and can be passed as the argument list to a template. 

  Whether the attributes are values or types is up to the user, and whether later attributes accumulate or override earlier ones is also up to how the user interprets them. 

  UDAs cannot be attached to template parameters. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/attribute.html>

Enums
=====

 **Contents** 1. [Named Enums](#named_enums)
	1. [Enum Default Initializer](#enum_default_initializer)
	2. [Enum Properties](#enum_properties)
2. [Anonymous Enums](#anonymous_enums)
3. [Manifest Constants](#manifest_constants)

 
```
EnumDeclaration:
    enum Identifier EnumBody
    enum Identifier : EnumBaseType EnumBody
    AnonymousEnumDeclaration

EnumBaseType:
    Type

EnumBody:
    { EnumMembers }
    ;

EnumMembers:
    EnumMember
    EnumMember ,
    EnumMember , EnumMembers

EnumMemberAttributes:
    EnumMemberAttribute
    EnumMemberAttribute EnumMemberAttributes

EnumMemberAttribute:
    DeprecatedAttribute
    UserDefinedAttribute
    @disable

EnumMember:
    EnumMemberAttributesopt Identifier
    EnumMemberAttributesopt Identifier = AssignExpression

AnonymousEnumDeclaration:
    enum : EnumBaseType { EnumMembers }
    enum { EnumMembers }
    enum { AnonymousEnumMembers }

AnonymousEnumMembers:
    AnonymousEnumMember
    AnonymousEnumMember ,
    AnonymousEnumMember , AnonymousEnumMembers

AnonymousEnumMember:
    EnumMember
    Type Identifier = AssignExpression

```
 Enum declarations are used to define a group of constants. 

 Named Enums
-----------

  Named enums are used to declare related constants and group them by giving them a unique type. The [*EnumMembers*](#EnumMembers) are declared in the scope of the named enum. The named enum declares a new type, and all the *EnumMembers* have that type. 

 This defines a new type `X` which has values `X.A=0`, `X.B=1`, `X.C=2`:

 
```
enum X { A, B, C }  // named enum

```
 If the *EnumBaseType* is not explicitly set, and the first *EnumMember* has an [*AssignExpression*](expression#AssignExpression), it is set to the type of that [*AssignExpression*](expression#AssignExpression). Otherwise, it defaults to type `int`.

 Named enum members may not have individual *Type*s. 

 A named enum member can be implicitly cast to its [*EnumBaseType*](#EnumBaseType), but *EnumBaseType* types cannot be implicitly cast to an enum type. 

 The value of an [*EnumMember*](#EnumMember) is given by its [*AssignExpression*](expression#AssignExpression). If there is no [*AssignExpression*](expression#AssignExpression) and it is the first *EnumMember*, its value is [*EnumBaseType*](#EnumBaseType)`.init`. 

 If there is no [*AssignExpression*](expression#AssignExpression) and it is not the first *EnumMember*, it is given the value of the previous *EnumMember*`+1`. If the value of the previous *EnumMember* is [*EnumBaseType*](#EnumBaseType)`.max`, it is an error. If the value of the previous *EnumMember*`+1` is the same as the value of the previous *EnumMember*, it is an error. (This can happen with floating point types.) 

 All *EnumMember*s are in scope for the [*AssignExpression*](expression#AssignExpression)s. 

 
```
enum A = 3;
enum B
{
    A = A // error, circular reference
}
enum C
{
    A = B,  // A = 4
    B = D,  // B = 4
    C = 3,  // C = 3
    D       // D = 4
}
enum E : C
{
    E1 = C.D,
    E2      // error, C.D is C.max
}

```
 An empty enum body (For example `enum E;`) signifies an opaque enum - the enum members are unknown.

 ### Enum Default Initializer

 The `.init` property of an enum type is the value of the first member of that enum. This is also the default initializer for the enum type. 

 
```
enum X { A=3, B, C }
X x;      // x is initialized to 3

```
 ### Enum Properties

 Enum properties only exist for named enums. 

 

Named Enum Properties| `.init` | First enum member value |
| `.min` | Smallest enum member value |
| `.max` | Largest enum member value |
| `.sizeof` | Size of storage for an enumerated value |

 For example:

 
```
enum X { A=3, B=1, C=4, D, E=2 }
X.init   // is X.A
X.min    // is X.B
X.max    // is X.D
X.sizeof // is same as int.sizeof

```
 The [*EnumBaseType*](#EnumBaseType) of named enums must support comparison in order to compute the `.max` and `.min` properties. 

 Anonymous Enums
---------------

 If the enum *Identifier* is not present, then the enum is an *anonymous enum*, and the [*EnumMembers*](#EnumMembers) are declared in the scope the [*EnumDeclaration*](#EnumDeclaration) appears in. No new type is created. 

 The *EnumMembers* can have different types. Those types are given by the first of: 

 1. The *Type*, if present. Types are not permitted when an [*EnumBaseType*](#EnumBaseType) is present.
2. The *EnumBaseType*, if present.
3. The type of the *AssignExpression*, if present.
4. The type of the previous *EnumMember*, if present.
5. `int`

 
```
enum { A, B, C }  // anonymous enum

```
 Defines the constants A=0, B=1, C=2, all of type `int`.

 Enums must have at least one member. 

 The value of an *EnumMember* is given by its [*AssignExpression*](expression#AssignExpression). If there is no [*AssignExpression*](expression#AssignExpression) and it is the first *EnumMember*, its value is the `.init` property of the *EnumMember*'s type. 

 If there is no [*AssignExpression*](expression#AssignExpression) and it is not the first *EnumMember*, it is given the value of the previous *EnumMember*`+1`. If the value of the previous *EnumMember* is the `.max` property if the previous *EnumMember*'s type, it is an error. If the value of the previous *EnumMember*`+1` is the same as the value of the previous *EnumMember*, it is an error. (This can happen with floating point types.) 

 All *EnumMember*s are in scope for the [*AssignExpression*](expression#AssignExpression)s. 

 
```
enum { A, B = 5+7, C, D = 8+C, E }

```
 Sets A=0, B=12, C=13, D=21, and E=22, all of type `int`.

 
```
enum : long { A = 3, B }

```
 Sets A=3, B=4 all of type `long`.

 
```
enum : string
{
    A = "hello",
    B = "betty",
    C     // error, cannot add 1 to "betty"
}

```
 
```
enum
{
    A = 1.2f,  // A is 1.2f of type float
    B,         // B is 2.2f of type float
    int C = 3, // C is 3 of type int
    D          // D is 4 of type int
}

```
 Manifest Constants
------------------

 If there is only one member of an anonymous enum, the `{ }` can be omitted. Gramatically speaking, this is an [*AutoDeclaration*](declaration#AutoDeclaration). 

 
```
enum i = 4;      // i is 4 of type int
enum long l = 3; // l is 3 of type long

```
 Manifest constants are not lvalues, meaning their address cannot be taken. They exist only in the memory of the compiler.

 
```
enum size = __traits(classInstanceSize, Foo);  // evaluated at compile-time

```
 The initializer for a manifest constant is evaluated using compile time function evaluation.

 
```
template Foo(T)
{
    // Not bad, but the 'size' variable will be located in the executable.
    const size_t size = T.sizeof;       // evaluated at compile-time

    // ... use of 'size' at compile time ...
}

template Bar(T)
{
    // Better, the manifest constant has no runtime location in the executable.
    enum size_t size = T.sizeof;        // evaluated at compile-time

    // ... use of 'size' at compile time ...

    // Taking the address of Foo!T.size also causes it to go into the exe file.
    auto p = &Foo!T.size;
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/enum.html>

Lexical
=======

 **Contents** 1. [Source Text](#source_text)
2. [Character Set](#character_set)
3. [End of File](#end_of_file)
4. [End of Line](#end_of_line)
5. [White Space](#white_space)
6. [Comments](#comment)
7. [Tokens](#tokens)
8. [Identifiers](#identifiers)
9. [String Literals](#string_literals)
	1. [Wysiwyg Strings](#wysiwyg)
	2. [Double Quoted Strings](#double_quoted_strings)
	3. [Hex Strings](#hex_strings)
	4. [Delimited Strings](#delimited_strings)
	5. [Token Strings](#token_strings)
	6. [String Postfix](#string_postfix)
10. [Escape Sequences](#escape_sequences)
11. [Character Literals](#characterliteral)
12. [Integer Literals](#integerliteral)
13. [Floating Point Literals](#floatliteral)
14. [Keywords](#keywords)
15. [Special Tokens](#specialtokens)
16. [Special Token Sequences](#special-token-sequence)

 The lexical analysis is independent of the syntax parsing and the semantic analysis. The lexical analyzer splits the source text up into tokens. The lexical grammar describes the syntax of these tokens. The grammar is designed to be suitable for high speed scanning and to make it easy to write a correct scanner. It has a minimum of special case rules and there is only one phase of translation.

 Source Text
-----------

 Source text can be in any one of the following encodings:

 * ASCII (strictly, 7-bit ASCII)
* UTF-8
* UTF-16BE
* UTF-16LE
* UTF-32BE
* UTF-32LE

 One of the following UTF BOMs (Byte Order Marks) can be present at the beginning of the source text:

 

UTF Byte Order Marks| **Format** | **BOM** |
| UTF-8 | EF BB BF |
| UTF-16BE | FE FF |
| UTF-16LE | FF FE |
| UTF-32BE | 00 00 FE FF |
| UTF-32LE | FF FE 00 00 |
| ASCII | no BOM |

 If the source file does not start with a BOM, then the first character must be less than or equal to U+0000007F.

 The source text is decoded from its source representation into Unicode [*Character*](#Character)s. The [*Character*](#Character)s are further divided into: [*WhiteSpace*](#WhiteSpace), [*EndOfLine*](#EndOfLine), [*Comment*](#Comment)s, [*SpecialTokenSequence*](#SpecialTokenSequence)s, and [*Token*](#Token)s, with the source terminated by an [*EndOfFile*](#EndOfFile).

 The source text is split into tokens using the maximal munch algorithm, i.e., the lexical analyzer makes the longest possible token. For example `>>` is a right shift token, not two greater than tokens. There are two exceptions to this rule:

 * A `..` embedded inside what looks like two floating point literals, as in `1..2`, is interpreted as if the `..` was separated by a space from the first integer.
* A `1.a` is interpreted as the three tokens `1`, `.`, and `a`, whereas `1. a` is interpreted as the two tokens `1.` and `a`.

 Character Set
-------------

 
```
Character:
    any Unicode character

```
 End of File
-----------

 
```
EndOfFile:
    physical end of the file
    \u0000
    \u001A
```
 The source text is terminated by whichever comes first.

 End of Line
-----------

 
```
EndOfLine:
    \u000D
    \u000A
    \u000D \u000A
    \u2028
    \u2029
    EndOfFile
```
 White Space
-----------

 
```
WhiteSpace:
    Space
    Space WhiteSpace

Space:
    \u0020
    \u0009
    \u000B
    \u000C

```
 Comments
--------

 
```
Comment:
    BlockComment
    LineComment
    NestingBlockComment

BlockComment:
    /* Charactersopt */

LineComment:
    // Charactersopt EndOfLine

NestingBlockComment:
    /+ NestingBlockCommentCharactersopt +/

NestingBlockCommentCharacters:
    NestingBlockCommentCharacter
    NestingBlockCommentCharacter NestingBlockCommentCharacters

NestingBlockCommentCharacter:
    Character
    NestingBlockComment

Characters:
    Character
    Character Characters
```
 There are three kinds of comments:

 1. Block comments can span multiple lines, but do not nest.
2. Line comments terminate at the end of the line.
3. Nesting block comments can span multiple lines and can nest.

  The contents of strings and comments are not tokenized. Consequently, comment openings occurring within a string do not begin a comment, and string delimiters within a comment do not affect the recognition of comment closings and nested `/+` comment openings. With the exception of `/+` occurring within a `/+` comment, comment openings within a comment are ignored. 

 
```
a = /+ // +/ 1;    // parses as if 'a = 1;'
a = /+ "+/" +/ 1"; // parses as if 'a = " +/ 1";'
a = /+ /* +/ */ 3; // parses as if 'a = */ 3;'

```
 Comments cannot be used as token concatenators, for example, `abc/**/def` is two tokens, `abc` and `def`, not one `abcdef` token.

 Tokens
------

 
```
Token:
    Identifier
    StringLiteral
    CharacterLiteral
    IntegerLiteral
    FloatLiteral
    Keyword
    /
    /=
    .
    ..
    ...
    &
    &=
    &&
    |
    |=
    ||
    -
    -=
    --
    +
    +=
    ++
    <
    <=
    <<
    <<=
    >
    >=
    >>=
    >>>=
    >>
    >>>
    !
    !=
    (
    )
    [
    ]
    {
    }
    ?
    ,
    ;
    :
    $
    =
    ==
    *
    *=
    %
    %=
    ^
    ^=
    ^^
    ^^=
    ~
    ~=
    @
    =>
    #


```
 Identifiers
-----------

 
```
Identifier:
    IdentifierStart
    IdentifierStart IdentifierChars

IdentifierChars:
    IdentifierChar
    IdentifierChar IdentifierChars

IdentifierStart:
    _
    Letter
    UniversalAlpha

IdentifierChar:
    IdentifierStart
    0
    NonZeroDigit

```
 Identifiers start with a letter, `_`, or universal alpha, and are followed by any number of letters, `_`, digits, or universal alphas. Universal alphas are as defined in ISO/IEC 9899:1999(E) Appendix D of the C99 Standard. Identifiers can be arbitrarily long, and are case sensitive.

 **Implementation Defined:** Identifiers starting with `__` (two underscores) are reserved. String Literals
---------------

 
```
StringLiteral:
    WysiwygString
    AlternateWysiwygString
    DoubleQuotedString

    HexString
    DelimitedString
    TokenString

WysiwygString:
    r" WysiwygCharactersopt " StringPostfixopt

AlternateWysiwygString:
    ` WysiwygCharactersopt ` StringPostfixopt

WysiwygCharacters:
    WysiwygCharacter
    WysiwygCharacter WysiwygCharacters

WysiwygCharacter:
    Character
    EndOfLine

DoubleQuotedString:
    " DoubleQuotedCharactersopt " StringPostfixopt

DoubleQuotedCharacters:
    DoubleQuotedCharacter
    DoubleQuotedCharacter DoubleQuotedCharacters

DoubleQuotedCharacter:
    Character
    EscapeSequence
    EndOfLine

EscapeSequence:
    \'
    \"
    \?
    \\
    \0
    \a
    \b
    \f
    \n
    \r
    \t
    \v
    \x HexDigit HexDigit
    \ OctalDigit
    \ OctalDigit OctalDigit
    \ OctalDigit OctalDigit OctalDigit
    \u HexDigit HexDigit HexDigit HexDigit
    \U HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit
    \ NamedCharacterEntity

HexString:
    x" HexStringCharsopt " StringPostfixopt

HexStringChars:
    HexStringChar
    HexStringChar HexStringChars

HexStringChar:
    HexDigit
    WhiteSpace
    EndOfLine

StringPostfix:
    c
    w
    d

DelimitedString:
    q" Delimiter WysiwygCharactersopt MatchingDelimiter "

TokenString:
    q{ Tokensopt }


```
  A string literal is either a double quoted string, a wysiwyg quoted string, a delimited string, a token string, or a hex string. 

 In all string literal forms, an [*EndOfLine*](#EndOfLine) is regarded as a single `\n` character.

 String literals are read only.

 **Undefined Behavior:** Writes to string literals cannot always be detected, but cause undefined behavior. ### Wysiwyg Strings

  Wysiwyg ("what you see is what you get") quoted strings can be defined using either of two syntaxes. 

  In the first form, they are enclosed between `r"` and `"`. All characters between the `r"` and `"` are part of the string. There are no escape sequences inside wysiwyg strings. 

 
```
r"I am Oz"
r"c:\games\Sudoku.exe"
r"ab\n" // string is 4 characters,
        // 'a', 'b', '\', 'n'

```
  Alternatively, wysiwyg strings can be enclosed by backquotes, using the ` character. 

 
```
`the Great and Powerful.`
`c:\games\Empire.exe`
`The "lazy" dog`
`a"b\n`  // string is 5 characters,
         // 'a', '"', 'b', '\', 'n'

```
 ### Double Quoted Strings

 Double quoted strings are enclosed by "". [*EscapeSequence*](#EscapeSequence)s can be embedded in them.

 
```
"Who are you?"
"c:\\games\\Doom.exe"
"ab\n"   // string is 3 characters,
         // 'a', 'b', and a linefeed
"ab
"        // string is 3 characters,
         // 'a', 'b', and a linefeed

```
 ### Hex Strings

 Hex strings allow string literals to be created using hex data. The hex data need not form valid UTF characters. 

 
```
x"0A"              // same as "\x0A"
x"00 FBCD 32FD 0A" // same as
                   // "\x00\xFB\xCD\x32\xFD\x0A"

```
 Whitespace and newlines are ignored, so the hex data can be easily formatted. The number of hex characters must be a multiple of 2.

 Note: Hex Strings are **deprecated**. Please use [`std.conv.hexString`](https://dlang.org/phobos/std_conv.html#hexString) instead.

 ### Delimited Strings

 Delimited strings use various forms of delimiters. The delimiter, whether a character or identifier, must immediately follow the " without any intervening whitespace. The terminating delimiter must immediately precede the closing " without any intervening whitespace. A *nesting delimiter* nests, and is one of the following characters: 

 

Nesting Delimiters| **Delimiter** | **Matching Delimiter** |
| `[` | `]` |
| ( | ) |
| `<` | `>` |
| `{` | `}` |

 
```
q"(foo(xxx))"   // "foo(xxx)"
q"[foo{]"       // "foo{"

```
 If the delimiter is an identifier, the identifier must be immediately followed by a newline, and the matching delimiter must be the same identifier starting at the beginning of the line: 

 
```
writeln(q"EOS
This
is a multi-line
heredoc string
EOS"
);

```
 The newline following the opening identifier is not part of the string, but the last newline before the closing identifier is part of the string. The closing identifier must be placed on its own line at the leftmost column. 

 Otherwise, the matching delimiter is the same as the delimiter character:

 
```
q"/foo]/"          // "foo]"
// q"/abc/def/"    // error

```
 ### Token Strings

 Token strings open with the characters `q``{` and close with the token `}`. In between must be valid D tokens. The `{` and `}` tokens nest. The string is formed of all the characters between the opening and closing of the token string, including comments. 

 
```
q{this is the voice of} // "this is the voice of"
q{/*}*/ }               // "/*}*/ "
q{ world(q{control}); } // " world(q{control}); "
q{ __TIME__ }           // " __TIME__ "
                        // i.e. it is not replaced with the time
// q{ __EOF__ }         // error
                        // __EOF__ is not a token, it's end of file

```
 ### String Postfix

 The optional *StringPostfix* character gives a specific type to the string, rather than it being inferred from the context. The types corresponding to the postfix characters are: 

 

String Literal Postfix Characters| **Postfix** | **Type** | **Alias** |
| c | `immutable(char)[]` | `string` |
| w | `immutable(wchar)[]` | `wstring` |
| d | `immutable(dchar)[]` | `dstring` |

 
```
"hello"c  // string
"hello"w  // wstring
"hello"d  // dstring

```
 The string literals are assembled as UTF-8 char arrays, and the postfix is applied to convert to wchar or dchar as necessary as a final step.

 Escape Sequences
----------------

 The escape sequences listed in [*EscapeSequence*](#EscapeSequence) are:

 

Escape Sequences| **Sequence** | **Meaning** |
| `'` | Literal single-quote: `'` |
| `"` | Literal double-quote: `"` |
| `?` | Literal question mark: `?` |
| `\` | Literal backslash: 
 |
| `\0` | Binary zero (NUL, U+0000). |
| `\a` | BEL (alarm) character (U+0007). |
| `\b` | Backspace (U+0008). |
| `\f` | Form feed (FF) (U+000C). |
| `\n` | End-of-line (U+000A). |
| `\r` | Carriage return (U+000D). |
| `\t` | Horizontal tab (U+0009). |
| `\v` | Vertical tab (U+000B). |
| `\x`*nn* | Byte value in hexadecimal, where *nn* is specified as two hexadecimal digits.For example: `\xFF` represents the character with the value 255. |
| *n**nn**nnn* | Byte value in octal.For example: `\101` represents the character with the value 65 (`'A'`). Analogous to hexadecimal characters, the largest byte value is `\377` (= `\xFF` in hexadecimal or `255` in decimal) |
| `\u`*nnnn* | Unicode character U+*nnnn*, where *nnnn* are four hexadecimal digits.For example, `\u03B3` represents the Unicode character γ (U+03B3 - GREEK SMALL LETTER GAMMA). |
| `\U`*nnnnnnnn* | Unicode character U+*nnnnnnnn*, where *nnnnnnnn* are 8 hexadecimal digits.For example, `\U0001F603` represents the Unicode character U+1F603 (SMILING FACE WITH OPEN MOUTH). |
| *name* | Named character entity from the HTML5 specification. These names begin with `&` and end with `;` | e.g. | `&`$D(euro;). See [*NamedCharacterEntity*](entity#NamedCharacterEntity). |

 Character Literals
------------------

 
```
CharacterLiteral:
    ' SingleQuotedCharacter '

SingleQuotedCharacter:
    Character
    EscapeSequence

```
 Character literals are a single character or escape sequence enclosed by single quotes.

 
```
'h'   // the letter h
'\n'  // newline
'\\'  // the backslash character

```
 Integer Literals
----------------

 
```
IntegerLiteral:
    Integer
    Integer IntegerSuffix

Integer:
    DecimalInteger
    BinaryInteger
    HexadecimalInteger

IntegerSuffix:
    L
    u
    U
    Lu
    LU
    uL
    UL

DecimalInteger:
    0
    NonZeroDigit
    NonZeroDigit DecimalDigitsUS

BinaryInteger:
    BinPrefix BinaryDigitsNoSingleUS

BinPrefix:
    0b
    0B

HexadecimalInteger:
    HexPrefix HexDigitsNoSingleUS

NonZeroDigit:
    1
    2
    3
    4
    5
    6
    7
    8
    9

DecimalDigits:
    DecimalDigit
    DecimalDigit DecimalDigits

DecimalDigitsUS:
    DecimalDigitUS
    DecimalDigitUS DecimalDigitsUS

DecimalDigitsNoSingleUS:
    DecimalDigit
    DecimalDigit DecimalDigitsUS
    DecimalDigitsUS DecimalDigit

DecimalDigitsNoStartingUS:
    DecimalDigit
    DecimalDigit DecimalDigitsUS

DecimalDigit:
    0
    NonZeroDigit

DecimalDigitUS:
    DecimalDigit
    _

BinaryDigitsNoSingleUS:
    BinaryDigit
    BinaryDigit BinaryDigitsUS
    BinaryDigitsUS BinaryDigit
    BinaryDigitsUS BinaryDigit BinaryDigitsUS

BinaryDigitsUS:
    BinaryDigitUS
    BinaryDigitUS BinaryDigitsUS

BinaryDigit:
    0
    1

BinaryDigitUS:
    BinaryDigit
    _

OctalDigit:
    0
    1
    2
    3
    4
    5
    6
    7

HexDigits:
    HexDigit
    HexDigit HexDigits

HexDigitsUS:
    HexDigitUS
    HexDigitUS HexDigitsUS

HexDigitsNoSingleUS:
    HexDigit
    HexDigit HexDigitsUS
    HexDigitsUS HexDigit

HexDigitsNoStartingUS:
    HexDigit
    HexDigit HexDigitsUS

HexDigit:
    DecimalDigit
    HexLetter

HexDigitUS:
    HexDigit
    _

HexLetter:
    a
    b
    c
    d
    e
    f
    A
    B
    C
    D
    E
    F

```
 Integers can be specified in decimal, binary, or hexadecimal.

 Decimal integers are a sequence of decimal digits.

 Binary integers are a sequence of binary digits preceded by a ‘0b’ or ‘0B’. 

 C-style octal integer notation was deemed too easy to mix up with decimal notation; it is only fully supported in string literals. D still supports octal integer literals interpreted at compile time through the [`std.conv.octal`](https://dlang.org/phobos/std_conv.html#octal) template, as in `octal!167`.

 Hexadecimal integers are a sequence of hexadecimal digits preceded by a ‘0x’ or ‘0X’. 

 Integers can have embedded ‘\_’ characters to improve readability, and which are ignored. 

 
```
20_000        // leagues under the sea
867_5309      // number on the wall
1_522_000     // thrust of F1 engine (lbf sea level)

```
 Integers can be immediately followed by one ‘L’ or one of ‘u’ or ‘U’ or both. Note that there is no ‘l’ suffix. 

 The type of the integer is resolved as follows:

 

Decimal Literal Types| **Literal** | **Type** |
 *Usual decimal notation* || `0 .. 2_147_483_647` | `int` |
| `2_147_483_648 .. 9_223_372_036_854_775_807` | `long` |
| `9_223_372_036_854_775_808 .. 18_446_744_073_709_551_615` | `ulong` |
 *Explicit suffixes* || `0L .. 9_223_372_036_854_775_807L` | `long` |
| `0U .. 4_294_967_295U` | `uint` |
| `4_294_967_296U .. 18_446_744_073_709_551_615U` | `ulong` |
| `0UL .. 18_446_744_073_709_551_615UL` | `ulong` |
 *Hexadecimal notation* || `0x0 .. 0x7FFF_FFFF` | `int` |
| `0x8000_0000 .. 0xFFFF_FFFF` | `uint` |
| `0x1_0000_0000 .. 0x7FFF_FFFF_FFFF_FFFF` | `long` |
| `0x8000_0000_0000_0000 .. 0xFFFF_FFFF_FFFF_FFFF` | `ulong` |
 *Hexadecimal notation with explicit suffixes* || `0x0L .. 0x7FFF_FFFF_FFFF_FFFFL` | `long` |
| `0x8000_0000_0000_0000L .. 0xFFFF_FFFF_FFFF_FFFFL` | `ulong` |
| `0x0U .. 0xFFFF_FFFFU` | `uint` |
| `0x1_0000_0000U .. 0xFFFF_FFFF_FFFF_FFFFU` | `ulong` |
| `0x0UL .. 0xFFFF_FFFF_FFFF_FFFFUL` | `ulong` |

 An integer literal may not exceed these values.

 **Best Practices:** Octal integer notation is not supported for integer literals. However, octal integer literals can be interpreted at compile time through the [`std.conv.octal`](https://dlang.org/phobos/std_conv.html#octal) template, as in `octal!167`. Floating Point Literals
-----------------------

 
```
FloatLiteral:
    Float
    Float Suffix
    Integer FloatSuffix
    Integer ImaginarySuffix
    Integer FloatSuffix ImaginarySuffix
    Integer RealSuffix ImaginarySuffix

Float:
    DecimalFloat
    HexFloat

DecimalFloat:
    LeadingDecimal .
    LeadingDecimal . DecimalDigits
    DecimalDigits . DecimalDigitsNoStartingUS DecimalExponent
    . DecimalInteger
    . DecimalInteger DecimalExponent
    LeadingDecimal DecimalExponent

DecimalExponent
    DecimalExponentStart DecimalDigitsNoSingleUS

DecimalExponentStart
    e
    E
    e+
    E+
    e-
    E-

HexFloat:
    HexPrefix HexDigitsNoSingleUS . HexDigitsNoStartingUS HexExponent
    HexPrefix . HexDigitsNoStartingUS HexExponent
    HexPrefix HexDigitsNoSingleUS HexExponent

HexPrefix:
    0x
    0X

HexExponent:
    HexExponentStart DecimalDigitsNoSingleUS

HexExponentStart:
    p
    P
    p+
    P+
    p-
    P-


Suffix:
    FloatSuffix
    RealSuffix
    ImaginarySuffix
    FloatSuffix ImaginarySuffix
    RealSuffix ImaginarySuffix

FloatSuffix:
    f
    F

RealSuffix:
    L

ImaginarySuffix:
    i

LeadingDecimal:
    DecimalInteger
    0 DecimalDigitsNoSingleUS

```
 Floats can be in decimal or hexadecimal format.

 Hexadecimal floats are preceded by a **0x** or **0X** and the exponent is a **p** or **P** followed by a decimal number serving as the exponent of 2. 

 Floating literals can have embedded ‘\_’ characters to improve readability, and which are ignored. 

 
```
2.645_751
6.022140857E+23
6_022.140857E+20
6_022_.140_857E+20_

```
 Floating literals with no suffix are of type `double`. Floating literals followed by **f** or **F** are of type `float`, and those followed by **L** are of type `real`. 

 If a floating literal is followed by **i**, then it is an *ireal* (imaginary) type. 

 Examples:

 
```
0x1.FFFFFFFFFFFFFp1023 // double.max
0x1p-52                // double.epsilon
1.175494351e-38F       // float.min
6.3i                   // idouble 6.3
6.3fi                  // ifloat 6.3
6.3Li                  // ireal 6.3

```
 The literal may not exceed the range of the type. The literal is rounded to fit into the significant digits of the type. 

 If a floating literal has a **.** and a type suffix, at least one digit must be in-between:

 
```
1f;  // OK, float
1.f; // error
1.;  // OK, double

```
 Keywords
--------

 Keywords are reserved identifiers.

 
```
Keyword:
    abstract
    alias
    align
    asm
    assert
    auto

    body
    bool
    break
    byte

    case
    cast
    catch
    cdouble
    cent
    cfloat
    char
    class
    const
    continue
    creal

    dchar
    debug
    default
    delegate
    delete (deprecated)
    deprecated
    do
    double

    else
    enum
    export
    extern

    false
    final
    finally
    float
    for
    foreach
    foreach_reverse
    function

    goto

    idouble
    if
    ifloat
    immutable
    import
    in
    inout
    int
    interface
    invariant
    ireal
    is

    lazy
    long

    macro (reserved)
    mixin
    module

    new
    nothrow
    null

    out
    override

    package
    pragma
    private
    protected
    public
    pure

    real
    ref
    return

    scope
    shared
    short
    static
    struct
    super
    switch
    synchronized

    template
    this
    throw
    true
    try
    typeid
    typeof

    ubyte
    ucent
    uint
    ulong
    union
    unittest
    ushort

    version
    void

    wchar
    while
    with

    __FILE__
    __FILE_FULL_PATH__
    __MODULE__
    __LINE__
    __FUNCTION__
    __PRETTY_FUNCTION__

    __gshared
    __traits
    __vector
    __parameters

```
 Special Tokens
--------------

  These tokens are replaced with other tokens according to the following table: 

 

Special Tokens| **Special Token** | **Replaced with** |
| `__DATE__` | string literal of the date of compilation "*mmm dd yyyy*" |
| `__EOF__` | tells the scanner to ignore everything after this token |
| `__TIME__` | string literal of the time of compilation "*hh:mm:ss*" |
| `__TIMESTAMP__` | string literal of the date and time of compilation "*www mmm dd hh:mm:ss yyyy*" |
| `__VENDOR__` | Compiler vendor string |
| `__VERSION__` | Compiler version as an integer |

 **Implementation Defined:** The replacement string literal for `__VENDOR__` and the replacement integer value for `__VERSION__`. Special Token Sequences
-----------------------

 
```
SpecialTokenSequence:
    # line IntegerLiteral EndOfLine
    # line IntegerLiteral Filespec EndOfLine

Filespec:
    " Charactersopt "

```
 Special token sequences are processed by the lexical analyzer, may appear between any other tokens, and do not affect the syntax parsing. 

 There is currently only one special token sequence, `#line`. 

 This sets the current source line number to [*IntegerLiteral*](#IntegerLiteral), and optionally the current source file name to [*Filespec*](#Filespec), beginning with the next line of source text. 

 The backslash character is not treated specially inside [*Filespec*](#Filespec) strings. 

 For example: 

 
```
int #line 6 "pkg/mod.d"
x;  // this is now line 6 of file pkg/mod.d

```
 **Implementation Defined:** The source file and line number is typically used for printing error messages and for mapping generated code back to the source for the symbolic debugging output. 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/lex.html>

Interfaces
==========

 **Contents** 1. [Interfaces with Contracts](#interface-contracts)
2. [Const and Immutable Interfaces](#const-interface)
3. [COM Interfaces](#com-interfaces)
4. [C++ Interfaces](#cpp-interfaces)

 An *Interface* describes a list of functions that a class which inherits from the interface must implement.

 
```
InterfaceDeclaration:
    interface Identifier ;
    interface Identifier BaseInterfaceListopt AggregateBody
    InterfaceTemplateDeclaration

BaseInterfaceList:
    : Interfaces

```
 **Implementation Defined:** Specialized interfaces may be supported:

 1. [*COM Interfaces*](#com-interfaces) are binary compatible with COM/OLE/ActiveX objects for Windows.
2. [*C++ Interfaces*](#cpp-interfaces) are binary compatible with C++ abstract classes.
3. [Objective-C Interfaces](objc_interface#protocols) are binary compatible with Objective-C protocols.

 A class that implements an interface can be implicitly converted to a reference to that interface.

 Interfaces cannot derive from classes; only from other interfaces. Classes cannot derive from an interface multiple times. 

 
```
interface D
{
    void foo();
}

class A : D, D  // error, duplicate interface
{
}

```
 An instance of an interface cannot be created.

 
```
interface D
{
    void foo();
}

...

D d = new D();  // error, cannot create instance of interface

```
 Virtual interface member functions do not have implementations. Interfaces are expected to implement static or final functions. 

 
```
interface D
{
    void bar() { }  // error, implementation not allowed
    static void foo() { } // ok
    final void abc() { } // ok
}

```
 Interfaces can have function templates in the members. All instantiated functions are implicitly `final`. 

 
```
interface D
{
    void foo(T)() { }  // ok, it's implicitly final
}

```
 Classes that inherit from an interface may not override final or static interface member functions.

 
```
interface D
{
    void bar();
    static void foo() { }
    final void abc() { }
}

class C : D
{
    void bar() { } // ok
    void foo() { } // error, cannot override static D.foo()
    void abc() { } // error, cannot override final D.abc()
}

```
 All interface functions must be defined in a class that inherits from that interface: 

 
```
interface D
{
    void foo();
}

class A : D
{
    void foo() { }  // ok, provides implementation
}

class B : D
{
    int foo() { }   // error, no void foo() implementation
}

```
 Interfaces can be inherited and functions overridden:

 
```
interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A
{
    int foo() { return 2; }
}

...

B b = new B();
b.foo();            // returns 2
D d = cast(D) b;    // ok since B inherits A's D implementation
d.foo();            // returns 2;

```
 Interfaces can be reimplemented in derived classes:

 
```
interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A, D
{
    int foo() { return 2; }
}

...

B b = new B();
b.foo();            // returns 2
D d = cast(D) b;
d.foo();            // returns 2
A a = cast(A) b;
D d2 = cast(D) a;
d2.foo();           // returns 2, even though it is A's D, not B's D

```
 A reimplemented interface must implement all the interface functions, it does not inherit them from a super class: 

 
```
interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A, D
{
}       // error, no foo() for interface D

```
 Interfaces with Contracts
-------------------------

 Interface member functions can have contracts even though there is no body for the function. The contracts are inherited by any class member function that implements that interface member function. 

 
```
interface I
{
    int foo(int i)
    in { assert(i > 7); }
    out (result) { assert(result & 1); }

    void bar();
}

```
 Const and Immutable Interfaces
------------------------------

 If an interface has `const` or `immutable` storage class, then all members of the interface are `const` or `immutable`. This storage class is not inherited. 

 COM Interfaces
--------------

 A variant on interfaces is the COM interface. A COM interface is designed to map directly onto a Windows COM object. Any COM object can be represented by a COM interface, and any D object with a COM interface can be used by external COM clients. 

 A COM interface is defined as one that derives from the interface `core.stdc.win`­`dows.com.IUnknown`. A COM interface differs from a regular D interface in that: 

 * It derives from the interface `core.stdc.windows.com.IUnknown`.
* It cannot be the argument to [`destroy`](https://dlang.org/phobos/object.html#destroy).
* References cannot be upcast to the enclosing class object, nor can they be downcast to a derived interface. Implement `QueryInterface()` for that interface in standard COM fashion to convert to another COM interface.
* Classes derived from COM interfaces are COM classes.
* The default linkage for member functions of COM classes is `extern(System)`. **Note:** To implement or override any base-class methods of D interfaces or classes (ones which do not inherit from `IUnknown`), explicitly mark them as having the `extern(D)` linkage. 
```
import core.sys.windows.windows;
import core.stdc.windows.com;

interface IText
{
    void write();
}

abstract class Printer : IText
{
    void print() { }
}

class C : Printer, IUnknown
{
    // Implements the IText `write` class method.
    extern(D) void write() { }

    // Overrides the Printer `print` class method.
    extern(D) override void print() { }

    // Overrides the Object base class `toString` method.
    extern(D) override string toString() { return "Class C"; }

    // Methods of class implementing the IUnknown interface have
    // the extern(System) calling convention by default.
    HRESULT QueryInterface(const(IID)*, void**);
    uint AddRef();
    uint Release();
}

```
 The same applies to other `Object` methods such as `opCmp`, `toHash`, etc.
* The first member of the COM `vtbl[]` is not the pointer to the InterfaceInfo, but the first virtual function pointer.

 See also [Modern COM Programming in D](http://www.lunesu.com/uploads/ModernCOMProgramminginD.pdf) 

 C++ Interfaces
--------------

 C++ interfaces are interfaces declared with C++ linkage: 

 
```
extern (C++) interface Ifoo
{
    void foo();
    void bar();
}

```
 which is meant to correspond with the following C++ declaration: 
```
class Ifoo
{
    virtual void foo();
    virtual void bar();
};

```
 Any interface that derives from a C++ interface is also a C++ interface. A C++ interface differs from a D interface in that: 

 * It cannot be the argument to [`destroy`](https://dlang.org/phobos/object.html#destroy).
* References cannot be upcast to the enclosing class object, nor can they be downcast to a derived interface.
* The C++ calling convention is the default convention for its member functions, rather than the D calling convention.
* The first member of the `vtbl[]` is not the pointer to the `Interface`, but the first virtual function pointer.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/interface.html>

Type Qualifiers
===============

 **Contents** 1. [Const and Immutable](#const_and_immutable)
2. [Immutable Storage Class](#immutable_storage_class)
3. [Const Storage Class](#const_storage_class)
4. [Immutable Type](#immutable_type)
5. [Creating Immutable Data](#creating_immutable_data)
6. [Removing Immutable or Const with a Cast](#removing_with_cast)
7. [Immutable Member Functions](#immutable_member_functions)
8. [Const Type](#const_type)
9. [Const Member Functions](#const_member_functions)
10. [Combining Qualifiers](#combining_qualifiers)
11. [Implicit Qualifier Conversions](#implicit_qualifier_conversions)

 Type qualifiers modify a type by applying a [*TypeCtor*](type#TypeCtor). *TypeCtor*s are: `const`, `immutable`, `shared`, and `inout`. Each applies transitively to all subtypes. 

 Const and Immutable
-------------------

 When examining a data structure or interface, it is very helpful to be able to easily tell which data can be expected to not change, which data might change, and who may change that data. This is done with the aid of the language typing system. Data can be marked as const or immutable, with the default being changeable (or *mutable*). 

 `immutable` applies to data that cannot change. Immutable data values, once constructed, remain the same for the duration of the program's execution. Immutable data can be placed in ROM (Read Only Memory) or in memory pages marked by the hardware as read only. Since immutable data does not change, it enables many opportunities for program optimization, and has applications in functional style programming. 

 `const` applies to data that cannot be changed by the const reference to that data. It may, however, be changed by another reference to that same data. Const finds applications in passing data through interfaces that promise not to modify them. 

 Both immutable and const are *transitive*, which means that any data reachable through an immutable reference is also immutable, and likewise for const. 

 Immutable Storage Class
-----------------------

  The simplest immutable declarations use it as a storage class. It can be used to declare manifest constants. 

 
```
immutable int x = 3;  // x is set to 3
x = 4;        // error, x is immutable
char[x] s;    // s is an array of 3 chars

```
 The type can be inferred from the initializer: 

 
```
immutable y = 4; // y is of type int
y = 5;           // error, y is immutable

```
 If the initializer is not present, the immutable can be initialized from the corresponding constructor: 

 
```
immutable int z;
void test()
{
    z = 3; // error, z is immutable
}
static this()
{
    z = 3; // ok, can set immutable that doesn't
           // have static initializer
}

```
  The initializer for a non-local immutable declaration must be evaluatable at compile time: 

 
```
int foo(int f) { return f * 3; }
int i = 5;
immutable x = 3 * 4;      // ok, 12
immutable y = i + 1;      // error, cannot evaluate at compile time
immutable z = foo(2) + 1; // ok, foo(2) can be evaluated at compile time, 7

```
 The initializer for a non-static local immutable declaration is evaluated at run time: 

 
```
int foo(int f)
{
    immutable x = f + 1;  // evaluated at run time
    x = 3;                // error, x is immutable
}

```
  Because immutable is transitive, data referred to by an immutable is also immutable: 

 
```
immutable char[] s = "foo";
s[0] = 'a';  // error, s refers to immutable data
s = "bar";   // error, s is immutable

```
 Immutable declarations can appear as lvalues, i.e. they can have their address taken, and occupy storage. 

 Const Storage Class
-------------------

  A const declaration is exactly like an immutable declaration, with the following differences: 

 * Any data referenced by the const declaration cannot be changed from the const declaration, but it might be changed by other references to the same data.
* The type of a const declaration is itself const.

 Immutable Type
--------------

  Data that will never change its value can be typed as immutable. The immutable keyword can be used as a *type qualifier*: 

 
```
immutable(char)[] s = "hello";

```
  The immutable applies to the type within the following parentheses. So, while `s` can be assigned new values, the contents of `s[]` cannot be: 

 
```
s[0] = 'b';  // error, s[] is immutable
s = null;    // ok, s itself is not immutable

```
  Immutability is transitive, meaning it applies to anything that can be referenced from the immutable type: 

 
```
immutable(char*)** p = ...;
p = ...;        // ok, p is not immutable
*p = ...;       // ok, *p is not immutable
**p = ...;      // error, **p is immutable
***p = ...;     // error, ***p is immutable

```
 Immutable used as a storage class is equivalent to using immutable as a type qualifier for the entire type of a declaration:

 
```
immutable int x = 3;   // x is typed as immutable(int)
immutable(int) y = 3;  // y is immutable

```
 Creating Immutable Data
-----------------------

  The first way is to use a literal that is already immutable, such as string literals. String literals are always immutable. 

 
```
auto s = "hello";   // s is immutable(char)[5]
char[] p = "world"; // error, cannot implicitly convert immutable
                    // to mutable

```
  The second way is to cast data to immutable. When doing so, it is up to the programmer to ensure that any mutable references to the same data are not used to modify the data after the cast. 

 
```
char[] s = ['a'];
s[0] = 'b'; // ok
immutable(char)[] p = cast(immutable)s; // ok, if data is not mutated
                                        // through s anymore
s[0] = 'c'; // undefined behavior
immutable(char)[] q = cast(immutable)s.dup; // always ok, unique reference

char[][] s2 = [['a', 'b'], ['c', 'd']];
immutable(char[][]) p2 = cast(immutable)s2.dup; // dangerous, only the first
                                                // level of elements is unique
s2[0] = ['x', 'y']; // ok, doesn't affect p2
s2[1][0] = 'z'; // undefined behavior
immutable(char[][]) q2 = [s2[0].dup, s2[1].dup]; // always ok, unique references

```
  The `.idup` property is a convenient way to create an immutable copy of an array: 

 
```
auto p = s.idup;
p[0] = ...;       // error, p[] is immutable

```
 Removing Immutable or Const with a Cast
---------------------------------------

  An immutable or const type qualifier can be removed with a cast: 

 
```
immutable int* p = ...;
int* q = cast(int*)p;

```
  This does not mean, however, that one can change the data: 

 
```
*q = 3; // allowed by compiler, but result is undefined behavior

```
  The ability to cast away immutable-correctness is necessary in some cases where the static typing is incorrect and not fixable, such as when referencing code in a library one cannot change. Casting is, as always, a blunt and effective instrument, and when using it to cast away immutable-correctness, one must assume the responsibility to ensure the immutability of the data, as the compiler will no longer be able to statically do so. 

  Note that casting away a const qualifier and then mutating is undefined behavior, too, even when the referenced data is mutable. This is so that compilers and programmers can make assumptions based on const alone. For example, here it may be assumed that `f` does not alter `x`: 

 
```
void f(const int* a);
void main()
{
    int x = 1;
    f(&x);
    assert(x == 1); // guaranteed to hold
}

```
 Immutable Member Functions
--------------------------

  Immutable member functions are guaranteed that the object and anything referred to by the `this` reference is immutable. They are declared as: 

 
```
struct S
{
    int x;

    void foo() immutable
    {
        x = 4;      // error, x is immutable
        this.x = 4; // error, x is immutable
    }
}

```
 Note that using immutable on the left hand side of a method does not apply to the return type: 

 
```
struct S
{
    immutable int[] bar()  // bar is still immutable, return type is not!
    {
    }
}

```
 To make the return type immutable, surround it with parentheses: 

 
```
struct S
{
    immutable(int[]) bar()  // bar is now mutable, return type is immutable.
    {
    }
}

```
 To make both the return type and the method immutable, write: 

 
```
struct S
{
    immutable(int[]) bar() immutable
    {
    }
}

```
 Const Type
----------

  Const types are like immutable types, except that const forms a read-only *view* of data. Other aliases to that same data may change it at any time. 

 Const Member Functions
----------------------

  Const member functions are functions that are not allowed to change any part of the object through the member function's this reference. 

 Combining Qualifiers
--------------------

 More than one qualifier may apply to a type. The order of application is irrelevant, for example given an unqualified type `T`, `const shared T` and `shared const T` are the same type. For that reason, this document depicts qualifier combinations without parentheses unless necessary and in alphabetic order.

 Applying a qualifier to a type that already has that qualifier is legal but has no effect, e.g. given an unqualified type `T`, `shared(const shared T)` yields the type `const shared T`.

 Applying the `immutable` qualifier to any type (qualified or not) results in `immutable T`. Applying any qualifier to `immutable T` results in `immutable T`. This makes `immutable` a fixed point of qualifier combinations and makes types such as `const(immutable(shared T))` impossible to create.

 Assuming `T` is an unqualified type, the graph below illustrates how qualifiers combine (combinations with `immutable` are omitted). For each node, applying the qualifier labeling the edge leads to the resulting type.

 ![Qualifier combination rules] Implicit Qualifier Conversions
------------------------------

 Values that have no mutable indirections (including structs that don't contain any field with mutable indirections) can be implicitly converted across *mutable*, `const`, `immutable`, `const shared`, `inout` and `inout shared`.

 References to qualified objects can be implicitly converted according to the following rules:

 ![Qualifier conversion rules]. The same information is shown below in tabular format:

 

Implicit Conversion of Reference Types| from/to | *mutable* | `const` | `shared` | `const shared` | `inout` | `const inout` | `inout shared` | `const inout shared` | `immutable` |
| *mutable* |  ✔ | ✔ |  |  |  |  |  |  |  |
| `const` |  |  ✔ |  |  |  |  |  |  |  |
| `const inout` |  |  ✔ |  |  |  |  ✔ |  |  |  |
| `const shared` |  |  |  |  ✔ |  |  |  |  |  |
| `const inout shared` |  |  |  |  ✔ |  |  |  |  ✔ |  |
| `immutable` |  |  ✔ |  |  ✔ |  |  ✔ |  |  ✔ | ✔ |
| `inout` |  |  ✔ |  |  |  ✔ | ✔ |  |  |  |
| `shared` |  |  |  ✔ | ✔ |  |  |  |  |  |
| `inout shared` |  |  |  |  ✔ |  |  |  ✔ | ✔ |  |

 If an implicit conversion is disallowed by the table, an [*Expression*](expression#Expression) may be converted if: 

 An expression may be converted from mutable or shared to immutable if the expression is unique and all expressions it transitively refers to are either unique or immutable. 

 An expression may be converted from mutable to shared if the expression is unique and all expressions it transitively refers to are either unique, immutable, or shared. 

 An expression may be converted from immutable to mutable if the expression is unique. 

 An expression may be converted from shared to mutable if the expression is unique. 

 A *Unique Expression* is one for which there are no other references to the value of the expression and all expressions it transitively refers to are either also unique or are immutable. For example:

 
```
void main()
{
    immutable int** p = new int*(null); // ok, unique

    int x;
    immutable int** q = new int*(&x); // error, there may be other references to x

    immutable int y;
    immutable int** r = new immutable(int)*(&y); // ok, y is immutable
}

```
 Otherwise, a [*CastExpression*](expression#CastExpression) can be used to force a conversion when an implicit version is disallowed, but this cannot be done in `@safe` code, and the correctness of it must be verified by the user. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/const3.html>

Contract Programming
====================

 **Contents** 1. [Assert Contract](#assert_contracts)
2. [Pre and Post Contracts](#pre_post_contracts)
3. [Invariants](#Invariants)
4. [References](#references)

 Contracts enable specifying conditions that must hold true when the flow of runtime execution reaches the contract. If a contract is not true, then the program is assumed to have entered an undefined state.

 **Rationale:** Building contract support into the language provides:

 1. a consistent look and feel for the contracts
2. tool support
3. the implementation can generate better code using information gathered from the contracts
4. easier management and enforcement of contracts
5. handling of contract inheritance

 ![Contracts make D bug resistant] Assert Contract
---------------

 See [*AssertExpression*](expression#AssertExpression).

 Pre and Post Contracts
----------------------

 See [contracts](function). 

 Invariants
----------

 See [Struct Invariants](https://dlang.org/struct.html#StructInvariant) and [Class Invariants](https://dlang.org/class.html#invariants).

 References
----------

 * [Contracts Reading List](https://web.archive.org/web/20080919174640/http://people.cs.uchicago.edu/~robby/contract-reading-list/)
* [Adding Contracts to Java](http://jan.newmarch.name/java/contracts/paper-long.html)

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/contracts.html>

Arrays
======

 **Contents** 1. [Kinds](#array-kinds)
	1. [Pointers](#pointers)
	2. [Static Arrays](#static-arrays)
	3. [Dynamic Arrays](#dynamic-arrays)
2. [Array Declarations](#declarations)
3. [Array Usage](#usage)
4. [Indexing](#indexing)
5. [Slicing](#slicing)
6. [Array Copying](#array-copying)
	1. [Overlapping Copying](#overlapping-copying)
7. [Array Setting](#array-setting)
8. [Array Concatenation](#array-concatenation)
9. [Array Operations](#array-operations)
10. [Pointer Arithmetic](#pointer-arithmetic)
11. [Rectangular Arrays](#rectangular-arrays)
12. [Array Length](#array-length)
13. [Array Properties](#array-properties)
	1. [Setting Dynamic Array Length](#resize)
	2. [Functions as Array Properties](#func-as-property)
14. [Array Bounds Checking](#bounds)
	1. [Disabling Array Bounds Checking](#disable-bounds-check)
15. [Array Initialization](#array-initialization)
	1. [Default Initialization](#default-initialization)
	2. [Void Initialization](#void-initialization)
	3. [Static Initialization of Statically Allocated Arrays](#static-init-static)
16. [Special Array Types](#special-array)
	1. [Strings](#strings)
	2. [Void Arrays](#void_arrays)
17. [Implicit Conversions](#implicit-conversions)

 Kinds
-----

 There are four kinds of arrays:

 

Kinds of Arrays| **Syntax** | **Description** |
| *type*\* | [Pointers to data](#pointers) |
| *type*[*integer*] | [Static arrays](#static-arrays) |
| *type*[] | [Dynamic arrays](#dynamic-arrays) |
| *type*[*type*] | [Associative arrays](hash-map) |

 ### Pointers

 
```
int* p;

```
 A pointer to type *T* has a value which is a reference (address) to another object of type *T*. It is commonly called a *pointer to T*. 

 If a pointer contains a *null* value, it is not pointing to a valid object.

 When a pointer to *T* is dereferenced, it must either contain a *null* value, or point to a valid object of type *T*.

 **Implementation Defined:** 1. The behavior when a *null* pointer is dereferenced. Typically the program will be aborted.

 **Undefined Behavior:** 1. Dereferencing a pointer that is not *null* and does not point to a valid object of type *T*.

 **Best Practices:** These are simple pointers to data. Pointers are provided for interfacing with C and for specialized systems work. There is no length associated with it, and so there is no way for the compiler or runtime to do bounds checking, etc., on it. Most conventional uses for pointers can be replaced with dynamic arrays, `out` and `ref` parameters, and reference types. ### Static Arrays

 
```
int[3] s;

```
 Static arrays have a length fixed at compile time. 

 The total size of a static array cannot exceed 16Mb. 

 A static array with a dimension of 0 is allowed, but no space is allocated for it. 

 Static arrays are value types. They are passed to and returned by functions by value. 

 **Best Practices:** 1. Use dynamic arrays for larger arrays.
2. Static arrays with 0 elements are useful as the last member of a variable length struct, or as the degenerate case of a template expansion.
3. Because static arrays are passed to functions by value, a larger array can consume a lot of stack space. Use dynamic arrays instead.

 ### Dynamic Arrays

 
```
int[] a;

```
 Dynamic arrays consist of a length and a pointer to the array data. Multiple dynamic arrays can share all or parts of the array data. 

 **Best Practices:** 1. Use dynamic arrays instead of pointers to arrays as much as practical. Indexing of dynamic arrays are bounds checked, avoiding buffer underflow and overflow problems.

 Array Declarations
------------------

 Declarations appear before the identifier being declared and read right to left, so: 

 
```
int[] a;      // dynamic array of ints
int[4][3] b;  // array of 3 arrays of 4 ints each
int[][5] c;   // array of 5 dynamic arrays of ints.
int*[]*[3] d; // array of 3 pointers to dynamic arrays of pointers to ints
int[]* e;     // pointer to dynamic array of ints

```
 Array Usage
-----------

 There are two broad kinds of operations to do on an array - affecting the handle to the array, and affecting the contents of the array. 

 The handle to an array is specified by naming the array, as in p, s or a: 

 
```
int* p;
int[3] s;
int[] a;

int[] b;

p = s.ptr; // p points to the first element of the array s.
p = a.ptr; // p points to the first element of the array a.

a = p;     // error, since the length of the array pointed
           // to by p is unknown
a = s;     // a is initialized to point to the s array
a = b;     // a points to the same array as b does

```
 Indexing
--------

 See also [*IndexExpression*](expression#IndexExpression).

 Slicing
-------

 *Slicing* an array means to specify a subarray of it. An array slice does not copy the data, it is only another reference to it. For example: 

 
```
void foo(int value)
{
  writeln("value=", value);
}

int[10] a;   // declare array of 10 ints
int[] b;

b = a[1..3]; // a[1..3] is a 2 element array consisting of
             // a[1] and a[2]
foo(b[1]);   // equivalent to foo(0)
a[2] = 3;
foo(b[1]);   // equivalent to foo(3)

```
 The [] is shorthand for a slice of the entire array. For example, the assignments to b: 

 
```
int[10] a = [ 1,2,3,4,5,6,7,8,9,10 ];
int[] b1, b2, b3, b4;

b1 = a;
b2 = a[];
b3 = a[0 .. a.length];
b4 = a[0 .. $];
writeln(b1);
writeln(b2);
writeln(b3);
writeln(b4);


```
 are all semantically equivalent. 

 Slicing is not only handy for referring to parts of other arrays, but for converting pointers into bounds-checked arrays: 

 
```
int[10] a = [ 1,2,3,4,5,6,7,8,9,10 ];

int* p = &a[2];
int[] b = p[0..8];
writeln(b);
writeln(p[7]);      // 10
writeln(p[8]);      // undefined behaviour
writeln(b[7]);      // 10
//writeln(b[8]);    // range error

```
 See also [*SliceExpression*](expression#SliceExpression).

 Array Copying
-------------

 When the slice operator appears as the left-hand side of an assignment expression, it means that the contents of the array are the target of the assignment rather than a reference to the array. Array copying happens when the left-hand side is a slice, and the right-hand side is an array of or pointer to the same type. 

 
```
int[3] s;
int[3] t;

s = t;             // the 3 elements of t are copied into s
s[] = t;           // the 3 elements of t are copied into s
s[] = t[];         // the 3 elements of t are copied into s
s[1..2] = t[0..1]; // same as s[1] = t[0]
s[0..2] = t[1..3]; // same as s[0] = t[1], s[1] = t[2]
s[0..4] = t[0..4]; // error, only 3 elements in s
s[0..2] = t;       // error, operands have different lengths

```
 ### Overlapping Copying

 Overlapping copies are an error:

 
```
s[0..2] = s[1..3]; // error, overlapping copy
s[1..3] = s[0..2]; // error, overlapping copy

```
 Disallowing overlapping makes it possible for more aggressive parallel code optimizations than possible with the serial semantics of C. 

 If overlapping is required, use [`std.algorithm.mutation.copy`](https://dlang.org/phobos/std_algorithm_mutation.html#copy): 

 
```
import std.algorithm;
int[] s = [1, 2, 3, 4];

copy(s[1..3], s[0..2]);
assert(s == [2, 3, 3, 4]);

```
 Array Setting
-------------

 If a slice operator appears as the left-hand side of an assignment expression, and the type of the right-hand side is the same as the element type of the left-hand side, then the array contents of the left-hand side are set to the right-hand side. 

 
```
int[3] s;
int* p;

s[] = 3;     // same as s[0] = 3, s[1] = 3, s[2] = 3
p[0..2] = 3; // same as p[0] = 3, p[1] = 3

```
 Array Concatenation
-------------------

 The binary operator ~ is the *cat* operator. It is used to concatenate arrays: 

 
```
int[] a;
int[] b;
int[] c;

a = b ~ c; // Create an array from the concatenation
           // of the b and c arrays

```
 Many languages overload the + operator to mean concatenation. This confusingly leads to, does: 

 
```
"10" + 3 + 4

```
 produce the number 17, the string "1034" or the string "107" as the result? It isn't obvious, and the language designers wind up carefully writing rules to disambiguate it - rules that get incorrectly implemented, overlooked, forgotten, and ignored. It's much better to have + mean addition, and a separate operator to be array concatenation. 

 Similarly, the ~= operator means append, as in: 

 
```
a ~= b; // a becomes the concatenation of a and b

```
 Concatenation always creates a copy of its operands, even if one of the operands is a 0 length array, so: 

 
```
a = b;           // a refers to b
a = b ~ c[0..0]; // a refers to a copy of b

```
 Appending does not always create a copy, see  [setting dynamic array length](#resize) for details. 

 Array Operations
----------------

 Many array operations, also known as vector operations, can be expressed at a high level rather than as a loop. For example, the loop: 

 
```
T[] a, b;
...
for (size_t i = 0; i < a.length; i++)
    a[i] = b[i] + 4;

```
 assigns to the elements of `a` the elements of `b` with `4` added to each. This can also be expressed in vector notation as: 

 
```
T[] a, b;
...
a[] = b[] + 4;

```
 A vector operation is indicated by the slice operator appearing as the left-hand side of an assignment or an op-assignment expression. The right-hand side can be an expression consisting either of an array slice of the same length and type as the left-hand side or a scalar expression of the element type of the left-hand side, in any combination. 

 
```
T[] a, b, c;
...
a[] -= (b[] + 4) * c[];

```
 The slice on the left and any slices on the right must not overlap. All operands are evaluated exactly once, even if the array slice has zero elements in it. 

 The order in which the array elements are computed is implementation defined, and may even occur in parallel. An application must not depend on this order. 

 Implementation note: Many vector operations are expected to take advantage of any vector math instructions available on the target computer. 

 Pointer Arithmetic
------------------

 
```
int[3] abc;              // static array of 3 ints
int[] def = [ 1, 2, 3 ]; // dynamic array of 3 ints

void dibb(int* array)
{
    array[2];     // means same thing as *(array + 2)
    *(array + 2); // get 3rd element
}

void diss(int[] array)
{
    array[2];     // ok
    *(array + 2); // error, array is not a pointer
}

void ditt(int[3] array)
{
    array[2];     // ok
    *(array + 2); // error, array is not a pointer
}

```
 Rectangular Arrays
------------------

 Experienced FORTRAN numerics programmers know that multidimensional "rectangular" arrays for things like matrix operations are much faster than trying to access them via pointers to pointers resulting from "array of pointers to array" semantics. For example, the D syntax: 

 
```
double[][] matrix;

```
 declares matrix as an array of pointers to arrays. (Dynamic arrays are implemented as pointers to the array data.) Since the arrays can have varying sizes (being dynamically sized), this is sometimes called "jagged" arrays. Even worse for optimizing the code, the array rows can sometimes point to each other! Fortunately, D static arrays, while using the same syntax, are implemented as a fixed rectangular layout in a contiguous block of memory: 

 
```
double[6][3] matrix = 0; // Sets all elements to 0.
writeln(matrix); // [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

```
 Note that dimensions and indices appear in opposite orders. Dimensions in the [declaration](#declarations) are read right to left whereas indices are read left to right: 

 
```
double[6][3] matrix = 0;
matrix[2][5] = 3.14; // Assignment to bottom right element.
writeln(matrix); // [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 3.14]]

static assert(!__traits(compiles, matrix[5][2])); // Array index out of bounds.

```
 Array Length
------------

 Within the [ ] of a static or a dynamic array, the symbol `$` represents the length of the array. 

 
```
int[4] foo;
int[]  bar = foo;
int*   p = &foo[0];

// These expressions are equivalent:
bar[]
bar[0 .. 4]
bar[0 .. $]
bar[0 .. bar.length]


p[0 .. $]      // '&dollar;' is not defined, since p is not an array
bar[0]+$            // '&dollar;' is not defined, out of scope of [ ]

bar[$-1] // retrieves last element of the array

```
 Array Properties
----------------

 Static array properties are:

 

Static Array Properties| **Property** | **Description** |
| `.init` | Returns an array literal with each element of the literal being the `.init` property of the array element type. |
| `.sizeof` | Returns the array length multiplied by the number of bytes per array element. |
| `.length` | Returns the number of elements in the array. This is a fixed quantity for static arrays. It is of type `size_t`. |
| `.ptr` | Returns a pointer to the first element of the array. |
| `.dup` | Create a dynamic array of the same size and copy the contents of the array into it. The copy will have any immutability or const stripped. If this conversion is invalid the call will not compile. |
| `.idup` | Create a dynamic array of the same size and copy the contents of the array into it. The copy is typed as being immutable. If this conversion is invalid the call will not compile. |

 Dynamic array properties are:

 

Dynamic Array Properties| **Property** | **Description** |
| `.init` | Returns `null`. |
| `.sizeof` | Returns the size of the dynamic array reference, which is 8 in 32-bit builds and 16 on 64-bit builds. |
| `.length` | Get/set number of elements in the array. It is of type `size_t`. |
| `.ptr` | Returns a pointer to the first element of the array. |
| `.dup` | Create a dynamic array of the same size and copy the contents of the array into it. The copy will have any immutability or const stripped. If this conversion is invalid the call will not compile. |
| `.idup` | Create a dynamic array of the same size and copy the contents of the array into it. The copy is typed as being immutable. If this conversion is invalid the call will not compile. |

 Examples:

 
```
int* p;
int[3] s;
int[] a;

p.length; // error, length not known for pointer
s.length; // compile time constant 3
a.length; // runtime value

p.dup;    // error, length not known
s.dup;    // creates an array of 3 elements, copies
          // elements s into it
a.dup;    // creates an array of a.length elements, copies
          // elements of a into it

```
 ### Setting Dynamic Array Length

 The `.length` property of a dynamic array can be set as the left-hand side of an = operator: 

 
```
array.length = 7;

```
 This causes the array to be reallocated in place, and the existing contents copied over to the new array. If the new array length is shorter, the array is not reallocated, and no data is copied. It is equivalent to slicing the array:

 
```
array = array[0..7];

```
 If the new array length is longer, the remainder is filled out with the default initializer. 

 To maximize efficiency, the runtime always tries to resize the array in place to avoid extra copying. It will always do a copy if the new size is larger and the array was not allocated via the new operator or resizing in place would overwrite valid data in the array. For example:

 
```
char[] a = new char[20];
char[] b = a[0..10];
char[] c = a[10..20];
char[] d = a;

b.length = 15; // always reallocates because extending in place would
               // overwrite other data in a.
b[11] = 'x';   // a[11] and c[1] are not affected

d.length = 1;
d.length = 20; // also reallocates, because doing this will overwrite a and
               // c

c.length = 12; // may reallocate in place if space allows, because nothing
               // was allocated after c.
c[5] = 'y';    // may affect contents of a, but not b or d because those
               // were reallocated.

a.length = 25; // This always reallocates because if c extended in place,
               // then extending a would overwrite c.  If c didn't
               // reallocate in place, it means there was not enough space,
               // which will still be true for a.
a[15] = 'z';   // does not affect c, because either a or c has reallocated.

```
 To guarantee copying behavior, use the .dup property to ensure a unique array that can be resized. Also, one may use the `.capacity` property to determine how many elements can be appended to the array without reallocating. 

 These issues also apply to appending arrays with the ~= operator. Concatenation using the ~ operator is not affected since it always reallocates. 

 Resizing a dynamic array is a relatively expensive operation. So, while the following method of filling an array: 

 
```
int[] array;
while (1)
{
    import core.stdc.stdio : getchar;
    auto c = getchar;
    if (!c)
        break;
    ++array.length;
    array[array.length - 1] = c;
}

```
 will work, it will be inefficient. A more practical approach would be to minimize the number of resizes: 
```
int[] array;
array.length = 100;        // guess
int i;
for (i = 0; ; i++)
{
    import core.stdc.stdio : getchar;
    auto c = getchar;
    if (!c)
        break;
    if (i == array.length)
        array.length *= 2;
    array[i] = c;
}
array.length = i;

```
 Base selection of the initial size on expected common use cases, which can be determined by instrumenting the code, or simply using good judgement. For example, when gathering user input from the console - it's unlikely to be longer than 80. 

 The `reserve` function expands an array's capacity for use by the append operator.

 
```
int[] array;
size_t cap = array.reserve(10); // request
array ~= [1, 2, 3, 4, 5];
assert(cap >= 10); // allocated may be more than request
assert(cap == array.capacity);

```
 ### Functions as Array Properties

 See [Uniform Function Call Syntax (UFCS)](https://dlang.org/function.html#pseudo-member).

 Array Bounds Checking
---------------------

 It is an error to index an array with an index that is less than 0 or greater than or equal to the array length. If an index is out of bounds, a RangeError exception is raised if detected at runtime, and an error if detected at compile time. A program may not rely on array bounds checking happening, for example, the following program is incorrect: 

 
```
import core.exception;
try
{
    auto array = [1, 2];
    for (auto i = 0; ; i++)
    {
        array[i] = 5;
    }
}
catch (RangeError)
{
    // terminate loop
}

```
 The loop is correctly written: 
```
auto array = [1, 2];
for (auto i = 0; i < array.length; i++)
{
    array[i] = 5;
}

```
 `Implementation Note:` Compilers should attempt to detect array bounds errors at compile time, for example: 

 
```
int[3] foo;
int x = foo[3]; // error, out of bounds

```
 Insertion of array bounds checking code at runtime should be turned on and off with a compile time switch. 

 **Undefined Behavior:** An out of bounds memory access will cause undefined behavior, therefore array bounds check is normally enabled in `@safe` functions. The runtime behavior is part of the language semantics. See also [Safe Functions](https://dlang.org/function.html#safe-functions).

 ### Disabling Array Bounds Checking

 Insertion of array bounds checking code at runtime may be turned off with a compiler switch [`-boundscheck`](https://dlang.org/dmd.html#switch-boundscheck). 

 If the bounds check in `@system` or `@trusted` code is disabled, the code correctness must still be guaranteed by the code author. 

 On the other hand, disabling the bounds check in `@safe` code will break the guaranteed memory safety by compiler. It's not recommended unless motivated by speed measurements. 

 Array Initialization
--------------------

 ### Default Initialization

 * Pointers are initialized to `null`.
* Static array contents are initialized to the default initializer for the array element type.
* Dynamic arrays are initialized to having 0 elements.
* Associative arrays are initialized to having 0 elements.

 ### Void Initialization

 Void initialization happens when the *Initializer* for an array is `void`. What it means is that no initialization is done, i.e. the contents of the array will be undefined. This is most useful as an efficiency optimization. Void initializations are an advanced technique and should only be used when profiling indicates that it matters. 

 to void initialise the elements of dynamic array use [`std.array.uninitializedArray`](https://dlang.org/phobos/std_array.html#uninitializedArray). 

 ### Static Initialization of Statically Allocated Arrays

 Static initalizations are supplied by a list of array element values enclosed in [ ]. The values can be optionally preceded by an index and a :. If an index is not supplied, it is set to the previous index plus 1, or 0 if it is the first value. 

 
```
int[3] a = [ 1:2, 3 ]; // a[0] = 0, a[1] = 2, a[2] = 3

```
 This is most handy when the array indices are given by enums:

 
```
enum Color { red, blue, green }

int[Color.max + 1] value =
  [ Color.blue :6,
    Color.green:2,
    Color.red  :5 ];

```
 These arrays are statically allocated when they appear in global scope. Otherwise, they need to be marked with `const` or `static` storage classes to make them statically allocated arrays.

 Special Array Types
-------------------

 ### Strings

 A string is an array of characters. String literals are just an easy way to write character arrays. String literals are immutable (read only). 

 
```
char[] str1 = "abc";                // error, "abc" is not mutable
char[] str2 = "abc".dup;            // ok, make mutable copy
immutable(char)[] str3 = "abc";     // ok
immutable(char)[] str4 = str1;      // error, str4 is not mutable
immutable(char)[] str5 = str1.idup; // ok, make immutable copy

```
 The name `string` is aliased to `immutable(char)[]`, so the above declarations could be equivalently written as: 

 
```
char[] str1 = "abc";     // error, "abc" is not mutable
char[] str2 = "abc".dup; // ok, make mutable copy
string str3 = "abc";     // ok
string str4 = str1;      // error, str4 is not mutable
string str5 = str1.idup; // ok, make immutable copy

```
 `char[]` strings are in UTF-8 format. `wchar[]` strings are in UTF-16 format. `dchar[]` strings are in UTF-32 format. 

 Strings can be copied, compared, concatenated, and appended:

 
```
str1 = str2;
if (str1 < str3) { ... }
func(str3 ~ str4);
str4 ~= str1;

```
 with the obvious semantics. Any generated temporaries get cleaned up by the garbage collector (or by using `alloca()`). Not only that, this works with any array not just a special String array. 

 A pointer to a char can be generated: 

 
```
char* p = &str[3]; // pointer to 4th element
char* p = str;     // pointer to 1st element

```
 Since strings, however, are not 0 terminated in D, when transferring a pointer to a string to C, add a terminating 0: 

 
```
str ~= "\0";

```
 or use the function `std.string.toStringz`. The type of a string is determined by the semantic phase of compilation. The type is one of: char[], wchar[], dchar[], and is determined by implicit conversion rules. If there are two equally applicable implicit conversions, the result is an error. To disambiguate these cases, a cast or a postfix of `c`, `w` or `d` can be used: 

 
```
cast(immutable(wchar) [])"abc" // this is an array of wchar characters
"abc"w                         // so is this

```
 String literals that do not have a postfix character and that have not been cast can be implicitly converted between string, wstring, and dstring as necessary. 

 
```
char c;
wchar w;
dchar d;

c = 'b';     // c is assigned the character 'b'
w = 'b';     // w is assigned the wchar character 'b'
//w = 'bc';  // error - only one wchar character at a time
w = "b"[0];  // w is assigned the wchar character 'b'
w = "\r"[0]; // w is assigned the carriage return wchar character
d = 'd';     // d is assigned the character 'd'

```
 #### Strings and Unicode

 Note that built-in comparison operators operate on a [code unit](http://www.unicode.org/glossary/#code_unit) basis. The end result for valid strings is the same as that of [code point](http://www.unicode.org/glossary/#code_point) for [code point](http://www.unicode.org/glossary/#code_point) comparison as long as both strings are in the same [normalization form](http://www.unicode.org/glossary/#normalization_form). Since normalization is a costly operation not suitable for language primitives it's assumed to be enforced by the user. 

 The standard library lends a hand for comparing strings with mixed encodings (by transparently decoding, see [`std.algorithm.cmp`](https://dlang.org/phobos/std_algorithm.html#cmp)), [case-insensitive comparison](https://dlang.org/phobos/std_uni.html#icmp) and [normalization](https://dlang.org/phobos/std_uni.html#normalize). 

 Last but not least, a desired string sorting order differs by culture and language and is usually nothing like code point for code point comparison. The natural order of strings is obtained by applying [the Unicode collation algorithm](http://www.unicode.org/reports/tr10/) that should be implemented in the standard library. 

 #### C's printf() and Strings

 `printf()` is a C function and is not part of D. `printf()` will print C strings, which are 0 terminated. There are two ways to use `printf()` with D strings. The first is to add a terminating 0, and cast the result to a char\*: 

 
```
str ~= "\0";
printf("the string is '%s'\n", str.ptr);

```
 or: 
```
import std.string;
printf("the string is '%s'\n", std.string.toStringz(str));

```
 String literals already have a 0 appended to them, so can be used directly:

 
```
printf("the string is '%s'\n", "string literal".ptr);

```
 So, why does the first string literal to printf not need the `.ptr`? The first parameter is prototyped as a `const(char)*`, and a string literal can be implicitly `cast` to a `const(char)*`. The rest of the arguments to printf, however, are variadic (specified by ...), and a string literal typed `immutable(char)[]` cannot pass to variadic parameters.

 The second way is to use the precision specifier. The length comes first, followed by the pointer:

 
```
printf("the string is '%.*s'\n", str.length, str.ptr);

```
 The best way is to use std.stdio.writefln, which can handle D strings:

 
```
import std.stdio;
writefln("the string is '%s'", str);

```
 ### Void Arrays

 There is a special type of array which acts as a wildcard that can hold arrays of any kind, declared as `void[]`. Void arrays are used for low-level operations where some kind of array data is being handled, but the exact type of the array elements are unimportant. The `.length` of a void array is the length of the data in bytes, rather than the number of elements in its original type. Array indices in indexing and slicing operations are interpreted as byte indices.

 Arrays of any type can be implicitly converted to a void array; the compiler inserts the appropriate calculations so that the `.length` of the resulting array's size is in bytes rather than number of elements. Void arrays cannot be converted back to the original type without using a cast, and it is an error to convert to an array type whose element size does not evenly divide the length of the void array.

 
```
void main()
{
    int[] data1 = [1,2,3];
    long[] data2;

    void[] arr = data1;            // OK, int[] implicit converts to void[].
    assert(data1.length == 3);
    assert(arr.length == 12);      // length is implicitly converted to bytes.

    //data1 = arr;                 // Illegal: void[] does not implicitly
                                   // convert to int[].
    int[] data3 = cast(int[]) arr; // OK, can convert with explicit cast.
    data2 = cast(long[]) arr;      // Runtime error: long.sizeof == 8, which
                                   // does not divide arr.length, which is 12
                                   // bytes.
}

```
 Void arrays can also be static if their length is known at compile-time. The length is specified in bytes:

 
```
void main()
{
    byte[2] x;
    int[2] y;

    void[2] a = x; // OK, lengths match
    void[2] b = y; // Error: int[2] is 8 bytes long, doesn't fit in 2 bytes.
}

```
 While it may seem that void arrays are just fancy syntax for `ubyte[]`, there is a subtle distinction. The garbage collector generally will not scan `ubyte[]` arrays for pointers, `ubyte[]` being presumed to contain only pure byte data, not pointers. However, it *will* scan `void[]` arrays for pointers, since such an array may have been implicitly converted from an array of pointers or an array of elements that contain pointers. Allocating an array that contains pointers as `ubyte[]` may run the risk of the GC collecting live memory if these pointers are the only remaining references to their targets.

 Implicit Conversions
--------------------

 A pointer `T*` can be implicitly converted to one of the following:

 * `void*`

 A static array `T[dim]` can be implicitly converted to one of the following: 

 * `T[]`
* `const(U)[]`
* `const(U[])`
* `void[]`

 A dynamic array `T[]` can be implicitly converted to one of the following (`U` is a base class of `T`):

 * `const(U)[]`
* `const(U[])`
* `void[]`

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/arrays.html>

Associative Arrays
==================

 **Contents** 1. [Removing Keys](#removing_keys)
2. [Testing Membership](#testing_membership)
3. [Using Classes as the KeyType](#using_classes_as_key)
4. [Using Structs or Unions as the KeyType](#using_struct_as_key)
5. [Construction or Assignment on Setting AA Entries](#construction_assignment_entries)
6. [Inserting if not present](#inserting_if_not_present)
7. [Advanced updating](#advanced_updating)
8. [Static Initialization of AAs](#static_initialization)
9. [Runtime Initialization of Immutable AAs](#runtime_initialization)
10. [Construction and Reference Semantics](#construction_and_ref_semantic)
11. [Properties](#properties)
	1. [Associative Array Example: word count](#aa_example)
	2. [Associative Array Example: counting Tuples](#aa_example_iteration)

 Associative arrays have an index that is not necessarily an integer, and can be sparsely populated. The index for an associative array is called the *key*, and its type is called the *KeyType*.

 Associative arrays are declared by placing the *KeyType* within the `[ ]` of an array declaration: 

 
```
int[string] aa;   // Associative array of ints that are
                  // indexed by string keys.
                  // The KeyType is string.
aa["hello"] = 3;  // set value associated with key "hello" to 3
int value = aa["hello"];  // lookup value from a key
assert(value == 3);

```
 Neither the *KeyType*s nor the element types of an associative array can be function types or `void`. 

 **Implementation Defined:** The built-in associative arrays do not preserve the order of the keys inserted into the array. In particular, in a `foreach` loop the order in which the elements are iterated is typically unspecified. Removing Keys
-------------

 Particular keys in an associative array can be removed with the `remove` function: 

 
```
aa.remove("hello");

```
 `remove(key)` does nothing if the given *key* does not exist and returns `false`. If the given *key* does exist, it removes it from the AA and returns `true`. 

 All keys can be removed by using the method `clear`.

 Testing Membership
------------------

 The [*InExpression*](expression#InExpression) yields a pointer to the value if the key is in the associative array, or `null` if not: 

 
```
int* p;

p = ("hello" in aa);
if (p !is null)
{
    *p = 4;  // update value associated with key
    assert(aa["hello"] == 4);
}

```
 **Undefined Behavior:** Adjusting the pointer to point before or after the element whose address is returned, and then dereferencing it. Using Classes as the KeyType
----------------------------

 Classes can be used as the *KeyType*. For this to work, the class definition must override the following member functions of class `Object`:

 * `size_t toHash() @trusted nothrow`
* `bool opEquals(Object)`

 Note that the parameter to `opEquals` is of type `Object`, not the type of the class in which it is defined.

 For example:

 
```
class Foo
{
    int a, b;

    override size_t toHash() { return a + b; }

    override bool opEquals(Object o)
    {
        Foo foo = cast(Foo) o;
        return foo && a == foo.a && b == foo.b;
    }
}

```
 **Implementation Defined:** `opCmp` is not used to check for equality by the associative array. However, since the actual `opEquals` or `opCmp` called is not decided until runtime, the compiler cannot always detect mismatched functions. Because of legacy issues, the compiler may reject an associative array key type that overrides `opCmp` but not `opEquals`. This restriction may be removed in future versions. **Undefined Behavior:** 1. If `toHash` must consistently be the same value when `opEquals` returns true. In other words, two objects that are considered equal should always have the same hash value. Otherwise, undefined behavior will result.

 **Best Practices:** 1. Use the attributes `@safe`, `@nogc`, `pure`, `const`, and `scope` as much as possible on the `toHash` and `opEquals` overrides.

 Using Structs or Unions as the KeyType
--------------------------------------

 If the *KeyType* is a struct or union type, a default mechanism is used to compute the hash and comparisons of it based on the fields of the struct value. A custom mechanism can be used by providing the following functions as struct members: 

 
```
size_t toHash() const @safe pure nothrow;
bool opEquals(ref const typeof(this) s) const @safe pure nothrow;

```
 For example:

 
```
import std.string;

struct MyString
{
    string str;

    size_t toHash() const @safe pure nothrow
    {
        size_t hash;
        foreach (char c; str)
            hash = (hash * 9) + c;
        return hash;
    }

    bool opEquals(ref const MyString s) const @safe pure nothrow
    {
        return std.string.cmp(this.str, s.str) == 0;
    }
}

```
 The functions can use `@trusted` instead of `@safe`.

 **Implementation Defined:** `opCmp` is not used to check for equality by the associative array. For this reason, and for legacy reasons, an associative array key is not allowed to define a specialized `opCmp`, but omit a specialized `opEquals`. This restriction may be removed in future versions of D. **Undefined Behavior:** 1. If `toHash` must consistently be the same value when `opEquals` returns true. In other words, two structs that are considered equal should always have the same hash value. Otherwise, undefined behavior will result.

 **Best Practices:** 1. Use the attributes `@nogc` as much as possible on the `toHash` and `opEquals` overrides.

 Construction or Assignment on Setting AA Entries
------------------------------------------------

 When an AA indexing access appears on the left side of an assignment operator, it is specially handled for setting an AA entry associated with the key.

 
```
string[int] aa;
string s;
s = aa[1];          // throws RangeError in runtime
aa[1] = "hello";    // handled for setting AA entry
s = aa[1];          // succeeds to lookup
assert(s == "hello");

```
 If the assigned value type is equivalent with the AA element type:

 1. If the indexing key does not yet exist in AA, a new AA entry will be allocated, and it will be initialized with the assigned value.
2. If the indexing key already exists in the AA, the setting runs normal assignment.

 
```
struct S
{
    int val;
    void opAssign(S rhs) { this.val = rhs.val * 2; }
}
S[int] aa;
aa[1] = S(10);  // first setting initializes the entry aa[1]
assert(aa[1].val == 10);
aa[1] = S(10);  // second setting invokes normal assignment, and
                // operator-overloading rewrites it to member opAssign function.
assert(aa[1].val == 20);

```
 If the assigned value type is **not** equivalent with the AA element type, the expression could invoke operator overloading with normal indexing access:

 
```
struct S
{
    int val;
    void opAssign(int v) { this.val = v * 2; }
}
S[int] aa;
aa[1] = 10;     // is rewritten to: aa[1].opAssign(10), and
                // throws RangeError before opAssign is called

```
 However, if the AA element type is a struct which supports an implicit constructor call from the assigned value, implicit construction is used for setting the AA entry:

 
```
struct S
{
    int val;
    this(int v) { this.val = v; }
    void opAssign(int v) { this.val = v * 2; }
}
S s = 1;    // OK, rewritten to: S s = S(1);
  s = 1;    // OK, rewritten to: s.opAssign(1);

S[int] aa;
aa[1] = 10; // first setting is rewritten to: aa[1] = S(10);
assert(aa[1].val == 10);
aa[1] = 10; // second setting is rewritten to: aa[1].opAssign(10);
assert(aa[1].val == 20);

```
 This is designed for efficient memory reuse with some value-semantics structs, eg. [`std.bigint.BigInt`](https://dlang.org/phobos/std_bigint.html#BigInt). 
```
import std.bigint;
BigInt[string] aa;
aa["a"] = 10;   // construct BigInt(10) and move it in AA
aa["a"] = 20;   // call aa["a"].opAssign(20)

```
 Inserting if not present
------------------------

 When AA access requires that there must be a value corresponding to the key, a value must be constructed and inserted if not present. The `require` function provides a means to construct a new value via a lazy argument. The lazy argument is evaluated when the key is not present. The `require` operation avoids the need to perform multiple key lookups.

 
```
class C{}
C[string] aa;

auto a = aa.require("a", new C);   // lookup "a", construct if not present

```
 Sometimes it is necessary to know whether the value was constructed or already exists. The `require` function doesn't provide a boolean parameter to indicate whether the value was constructed but instead allows the construction via a function or delegate. This allows the use of any mechanism as demonstrated below.

 
```
class C{}
C[string] aa;

bool constructed;
auto a = aa.require("a", { constructed=true; return new C;}());
assert(constructed == true);

C newc;
auto b = aa.require("b", { newc = new C; return newc;}());
assert(b is newc);

```
 Advanced updating
-----------------

 Typically updating a value in an associative array is simply done with an assign statement.

 
```
int[string] aa;

aa["a"] = 3;  // set value associated with key "a" to 3

```
 Sometimes it is necessary to perform different operations depending on whether a value already exists or needs to be constructed. The `update` function provides a means to construct a new value via the `create` delegate or update an existing value via the `update` delegate. The `update` operation avoids the need to perform multiple key lookups.

 
```
class C{}
C[string] aa;

C older;
C newer;
aa.update("a",
{
    newer = new C;
    return newer;
},
(ref C c)
{
    older = c;
    newer = new C;
    return newer;
});

```
 Static Initialization of AAs
----------------------------

 NOTE: Not yet implemented. 
```
immutable long[string] aa = [
  "foo": 5,
  "bar": 10,
  "baz": 2000
];

unittest
{
    assert(aa["foo"] == 5);
    assert(aa["bar"] == 10);
    assert(aa["baz"] == 2000);
}

```
 Runtime Initialization of Immutable AAs
---------------------------------------

 Immutable associative arrays are often desirable, but sometimes initialization must be done at runtime. This can be achieved with a constructor (static constructor depending on scope), a buffer associative array and `assumeUnique`:

 
```
immutable long[string] aa;

shared static this()
{
    import std.exception : assumeUnique;
    import std.conv : to;

    long[string] temp; // mutable buffer
    foreach(i; 0 .. 10)
    {
        temp[to!string(i)] = i;
    }
    temp.rehash; // for faster lookups

    aa = assumeUnique(temp);
}

unittest
{
    assert(aa["1"] == 1);
    assert(aa["5"] == 5);
    assert(aa["9"] == 9);
}

```
 Construction and Reference Semantics
------------------------------------

 An Associative Array defaults to `null`, and is constructed upon assigning the first key/value pair. However, once constructed, an associative array has *reference semantics*, meaning that assigning one array to another does not copy the data. This is especially important when attempting to create multiple references to the same array.

 
```
int[int] aa;             // defaults to null
int[int] aa2 = aa;       // copies the null reference
aa[1] = 1;
assert(aa2.length == 0); // aa2 still is null
aa2 = aa;
aa2[2] = 2;
assert(aa[2] == 2);      // now both refer to the same instance

```
 Properties
----------

 Properties for associative arrays are:

 

Associative Array Properties| **Property** | **Description** |
| `.sizeof` | Returns the size of the reference to the associative array; it is 4 in 32-bit builds and 8 on 64-bit builds. |
| `.length` | Returns number of values in the associative array. Unlike for dynamic arrays, it is read-only. |
| `.dup` | Create a new associative array of the same size and copy the contents of the associative array into it. |
| `.keys` | Returns dynamic array, the elements of which are the keys in the associative array. |
| `.values` | Returns dynamic array, the elements of which are the values in the associative array. |
| `.rehash` | Reorganizes the associative array in place so that lookups are more efficient. `rehash` is effective when, for example, the program is done loading up a symbol table and now needs fast lookups in it. Returns a reference to the reorganized array. |
| `.clear` | Removes all remaining keys and values from an associative array. The array is not rehashed after removal, to allow for the existing storage to be reused. This will affect all references to the same instance and is not equivalent to `destroy(aa)` which only sets the current reference to `null` |
| `.byKey()` | Returns a forward range suitable for use as a *ForeachAggregate* to a [*ForeachStatement*](statement#ForeachStatement) which will iterate over the keys of the associative array. |
| `.byValue()` | Returns a forward range suitable for use as a *ForeachAggregate* to a [*ForeachStatement*](statement#ForeachStatement) which will iterate over the values of the associative array. |
| `.byKeyValue()` | Returns a forward range suitable for use as a *ForeachAggregate* to a  [*ForeachStatement*](statement#%20%20%20%20%20%20%20%20ForeachStatement) which will iterate over key-value pairs of the associative array. The returned pairs are represented by an opaque type with `.key` and `.value` properties for accessing the key and value of the pair, respectively. Note that this is a low-level interface to iterating over the associative array and is not compatible with the [`Tuple`](https://dlang.org/phobos/std_typecons.html#Tuple) type in Phobos. For compatibility with `Tuple`, use [std.array.byPair](https://dlang.org/phobos/std_array.html#byPair) instead. |
| `.get(Key key, lazy Value defVal)` |  Looks up `key`; if it exists returns corresponding value else evaluates and returns `defVal`. |
| `.require(Key key, lazy Value value)` |  Looks up `key`; if it exists returns corresponding value else evaluates `value`, adds it to the associative array and returns it. |
| `.update(Key key, Value delegate() create, Value delegate(Value) update)` |  Looks up `key`; if it exists applies the `update` delegate else evaluates the `create` delegate and adds it to the associative array |

 

---

 ### Associative Array Example: word count

 Let's consider the file is ASCII encoded with LF EOL. In general case we should use *dchar c* for iteration over code points and functions from [std.uni](https://dlang.org/phobos/std_uni.html). 

 
```
import std.file;         // D file I/O
import std.stdio;
import std.ascii;

void main (string[] args)
{
    ulong totalWords, totalLines, totalChars;
    ulong[string] dictionary;

    writeln("   lines   words   bytes file");
    foreach (arg; args[1 .. $]) // for each argument except the first one
    {
        ulong wordCount, lineCount, charCount;

        foreach(line; File(arg).byLine())
        {
            bool inWord;
            size_t wordStart;

            void tryFinishWord(size_t wordEnd)
            {
                if (inWord)
                {
                    auto word = line[wordStart .. wordEnd];
                    ++dictionary[word.idup];   // increment count for word
                    inWord = false;
                }
            }

            foreach (i, char c; line)
            {
                if (std.ascii.isDigit(c))
                {
                    // c is a digit (0..9)
                }
                else if (std.ascii.isAlpha(c))
                {
                    // c is an ASCII letter (A..Z, a..z)
                    if (!inWord)
                    {
                        wordStart = i;
                        inWord = true;
                        ++wordCount;
                    }
                }
                else
                    tryFinishWord(i);
                ++charCount;
            }
            tryFinishWord(line.length);
            ++lineCount;
        }

        writefln("%8s%8s%8s %s", lineCount, wordCount, charCount, arg);
        totalWords += wordCount;
        totalLines += lineCount;
        totalChars += charCount;
    }

    if (args.length > 2)
    {
        writefln("-------------------------------------\n%8s%8s%8s total",
                 totalLines, totalWords, totalChars);
    }

    writeln("-------------------------------------");
    foreach (word; dictionary.keys.sort)
    {
        writefln("%3s %s", dictionary[word], word);
    }
}

```
 ### Associative Array Example: counting Tuples

 An Associative Array can be iterated in key/value fashion using a [foreach statement](statement#ForeachStatement). As an example, the number of occurrences of all possible substrings of length 2 (aka 2-mers) in a string will be counted:

 
```
import std.range : dropOne, only, save, zip;
import std.stdio : writefln;
import std.typecons : Tuple;
import std.utf : byCodeUnit; // avoids UTF-8 auto-decoding

int[Tuple!(immutable char, immutable char)] aa;

// The string `arr` has a limited alphabet: {A, C, G, T}
// Thus, for better performance, iteration can be done _without_ decoding
auto arr = "AGATAGA".byCodeUnit;

// iterate over all pairs in the string and observe each pair
// ('A', 'G'), ('G', 'A'), ('A', 'T'), ...
foreach (window; arr.zip(arr.save.dropOne))
    aa[window]++;

// iterate over all key/value pairs of the Associative Array
foreach (key, value; aa)
{
    // the second parameter uses tuple-expansion
    writefln("key: %s [%s], value: %d", key, key.expand.only, value);
}

```
 
```
% rdmd count.d
key: Tuple!(immutable(char), immutable(char))('A', 'G') [AG], value: 2
key: Tuple!(immutable(char), immutable(char))('G', 'A') [GA], value: 2
key: Tuple!(immutable(char), immutable(char))('A', 'T') [AT], value: 1
key: Tuple!(immutable(char), immutable(char))('T', 'A') [TA], value: 1

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/hash-map.html>

Template Mixins
===============

 **Contents** 1. [Mixin Scope](#mixin_scope)

 A *TemplateMixin* takes an arbitrary set of declarations from the body of a *TemplateDeclaration* and inserts them into the current context.

 
```
TemplateMixinDeclaration:
    mixin template Identifier TemplateParameters Constraintopt { DeclDefsopt }

TemplateMixin:
    mixin MixinTemplateName TemplateArgumentsopt Identifieropt ;

MixinTemplateName:
    . MixinQualifiedIdentifier
    MixinQualifiedIdentifier
    Typeof . MixinQualifiedIdentifier

MixinQualifiedIdentifier:
    Identifier
    Identifier . MixinQualifiedIdentifier
    TemplateInstance . MixinQualifiedIdentifier

```
 A *TemplateMixin* can occur in declaration lists of modules, classes, structs, unions, and as a statement. The *MixinTemplateName* refers to a *TemplateDeclaration* or *TemplateMixinDeclaration*. If the *TemplateDeclaration* has no parameters, the mixin form that has no !(*TemplateArgumentList*) can be used. 

 Unlike a template instantiation, a template mixin's body is evaluated within the scope where the mixin appears, not where the template declaration is defined. It is analogous to cutting and pasting the body of the template into the location of the mixin into a [nested scope](#mixin_scope). It is useful for injecting parameterized ‘boilerplate’ code, as well as for creating templated nested functions, which is not possible with template instantiations. 

 
```
mixin template Foo()
{
    int x = 5;
}

mixin Foo;

struct Bar
{
    mixin Foo;
}

void test()
{
    writefln("x = %d", x);         // prints 5
    {
        Bar b;
        int x = 3;

        writefln("b.x = %d", b.x); // prints 5
        writefln("x = %d", x);     // prints 3
        {
            mixin Foo;
            writefln("x = %d", x); // prints 5
            x = 4;
            writefln("x = %d", x); // prints 4
        }
        writefln("x = %d", x);     // prints 3
    }
    writefln("x = %d", x);         // prints 5
}

```
 Mixins can be parameterized:

 
```
mixin template Foo(T)
{
    T x = 5;
}

mixin Foo!(int);           // create x of type int

```
 Mixins can add virtual functions to a class:

 
```
mixin template Foo()
{
    void func() { writeln("Foo.func()"); }
}

class Bar
{
    mixin Foo;
}

class Code : Bar
{
    override void func() { writeln("Code.func()"); }
}

void test()
{
    Bar b = new Bar();
    b.func();      // calls Foo.func()

    b = new Code();
    b.func();      // calls Code.func()
}

```
 Mixins are evaluated in the scope of where they appear, not the scope of the template declaration:

 
```
int y = 3;

mixin template Foo()
{
    int abc() { return y; }
}

void test()
{
    int y = 8;
    mixin Foo; // local y is picked up, not global y
    assert(abc() == 8);
}

```
 Mixins can parameterize symbols using alias parameters:

 
```
mixin template Foo(alias b)
{
    int abc() { return b; }
}

void test()
{
    int y = 8;
    mixin Foo!(y);
    assert(abc() == 8);
}

```
 This example uses a mixin to implement a generic Duff's device for an arbitrary statement (in this case, the arbitrary statement is in bold). A nested function is generated as well as a delegate literal, these can be inlined by the compiler:

 
```
mixin template duffs_device(alias id1, alias id2, alias s)
{
    void duff_loop()
    {
        if (id1 < id2)
        {
            typeof(id1) n = (id2 - id1 + 7) / 8;
            switch ((id2 - id1) % 8)
            {
                case 0: do { s(); goto case;
                case 7:      s(); goto case;
                case 6:      s(); goto case;
                case 5:      s(); goto case;
                case 4:      s(); goto case;
                case 3:      s(); goto case;
                case 2:      s(); goto case;
                case 1:      s(); continue;
                default:     assert(0, "Impossible");
                        } while (--n > 0);
            }
        }
    }
}

void foo() { writeln("foo"); }

void test()
{
    int i = 1;
    int j = 11;

    mixin duffs_device!(i, j, delegate { foo(); });
    duff_loop();  // executes foo() 10 times
}

```
 Mixin Scope
-----------

 The declarations in a mixin are placed in a nested scope and then ‘imported’ into the surrounding scope. If the name of a declaration in a mixin is the same as a declaration in the surrounding scope, the surrounding declaration overrides the mixin one:

 
```
int x = 3;

mixin template Foo()
{
    int x = 5;
    int y = 5;
}

mixin Foo;
int y = 3;

void test()
{
    writefln("x = %d", x);  // prints 3
    writefln("y = %d", y);  // prints 3
}

```
 If two different mixins are put in the same scope, and each define a declaration with the same name, there is an ambiguity error when the declaration is referenced:

 
```
mixin template Foo()
{
    int x = 5;
    void func(int x) { }
}

mixin template Bar()
{
    int x = 4;
    void func(long x) { }
}

mixin Foo;
mixin Bar;

void test()
{
    import std.stdio : writefln;
    writefln("x = %d", x); // error, x is ambiguous
    func(1);               // error, func is ambiguous
}

```
 The call to `func()` is ambiguous because Foo.func and Bar.func are in different scopes. 

 If a mixin has an *Identifier*, it can be used to disambiguate between conflicting symbols: 

 
```
int x = 6;

mixin template Foo()
{
    int x = 5;
    int y = 7;
    void func() { }
}

mixin template Bar()
{
    int x = 4;
    void func() { }
}

mixin Foo F;
mixin Bar B;

void test()
{
    writefln("y = %d", y);     // prints 7
    writefln("x = %d", x);     // prints 6
    writefln("F.x = %d", F.x); // prints 5
    writefln("B.x = %d", B.x); // prints 4
    F.func();                  // calls Foo.func
    B.func();                  // calls Bar.func
}

```
 Alias declarations can be used to overload together functions declared in different mixins:

 
```
mixin template Foo()
{
    void func(int x) {  }
}

mixin template Bar()
{
    void func(long x) {  }
}

mixin Foo!() F;
mixin Bar!() B;

alias func = F.func;
alias func = B.func;

void main()
{
    func(1);  // calls B.func
    func(1L); // calls F.func
}

```
 A mixin has its own scope, even if a declaration is overridden by the enclosing one:

 
```
int x = 4;

mixin template Foo()
{
    int x = 5;
    int bar() { return x; }
}

mixin Foo;

void test()
{
    writefln("x = %d", x);         // prints 4
    writefln("bar() = %d", bar()); // prints 5
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/template-mixin.html>

Classes
=======

 **Contents** 1. [Access Control](#access_control)
2. [Fields](#fields)
3. [Field Properties](#field_properties)
4. [Class Properties](#class_properties)
5. [Super Class](#super_class)
6. [Member Functions (a.k.a. Methods)](#member-functions)
	1. [Objective-C linkage](#objc-member-functions)
7. [Synchronized Classes](#synchronized-classes)
8. [Constructors](#constructors)
	1. [Delegating Constructors](#delegating-constructors)
	2. [Implicit Base Class Construction](#implicit-base-construction)
	3. [Class Instantiation](#class-instantiation)
	4. [Constructor Attributes](#constructor-attributes)
	5. [Field initialization inside a constructor](#field-init)
9. [Destructors](#destructors)
10. [Static Constructors](#static-constructor)
11. [Static Destructors](#static-destructor)
12. [Shared Static Constructors](#shared_static_constructors)
13. [Shared Static Destructors](#shared_static_destructors)
14. [Class Invariants](#invariants)
15. [Class Allocators](#allocators)
16. [Class Deallocators](#deallocators)
17. [Alias This](#alias-this)
18. [Scope Classes](#auto)
19. [Final Classes](#final)
20. [Nested Classes](#nested)
	1. [Static Nested Classes](#static-nested)
	2. [Context Pointer](#nested-context)
	3. [Explicit Instantiation](#nested-explicit)
	4. [`outer` Property](#outer-property)
	5. [Anonymous Nested Classes](#anonymous)
21. [Const, Immutable and Shared Classes](#const-class)

 The object-oriented features of D all come from classes. The class hierarchy has as its root the class Object. Object defines a minimum level of functionality that each derived class has, and a default implementation for that functionality. 

 Classes are programmer defined types. Support for classes are what make D an object oriented language, giving it encapsulation, inheritance, and polymorphism. D classes support the single inheritance paradigm, extended by adding support for interfaces. Class objects are instantiated by reference only. 

 A class can be exported, which means its name and all its non-private members are exposed externally to the DLL or EXE. 

 A class declaration is defined: 

 
```
ClassDeclaration:
    class Identifier ;
    class Identifier BaseClassListopt AggregateBody
    ClassTemplateDeclaration

BaseClassList:
    : SuperClass
    : SuperClass , Interfaces
    : Interfaces

SuperClass:
    BasicType

Interfaces:
    Interface
    Interface , Interfaces

Interface:
    BasicType

```
 Classes consist of:

 * a super class
* interfaces
* a nested anonymous metaclass for classes declared with `extern (Objective-C)`
* dynamic fields
* static fields
* types
* [an optional synchronized attribute](#synchronized-classes)
* [member functions](#member-functions)
	+ static member functions
	+ [Virtual Functions](function#virtual-functions)
	+ [Constructors](#constructors)
	+ [Destructors](#destructors)
	+ [Static Constructors](#static-constructor)
	+ [Static Destructors](#static-destructor)
	+ [*SharedStaticConstructor*](#SharedStaticConstructor)s
	+ [*SharedStaticDestructor*](#SharedStaticDestructor)s
	+ [Class Invariants](#invariants)
	+ [Unit Tests](unittest#unittest)
	+ [Class Allocators](#allocators)
	+ [Class Deallocators](#deallocators)
	+ [Alias This](#alias-this)

 A class is defined:

 
```
class Foo
{
    ... members ...
}

```
 Note that there is no trailing `;` after the closing `}` of the class definition. It is also not possible to declare a variable var like:

 
```
class Foo { } var;

```
 Instead: 
```
class Foo { }
Foo var;

```
 Access Control
--------------

 Access to class members is controlled using  [visibility attributes](attribute#visibility_attributes). The default visibility attribute is `public`. 

 Fields
------

 Class members are always accessed with the `.` operator. 

 Members of a base class can be accessed by prepending the name of the base class followed by a dot:

 
```
class A { int a; int a2;}
class B : A { int a; }

void foo(B b)
{
    b.a = 3;   // accesses field B.a
    b.a2 = 4;  // accesses field A.a2
    b.A.a = 5; // accesses field A.a
}

```
 The D compiler is free to rearrange the order of fields in a class to optimally pack them in an implementation-defined manner. Consider the fields much like the local variables in a function - the compiler assigns some to registers and shuffles others around all to get the optimal stack frame layout. This frees the code designer to organize the fields in a manner that makes the code more readable rather than being forced to organize it according to machine optimization rules. Explicit control of field layout is provided by struct/union types, not classes. 

 Fields of `extern(Objective-C)` classes have a dynamic offset. That means that the base class can change (add or remove instance variables) without the subclasses needing to recompile or relink. 

 Field Properties
----------------

 The `.offsetof` property gives the offset in bytes of the field from the beginning of the class instantiation. `.offsetof` is not available for fields of `extern(Objective-C)` classes due to their fields having a dynamic offset. `.offsetof` can only be applied to expressions which produce the type of the field itself, not the class type: 

 
```
class Foo
{
    int x;
}
...
void test(Foo foo)
{
    size_t o;

    o = Foo.x.offsetof; // error, Foo.x needs a 'this' reference
    o = foo.x.offsetof; // ok
}

```
 Class Properties
----------------

 The `.tupleof` property is an [expression sequence](template#variadic-templates) of all the fields in the class, excluding the hidden fields and the fields in the base class. `.tupleof` is not available for `extern(Objective-C)` classes due to their fields having a dynamic offset. 

 
```
class Foo { int x; long y; }

void test(Foo foo)
{
    import std.stdio;
    static assert(typeof(foo.tupleof).stringof == `(int, long)`);

    foo.tupleof[0] = 1; // set foo.x to 1
    foo.tupleof[1] = 2; // set foo.y to 2
    foreach (x; foo.tupleof)
        write(x);       // prints 12
}

```
 The properties `.__vptr` and `.__monitor` give access to the class object's vtbl[] and monitor, respectively, but should not be used in user code. 

 Super Class
-----------

 All classes inherit from a super class. If one is not specified, it inherits from [`Object`](https://dlang.org/phobos/object.html#Object). `Object` forms the root of the D class inheritance hierarchy. Member Functions (a.k.a. Methods)
---------------------------------

 Non-static member functions have an extra hidden parameter called *this* through which the class object's other members can be accessed. 

 Non-static member functions can have, in addition to the usual [*FunctionAttribute*](function#FunctionAttribute)s, the attributes `const`, `immutable`, `shared`, or `inout`. These attributes apply to the hidden *this* parameter. 

 
```
class C
{
    int a;
    const void foo()
    {
        a = 3; // error, 'this' is const
    }
    void foo() immutable
    {
        a = 3; // error, 'this' is immutable
    }
}

```
 ### Objective-C linkage

 Static member functions with `Objective-C` linkage also have an extra hidden parameter called *this* through which the class object's other members can be accessed. 

 Member functions with Objective-C linkage have an additional hidden, anonymous, parameter which is the selector the function was called with. 

 Static member functions with Objective-C linkage are placed in the hidden nested metaclass as non-static member functions. 

 Synchronized Classes
--------------------

 All member functions of synchronized classes are synchronized. A static member function is synchronized on the *classinfo* object for the class, which means that one monitor is used for all static member functions for that synchronized class. For non-static functions of a synchronized class, the monitor used is part of the class object. For example: 

 
```
synchronized class Foo
{
    void bar() { ...statements... }
}

```
 is equivalent to (as far as the monitors go): 

 
```
synchronized class Foo
{
    void bar()
    {
        synchronized (this) { ...statements... }
    }
}

```
 Member functions of non-synchronized classes can be individually marked as synchronized. 

 
```
class Foo
{
    synchronized void foo() { }  // foo is synchronized
}

```
 Member fields of a synchronized class cannot be public: 

 
```
synchronized class Foo
{
    int foo;  // disallowed: public field
}

synchronized class Bar
{
    private int bar;  // ok
}

```
 The `synchronized` attribute can only be applied to classes, structs cannot be marked to be synchronized.

 Constructors
------------

 
```
Constructor:
    this Parameters MemberFunctionAttributesopt ;
    this Parameters MemberFunctionAttributesopt FunctionBody
    ConstructorTemplate

```
 Fields are by default initialized to the default initializer for their type (usually 0 for integer types and NAN for floating point types). If the field declaration has an optional [*Initializer*](declaration#Initializer) that will be used instead of the default. 

 
```
class Abc
{
    int a;      // default initializer for a is 0
    long b = 7; // default initializer for b is 7
    float f;    // default initializer for f is NAN
}

```
 The *Initializer* is evaluated at compile time.

 This initialization is done before any constructors are called.

 Constructors are defined with a function name of `this` and have no return value:

 
```
class Foo
{
    this(int x)  // declare constructor for Foo
    {   ...
    }
    this()
    {   ...
    }
}

```
 Base class construction is done by calling the base class constructor by the name `super`:

 
```
class A { this(int y) { } }

class B : A
{
    int j;
    this()
    {
        ...
        super(3);  // call base constructor A.this(3)
        ...
    }
}

```
 ### Delegating Constructors

 A constructor can call another constructor for the same class in order to share common initializations. This is called a *delegating constructor*: 

 
```
class C
{
    int j;
    this()
    {
        ...
    }
    this(int i)
    {
        this(); // delegating constructor call
        j = i;
    }
}

```
 The following restrictions apply:

 1. It is illegal for constructors to mutually call each other. 
```
this() { this(1); }
this(int i) { this(); } // illegal, cyclic constructor calls

```
 **Implementation Defined:** The compiler is not required to detect cyclic constructor calls. **Undefined Behavior:** If the program executes with cyclic constructor calls.
2. If a constructor's code contains a delegating constructor call, all possible execution paths through the constructor must make exactly one delegating constructor call: 
```
this() { a || super(); }       // illegal

this() { (a) ? this(1) : super(); }     // ok

this()
{
    for (...)
    {
        super();  // illegal, inside loop
    }
}

```
3. It is illegal to refer to `this` implicitly or explicitly prior to making a delegating constructor call.
4. Delegating constructor calls cannot appear after labels.

 ### Implicit Base Class Construction

 If there is no constructor for a class, but there is a constructor for the base class, a default constructor is implicitly generated with the form:

 
```
this() { }

```
 If no calls to a delegating constructor or `super` appear in a constructor, and the base class has a nullary constructor, a call to `super()` is inserted at the beginning of the constructor. If that base class has a constructor that requires arguments and no nullary constructor, a matching call to `super` is required.

 ### Class Instantiation

 Instances of class objects are created with a [*NewExpression*](expression#NewExpression):

 
```
A a = new A(3);

```
 The following steps happen:

 1. Storage is allocated for the object. If this fails, rather than return `null`, an [OutOfMemoryError](https://dlang.org/library/core/exception/out_of_memory_error.html) is thrown. Thus, tedious checks for null references are unnecessary.
2. The raw data is statically initialized using the values provided in the class definition. The pointer to the vtbl[] (the array of pointers to virtual functions) is assigned. Constructors are passed fully formed objects for which virtual functions can be called. This operation is equivalent to doing a memory copy of a static version of the object onto the newly allocated one.
3. If there is a constructor defined for the class, the constructor matching the argument list is called.
4. If a delegating constructor is not called, a call to the base class's default constructor is issued.
5. The body of the constructor is executed.
6. If class invariant checking is turned on, the class invariant is called at the end of the constructor.

 ### Constructor Attributes

 Constructors can have one of these member function attributes: `const`, `immutable`, and `shared`. Construction of qualified objects will then be restricted to the implemented qualified constructors. 

 
```
class C
{
    this();   // non-shared mutable constructor
}

// create mutable object
C m = new C();

// create const object using mutable constructor
const C c2 = new const C();

// a mutable constructor cannot create an immutable object
// immutable C i = new immutable C();

// a mutable constructor cannot create a shared object
// shared C s = new shared C();

```
 Constructors can be overloaded with different attributes. 

 
```
class C
{
    this();               // non-shared mutable constructor
    this() shared;        // shared mutable constructor
    this() immutable;     // immutable constructor
}

C m = new C();
shared s = new shared C();
immutable i = new immutable C();

```
 #### Pure Constructors

 If the constructor can create a unique object (e.g. if it is `pure`), the object can be implicitly convertible to any qualifiers. 

 
```
class C
{
    this() pure;
    // Based on the definition, this creates a mutable object. But the
    // created object cannot contain any mutable global data.
    // Therefore the created object is unique.

    this(int[] arr) immutable pure;
    // Based on the definition, this creates an immutable object. But
    // the argument int[] never appears in the created object so it
    // isn't implicitly convertible to immutable. Also, it cannot store
    // any immutable global data.
    // Therefore the created object is unique.
}

immutable i = new immutable C();           // this() pure is called
shared s = new shared C();                 // this() pure is called
C m = new C([1,2,3]);       // this(int[]) immutable pure is called

```
 ### Field initialization inside a constructor

 In a constructor body, the first instance of field assignment is its initialization. 

 
```
class C
{
    int num;
    this()
    {
        num = 1;  // initialization
        num = 2;  // assignment
    }
}

```
 If the field type has an [`opAssign`](operatoroverloading#assignment) method, it will not be used for initialization.

 
```
struct A
{
    this(int n) {}
    void opAssign(A rhs) {}
}
class C
{
    A val;
    this()
    {
        val = A(1);  // val is initialized to the value of A(1)
        val = A(2);  // rewritten to val.opAssign(A(2))
    }
}

```
 If the field type is not mutable, multiple initialization will be rejected.

 
```
class C
{
    immutable int num;
    this()
    {
        num = 1;  // OK
        num = 2;  // Error: multiple field initialization
    }
}

```
 If the field is initialized on one path, it must be initialized on all paths.

 
```
class C
{
    immutable int num;
    immutable int ber;
    this(int i)
    {
        if (i)
            num = 3;   // initialization
        else
            num = 4;   // initialization
    }
    this(long j)
    {
        j ? (num = 3) : (num = 4); // ok
        j || (ber = 3);  // error, intialized on only one path
        j && (ber = 3);  // error, intialized on only one path
    }
}

```
 A field initialization may not appear in a loop or after a label.

 
```
class C
{
    immutable int num;
    immutable string str;
    this()
    {
        foreach (i; 0..2)
        {
            num = 1;    // Error: field initialization not allowed in loops
        }
        size_t i = 0;
    Label:
        str = "hello";  // Error: field initialization not allowed after labels
        if (i++ < 2)
            goto Label;
    }
}

```
 If a field's type has disabled default construction, then it must be initialized in the constructor.

 
```
struct S { int y; @disable this(); }

class C
{
    S s;
    this(S t) { s = t; }    // ok
    this(int i) { this(); } // ok
    this() { }              // error, s not initialized
}

```
 Destructors
-----------

 
```
Destructor:
    ~ this ( ) MemberFunctionAttributesopt ;
    ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 The garbage collector calls the destructor function when the object is deleted. The syntax is:

 
```
class Foo
{
    ~this() // destructor for Foo
    {
    }
}

```
 There can be only one destructor per class, the destructor does not have any parameters, and has no attributes. It is always virtual. 

 The destructor is expected to release any resources held by the object. 

 The program can explicitly inform the garbage collector that an object is no longer referred to with [`destroy`](https://dlang.org/phobos/object.html#destroy), and then the garbage collector calls the destructor immediately. The destructor is guaranteed to never be called twice. 

 The destructor for the super class automatically gets called when the destructor ends. There is no way to call the super destructor explicitly. 

 The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreferenced objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members which are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects destructed with [`destroy`](https://dlang.org/phobos/object.html#destroy), as the destructor is not being run by the garbage collector, meaning all references are valid. 

 Objects referenced from the data segment never get collected by the gc. 

 Static Constructors
-------------------

 
```
StaticConstructor:
    static this ( ) MemberFunctionAttributesopt ;
    static this ( ) MemberFunctionAttributesopt FunctionBody

```
 A static constructor is a function that performs initializations of thread local data before the `main()` function gets control for the main thread, and upon thread startup.

 Static constructors are used to initialize static class members with values that cannot be computed at compile time.

 Static constructors in other languages are built implicitly by using member initializers that can't be computed at compile time. The trouble with this stems from not having good control over exactly when the code is executed, for example: 

 
```
class Foo
{
    static int a = b + 1;
    static int b = a * 2;
}

```
 What values do a and b end up with, what order are the initializations executed in, what are the values of a and b before the initializations are run, is this a compile error, or is this a runtime error? Additional confusion comes from it not being obvious if an initializer is static or dynamic. D makes this simple. All member initializations must be determinable by the compiler at compile time, hence there is no order-of-evaluation dependency for member initializations, and it is not possible to read a value that has not been initialized. Dynamic initialization is performed by a static constructor, defined with a special syntax `static this()`.

 
```
class Foo
{
    static int a;         // default initialized to 0
    static int b = 1;
    static int c = b + a; // error, not a constant initializer

    static this()    // static constructor
    {
        a = b + 1;          // a is set to 2
        b = a * 2;          // b is set to 4
    }
}

```
 If `main()` or the thread returns normally, (does not throw an exception), the static destructor is added to the list of functions to be called on thread termination.

 Static constructors have empty parameter lists.

  Static constructors within a module are executed in the lexical order in which they appear. All the static constructors for modules that are directly or indirectly imported are executed before the static constructors for the importer. 

  The `static` in the static constructor declaration is not an attribute, it must appear immediately before the `this`: 

 
```
class Foo
{
    static this() { ... } // a static constructor
    static private this() { ... } // not a static constructor
    static
    {
        this() { ... }      // not a static constructor
    }
    static:
        this() { ... }      // not a static constructor
}

```
 Static Destructors
------------------

 
```
StaticDestructor:
    static ~ this ( ) MemberFunctionAttributesopt ;
    static ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 A static destructor is defined as a special static function with the syntax `static ~this()`. 
```
class Foo
{
    static ~this() // static destructor
    {
    }
}

```
  A static destructor gets called on thread termination, but only if the static constructor completed successfully. Static destructors have empty parameter lists. Static destructors get called in the reverse order that the static constructors were called in. 

  The `static` in the static destructor declaration is not an attribute, it must appear immediately before the `~this`: 

 
```
class Foo
{
    static ~this() { ... }  // a static destructor
    static private ~this() { ... } // not a static destructor
    static
    {
        ~this() { ... }  // not a static destructor
    }
    static:
        ~this() { ... }  // not a static destructor
}

```
 Shared Static Constructors
--------------------------

 
```
SharedStaticConstructor:
    shared static this ( ) MemberFunctionAttributesopt ;
    shared static this ( ) MemberFunctionAttributesopt FunctionBody

```
 Shared static constructors are executed before any [*StaticConstructor*](#StaticConstructor)s, and are intended for initializing any shared global data. 

 Shared Static Destructors
-------------------------

 
```
SharedStaticDestructor:
    shared static ~ this ( ) MemberFunctionAttributesopt ;
    shared static ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 Shared static destructors are executed at program termination in the reverse order that [*SharedStaticConstructor*](#SharedStaticConstructor)s were executed. 

 Class Invariants
----------------

 
```
ClassInvariant:
    invariant ( ) BlockStatement
    invariant BlockStatement
    invariant ( AssertArguments ) ;

```
 *ClassInvariant* specify the relationships among the members of a class instance. Those relationships must hold for any interactions with the instance from its public interface. 

 The invariant is in the form of a `const` member function. The invariant is defined to *hold* if all the [*AssertExpression*](expression#AssertExpression)s within the invariant that are executed succeed. 

 If the invariant does not hold, then the program enters an invalid state.

 Any class invariants for base classes are applied before the class invariant for the derived class.

 There may be multiple invariants in a class. They are applied in lexical order.

 *ClassInvariant*s must hold at the exit of the class constructor (if any), at the entry of the class destructor (if any).

 *ClassInvariant*s must hold at the entry and exit of all public or exported non-static member functions. The order of application of invariants is: 


1. preconditions
2. invariant
3. function body
4. invariant
5. postconditions

 The invariant need not hold if the class instance is implicitly constructed using the default `.init` value.

 
```
class Date
{
    this(int d, int h)
    {
        day = d;    // days are 1..31
        hour = h;   // hours are 0..23
    }

    invariant
    {
        assert(1 <= day && day <= 31);
        assert(0 <= hour && hour < 24);
    }

  private:
    int day;
    int hour;
}

```
 Public or exported non-static member functions cannot be called from within an invariant.

 
```
class Foo
{
    public void f() { }
    private void g() { }

    invariant
    {
        f();  // error, cannot call public member function from invariant
        g();  // ok, g() is not public
    }
}

```
 **Undefined Behavior:** happens if the invariant does not hold and execution continues. **Implementation Defined:** 1. Whether the *Class Invariant* is executed at runtime or not. This is typically controlled with a compiler switch.
2. The behavior when the invariant does not hold is typically the same as for when [*AssertExpression*](expression#AssertExpression)s fail.

 **Best Practices:** 1. Do not indirectly call exported or public member functions within a class invariant, as this can result in infinite recursion.
2. Avoid reliance on side effects in the invariant. as the invariant may or may not be executed.
3. Avoid having mutable public fields of classes with invariants, as then the invariant cannot verify the public interface.

 Class Allocators
----------------

 **Note**: Class allocators are deprecated in D2. 
```
Allocator:
    new Parameters ;
    new Parameters FunctionBody

```
 A class member function of the form:

 
```
new(size_t size)
{
    ...
}

```
 is called a class allocator. The class allocator can have any number of parameters, provided the first one is of type `size_t`. Any number can be defined for a class, the correct one is determined by the usual function overloading rules. When a new expression: 
```
new Foo;

```
 is executed, and Foo is a class that has an allocator, the allocator is called with the first argument set to the size in bytes of the memory to be allocated for the instance. The allocator must allocate the memory and return it as a `void*`. If the allocator fails, it must not return a `null`, but must throw an exception. If there is more than one parameter to the allocator, the additional arguments are specified within parentheses after the `new` in the *NewExpression*: 
```
class Foo
{
    this(string a) { ... }

    new(size_t size, int x, int y)
    {
        ...
    }
}

...

new(1,2) Foo(a);        // calls new(Foo.sizeof,1,2)

```
 Derived classes inherit any allocator from their base class, if one is not specified. 

 The class allocator is not called if the instance is created on the stack. 

 See also  [Explicit Class Instance Allocation](https://wiki.dlang.org/Memory_Management#Explicit_Class_Instance_Allocation). 

 Class Deallocators
------------------

 **Note**: Class deallocators and the delete operator are deprecated in D2. Use the `destroy` function to finalize an object by calling its destructor. The memory of the object is **not** immediately deallocated, instead the GC will collect the memory of the object at an undetermined point after finalization: 
```
class Foo { int x; this() { x = 1; } }
Foo foo = new Foo;
destroy(foo);
assert(foo.x == int.init);  // object is still accessible

```
 
```
Deallocator:
    delete Parameters ;
    delete Parameters FunctionBody

```
 A class member function of the form:

 
```
delete(void *p)
{
    ...
}

```
 is called a class deallocator. The deallocator must have exactly one parameter of type `void*`. Only one can be specified for a class. When a delete expression: 
```
delete f;

```
 is executed, and f is a reference to a class instance that has a deallocator, the deallocator is called with a pointer to the class instance after the destructor (if any) for the class is called. It is the responsibility of the deallocator to free the memory. Derived classes inherit any deallocator from their base class, if one is not specified. 

 The class allocator is not called if the instance is created on the stack. 

 See also  [Explicit Class Instance Allocation](https://wiki.dlang.org/Memory_Management#Explicit_Class_Instance_Allocation). 

 Alias This
----------

 
```
AliasThis:
    alias Identifier this ;

```
 An *AliasThis* declaration names a member to subtype. The *Identifier* names that member. 

 A class or struct can be implicitly converted to the *AliasThis* member. 

 
```
struct S
{
    int x;
    alias x this;
}

int foo(int i) { return i * 2; }

void test()
{
    S s;
    s.x = 7;
    int i = -s;  // i == -7
    i = s + 8;   // i == 15
    i = s + s;   // i == 14
    i = 9 + s;   // i == 16
    i = foo(s);  // implicit conversion to int
}

```
 If the member is a class or struct, undefined lookups will be forwarded to the *AliasThis* member. 

 
```
struct Foo
{
    int baz = 4;
    int get() { return 7; }
}

class Bar
{
    Foo foo;
    alias foo this;
}

void test()
{
    auto bar = new Bar;
    int i = bar.baz; // i == 4
    i = bar.get(); // i == 7
}

```
 If the *Identifier* refers to a property member function with no parameters, conversions and undefined lookups are forwarded to the return value of the function. 

 
```
struct S
{
    int x;
    @property int get()
    {
        return x * 2;
    }
    alias get this;
}

void test()
{
    S s;
    s.x = 2;
    int i = s; // i == 4
}

```
 If an aggregate declaration defines an `opCmp` or `opEquals` method, it will take precedence to that of the aliased this member. Note that, unlike an `opCmp` method, an `opEquals` method is implicitly defined for a `struct` declaration if a user defined one isn't provided; this means that if the aliased this member `opEquals` is preferred it should be explicitly defined: 

 
```
struct S
{
    int a;
    bool opEquals(S rhs) const
    {
        return this.a == rhs.a;
    }
}

struct T
{
    int b;
    S s;
    alias s this;
}

struct U
{
    int a;
    bool opCmp(U rhs) const
    {
        return this.a < rhs.a;
    }
}

struct V
{
    int b;
    U u;
    alias u this;
}

void main()
{
    S s1, s2;
    T t1, t2;
    U u1, u2;
    V v1, v2;

    assert(s1 == s2);      // calls S.opEquals
    assert(t1 == t2);      // calls compiler generated T.opEquals that implements member-wise equality
    assert(!(u1 < u2));    // calls U.opCmp
    assert(!(v1 < v2));    // calls U.opCmp because V does not define an opCmp method
                           // so the alias this of v1 is employed; U.opCmp expects a
                           // paramter of type U, so alias this of v2 is used

    assert(s1 == t1);      // calls s1.opEquals(t1.s);
    assert(t1 == s1);      // calls t1.s.opEquals(s1);
    assert(!(u1 < v1));    // calls u1.opCmp(v1.u);
    assert(!(v1 < u1));    // calls v1.u.opCmp(v1);
}

```
 [*Attribute*](attribute#Attribute)s are ignored for `AliasThis`. 

 Multiple *AliasThis* are currently not allowed.

 Scope Classes
-------------

 **Note**: Scope classes have been [recommended for deprecation](https://dlang.org/deprecate.html#scope%20for%20allocating%20classes%20on%20the%20stack). A scope class is a class with the `scope` attribute, as in:

 
```
scope class Foo { ... }

```
 The scope characteristic is inherited, so any classes derived from a scope class are also scope.

 A scope class reference can only appear as a function local variable. It must be declared as being `scope`:

 
```
scope class Foo { ... }

void func()
{
    Foo f;    // error, reference to scope class must be scope
    scope Foo g = new Foo(); // correct
}

```
 When a scope class reference goes out of scope, the destructor (if any) for it is automatically called. This holds true even if the scope was exited via a thrown exception.

 Final Classes
-------------

 Final classes cannot be subclassed:

 
```
final class A { }
class B : A { }  // error, class A is final

```
 Methods of a final class are `final` by default.

 Nested Classes
--------------

 A *nested class* is a class that is declared inside the scope of a function or another class. A nested class has access to the variables and other symbols of the classes and functions it is nested inside:

 
```
class Outer
{
    int m;

    class Inner
    {
        int foo()
        {
            return m;   // Ok to access member of Outer
        }
    }
}

void func()
{
    int m;

    class Inner
    {
        int foo()
        {
            return m; // Ok to access local variable m of func()
        }
    }
}

```
 ### Static Nested Classes

 If a nested class has the `static` attribute, then it can not access variables of the enclosing scope that are local to the stack or need a `this` reference:

 
```
class Outer
{
    int m;
    static int n;

    static class Inner
    {
        int foo()
        {
            return m;   // Error, Inner is static and m needs a this
            return n;   // Ok, n is static
        }
    }
}

void func()
{
    int m;
    static int n;

    static class Inner
    {
        int foo()
        {
            return m;   // Error, Inner is static and m is local to the stack
            return n;   // Ok, n is static
        }
    }
}

```
 ### Context Pointer

 Non-static nested classes work by containing an extra hidden member (called the context pointer) that is the frame pointer of the enclosing function if it is nested inside a function, or the `this` reference of the enclosing class's instance if it is nested inside a class.

 When a non-static nested class is instantiated, the context pointer is assigned before the class's constructor is called, therefore the constructor has full access to the enclosing variables. A non-static nested class can only be instantiated when the necessary context pointer information is available:

 
```
class Outer
{
    class Inner { }

    static class SInner { }
}

void func()
{
    class Nested { }

    Outer o = new Outer;        // Ok
    Outer.Inner oi = new Outer.Inner;   // Error, no 'this' for Outer
    Outer.SInner os = new Outer.SInner; // Ok

    Nested n = new Nested;      // Ok
}

```
 ### Explicit Instantiation

 A `this` reference can be supplied to the creation of an inner class instance by prefixing it to the *NewExpression*: 

 
```
class Outer
{
    int a;

    class Inner
    {
        int foo()
        {
            return a;
        }
    }
}

int bar()
{
    Outer o = new Outer;
    o.a = 3;
    Outer.Inner oi = o.new Inner;
    return oi.foo();    // returns 3
}

```
 Here `o` supplies the `this` reference to the inner class instance of `Outer`. 

 ### 
`outer` Property

 For a nested class instance, the `.outer` property is the `this` reference for the enclosing class's instance. If there is no enclosing class context, `.outer` would be a `void*` to the enclosing function frame. 

 
```
class Outer
{
    class Inner1
    {
        Outer getOuter()
        {
            return this.outer;
        }
    }

    void foo()
    {
        Inner1 i = new Inner1;
        assert(i.getOuter() is this);
    }

    void bar()
    {
        // x is referenced from nested scope, so
        // bar makes a closure environment.
        int x = 1;

        class Inner2
        {
            Outer getOuter()
            {
                x = 2;
                // The Inner2 instance has access to the function frame
                // of bar as a static frame pointer, but .outer returns
                // the enclosing Outer class instance property.
                return this.outer;
            }
        }

        Inner2 i = new Inner2;
        assert(i.getOuter() is this);
    }

    // baz cannot access an instance of Outer
    static void baz()
    {
        // make a closure environment
        int x = 1;

        class Inner3
        {
            void* getOuter()
            {
                x = 2;
                // There's no accessible enclosing class instance, so the
                // .outer property returns the function frame of baz.
                return this.outer;
            }
        }

        Inner3 i = new Inner3;
        assert(i.getOuter() !is null);
    }
}

```
 ### Anonymous Nested Classes

 An anonymous nested class is both defined and instantiated with a *NewAnonClassExpression*: 

 
```
NewAnonClassExpression:
    new AllocatorArgumentsopt class ConstructorArgsopt SuperClassopt Interfacesopt AggregateBody

ConstructorArgs:
    ( ArgumentListopt )

```
 which is equivalent to: 
```
class Identifier : SuperClass Interfaces AggregateBody
// ...
new AllocatorArguments Identifier ConstructorArgs

```
 where *Identifier* is the name generated for the anonymous nested class. 
```
interface I
{
    void foo();
}

auto obj = new class I
{
    void foo()
    {
        writeln("foo");
    }
};
obj.foo();

```
 Const, Immutable and Shared Classes
-----------------------------------

 If a *ClassDeclaration* has a `const`, `immutable` or `shared` storage class, then it is as if each member of the class was declared with that storage class. If a base class is const, immutable or shared, then all classes derived from it are also const, immutable or shared. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/class.html>

Operator Overloading
====================

 **Contents** 1. [Unary Operator Overloading](#unary)
	1. [Postincrement *e*`++` and Postdecrement *e*`--` Operators](#postincrement_postdecrement_operators)
	2. [Overloading Index Unary Operators](#index_unary_operators)
	3. [Overloading Slice Unary Operators](#slice_unary_operators)
2. [Cast Operator Overloading](#cast)
	1. [Boolean Operations](#boolean_operators)
3. [Binary Operator Overloading](#binary)
4. [Overloading the Comparison Operators](#eqcmp)
	1. [Overloading `==` and `!=`](#equals)
	2. [Overloading `<`, `<``=`, `>`, and `>``=`](#compare)
5. [Function Call Operator Overloading `f()`](#function-call)
	1. [Static opCall](#static-opcall)
6. [Assignment Operator Overloading](#assignment)
	1. [Index Assignment Operator Overloading](#index_assignment_operator)
	2. [Slice Assignment Operator Overloading](#slice_assignment_operator)
7. [Op Assignment Operator Overloading](#op-assign)
	1. [Index Op Assignment Operator Overloading](#index_op_assignment)
	2. [Slice Op Assignment Operator Overloading](#slice_op_assignment)
8. [Array Indexing and Slicing Operators Overloading](#array-ops)
	1. [Index Operator Overloading](#array)
	2. [Slice Operator Overloading](#slice)
	3. [Dollar Operator Overloading](#dollar)
9. [Forwarding](#dispatch)
10. [D1 style operator overloading](#old-style)

 Operator overloading is accomplished by rewriting operators whose operands are class or struct objects into calls to specially named members. No additional syntax is used. 

 * [Unary Operator Overloading](#unary)
* [Cast Operator Overloading](#cast)
* [Binary Operator Overloading](#binary)
* [Overloading the Comparison Operators](#eqcmp)
	+ [Overloading `==` and `!=`](#equals)
	+ [Overloading `<`, `<=`, `>`, and `>=`](#compare)
* [Function Call Operator Overloading](#function-call)
* [Assignment Operator Overloading](#assignment)
* [Op Assignment Operator Overloading](#op-assign)
* [Array Indexing and Slicing Operators Overloading](#array-ops)
	+ [Index Operator Overloading](#array)
	+ [Slice Operator Overloading](#slice)
	+ [Dollar Operator Overloading](#dollar)
* [Forwarding](#dispatch)
* [D1 style operator overloading](#old-style)

 Unary Operator Overloading
--------------------------

 

Overloadable Unary Operators| ***op*** | ***rewrite*** |
| `-`*e* | *e*`.opUnary!("-")()` |
| `+`*e* | *e*`.opUnary!("+")()` |
| `~`*e* | *e*`.opUnary!("~")()` |
| `*`*e* | *e*`.opUnary!("*")()` |
| `++`*e* | *e*`.opUnary!("++")()` |
| `--`*e* | *e*`.opUnary!("--")()` |

 For example, in order to overload the `-` (negation) operator for struct S, and no other operator:

 
```
struct S
{
    int m;

    int opUnary(string s)() if (s == "-")
    {
        return -m;
    }
}

int foo(S s)
{
    return -s;
}

```
 ### Postincrement *e*`++` and Postdecrement *e*`--` Operators

 These are not directly overloadable, but instead are rewritten in terms of the ++*e* and --*e* prefix operators: 

 

Postfix Operator Rewrites| ***op*** | ***rewrite*** |
| *e*`--` | `(auto t =` *e*`, --`*e*`, t)` |
| *e*`++` | `(auto t =` *e*`, ++`*e*`, t)` |

 ### Overloading Index Unary Operators

 

Overloadable Index Unary Operators| ***op*** | ***rewrite*** |
| `-`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("-")(`*b*1, *b*2, ... *b*n`)` |
| `+`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("+")(`*b*1, *b*2, ... *b*n`)` |
| `~`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("~")(`*b*1, *b*2, ... *b*n`)` |
| `*`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("*")(`*b*1, *b*2, ... *b*n`)` |
| `++`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("++")(`*b*1, *b*2, ... *b*n`)` |
| `--`*a*`[`*b*1, *b*2, ... *b*n`]` | *a*`.opIndexUnary!("--")(`*b*1, *b*2, ... *b*n`)` |

 ### Overloading Slice Unary Operators

 

Overloadable Slice Unary Operators| ***op*** | ***rewrite*** |
| `-`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("-")(`*a*`.opSlice(`*i*, *j*`))` |
| `+`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("+")(`*a*`.opSlice(`*i*, *j*`))` |
| `~`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("~")(`*a*`.opSlice(`*i*, *j*`))` |
| `*`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("*")(`*a*`.opSlice(`*i*, *j*`))` |
| `++`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("++")(`*a*`.opSlice(`*i*, *j*`))` |
| `--`*a*`[`*i*..*j*`]` | *a*`.opIndexUnary!("--")(`*a*`.opSlice(`*i*, *j*`))` |
| `-`*a*`[ ]` | *a*`.opIndexUnary!("-")()` |
| `+`*a*`[ ]` | *a*`.opIndexUnary!("+")()` |
| `~`*a*`[ ]` | *a*`.opIndexUnary!("~")()` |
| `*`*a*`[ ]` | *a*`.opIndexUnary!("*")()` |
| `++`*a*`[ ]` | *a*`.opIndexUnary!("++")()` |
| `--`*a*`[ ]` | *a*`.opIndexUnary!("--")()` |

 For backward compatibility, if the above rewrites fail to compile and `opSliceUnary` is defined, then the rewrites `a.opSliceUnary!(op)(i, j)` and `a.opSliceUnary!(op)` are tried instead, respectively.

 Cast Operator Overloading
-------------------------

 To define how one type can be cast to another, define the `opCast` template method, which is used as follows:

 

Cast Operators| ***op*** | ***rewrite*** |
| `cast(`*type*`)` *e* | *e*`.opCast!(`*type*`)()` |

 Note that `opCast` is only ever used with an explicit `cast` expression, except in the case of boolean operations (see next section)

 ### Boolean Operations

 Notably absent from the list of overloaded unary operators is the ! logical negation operator. More obscurely absent is a unary operator to convert to a bool result. Instead, these are covered by a rewrite to: 

 
```
opCast!(bool)(e)

```
 So,

 
```
if (e)   =>  if (e.opCast!(bool))
if (!e)  =>  if (!e.opCast!(bool))

```
 etc., whenever a bool result is expected. This only happens, however, for instances of structs. Class references are converted to bool by checking to see if the class reference is null or not. 

 Binary Operator Overloading
---------------------------

 The following binary operators are overloadable:

 

Overloadable Binary Operators| `+` | `-` | `*` | `/` | `%` | `^^` | `&` |
| `|` | `^` | `<``<` | `>``>` | `>``>``>` | `~` | `in` |

 The expression:

 
```
a op b

```
 is rewritten as both:

 
```
a.opBinary!("op")(b)
b.opBinaryRight!("op")(a)

```
 and the one with the ‘better’ match is selected. It is an error for both to equally match. 

 Operator overloading for a number of operators can be done at the same time. For example, if only the + or - operators are supported:

 
```
T opBinary(string op)(T rhs)
{
    static if (op == "+") return data + rhs.data;
    else static if (op == "-") return data - rhs.data;
    else static assert(0, "Operator "~op~" not implemented");
}

```
 To do them all en masse:

 
```
T opBinary(string op)(T rhs)
{
    return mixin("data "~op~" rhs.data");
}

```
 Note that `opIn` and `opIn_r` have been deprecated in favor of `opBinary!"in"` and `opBinaryRight!"in"` respectively.

 Overloading the Comparison Operators
------------------------------------

 D allows overloading of the comparison operators `==`, `!=`, `<`, `<=`, `>=`, `>` via two functions, `opEquals` and `opCmp`.

 The equality and inequality operators are treated separately because while practically all user-defined types can be compared for equality, only a subset of types have a meaningful ordering. For example, while it makes sense to determine if two RGB color vectors are equal, it is not meaningful to say that one color is greater than another, because colors do not have an ordering. Thus, one would define `opEquals` for a `Color` type, but not `opCmp`.

 Furthermore, even with orderable types, the order relation may not be linear. For example, one may define an ordering on sets via the subset relation, such that `x < y` is true if `x` is a (strict) subset of `y`. If `x` and `y` are disjoint sets, then neither `x < y` nor `y < x` holds, but that does not imply that `x == y`. Thus, it is insufficient to determine equality purely based on `opCmp` alone. For this reason, `opCmp` is only used for the inequality operators `<`, `<=`, `>=`, and `>`. The equality operators `==` and `!=` always employ `opEquals` instead.

 Therefore, it is the programmer's responsibility to ensure that `opCmp` and `opEquals` are consistent with each other. If `opEquals` is not specified, the compiler provides a default version that does member-wise comparison. If this suffices, one may define only `opCmp` to customize the behaviour of the inequality operators. But if not, then a custom version of `opEquals` should be defined as well, in order to preserve consistent semantics between the two kinds of comparison operators.

 Finally, if the user-defined type is to be used as a key in the built-in associative arrays, then the programmer must ensure that the semantics of `opEquals` and `toHash` are consistent. If not, the associative array may not work in the expected manner.

 ### Overloading `==` and `!=`

 Expressions of the form `a != b` are rewritten as `!(a == b)`.

 Given `a == b` :

 1. If a and b are both class objects, then the expression is rewritten as: 
```
.object.opEquals(a, b)

```
 and that function is implemented as:

 
```
bool opEquals(Object a, Object b)
{
    if (a is b) return true;
    if (a is null || b is null) return false;
    if (typeid(a) == typeid(b)) return a.opEquals(b);
    return a.opEquals(b) && b.opEquals(a);
}

```
2. Otherwise the expressions `a.opEquals(b)` and `b.opEquals(a)` are tried. If both resolve to the same `opEquals` function, then the expression is rewritten to be `a.opEquals(b)`.
3. If one is a better match than the other, or one compiles and the other does not, the first is selected.
4. Otherwise, an error results.

 If overridding `Object.opEquals()` for classes, the class member function signature should look like:

 
```
class C
{
    override bool opEquals(Object o) { ... }
}

```
 If structs declare an `opEquals` member function for the identity comparison, it could have several forms, such as:

 
```
struct S
{
    // lhs should be mutable object
    bool opEquals(const S s) { ... }        // for r-values (e.g. temporaries)
    bool opEquals(ref const S s) { ... }    // for l-values (e.g. variables)

    // both hand side can be const object
    bool opEquals(const S s) const { ... }  // for r-values (e.g. temporaries)
}

```
 Alternatively, declare a single templated `opEquals` function with an [auto ref](template#auto-ref-parameters) parameter:

 
```
struct S
{
    // for l-values and r-values,
    // with converting both hand side implicitly to const
    bool opEquals()(auto ref const S s) const { ... }
}

```
 ### Overloading `<`, `<``=`, `>`, and `>``=`

 Comparison operations are rewritten as follows:

 

Rewriting of comparison operations| **comparison** | **rewrite 1** | **rewrite 2** |
| `a` `<` `b` | `a.opCmp(b)` `<` `0` | `b.opCmp(a)` `>` `0` |
| `a` `<``= b` | `a.opCmp(b)` `<``= 0` | `b.opCmp(a)` `>``= 0` |
| `a` `>``b` | `a.opCmp(b)` `>` `0` | `b.opCmp(a)` `<` `0` |
| `a` `>``= b` | `a.opCmp(b)` `>``= 0` | `b.opCmp(a)` `<``= 0` |

 Both rewrites are tried. If only one compiles, that one is taken. If they both resolve to the same function, the first rewrite is done. If they resolve to different functions, the best matching one is used. If they both match the same, but are different functions, an ambiguity error results.

 If overriding `Object.opCmp()` for classes, the class member function signature should look like:

 
```
class C
{
    override int opCmp(Object o) { ... }
}

```
 If structs declare an `opCmp` member function, it should have the following form:

 
```
struct S
{
    int opCmp(ref const S s) const { ... }
}

```
 Note that `opCmp` is only used for the inequality operators; expressions like `a == b` always uses `opEquals`. If `opCmp` is defined but `opEquals` isn't, the compiler will supply a default version of `opEquals` that performs member-wise comparison. If this member-wise comparison is not consistent with the user-defined `opCmp`, then it is up to the programmer to supply an appropriate version of `opEquals`. Otherwise, inequalities like `a <= b` will behave inconsistently with equalities like `a == b`.

 Function Call Operator Overloading `f()`
----------------------------------------

 The function call operator, `()`, can be overloaded by declaring a function named `opCall`: 

 
```
struct F
{
    int opCall();
    int opCall(int x, int y, int z);
}

void test()
{
    F f;
    int i;

    i = f();      // same as i = f.opCall();
    i = f(3,4,5); // same as i = f.opCall(3,4,5);
}

```
 In this way a struct or class object can behave as if it were a function. 

 Note that merely declaring `opCall` automatically disables [struct literal](struct#StructLiteral) syntax. To avoid the limitation, declare a [constructor](struct#Struct-Constructor) so that it takes priority over `opCall` in `Type(...)` syntax. 

 
```
struct Multiplier
{
    int factor;
    this(int num) { factor = num; }
    int opCall(int value) { return value * factor; }
}
void test()
{
    Multiplier m = Multiplier(10);  // invoke constructor
    int result = m(5);              // invoke opCall
    assert(result == 50);
}

```
 ### Static opCall

 `static opCall` also works as expected for a function call operator with type names. 

 
```
struct Double
{
    static int opCall(int x) { return x * 2; }
}
void test()
{
    int i = Double(2);
    assert(i == 4);
}

```
 Mixing struct constructors and `static opCall` is not allowed.

 
```
struct S
{
    this(int i) {}
    static S opCall()  // disallowed due to constructor
    {
        return S.init;
    }
}

```
 Note: `static opCall` can be used to simulate struct constructors with no arguments, but this is not recommended practice. Instead, the preferred solution is to use a factory function to create struct instances. 

 Assignment Operator Overloading
-------------------------------

 The assignment operator `=` can be overloaded if the left hand side is a struct aggregate, and `opAssign` is a member function of that aggregate.

 For struct types, operator overloading for the identity assignment is allowed. 
```
struct S
{
    // identity assignment, allowed.
    void opAssign(S rhs);

    // not identity assignment, also allowed.
    void opAssign(int);
}
S s;
s = S();      // Rewritten to s.opAssign(S());
s = 1;        // Rewritten to s.opAssign(1);

```
 However for class types, identity assignment is not allowed. All class types have reference semantics, so identity assignment by default rebinds the left-hand-side to the argument at the right, and this is not overridable. 
```
class C
{
    // If X is the same type as C or the type which is
    // implicitly convertible to C, then opAssign would
    // accept identity assignment, which is disallowed.
    // C opAssign(...);
    // C opAssign(X);
    // C opAssign(X, ...);
    // C opAssign(X ...);
    // C opAssign(X, U = defaultValue, etc.);

    // not an identity assignment - allowed
    void opAssign(int);
}
C c = new C();
c = new C();  // Rebinding referencee
c = 1;        // Rewritten to c.opAssign(1);

```
 ### Index Assignment Operator Overloading

 If the left hand side of an assignment is an index operation on a struct or class instance, it can be overloaded by providing an `opIndexAssign` member function. Expressions of the form `a[`*b*1, *b*2, ... *b*n`] = c` are rewritten as `a.opIndexAssign(c,` *b*1, *b*2, ... *b*n`)`. 

 
```
struct A
{
    int opIndexAssign(int value, size_t i1, size_t i2);
}

void test()
{
    A a;
    a[i,3] = 7;  // same as a.opIndexAssign(7,i,3);
}

```
 ### Slice Assignment Operator Overloading

 If the left hand side of an assignment is a slice operation on a struct or class instance, it can be overloaded by implementing an `opIndexAssign` member function that takes the return value of the `opSlice` function as parameter(s). Expressions of the form `a[`*i*..*j*`] = c` are rewritten as `a.opIndexAssign(c,` `a.opSlice(`*i*, *j*`))`, and `a[] = c` as `a.opIndexAssign(c)`. 

 See [Array Indexing and Slicing Operators Overloading](#array-ops) for more details. 

 
```
struct A
{
    int opIndexAssign(int v);  // overloads a[] = v
    int opIndexAssign(int v, size_t[2] x);  // overloads a[i .. j] = v
    int[2] opSlice(size_t x, size_t y);     // overloads i .. j
}

void test()
{
    A a;
    int v;

    a[] = v;  // same as a.opIndexAssign(v);
    a[3..4] = v;  // same as a.opIndexAssign(v, a.opSlice(3,4));
}

```
 For backward compatibility, if rewriting `a[`*i*..*j*`]` as `a.opIndexAssign(a.opSlice(`*i*, *j*`))` fails to compile, the legacy rewrite `opSliceAssign(c,` *i*, *j*`)` is used instead. 

 Op Assignment Operator Overloading
----------------------------------

 The following op assignment operators are overloadable:

 

Overloadable Op Assignment Operators| `+=` | `-=` | `*=` | `/=` | `%``=` | `^^=` | `&``=` |
| `|``=` | `^=` | `<``<``=` | `>``>``=` | `>``>``>``=` | `~=` |  |

 The expression:

 
```
a op= b

```
 is rewritten as:

 
```
a.opOpAssign!("op")(b)

```
 ### Index Op Assignment Operator Overloading

 If the left hand side of an *op*= is an index expression on a struct or class instance and `opIndexOpAssign` is a member:

 
```
a[b1, b2, ... bn] op= c

```
 it is rewritten as:

 
```
a.opIndexOpAssign!("op")(c, b1, b2, ... bn)

```
 ### Slice Op Assignment Operator Overloading

 If the left hand side of an *op*= is a slice expression on a struct or class instance and `opIndexOpAssign` is a member:

 
```
a[i..j] op= c

```
 it is rewritten as:

 
```
a.opIndexOpAssign!("op")(c, a.opSlice(i, j))

```
 and

 
```
a[] op= c

```
 it is rewritten as:

 
```
a.opIndexOpAssign!("op")(c)

```
 For backward compatibility, if the above rewrites fail and `opSliceOpAssign` is defined, then the rewrites `a.opSliceOpAssign(c, i, j)` and `a.opSliceOpAssign(c)` are tried, respectively. 

 Array Indexing and Slicing Operators Overloading
------------------------------------------------

 The array indexing and slicing operators are overloaded by implementing the `opIndex`, `opSlice`, and `opDollar` methods. These may be combined to implement multidimensional arrays. 

 The code example below shows a simple implementation of a 2-dimensional array with overloaded indexing and slicing operators. The explanations of the various constructs employed are given in the sections following.

 
```
struct Array2D(E)
{
    E[] impl;
    int stride;
    int width, height;

    this(int width, int height, E[] initialData = [])
    {
        impl = initialData;
        this.stride = this.width = width;
        this.height = height;
        impl.length = width * height;
    }

    // Index a single element, e.g., arr[0, 1]
    ref E opIndex(int i, int j) { return impl[i + stride*j]; }

    // Array slicing, e.g., arr[1..2, 1..2], arr[2, 0..&dollar;], arr[0..&dollar;, 1].
    Array2D opIndex(int[2] r1, int[2] r2)
    {
        Array2D result;

        auto startOffset = r1[0] + r2[0]*stride;
        auto endOffset = r1[1] + (r2[1] - 1)*stride;
        result.impl = this.impl[startOffset .. endOffset];

        result.stride = this.stride;
        result.width = r1[1] - r1[0];
        result.height = r2[1] - r2[0];

        return result;
    }
    auto opIndex(int[2] r1, int j) { return opIndex(r1, [j, j+1]); }
    auto opIndex(int i, int[2] r2) { return opIndex([i, i+1], r2); }

    // Support for `x..y` notation in slicing operator for the given dimension.
    int[2] opSlice(size_t dim)(int start, int end)
        if (dim >= 0 && dim < 2)
    in { assert(start >= 0 && end <= this.opDollar!dim); }
    body
    {
        return [start, end];
    }

    // Support `&dollar;` in slicing notation, e.g., arr[1..&dollar;, 0..&dollar;-1].
    @property int opDollar(size_t dim : 0)() { return width; }
    @property int opDollar(size_t dim : 1)() { return height; }
}

unittest
{
    auto arr = Array2D!int(4, 3, [
        0, 1, 2,  3,
        4, 5, 6,  7,
        8, 9, 10, 11
    ]);

    // Basic indexing
    assert(arr[0, 0] == 0);
    assert(arr[1, 0] == 1);
    assert(arr[0, 1] == 4);

    // Use of opDollar
    assert(arr[$-1, 0] == 3);
    assert(arr[0, $-1] == 8);   // Note the value of &dollar; differs by dimension
    assert(arr[$-1, $-1] == 11);

    // Slicing
    auto slice1 = arr[1..$, 0..$];
    assert(slice1[0, 0] == 1 && slice1[1, 0] == 2  && slice1[2, 0] == 3 &&
           slice1[0, 1] == 5 && slice1[1, 1] == 6  && slice1[2, 1] == 7 &&
           slice1[0, 2] == 9 && slice1[1, 2] == 10 && slice1[2, 2] == 11);

    auto slice2 = slice1[0..2, 1..$];
    assert(slice2[0, 0] == 5 && slice2[1, 0] == 6 &&
           slice2[0, 1] == 9 && slice2[1, 1] == 10);

    // Thin slices
    auto slice3 = arr[2, 0..$];
    assert(slice3[0, 0] == 2 &&
           slice3[0, 1] == 6 &&
           slice3[0, 2] == 10);

    auto slice4 = arr[0..3, 2];
    assert(slice4[0, 0] == 8 && slice4[1, 0] == 9 && slice4[2, 0] == 10);
}

```
 ### Index Operator Overloading

 Expressions of the form `arr[`*b*1, *b*2, ... *b*n`]` are translated into `arr.opIndex(`*b*1, *b*2, ... *b*n`)`. For example: 

 
```
struct A
{
    int opIndex(size_t i1, size_t i2, size_t i3);
}

void test()
{
    A a;
    int i;
    i = a[5,6,7];  // same as i = a.opIndex(5,6,7);
}

```
 In this way a struct or class object can behave as if it were an array. 

 If an index expression can be rewritten using `opIndexAssign` or `opIndexOpAssign`, those are preferred over `opIndex`. 

 ### Slice Operator Overloading

 Overloading the slicing operator means overloading expressions like `a[]` or `a[`*i*..*j*`]`, where the expressions inside the square brackets contain slice expressions of the form *i*..*j*. 

 To overload `a[]`, simply define `opIndex` with no parameters: 

 
```
struct S
{
    int[] impl;
    int[] opIndex()
    {
        return impl[];
    }
}
void test()
{
    auto s = S([1,2,3]);
    auto t = s[]; // calls s.opIndex()
    assert(t == [1,2,3]);
}

```
 To overload array indexing of the form `a[`*i*..*j*`,` ...`]`, two steps are needed. First, the expressions of the form *i*..*j* are translated via `opSlice` into user-defined objects that encapsulate the endpoints *i* and *j*. Then these user-defined objects are passed to `opIndex` to perform the actual slicing. This design was chosen in order to support mixed indexing and slicing in multidimensional arrays; for example, in translating expressions like `arr[1, 2..3, 4]`. 

 More precisely, an expression of the form `arr[`*b*1, *b*2, ... *b*n`]` is translated into `arr.opIndex(`*c*1, *c*2, ... *c*n`)`. Each argument *b*i can be either a single expression, in which case it is passed directly as the corresponding argument  *c*i to `opIndex`; or it can be a slice expression of the form *x*i`..`*y*i, in which case the corresponding argument *c*i to `opIndex` is `arr.opSlice!i(`*x*i`,` *y*i`)`. Namely: 

 

| ***op*** | ***rewrite*** |
| --- | --- |
| `arr[1, 2, 3]` | `arr.opIndex(1, 2, 3)` |
| `arr[1..2, 3..4, 5..6]` | `arr.opIndex(arr.opSlice!0(1,2), arr.opSlice!1(3,4), arr.opSlice!2(5,6))` |
| `arr[1, 2..3, 4]` | `arr.opIndex(1, arr.opSlice!1(2,3), 4)` |

 Similar translations are done for assignment operators involving slicing, for example: 

 

| ***op*** | ***rewrite*** |
| --- | --- |
| `arr[1, 2..3, 4] = c` | `arr.opIndexAssign(c, 1, arr.opSlice!1(2, 3), 4)` |
| `arr[2, 3..4] += c` | `arr.opIndexOpAssign!"+"(c, 2, arr.opSlice!1(2, 3))` |

 The intention is that `opSlice!i` should return a user-defined object that represents an interval of indices along the `i`'th dimension of the array. This object is then passed to `opIndex` to perform the actual slicing operation. If only one-dimensional slicing is desired, `opSlice` may be declared without the compile-time parameter `i`. 

 Note that in all cases, `arr` is only evaluated once. Thus, an expression like `getArray()[1, 2..3, $-1]=c` has the effect of:

 
```
auto __tmp = getArray();
__tmp.opIndexAssign(c, 1, __tmp.opSlice!1(2,3), __tmp.opDollar!2 - 1);

```
 where the initial function call to `getArray` is only executed once. 

 For backward compatibility, `a[]` and `a[`*i*..*j*`]` can also be overloaded by implementing `opSlice()` with no arguments and `opSlice(`*i*, *j*`)` with two arguments, respectively. This only applies for one-dimensional slicing, and dates from when D did not have full support for multidimensional arrays. This usage of `opSlice` is discouraged. 

 ### Dollar Operator Overloading

 Within the arguments to array index and slicing operators, `$` gets translated to `opDollar!i`, where `i` is the position of the expression `$` appears in. For example: 

 

| ***op*** | ***rewrite*** |
| --- | --- |
| `arr[$-1, $-2, 3]` | `arr.opIndex(arr.opDollar!0 - 1, arr.opDollar!1 - 2, 3)` |
| `arr[1, 2, 3..$]` | `arr.opIndex(1, 2, arr.opSlice!2(3, arr.opDollar!2))` |

 The intention is that `opDollar!i` should return the length of the array along its `i`'th dimension, or a user-defined object representing the end of the array along that dimension, that is understood by `opSlice` and `opIndex`. 

 
```
struct Rectangle
{
    int width, height;
    int[][] impl;
    this(int w, int h)
    {
        width = w;
        height = h;
        impl = new int[w][h];
    }
    int opIndex(size_t i1, size_t i2)
    {
        return impl[i1][i2];
    }
    int opDollar(size_t pos)()
    {
        static if (pos==0)
            return width;
        else
            return height;
    }
}

void test()
{
    auto r = Rectangle(10,20);
    int i = r[$-1, 0];    // same as: r.opIndex(r.opDollar!0, 0),
                          // which is r.opIndex(r.width-1, 0)
    int j = r[0, $-1];    // same as: r.opIndex(0, r.opDollar!1)
                          // which is r.opIndex(0, r.height-1)
}

```
 As the above example shows, a different compile-time argument is passed to `opDollar` depending on which argument it appears in. A `$` appearing in the first argument gets translated to `opDollar!0`, a `$` appearing in the second argument gets translated to `opDollar!1`, and so on. Thus, the appropriate value for `$` can be returned to implement multidimensional arrays. 

 Note that `opDollar!i` is only evaluated once for each `i` where `$` occurs in the corresponding position in the indexing operation. Thus, an expression like `arr[$-sqrt($), 0, $-1]` has the effect of: 

 
```
auto __tmp1 = arr.opDollar!0;
auto __tmp2 = arr.opDollar!2;
arr.opIndex(__tmp1 - sqrt(__tmp1), 0, __tmp2 - 1);

```
 If `opIndex` is declared with only one argument, the compile-time argument to `opDollar` may be omitted. In this case, it is illegal to use `$` inside an array indexing expression with more than one argument. 

 Forwarding
----------

 Member names not found in a class or struct can be forwarded to a template function named `opDispatch` for resolution. 

 
```
import std.stdio;

struct S
{
    void opDispatch(string s, T)(T i)
    {
        writefln("S.opDispatch('%s', %s)", s, i);
    }
}

class C
{
    void opDispatch(string s)(int i)
    {
        writefln("C.opDispatch('%s', %s)", s, i);
    }
}

struct D
{
    template opDispatch(string s)
    {
        enum int opDispatch = 8;
    }
}

void main()
{
    S s;
    s.opDispatch!("hello")(7);
    s.foo(7);

    auto c = new C();
    c.foo(8);

    D d;
    writefln("d.foo = %s", d.foo);
    assert(d.foo == 8);
}

```
 D1 style operator overloading
-----------------------------

  The [D1 operator overload mechanisms](http://digitalmars.com/d/1.0/operatoroverloading.html) are deprecated. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/operatoroverloading.html>

Errors
======

 **Contents** 1. [The Error Handling Problem](#the_error_handling_problem)
2. [The D Error Handling Solution](#the_d_error_handling_solution)

 
> I came, I coded, I crashed. Julius C'ster
> 
> 

 ![Erroneous D-Man] All programs have to deal with errors. Errors are unexpected conditions that are not part of the normal operation of a program. Examples of common errors are: * Out of memory.
* Out of disk space.
* Invalid file name.
* Attempting to write to a read-only file.
* Attempting to read a non-existent file.
* Requesting a system service that is not supported.

 The Error Handling Problem
--------------------------

 The traditional C way of detecting and reporting errors is not traditional, it is ad-hoc and varies from function to function, including: * Returning a NULL pointer.
* Returning a 0 value.
* Returning a non-zero error code.
* Requiring errno to be checked.
* Requiring that a function be called to check if the previous function failed.

 To deal with these possible errors, tedious error handling code must be added to each function call. If an error happened, code must be written to recover from the error, and the error must be reported to the user in some user friendly fashion. If an error cannot be handled locally, it must be explicitly propagated back to its caller. The long list of errno values needs to be converted into appropriate text to be displayed. Adding all the code to do this can consume a large part of the time spent coding a project - and still, if a new errno value is added to the runtime system, the old code can not properly display a meaningful error message.

 Good error handling code tends to clutter up what otherwise would be a neat and clean looking implementation.

 Even worse, good error handling code is itself error prone, tends to be the least tested (and therefore buggy) part of the project, and is frequently simply omitted. The end result is likely a "blue screen of death" as the program failed to deal with some unanticipated error.

 Quick and dirty programs are not worth writing tedious error handling code for, and so such utilities tend to be like using a table saw with no blade guards.

 What's needed is an error handling philosophy and methodology such that: * It is standardized - consistent usage makes it more useful.
* The result is reasonable even if the programmer fails to check for errors.
* Old code can be reused with new code without having to modify the old code to be compatible with new error types.
* No errors get inadvertently ignored.
* ‘Quick and dirty’ utilities can be written that still correctly handle errors.
* It is easy to make the error handling source code look good.

 The D Error Handling Solution
-----------------------------

 Let's first make some observations and assumptions about errors: * Errors are not part of the normal flow of a program. Errors are exceptional, unusual, and unexpected.
* Because errors are unusual, execution of error handling code is not performance critical.
* The normal flow of program logic is performance critical.
* All errors must be dealt with in some way, either by code explicitly written to handle them, or by some system default handling.
* The code that detects an error knows more about the error than the code that must recover from the error.

 The solution is to use exception handling to report errors. All errors are objects derived from abstract [`class $Error`](https://dlang.org/phobos/object.html#Error). `Error` has a pure virtual function called toString() which produces a `string` with a human readable description of the error.

 If code detects an error like "out of memory," then an `Error` is thrown with a message saying "Out of memory". The function call stack is unwound, looking for a handler for the Error. [Finally blocks](statement#TryStatement) are executed as the stack is unwound. If an error handler is found, execution resumes there. If not, the default Error handler is run, which displays the message and terminates the program.

 How does this meet our criteria?

  It is standardized - consistent usage makes it more useful. This is the D way, and is used consistently in the D runtime library and examples. The result is reasonable result even if the programmer fails to check for errors. If no catch handlers are there for the errors, then the program gracefully exits through the default error handler with an appropriate message. Old code can be reused with new code without having to modify the old code to be compatible with new error types. Old code can decide to catch all errors, or only specific ones, propagating the rest upwards. In any case, there is no more need to correlate error numbers with messages, the correct message is always supplied. No errors get inadvertently ignored. Error exceptions get handled one way or another. There is nothing like a NULL pointer return indicating an error, followed by trying to use that NULL pointer. 'Quick and dirty' utilities can be written that still correctly handle errors. Quick and dirty code need not write any error handling code at all, and don't need to check for errors. The errors will be caught, an appropriate message displayed, and the program gracefully shut down all by default. It is easy to make the error handling source code look good. The try/catch/finally statements look a lot nicer than endless if (error) goto errorhandler; statements.  How does this meet our assumptions about errors?  Errors are not part of the normal flow of a program. Errors are exceptional, unusual, and unexpected. D exception handling fits right in with that. Because errors are unusual, execution of error handling code is not performance critical. Exception handling stack unwinding is a relatively slow process. The normal flow of program logic is performance critical. Since the normal flow code does not have to check every function call for error returns, it can be realistically faster to use exception handling for the errors. All errors must be dealt with in some way, either by code explicitly written to handle them, or by some system default handling. If there's no handler for a particular error, it is handled by the runtime library default handler. If an error is ignored, it is because the programmer specifically added code to ignore an error, which presumably means it was intentional. The code that detects an error knows more about the error than the code that must recover from the error. There is no more need to translate error codes into human readable strings, the correct string is generated by the error detection code, not the error recovery code. This also leads to consistent error messages for the same error between applications.  Using exceptions to handle errors leads to another issue - how to write exception safe programs. [Here's how](https://dlang.org/exception-safe.html). 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/errors.html>

Unit Tests
==========

 **Contents** 1. [Attributed Unittests](#attributes_unittest)
2. [Documented Unittests](#documented-unittests)

 
```
UnitTest:
    unittest BlockStatement

```
 Unit tests are a builtin framework of test cases applied to a module to determine if it is working properly. A D program can be run with unit tests enabled or disabled. 

 Unit tests are a special function defined like:

 
```
unittest
{
    ...test code...
}

```
 Individual tests are specified in the unit test using [AssertExpressions](expression#AssertExpression). Unlike *AssertExpression*s used elsewhere, the assert is not assumed to hold, and upon assert failure the program is still in a defined state. 

 There can be any number of unit test functions in a module, including within struct, union and class declarations. They are executed in lexical order. 

 Unit tests, when enabled, are run after all static initialization is complete and before the `main()` function is called. 

 For example, given a class `Sum` that is used to add two values, a unit test can be given:

 
```
class Sum
{
    int add(int x, int y) { return x + y; }

    unittest
    {
        Sum sum = new Sum;
        assert(sum.add(3,4) == 7);
        assert(sum.add(-2,0) == -2);
    }
}

```
 When unit tests are enabled, the [version identifier](version#PredefinedVersions) `unittest` is predefined. 

 Attributed Unittests
--------------------

 A unittest may be attributed with any of the global function attributes. Such unittests are useful in verifying the given attribute(s) on a template function:

 
```
void myFunc(T)(T[] data)
{
    if (data.length > 2)
        data[0] = data[1];
}

@safe nothrow unittest
{
    auto arr = [1,2,3];
    myFunc(arr);
    assert(arr == [2,2,3]);
}

```
 This unittest verifies that `myFunc` contains only `@safe`, `nothrow` code. Although this can also be accomplished by attaching these attributes to `myFunc` itself, that would prevent `myFunc` from being instantiated with types `T` that have `@system` or throwing code in their `opAssign` method, or other methods that `myFunc` may call. The above idiom allows `myFunc` to be instantiated with such types, yet at the same time verify that the `@system` and throwing behavior is not introduced by the code within `myFunc` itself.

 **Implementation Defined:** 1. If unit tests are not enabled, the implementation is not required to check the [*UnitTest*](#UnitTest) for syntactic or semantic correctness. This is to reduce the compile time impact of larger unit test sections. The tokens must still be valid, and the implementation can merely count `{` and `}` tokens to find the end of the [*UnitTest*](#UnitTest)'s [*BlockStatement*](statement#BlockStatement).
2. The presentation of unit test results to the user.
3. The method used to enable or disable the unit tests. Use of a compiler switch such as [**-unittest**](https://dlang.org/dmd.html#switch-unittest) to enable them is suggested.
4. The order in which modules are called to run their unit tests.
5. Whether the program stops on the first unit test failure, or continues running the unit tests.

 **Best Practices:** 1. Using unit tests in conjunction with coverage testing (such as [**-cov**](https://dlang.org/dmd.html#switch-cov)) is effective.
2. A unit test for a function should appear immediately following it.

 Documented Unittests
--------------------

 Documented unittests allow the developer to deliver code examples to the user, while at the same time automatically verifying that the examples are valid. This avoids the frequent problem of having outdated documentation for some piece of code.

 If a declaration is followed by a documented unittest, the code in the unittest will be inserted in the **example** section of the declaration:

 
```
/// Math class
class Math
{
    /// add function
    static int add(int x, int y) { return x + y; }

    ///
    unittest
    {
        assert(add(2, 2) == 4);
    }
}

///
unittest
{
    auto math = new Math();
    auto result = math.add(2, 2);
}

```
 The above will generate the following documentation:

 
class Math;  
Math class  
  
 **Example:**
```
auto math = new Math;
auto result = math.add(2, 2);

```

  
 
int add(int *x*, int *y*);  
add function  
  
 **Example:**
```
assert(add(2, 2) == 4);

```
     A unittest which is not documented, or is marked as private will not be used to generate code samples.

 There can be multiple documented unittests and they can appear in any order. They will be attached to the last non-unittest declaration:

 
```
/// add function
int add(int x, int y) { return x + y; }

/// code sample generated
unittest
{
    assert(add(1, 1) == 2);
}

/// code sample not generated because the unittest is private
private unittest
{
    assert(add(2, 2) == 4);
}

unittest
{
    /// code sample not generated because the unittest isn't documented
    assert(add(3, 3) == 6);
}

/// code sample generated, even if it only includes comments (or is empty)
unittest
{
    /** assert(add(4, 4) == 8); */
}

```
 The above will generate the following documentation:

 
int add(int *x*, int *y*);  
add function  
  
 **Examples:**  
 code sample generated 
```

assert(add(1, 1) == 2);

```
   
  
**Examples:**  
 code sample generated, even if it is empty or only includes comments 
```

/** assert(add(4, 4) == 8); */

```
   
  
   

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/unittest.html>

Garbage Collection
==================

 **Contents** 1. [How Garbage Collection Works](#how_gc_works)
2. [Interfacing Garbage Collected Objects With Foreign Code](#gc_foreign_obj)
3. [Pointers and the Garbage Collector](#pointers_and_gc)
4. [Working with the Garbage Collector](#working_with_the_gc)
5. [Object Pinning and a Moving Garbage Collector](#obj_pinning_and_gc)
6. [Configuring the Garbage Collector](#gc_config)
7. [Precise Heap Scanning](#precise_gc)
8. [Precise Scanning of the DATA and TLS segment](#precise_dataseg)
9. [Parallel marking](#gc_parallel)
10. [Adding your own Garbage Collector](#gc_registry)
11. [References](#references)

 D is a systems programming language with support for garbage collection. Usually it is not necessary to free memory explicitly. Just allocate as needed, and the garbage collector will periodically return all unused memory to the pool of available memory. 

 D also provides the mechanisms to write code where the garbage collector is **not involved**. More information is provided below. 

 Programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of garbage collection. Experience both with new projects written with garbage collection in mind, and converting existing projects to garbage collection shows that: 

 * Garbage collected programs are often faster. This is counterintuitive, but the reasons are:
	+ Reference counting is a common solution to solve explicit memory allocation problems. The code to implement the increment and decrement operations whenever assignments are made is one source of slowdown. Hiding it behind smart pointer classes doesn't help the speed. (Reference counting methods are not a general solution anyway, as circular references never get deleted.)
	+ Destructors are used to deallocate resources acquired by an object. For most classes, this resource is allocated memory. With garbage collection, most destructors then become empty and can be discarded entirely.
	+ All those destructors freeing memory can become significant when objects are allocated on the stack. For each one, some mechanism must be established so that if an exception happens, the destructors all get called in each frame to release any memory they hold. If the destructors become irrelevant, then there's no need to set up special stack frames to handle exceptions, and the code runs faster.
	+ Garbage collection kicks in only when memory gets tight. When memory is not tight, the program runs at full speed and does not spend any time tracing and freeing memory.
	+ Garbage collected programs do not suffer from gradual deterioration due to an accumulation of memory leaks.
* Garbage collectors reclaim unused memory, therefore they do not suffer from "memory leaks" which can cause long running applications to gradually consume more and more memory until they bring down the system. GC programs have longer term stability.
* Garbage collected programs have fewer hard-to-find pointer bugs. This is because there are no dangling references to freed memory. There is no code to explicitly manage memory, hence no bugs in such code.
* Garbage collected programs are faster to develop and debug, because there's no need for developing, debugging, testing, or maintaining the explicit deallocation code.

 Garbage collection is not a panacea. There are some downsides: 

 * It is not always obvious when the GC allocates memory, which in turn can trigger a collection, so the program can pause unexpectedly.
* The time it takes for a collection to complete is not bounded. While in practice it is very quick, this cannot normally be guaranteed.
* Normally, all threads other than the collector thread must be halted while the collection is in progress.
* Garbage collectors can keep around some memory that an explicit deallocator would not.
* Garbage collection should be implemented as a basic operating system kernel service. But since it is not, garbage collecting programs must carry around with them the garbage collection implementation. While this can be a shared library, it is still there.

 These constraints are addressed by techniques outlined in [Memory Management](https://wiki.dlang.org/Memory_Management), including the mechanisms provided by D to control allocations outside the GC heap. 

 There is currently work in progress to make the runtime library free of GC heap allocations, to allow its use in scenarios where the use of GC infrastructure is not possible. 

 How Garbage Collection Works
----------------------------

 The GC works by:

 1. Stopping all other threads than the thread currently trying to allocate GC memory.
2. ‘Hijacking’ the current thread for GC work.
3. Scanning all ‘root’ memory ranges for pointers into GC allocated memory.
4. Recursively scanning all allocated memory pointed to by roots looking for more pointers into GC allocated memory.
5. Freeing all GC allocated memory that has no active pointers to it and do not need destructors to run.
6. Queueing all unreachable memory that needs destructors to run.
7. Resuming all other threads.
8. Running destructors for all queued memory.
9. Freeing any remaining unreachable memory.
10. Returning the current thread to whatever work it was doing.

 Interfacing Garbage Collected Objects With Foreign Code
-------------------------------------------------------

 The garbage collector looks for roots in:

 1. the static data segment
2. the stacks and register contents of each thread
3. the TLS (thread-local storage) areas of each thread
4. any roots added by core.memory.GC.addRoot() or core.memory.GC.addRange()

 If the only pointer to an object is held outside of these areas, then the collector will miss it and free the memory. 

 To avoid this from happening, either

 * maintain a pointer to the object in an area the collector does scan for pointers;
* add a root where a pointer to the object is stored using core.memory.GC.addRoot() or core.memory.GC.addRange().
* reallocate and copy the object using the foreign code's storage allocator or using the C runtime library's malloc/free.

 Pointers and the Garbage Collector
----------------------------------

 Pointers in D can be broadly divided into two categories: Those that point to garbage collected memory, and those that do not. Examples of the latter are pointers created by calls to C's malloc(), pointers received from C library routines, pointers to static data, pointers to objects on the stack, etc. For those pointers, anything that is legal in C can be done with them. 

 For garbage collected pointers and references, however, there are some restrictions. These restrictions are minor, but they are intended to enable the maximum flexibility in garbage collector design. 

 **Undefined Behavior:** * Do not xor pointers with other values, like the xor pointer linked list trick used in C.
* Do not use the xor trick to swap two pointer values.
* Do not store pointers into non-pointer variables using casts and other tricks. 
```
void* p;
...
int x = cast(int)p;   // error: undefined behavior

```
 The garbage collector does not scan non-pointer fields for GC pointers.
* Do not take advantage of alignment of pointers to store bit flags in the low order bits: 
```
p = cast(void*)(cast(int)p | 1);  // error: undefined behavior

```
* Do not store into pointers values that may point into the garbage collected heap: 
```
p = cast(void*)12345678;   // error: undefined behavior

```
 A copying garbage collector may change this value.
* Do not store magic values into pointers, other than `null`.
* Do not write pointer values out to disk and read them back in again.
* Do not use pointer values to compute a hash function. A copying garbage collector can arbitrarily move objects around in memory, thus invalidating the computed hash value.
* Do not depend on the ordering of pointers: 
```
if (p1 < p2)  // error: undefined behavior
    ...

```
 since, again, the garbage collector can move objects around in memory.
* Do not add or subtract an offset to a pointer such that the result points outside of the bounds of the garbage collected object originally allocated. 
```
char* p = new char[10];
char* q = p + 6; // ok
q = p + 11;      // error: undefined behavior
q = p - 1;       // error: undefined behavior

```
* Do not misalign pointers if those pointers may point into the GC heap, such as: 
```
struct Foo
{
  align (1):
    byte b;
    char* p;  // misaligned pointer
}

```
 Misaligned pointers may be used if the underlying hardware supports them **and** the pointer is never used to point into the GC heap.
* Do not use byte-by-byte memory copies to copy pointer values. This may result in intermediate conditions where there is not a valid pointer, and if the gc pauses the thread in such a condition, it can corrupt memory. Most implementations of `memcpy()` will work since the internal implementation of it does the copy in aligned chunks greater than or equal to the pointer size, but since this kind of implementation is not guaranteed by the C standard, use `memcpy()` only with extreme caution.
* Do not have pointers in a struct instance that point back to the same instance. The trouble with this is if the instance gets moved in memory, the pointer will point back to where it came from, with likely disastrous results.

 Things that are reliable and can be done:

 * Use a union to share storage with a pointer: 
```
union U { void* ptr; int value }

```
* A pointer to the start of a garbage collected object need not be maintained if a pointer to the interior of the object exists. 
```
char[] p = new char[10];
char[] q = p[3..6];
// q is enough to hold on to the object, don't need to keep
// p as well.

```

 One can avoid using pointers anyway for most tasks. D provides features rendering most explicit pointer uses obsolete, such as reference objects, dynamic arrays, and garbage collection. Pointers are provided in order to interface successfully with C APIs and for some low level work. 

 Working with the Garbage Collector
----------------------------------

 Garbage collection doesn't solve every memory deallocation problem. For example, if a pointer to a large data structure is kept, the garbage collector cannot reclaim it, even if it is never referred to again. To eliminate this problem, it is good practice to set a reference or pointer to an object to null when no longer needed. 

 This advice applies only to static references or references embedded inside other objects. There is not much point for such stored on the stack to be nulled because new stack frames are initialized anyway. 

 Object Pinning and a Moving Garbage Collector
---------------------------------------------

 Although D does not currently use a moving garbage collector, by following the rules listed above one can be implemented. No special action is required to pin objects. A moving collector will only move objects for which there are no ambiguous references, and for which it can update those references. All other objects will be automatically pinned. 

 D Operations That Involve the Garbage Collector
-----------------------------------------------

 Some sections of code may need to avoid using the garbage collector. The following constructs may allocate memory using the garbage collector: 

 * [*NewExpression*](expression#NewExpression)
* Array appending
* Array concatenation
* Array literals (except when used to initialize static data)
* Associative array literals
* Any insertion, removal, or lookups in an associative array
* Extracting keys or values from an associative array
* Taking the address of (i.e. making a delegate to) a nested function that accesses variables in an outer scope
* A function literal that accesses variables in an outer scope
* An [*AssertExpression*](expression#AssertExpression) that fails its condition

 Configuring the Garbage Collector
---------------------------------

 Since version 2.067, The garbage collector can now be configured through the command line, the environment or by options embedded into the executable. 

 By default, GC options can only be passed on the command line of the program to run, e.g.

 
```
app "--DRT-gcopt=profile:1 minPoolSize:16" arguments to app

```
 Available GC options are:

 * disable:0|1 - start disabled
* profile:0|1 - enable profiling with summary when terminating program
* gc:conservative|precise|manual - select gc implementation (default = conservative)
* initReserve:N - initial memory to reserve in MB
* minPoolSize:N - initial and minimum pool size in MB
* maxPoolSize:N - maximum pool size in MB
* incPoolSize:N - pool size increment MB
* parallel:N - number of additional threads for marking
* heapSizeFactor:N - targeted heap size to used memory ratio
* cleanup:none|collect|finalize - how to treat live objects when terminating
	+ collect: run a collection (the default for backward compatibility)
	+ none: do nothing
	+ finalize: all live objects are finalized unconditionally

 In addition, --DRT-gcopt=help will show the list of options and their current settings. 

 Command line options starting with "--DRT-" are filtered out before calling main, so the program will not see them. They are still available via `rt_args`. 

 Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using its default from the runtime:

 
```
extern(C) __gshared bool rt_cmdline_enabled = false;

```
 Likewise, declare a boolean `rt_envvars_enabled` to enable configuration via the environment variable `DRT_GCOPT`:

 
```
extern(C) __gshared bool rt_envvars_enabled = true;

```
 Setting default configuration properties in the executable can be done by specifying an array of options named `rt_options`:

 
```
extern(C) __gshared string[] rt_options = [ "gcopt=initReserve:100 profile:1" ];

```
 Evaluation order of options is `rt_options`, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable. 

 Precise Heap Scanning
---------------------

 Selecting `precise` as the garbage collector via the options above means type information will be used to identify actual or possible pointers or references within heap allocated data objects. Non-pointer data will not be interpreted as a reference to other memory as a "false pointer". The collector has to make pessimistic assumptions if a memory slot can contain both a pointer or an integer value, it will still be scanned (e.g. in a `union`). 

 To use the GC memory functions from `core.memory` for data with a mixture of pointers and non-pointer data, pass the TypeInfo of the allocated struct, class, or type as the optional parameter. The default `null` is interpreted as memory that might contain pointers everywhere.

 
```
struct S { size_t hash; Data* data; }
S* s = cast(S*)GC.malloc(S.sizeof, 0, typeid(S));

```
 Attention: Enabling precise scanning needs slightly more caution with type declarations. For example, when reserving a buffer as part of a struct and later emplacing an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using `void*` is usually the best option as it also ensures proper alignment for pointers being scanned by the GC. 

 Precise Scanning of the DATA and TLS segment
--------------------------------------------

 **Windows only:** As of version 2.075, the DATA (global shared data) and TLS segment (thread local data) of an executable or DLL can be configured to be scanned precisely by the garbage collector instead of conservatively. This takes advantage of information emitted by the compiler to identify possible mutable pointers inside these segments. Immutable pointers [with initializers](const3#immutable_storage_class) are excluded from scanning, too, as they can only point to preallocated memory. 

 Precise scanning can be enabled with the D runtime option "scanDataSeg". Possible option values are "conservative" (default) and "precise". As with the GC options, it can be specified on the command line, in the environment or embedded into the executable, e.g.

 
```
extern(C) __gshared string[] rt_options = [ "scanDataSeg=precise" ];

```
 Attention: Enabling precise scanning needs slightly more caution typing global memory. For example, to pre-allocate memory in the DATA/TLS segment and later emplace an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using `void*` is usually the best option as it also ensures proper alignment for pointers being scanned by the GC.

 
```
class Singleton { void[] mem; }
void*[(__traits(classInstanceSize, Singleton) - 1) / (void*).sizeof + 1]
    singleton_store;
static this()
{
    emplace!Singleton(singleton_store).mem = allocateMem();
}
Singleton singleton() { return cast(Singleton)singleton_store.ptr; }

```
 For precise typing of that area, let the compiler generate the class instance into the DATA segment: 
```
class Singleton { void[] mem; }
shared(Singleton) singleton = new Singleton;
shared static this() { singleton.mem = allocateSharedMem(); }

```
 This doesn't work for TLS memory, though. Parallel marking
----------------

 By default the garbage collector uses all available CPU cores to mark the heap.

 This might affect your application if it has threads that are not suspended during the mark phase of the collection. Configure the number of additional threads used for marking by GC option `parallel`, e.g. by passing `--DRT-gcopt=parallel:2` on the command line or embedding the option into the binary via `rt_options`. The number of threads actually created is limited to [`core.cpuid.threadsPerCPU-1`](https://dlang.org/library/core/cpuid/threads_per_cpu.html). A value of `0` disables parallel marking completely.

 Adding your own Garbage Collector
---------------------------------

 GC implementations are added to a registry that allows to supply more implementations by just linking them into the binary. To do so add a function that is executed before the D runtime initialization using `pragma(crt_constructor)`:

 
```
import core.gc.gcinterface, core.gc.registry;
extern (C) pragma(crt_constructor) void registerMyGC()
{
    registerGCFactory("mygc", &createMyGC);
}

GC createMyGC()
{
    __gshared instance = new MyGC;
    instance.initialize();
    return instance;
}

class MyGC : GC { /*...*/ }

```
 [The GC modules defining the interface (gc.interface) and registration (gc.registry) are currently not public and are subject to change from version to version. Add an import search path to the druntime/src path to compile the example.]

 The new GC is added to the list of available garbage collectors that can be selected via the usual configuration options, e.g. by embedding `rt_options` into the binary:

 
```
extern (C) __gshared string[] rt_options = ["gcopt=gc:mygc"];

```
 The standard GC implementation from a statically linked binary can be removed by redefining the function `extern(C) void* register_default_gcs()`. If no custom garbage collector has been registered all attempts to allocate GC managed memory will terminate the application with an appropriate message.

 References
----------

 * [Wikipedia](https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29)
* [GC FAQ](http://www.iecc.com/gclist/GC-faq.html)
* [Uniprocessor Garbage Collector Techniques](ftp://ftp.cs.utexas.edu/pub/garbage/gcsurvey.ps)
* [Garbage Collection: Algorithms for Automatic Dynamic Memory Management](http://amazon.com/exec/obidos/ASIN/0471941484/classicempire)

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/garbage.html>

Floating Point
==============

 **Contents** 1. [Floating Point Intermediate Values](#fp_intermediate_values)
2. [Floating Point Constant Folding](#fp_const_folding)
3. [Rounding Control](#rounding_control)
4. [Exception Flags](#esception_flags)
5. [Floating Point Transformations](#floating-point-transformations)

 Floating Point Intermediate Values
----------------------------------

 On many computers, greater precision operations do not take any longer than lesser precision operations, so it makes numerical sense to use the greatest precision available for internal temporaries. The philosophy is not to dumb down the language to the lowest common hardware denominator, but to enable the exploitation of the best capabilities of target hardware. 

 For floating point operations and expression intermediate values, a greater precision can be used than the type of the expression. Only the minimum precision is set by the types of the operands, not the maximum. **Implementation Note:** On Intel x86 machines, for example, it is expected (but not required) that the intermediate calculations be done to the full 80 bits of precision implemented by the hardware. 

 It's possible that, due to greater use of temporaries and common subexpressions, optimized code may produce a more accurate answer than unoptimized code. 

 Algorithms should be written to work based on the minimum precision of the calculation. They should not degrade or fail if the actual precision is greater. Float or double types, as opposed to the real (extended) type, should only be used for: 

 * reducing memory consumption for large arrays
* when speed is more important than accuracy
* data and function argument compatibility with C

 Floating Point Constant Folding
-------------------------------

 Regardless of the type of the operands, floating point constant folding is done in `real` or greater precision. It is always done following IEEE 754 rules and round-to-nearest is used.

 Floating point constants are internally represented in the implementation in at least `real` precision, regardless of the constant's type. The extra precision is available for constant folding. Committing to the precision of the result is done as late as possible in the compilation process. For example:

 
```
const float f = 0.2f;
writeln(f - 0.2);

```
 will print 0. A non-const static variable's value cannot be propagated at compile time, so:

 
```
static float f = 0.2f;
writeln(f - 0.2);

```
 will print 2.98023e-09. Hex floating point constants can also be used when specific floating point bit patterns are needed that are unaffected by rounding. To find the hex value of 0.2f:

 
```
import std.stdio;

void main()
{
    writefln("%a", 0.2f);
}

```
 which is 0x1.99999ap-3. Using the hex constant:

 
```
const float f = 0x1.99999ap-3f;
writeln(f - 0.2);

```
 prints 2.98023e-09.

 Different compiler settings, optimization settings, and inlining settings can affect opportunities for constant folding, therefore the results of floating point calculations may differ depending on those settings.

 Rounding Control
----------------

 IEEE 754 floating point arithmetic includes the ability to set 4 different rounding modes. These are accessible via the functions in `core.stdc.fenv`. 

 If the floating-point rounding mode is changed within a function, it must be restored before the function exits. If this rule is violated (for example, by the use of inline asm), the rounding mode used for subsequent calculations is undefined. 

 Exception Flags
---------------

 IEEE 754 floating point arithmetic can set several flags based on what happened with a computation:

 

|  |
| --- |
| `FE_INVALID` |
| `FE_DENORMAL` |
| `FE_DIVBYZERO` |
| `FE_OVERFLOW` |
| `FE_UNDERFLOW` |
| `FE_INEXACT` |

 These flags can be set/reset via the functions in `core.stdc.fenv`.

 Floating Point Transformations
------------------------------

 An implementation may perform transformations on floating point computations in order to reduce their strength, i.e. their runtime computation time. Because floating point math does not precisely follow mathematical rules, some transformations are not valid, even though some other programming languages still allow them. 

 The following transformations of floating point expressions are not allowed because under IEEE rules they could produce different results. 

 

Disallowed Floating Point Transformations| **transformation** | **comments** |
| *x* + 0 → *x* | not valid if *x* is -0  |
| *x* - 0 → *x* | not valid if *x* is ±0 and rounding is towards -∞  |
|  -*x* ↔ 0 - *x* | not valid if *x* is +0  |
| *x* - *x* → 0  | not valid if *x* is NaN or ±∞  |
| *x* - *y* ↔ -(*y* - *x*)  | not valid because (1-1=+0) whereas -(1-1)=-0  |
| *x* \* 0 → 0  | not valid if *x* is NaN or ±∞  |
| *x* / *c* ↔ *x* \* (1/*c*)  | valid if (1/*c*) yields an e*x*act result  |
| *x* != *x* → false  | not valid if *x* is a NaN  |
| *x* == *x* → true  | not valid if *x* is a NaN  |
| *x* !*op* *y* ↔ !(*x* *op* *y*)  | not valid if *x* or *y* is a NaN  |

 Of course, transformations that would alter side effects are also invalid.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/float.html>

Templates
=========

 **Contents** 1. [Explicit Template Instantiation](#explicit_tmp_instantiation)
	1. [Practical Example](#copy_example)
2. [Instantiation Scope](#instantiation_scope)
3. [Argument Deduction](#argument_deduction)
4. [Template Type Parameters](#template_type_parameters)
	1. [Specialization](#parameters_specialization)
5. [Template This Parameters](#template_this_parameter)
6. [Template Value Parameters](#template_value_parameter)
7. [Template Alias Parameters](#aliasparameters)
	1. [Typed alias parameters](#typed_alias_op)
	2. [Specialization](#alias_parameter_specialization)
8. [Template Sequence Parameters](#variadic-templates)
	1. [Specialization](#variadic_template_specialization)
9. [Template Parameter Default Values](#template_parameter_def_values)
10. [Eponymous Templates](#implicit_template_properties)
11. [Template Constructors](#template_ctors)
12. [Aggregate Templates](#aggregate_templates)
13. [Function Templates](#function-templates)
14. [Enum & Variable Templates](#variable-template)
15. [Alias Templates](#alias-template)
	1. [Function Templates with Auto Ref Parameters](#auto-ref-parameters)
16. [Nested Templates](#nested-templates)
	1. [Implicit Nesting](#implicit-nesting)
	2. [Context Limitation](#nested_template_limitation)
17. [Recursive Templates](#recursive_templates)
18. [Template Constraints](#template_constraints)
19. [Limitations](#limitations)

 Templates are D's approach to generic programming. Templates are defined with a *TemplateDeclaration*: 

 
```
TemplateDeclaration:
    template Identifier TemplateParameters Constraintopt { DeclDefsopt }

TemplateParameters:
    ( TemplateParameterListopt )

TemplateParameterList:
    TemplateParameter
    TemplateParameter ,
    TemplateParameter , TemplateParameterList

TemplateParameter:
    TemplateTypeParameter
    TemplateValueParameter
    TemplateAliasParameter
    TemplateSequenceParameter
    TemplateThisParameter

```
 The body of the *TemplateDeclaration* must be syntactically correct even if never instantiated. Semantic analysis is not done until instantiated. A template forms its own scope, and the template body can contain classes, structs, types, enums, variables, functions, and other templates. 

 Template parameters can be types, values, symbols, or sequences. Types can be any type. Value parameters must be of an integral type, floating point type, or string type and specializations for them must resolve to an integral constant, floating point constant, null, or a string literal. Symbols can be any non-local symbol. Sequences can contain zero or more types, values or symbols. 

 Template parameter specializations constrain the values or types the *TemplateParameter* can accept. 

 Template parameter defaults are the value or type to use for the *TemplateParameter* in case one is not supplied. 

 Explicit Template Instantiation
-------------------------------

 Templates are explicitly instantiated with: 

 
```
TemplateInstance:
    Identifier TemplateArguments

TemplateArguments:
    ! ( TemplateArgumentListopt )
    ! TemplateSingleArgument

TemplateArgumentList:
    TemplateArgument
    TemplateArgument ,
    TemplateArgument , TemplateArgumentList

TemplateArgument:
    Type
    AssignExpression
    Symbol

Symbol:
    SymbolTail
    . SymbolTail

SymbolTail:
    Identifier
    Identifier . SymbolTail
    TemplateInstance
    TemplateInstance . SymbolTail

TemplateSingleArgument:
    Identifier
    FundamentalType
    CharacterLiteral
    StringLiteral
    IntegerLiteral
    FloatLiteral
    true
    false
    null
    this
    SpecialKeyword

```
 Once instantiated, the declarations inside the template, called the template members, are in the scope of the *TemplateInstance*:

 
```
template TFoo(T) { alias Ptr = T*; }
...
TFoo!(int).Ptr x; // declare x to be of type int*

```
 If the [*TemplateArgument*](#TemplateArgument) is one token long, the parentheses can be omitted:

 
```
TFoo!int.Ptr x;   // same as TFoo!(int).Ptr x;

```
 A template instantiation can be aliased:

 
```
template TFoo(T) { alias Ptr = T*; }
alias foo = TFoo!(int);
foo.Ptr x;        // declare x to be of type int*

```
 Multiple instantiations of a *TemplateDeclaration* with the same *TemplateArgumentList* will all refer to the same instantiation. For example:

 
```
template TFoo(T) { T f; }
alias a = TFoo!(int);
alias b = TFoo!(int);
...
a.f = 3;
assert(b.f == 3);  // a and b refer to the same instance of TFoo

```
 This is true even if the *TemplateInstance*s are done in different modules. 

 Even if template arguments are implicitly converted to the same template parameter type, they still refer to the same instance. This example uses a [`struct` template](#aggregate_templates):

 
```
struct TFoo(int x) { }

// Different template parameters create different struct types
static assert(!is(TFoo!(3) == TFoo!(2)));
// 3 and 2+1 are both 3 of type int - same TFoo instance
static assert(is(TFoo!(3) == TFoo!(2 + 1)));

// 3u is implicitly converted to 3 to match int parameter,
// and refers to exactly the same instance as TFoo!(3)
static assert(is(TFoo!(3) == TFoo!(3u)));

```
 If multiple templates with the same *Identifier* are declared, they are distinct if they have a different number of arguments or are differently specialized. 

 ### Practical Example

 A simple generic copy template would be:

 
```
template TCopy(T)
{
    void copy(out T to, T from)
    {
        to = from;
    }
}

```
 To use this template, it must first be instantiated with a specific type:

 
```
int i;
TCopy!(int).copy(i, 3);

```
 See also [function templates](#function-templates).

 Instantiation Scope
-------------------

 *TemplateInstance*s are always instantiated in the scope of where the *TemplateDeclaration* is declared, with the addition of the template parameters being declared as aliases for their deduced types. 

 For example:

   
  
 *module a* 
```
template TFoo(T) { void bar() { func(); } }

```
 *module b* 
```
import a;

void func() { }
alias f = TFoo!(int); // error: func not defined in module a

```
 and:   
  
 *module a* 
```
template TFoo(T) { void bar() { func(1); } }
void func(double d) { }

```
 *module b* 
```
import a;

void func(int i) { }
alias f = TFoo!(int);
...
f.bar();  // will call a.func(double)

```
 *TemplateParameter* specializations and default values are evaluated in the scope of the *TemplateDeclaration*. 

 Argument Deduction
------------------

 The types of template parameters are deduced for a particular template instantiation by comparing the template argument with the corresponding template parameter. 

 For each template parameter, the following rules are applied in order until a type is deduced for each parameter: 

 1. If there is no type specialization for the parameter, the type of the parameter is set to the template argument.
2. If the type specialization is dependent on a type parameter, the type of that parameter is set to be the corresponding part of the type argument.
3. If after all the type arguments are examined, there are any type parameters left with no type assigned, they are assigned types corresponding to the template argument in the same position in the *TemplateArgumentList*.
4. If applying the above rules does not result in exactly one type for each template parameter, then it is an error.

 For example:

 
```
template TFoo(T) { }
alias foo1 = TFoo!(int);     // (1) T is deduced to be int
alias foo2 = TFoo!(char*);   // (1) T is deduced to be char*

template TBar(T : T*) { }
alias bar = TBar!(char*);    // (2) T is deduced to be char

template TAbc(D, U : D[]) { }
alias abc1 = TAbc!(int, int[]);  // (2) D is deduced to be int, U is int[]
alias abc2 = TAbc!(char, int[]); // (4) error, D is both char and int

template TDef(D : E*, E) { }
alias def = TDef!(int*, int);  // (1) E is int
                               // (3) D is int*

```
 Deduction from a specialization can provide values for more than one parameter:

 
```
template Foo(T: T[U], U)
{
    ...
}

Foo!(int[long])  // instantiates Foo with T set to int, U set to long

```
 When considering matches, a class is considered to be a match for any super classes or interfaces:

 
```
class A { }
class B : A { }

template TFoo(T : A) { }
alias foo = TFoo!(B);      // (3) T is B

template TBar(T : U*, U : A) { }
alias bar = TBar!(B*, B);  // (2) T is B*
                           // (3) U is B

```
 Template Type Parameters
------------------------

 
```
TemplateTypeParameter:
    Identifier
    Identifier TemplateTypeParameterSpecialization
    Identifier TemplateTypeParameterDefault
    Identifier TemplateTypeParameterSpecialization TemplateTypeParameterDefault

TemplateTypeParameterSpecialization:
    : Type

TemplateTypeParameterDefault:
    = Type

```
 ### Specialization

 Templates may be specialized for particular types of arguments by following the template parameter identifier with a : and the specialized type. For example:

 
```
template TFoo(T)        { ... } // #1
template TFoo(T : T[])  { ... } // #2
template TFoo(T : char) { ... } // #3
template TFoo(T, U, V)  { ... } // #4

alias foo1 = TFoo!(int);            // instantiates #1
alias foo2 = TFoo!(double[]);       // instantiates #2 with T being double
alias foo3 = TFoo!(char);           // instantiates #3
alias fooe = TFoo!(char, int);      // error, number of arguments mismatch
alias foo4 = TFoo!(char, int, int); // instantiates #4

```
 The template picked to instantiate is the one that is most specialized that fits the types of the *TemplateArgumentList*. If the result is ambiguous, it is an error. 

 Template This Parameters
------------------------

 
```
TemplateThisParameter:
    this TemplateTypeParameter

```
 *TemplateThisParameter*s are used in member function templates to pick up the type of the *this* reference. It also will infer the mutability of the `this` reference. For example, if `this` is `const`, then the function is marked `const`.

 
```
import std.stdio;

struct S
{
    const void foo(this T)(int i)
    {
        writeln(typeid(T));
    }
}

void main()
{
    const(S) s;
    (&s).foo(1);
    S s2;
    s2.foo(2);
    immutable(S) s3;
    s3.foo(3);
}

```
 Prints: 
```
const(S)
S
immutable(S)

```
 This is especially useful when used with inheritance. For example, consider the implementation of a final base method which returns a derived class type. Typically this would return a base type, but that would prohibit calling or accessing derived properties of the type:

 
```
interface Addable(T)
{
    final auto add(T t)
    {
        return this;
    }
}

class List(T) : Addable!T
{
    List remove(T t)
    {
        return this;
    }
}

void main()
{
    auto list = new List!int;
    list.add(1).remove(1);  // error: no 'remove' method for Addable!int
}

```
 Here the method `add` returns the base type, which doesn't implement the `remove` method. The `template this` parameter can be used for this purpose:

 
```
interface Addable(T)
{
    final R add(this R)(T t)
    {
        return cast(R)this;  // cast is necessary, but safe
    }
}

class List(T) : Addable!T
{
    List remove(T t)
    {
        return this;
    }
}

void main()
{
    auto list = new List!int;
    list.add(1).remove(1);  // ok
}

```
 Template Value Parameters
-------------------------

 
```
TemplateValueParameter:
    BasicType Declarator
    BasicType Declarator TemplateValueParameterSpecialization
    BasicType Declarator TemplateValueParameterDefault
    BasicType Declarator TemplateValueParameterSpecialization TemplateValueParameterDefault

TemplateValueParameterSpecialization:
    : ConditionalExpression

TemplateValueParameterDefault:
    = AssignExpression
    = SpecialKeyword

```
 Template value parameter types can be any type which can be statically initialized at compile time. Template value arguments can be integer values, floating point values, nulls, string values, array literals of template value arguments, associative array literals of template value arguments, or struct literals of template value arguments.

 
```
template foo(string s)
{
    string bar() { return s ~ " betty"; }
}

void main()
{
    writefln("%s", foo!("hello").bar()); // prints: hello betty
}

```
 This example of template foo has a value parameter that is specialized for 10:

 
```
template foo(U : int, int v : 10)
{
    U x = v;
}

void main()
{
    assert(foo!(int, 10).x == 10);
}

```
 Template Alias Parameters
-------------------------

 
```
TemplateAliasParameter:
    alias Identifier TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt
    alias BasicType Declarator TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt

TemplateAliasParameterSpecialization:
    : Type
    : ConditionalExpression

TemplateAliasParameterDefault:
    = Type
    = ConditionalExpression

```
 Alias parameters enable templates to be parameterized with symbol names or values computed at compile-time. Almost any kind of D symbol can be used, including user-defined type names, global names, local names, module names, template names, and template instance names. 

 **Symbol examples:**

 * User-defined type names 
```
class Foo
{
    static int x;
}

template Bar(alias a)
{
    alias sym = a.x;
}

void main()
{
    alias bar = Bar!(Foo);
    bar.sym = 3;  // sets Foo.x to 3
}

```
* Global names 
```
shared int x;

template Foo(alias var)
{
    auto ptr = &var;
}

void main()
{
    alias bar = Foo!(x);
    *bar.ptr = 3;       // set x to 3
    static shared int y;
    alias abc = Foo!(y);
    *abc.ptr = 3;       // set y to 3
}

```
* Local names 
```
template Foo(alias var)
{
    void inc() { var++; }
}

void main()
{
    int v = 4;
    alias foo = Foo!v;
    foo.inc();
    assert(v == 5);
}

```
 See also [Implicit Template Nesting](#implicit-nesting).
* Module names 
```
import std.conv;

template Foo(alias a)
{
    alias sym = a.text;
}

void main()
{
    alias bar = Foo!(std.conv);
    bar.sym(3);   // calls std.conv.text(3)
}

```
* Template names 
```
shared int x;

template Foo(alias var)
{
    auto ptr = &var;
}

template Bar(alias Tem)
{
    alias instance = Tem!(x);
}

void main()
{
    alias bar = Bar!(Foo);
    *bar.instance.ptr = 3;  // sets x to 3
}

```
* Template instance names 
```
shared int x;

template Foo(alias var)
{
    auto ptr = &var;
}

template Bar(alias sym)
{
    alias p = sym.ptr;
}

void main()
{
    alias foo = Foo!(x);
    alias bar = Bar!(foo);
    *bar.p = 3;  // sets x to 3
}

```

 **Value examples:**

 * Literals 
```
template Foo(alias x, alias y)
{
    static int i = x;
    static string s = y;
}

void main()
{
    alias foo = Foo!(3, "bar");
    writeln(foo.i, foo.s);  // prints 3bar
}

```
* Compile-time values 
```
template Foo(alias x)
{
    static int i = x;
}

void main()
{
    // compile-time argument evaluation
    enum two = 1 + 1;
    alias foo = Foo!(5 * two);
    assert(foo.i == 10);
    static assert(foo.stringof == "Foo!10");

    // compile-time function evaluation
    int get10() { return 10; }
    alias bar = Foo!(get10());
    // bar is the same template instance as foo
    assert(&bar.i is &foo.i);
}

```
* Lambdas 
```
template Foo(alias fun)
{
    enum val = fun(2);
}

alias foo = Foo!((int x) => x * x);
static assert(foo.val == 4);

```

 ### Typed alias parameters

 Alias parameters can also be typed. These parameters will accept symbols of that type:

 
```
template Foo(alias int x) { }
int x;
float f;

Foo!x;  // ok
Foo!f;  // fails to instantiate

```
 ### Specialization

 Alias parameters can accept both literals and user-defined type symbols, but they are less specialized than the matches to type parameters and value parameters:

 
```
template Foo(T)         { ... }  // #1
template Foo(int n)     { ... }  // #2
template Foo(alias sym) { ... }  // #3

struct S {}
int var;

alias foo1  = Foo!(S);      // instantiates #1
alias foo2  = Foo!(1);      // instantiates #2
alias foo3a = Foo!([1,2]);  // instantiates #3
alias foo3b = Foo!(var);    // instantiates #3

```
 
```
template Bar(alias A) { ... }                 // #4
template Bar(T : U!V, alias U, V...) { ... }  // #5

class C(T) {}
alias bar = Bar!(C!int);    // instantiates #5

```
 Template Sequence Parameters
----------------------------

 
```
TemplateSequenceParameter:
    Identifier ...

```
 If the last template parameter in the *TemplateParameterList* is declared as a *TemplateSequenceParameter*, it is a match with any trailing template arguments. Such a sequence of arguments can be defined using the template [`std.meta.AliasSeq`](https://dlang.org/phobos/std_meta.html#AliasSeq) and will thus henceforth be referred to by that name for clarity. An *AliasSeq* is not itself a type, value, or symbol. It is a compile-time sequence of any mix of types, values or symbols. 

 An *AliasSeq* whose elements consist entirely of types is called a type sequence or *TypeSeq*. An *AliasSeq* whose elements consist entirely of values is called a value sequence or *ValueSeq*. 

 An *AliasSeq* can be used as an argument list to instantiate another template, or as the list of parameters for a function.

 
```
template print(args...)
{
    void print()
    {
        writeln("args are ", args); // args is a ValueSeq
    }
}

template write(Args...)
{
    void write(Args args) // Args is a TypeSeq
                          // args is a ValueSeq
    {
        writeln("args are ", args);
    }
}

void main()
{
    print!(1,'a',6.8).print();                    // prints: args are 1a6.8
    write!(int, char, double).write(1, 'a', 6.8); // prints: args are 1a6.8
}

```
 The number of elements in an *AliasSeq* can be retrieved with the `.length` property. The *n*th element can be retrieved by indexing the *AliasSeq* with [*n*], and sub-sequences are denoted by the slicing syntax. 

 *AliasSeq*-s are static compile-time entities, there is no way to dynamically change, add, or remove elements either at compile-time or run-time. 

 Type sequences can be deduced from the trailing parameters of an implicitly instantiated function template:

 
```
template print(T, Args...)
{
    void print(T first, Args args)
    {
        writeln(first);
        static if (args.length) // if more arguments
            print(args);        // recurse for remaining arguments
    }
}

void main()
{
    print(1, 'a', 6.8);
}

```
 prints: 
```
1
a
6.8

```
 Type sequences can also be deduced from the type of a delegate or function parameter list passed as a function argument:

 
```
import std.stdio;

/* Partially applies a delegate by tying its first argument to a particular value.
 * R = return type
 * T = first argument type
 * Args = TypeSeq of remaining argument types
 */
R delegate(Args) partial(R, T, Args...)(R delegate(T, Args) dg, T first)
{
    // return a closure
    return (Args args) => dg(first, args);
}

void main()
{
    int plus(int x, int y, int z)
    {
        return x + y + z;
    }

    auto plus_two = partial(&plus, 2);
    writefln("%d", plus_two(6, 8)); // prints 16
}

```
 See also: [`std.functional.partial`](https://dlang.org/phobos/std_functional.html#partial) ### Specialization

 If both a template with a sequence parameter and a template without a sequence parameter exactly match a template instantiation, the template without a *TemplateSequenceParameter* is selected.

 
```
template Foo(T)         { pragma(msg, "1"); }   // #1
template Foo(int n)     { pragma(msg, "2"); }   // #2
template Foo(alias sym) { pragma(msg, "3"); }   // #3
template Foo(Args...)   { pragma(msg, "4"); }   // #4

import std.stdio;

// Any sole template argument will never match to #4
alias foo1 = Foo!(int);          // instantiates #1
alias foo2 = Foo!(3);            // instantiates #2
alias foo3 = Foo!(std);          // instantiates #3

alias foo4 = Foo!(int, 3, std);  // instantiates #4

```
 Template Parameter Default Values
---------------------------------

 Trailing template parameters can be given default values:

 
```
template Foo(T, U = int) { ... }
Foo!(uint,long); // instantiate Foo with T as uint, and U as long
Foo!(uint);      // instantiate Foo with T as uint, and U as int

template Foo(T, U = T*) { ... }
Foo!(uint);      // instantiate Foo with T as uint, and U as uint*

```
 Eponymous Templates
-------------------

 If a template contains members whose name is the same as the template identifier then these members are assumed to be referred to in a template instantiation:

 
```
template foo(T)
{
    T foo; // declare variable foo of type T
}

void main()
{
    foo!(int) = 6; // instead of foo!(int).foo
}

```
 Using functions and more types than the template:

 
```
template foo(S, T)
{
    // each member contains all the template parameters
    void foo(S s, T t) {}
    void foo(S s, T t, string) {}
}

void main()
{
    foo(1, 2, "test"); // foo!(int, int).foo(1, 2, "test")
    foo(1, 2); // foo!(int, int).foo(1, 2)
}

```
 When the template parameters must be deduced, the eponymous members can't rely on a [`static if`](version#StaticIfCondition) condition since the deduction relies on how the in members are used:

 
```
template foo(T)
{
    static if (is(T)) // T is not yet known...
        void foo(T t) {} // T is deduced from the member usage
}

void main()
{
    foo(0); // Error: cannot deduce function from argument types
    foo!int(0); // Ok since no deduction necessary
}

```
 Template Constructors
---------------------

 
```
ConstructorTemplate:
    this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt :
    this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt FunctionBody

```
 Templates can be used to form constructors for classes and structs. 

 Aggregate Templates
-------------------

 
```
ClassTemplateDeclaration:
    class Identifier TemplateParameters ;
    class Identifier TemplateParameters Constraintopt BaseClassListopt AggregateBody
    class Identifier TemplateParameters BaseClassListopt Constraintopt AggregateBody

InterfaceTemplateDeclaration:
    interface Identifier TemplateParameters ;
    interface Identifier TemplateParameters Constraintopt BaseInterfaceListopt AggregateBody
    interface Identifier TemplateParameters BaseInterfaceList Constraint AggregateBody

StructTemplateDeclaration:
    struct Identifier TemplateParameters ;
    struct Identifier TemplateParameters Constraintopt AggregateBody

UnionTemplateDeclaration:
    union Identifier TemplateParameters ;
    union Identifier TemplateParameters Constraintopt AggregateBody

```
 If a template declares exactly one member, and that member is a class with the same name as the template (see [Eponymous Templates](#implicit_template_properties):)

 
```
template Bar(T)
{
    class Bar
    {
        T member;
    }
}

```
 then the semantic equivalent, called a *ClassTemplateDeclaration* can be written as: 
```
class Bar(T)
{
    T member;
}

```
 See also: [Template This Parameters](#template_this_parameter). 

 Analogously to class templates, struct, union and interfaces can be transformed into templates by supplying a template parameter list. 

 Function Templates
------------------

 If a template declares exactly one member, and that member is a function with the same name as the template, it is a function template declaration. Alternatively, a function template declaration is a function declaration with a [*TemplateParameterList*](#TemplateParameterList) immediately preceding the [*Parameters*](function#Parameters). 

 A function template to compute the square of type *T* is:

 
```
T Square(T)(T t)
{
    return t * t;
}

```
 It is lowered to:

 
```
template Square(T)
{
    T Square(T t)
    {
        return t * t;
    }
}

```
 Function templates can be explicitly instantiated with a !(*TemplateArgumentList*):

 
```
writefln("The square of %s is %s", 3, Square!(int)(3));

```
 or implicitly, where the *TemplateArgumentList* is deduced from the types of the function arguments: 
```
writefln("The square of %s is %s", 3, Square(3));  // T is deduced to be int

```
 If there are fewer arguments supplied in the *TemplateArgumentList* than parameters in the *TemplateParameterList*, the arguments fulfill parameters from left to right, and the rest of the parameters are then deduced from the function arguments. 

 The process of deducing template type parameters from function arguments is called Implicit Function Template Instantiation (IFTI). 

 Function template type parameters that are to be implicitly deduced may not have specializations:

 
```
void Foo(T : T*)(T t) { ... }

int x,y;
Foo!(int*)(x);   // ok, T is not deduced from function argument
Foo(&y);         // error, T has specialization

```
 Template arguments not implicitly deduced can have default values:

 
```
void Foo(T, U=T*)(T t) { U p; ... }

int x;
Foo(x);    // T is int, U is int*

```
 If template type parameters match the literal expressions on function arguments, the deduced types may consider narrowing conversions of them. 

 
```
void foo(T)(T v)        { pragma(msg, "in foo, T = ", T); }
void bar(T)(T v, T[] a) { pragma(msg, "in bar, T = ", T); }

foo(1);
// an integer literal type is analyzed as int by default
// then T is deduced to int

short[] arr;
bar(1, arr);
// arr is short[], and the integer literal 1 is
// implicitly convertible to short.
// then T will be deduced to short.

bar(1, [2.0, 3.0]);
// the array literal is analyzed as double[],
// and the integer literal 1 is implicitly convertible to double.
// then T will be deduced to double.

```
 The deduced type parameter for dynamic array and pointer arguments has an unqualified head:

 
```
void foo(T)(T arg) { pragma(msg, T); }

int[] marr;
const(int[]) carr;
immutable(int[]) iarr;
foo(marr);  // T == int[]
foo(carr);  // T == const(int)[]
foo(iarr);  // T == immutable(int)[]

int* mptr;
const(int*) cptr;
immutable(int*) iptr;
foo(mptr);  // T == int*
foo(cptr);  // T == const(int)*
foo(iptr);  // T == immutable(int)*

```
 Type parameter deduction is not influenced by the order of function arguments. 

 Function templates can have their return types deduced based on the [*ReturnStatement*](statement#ReturnStatement)s in the function, just as with normal functions. See [Auto Functions](https://dlang.org/function.html#auto-functions). 

 
```
auto Square(T)(T t)
{
    return t * t;
}

```
 Variadic Function Templates can have parameters with default values. These parameters are always set to their default value in case of IFTI. 

 
```
size_t fun(T...)(T t, string file = __FILE__)
{
    import std.stdio;
    writeln(file, " ", t);
    return T.length;
}
assert(fun(1, "foo") == 2);  // uses IFTI
assert(fun!int(1, "foo") == 1);  // no IFTI

```
 Enum & Variable Templates
-------------------------

 Like aggregates and functions, manifest constant and variable declarations can have template parameters, providing there is an [*Initializer*](declaration#Initializer):

 
```
enum string constant(TL...) = TL.stringof;
ubyte[T.sizeof] storage(T) = 0;
auto array(alias a) = a;

```
 These declarations are transformed into templates:

 
```
template constant(TL...)
{
    enum string constant = TL.stringof;
}
template storage(T)
{
    ubyte[T.sizeof] storage = 0;
}
template array(alias a)
{
    auto array = a;
}

```
 Alias Templates
---------------

 [*AliasDeclaration*](declaration#AliasDeclaration) can also have optional template parameters:

 
```
alias Sequence(TL...) = TL;

```
 It is lowered to: 
```
template Sequence(TL...)
{
    alias Sequence = TL;
}

```
 ### Function Templates with Auto Ref Parameters

 An auto ref function template parameter becomes a ref parameter if its corresponding argument is an lvalue, otherwise it becomes a value parameter:

 
```
int foo(Args...)(auto ref Args args)
{
    int result;

    foreach (i, v; args)
    {
        if (v == 10)
            assert(__traits(isRef, args[i]));
        else
            assert(!__traits(isRef, args[i]));
        result += v;
    }
    return result;
}

void main()
{
    int y = 10;
    int r;
    r = foo(8);       // returns 8
    r = foo(y);       // returns 10
    r = foo(3, 4, y); // returns 17
    r = foo(4, 5, y); // returns 19
    r = foo(y, 6, y); // returns 26
}

```
 Auto ref parameters can be combined with auto ref return attributes:

 
```
auto ref min(T, U)(auto ref T lhs, auto ref U rhs)
{
    return lhs > rhs ? rhs : lhs;
}

void main()
{
    int x = 7, y = 8;
    int i;

    i = min(4, 3);     // returns 3
    i = min(x, y);     // returns 7
    min(x, y) = 10;    // sets x to 10
    static assert(!__traits(compiles, min(3, y) = 10));
    static assert(!__traits(compiles, min(y, 3) = 10));
}

```
 Nested Templates
----------------

 If a template is declared in aggregate or function local scope, the instantiated functions will implicitly capture the context of the enclosing scope.

 
```
class C
{
    int num;

    this(int n) { num = n; }

    template Foo()
    {
        // 'foo' can access 'this' reference of class C object.
        void foo(int n) { this.num = n; }
    }
}

void main()
{
    auto c = new C(1);
    assert(c.num == 1);

    c.Foo!().foo(5);
    assert(c.num == 5);

    template Bar()
    {
        // 'bar' can access local variable of 'main' function.
        void bar(int n) { c.num = n; }
    }
    Bar!().bar(10);
    assert(c.num == 10);
}

```
 Above, `Foo!().foo` will work just the same as a member function of class `C`, and `Bar!().bar` will work just the same as a nested function within function `main()`.

 ### Implicit Nesting

 If a template has a [template alias parameter](#aliasparameters), and is instantiated with a local symbol, the instantiated function will implicitly become nested in order to access runtime data of the given local symbol.

 
```
template Foo(alias sym)
{
    void foo() { sym = 10; }
}

class C
{
    int num;

    this(int n) { num = n; }

    void main()
    {
        assert(this.num == 1);

        alias fooX = Foo!(C.num).foo;

        // fooX will become member function implicitly, so &fooX
        //     returns a delegate object.
        static assert(is(typeof(&fooX) == delegate));

        fooX(); // called by using valid 'this' reference.
        assert(this.num == 10);  // OK
    }
}

void main()
{
    new C(1).main();

    int num;
    alias fooX = Foo!num.foo;

    // fooX will become nested function implicitly, so &fooX
    //     returns a delegate object.
    static assert(is(typeof(&fooX) == delegate));

    fooX();
    assert(num == 10);  // OK
}

```
 Not only functions, but also instantiated class and struct types can become nested via implicitly captured context.

 
```
class C
{
    int num;
    this(int n) { num = n; }

    class N(T)
    {
        // instantiated class N!T can become nested in C
        T foo() { return num * 2; }
    }
}

void main()
{
    auto c = new C(10);
    auto n = c.new N!int();
    assert(n.foo() == 20);
}

```
 See also: [Nested Class Instantiation](class#nested-explicit).

 
```
void main()
{
    int num = 10;
    struct S(T)
    {
        // instantiated struct S!T can become nested in main()
        T foo() { return num * 2; }
    }
    S!int s;
    assert(s.foo() == 20);
}

```
 A templated `struct` can become a nested `struct` if it is instantiated with a local symbol passed as an aliased argument:

 
```
struct A(alias F)
{
    int fun(int i) { return F(i); }
}

A!F makeA(alias F)() { return A!F(); }

void main()
{
    int x = 40;
    int fun(int i) { return x + i; }
    A!fun a = makeA!fun();
    assert(a.fun(2) == 42);
}

```
 ### Context Limitation

 Currently nested templates can capture at most one context. As a typical example, non-static template member functions cannot take local symbol by using template alias parameter.

 
```
class C
{
    int num;
    void foo(alias sym)() { num = sym * 2; }
}

void main()
{
    auto c = new C();
    int var = 10;
    c.foo!var();    // NG, foo!var requires two contexts, 'this' and 'main()'
}

```
 But, if one context is indirectly accessible from other context, it is allowed.

 
```
int sum(alias x, alias y)() { return x + y; }

void main()
{
    int a = 10;
    void nested()
    {
        int b = 20;
        assert(sum!(a, b)() == 30);
    }
    nested();
}

```
 Two local variables `a` and `b` are in different contexts, but outer context is indirectly accessible from innter context, so nested template instance `sum!(a, b)` will capture only inner context.

 Recursive Templates
-------------------

 Template features can be combined to produce some interesting effects, such as compile time evaluation of non-trivial functions. For example, a factorial template can be written:

 
```
template factorial(int n)
{
    static if (n == 1)
        enum factorial = 1;
    else
        enum factorial = n * factorial!(n - 1);
}

static assert(factorial!(4) == 24);

```
 For more information and a CTFE (Compile-time Function Execution) factorial alternative, see: [Template Recursion](https://dlang.org/articles/templates-revisited.html#template-recursion). 

 Template Constraints
--------------------

 
```
Constraint:
    if ( Expression )

```
 *Constraint*s are used to impose additional constraints on matching arguments to a template beyond what is possible in the [*TemplateParameterList*](#TemplateParameterList). The *Expression* is computed at compile time and returns a result that is converted to a boolean value. If that value is true, then the template is matched, otherwise the template is not matched. 

 For example, the following function template only matches with odd values of `N`:

 
```
void foo(int N)()
    if (N & 1)
{
    ...
}
...
foo!(3)();  // OK, matches
foo!(4)();  // Error, no match

```
 Template constraints can be used with aggregate types (structs, classes, unions). Constraints are effectively used with library module [`std.traits`](https://dlang.org/phobos/std_traits.html):

 
```
import std.traits;

struct Bar(T)
    if (isIntegral!T)
{
    ...
}
...
auto x = Bar!int;       // OK, int is an integral type
auto y = Bar!double;    // Error, double does not satisfy constraint

```
 Limitations
-----------

 Templates cannot be used to add non-static fields or virtual functions to classes or interfaces. For example:

 
```
class Foo
{
    template TBar(T)
    {
        T xx;               // becomes a static field of Foo
        int func(T) { ... } // non-virtual

        static T yy;                        // Ok
        static int func(T t, int y) { ... } // Ok
    }
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/template.html>

Interfacing to C
================

 **Contents** 1. [Calling C Functions](#calling_c_functions)
2. [Storage Allocation](#storage_allocation)
3. [Data Type Compatibility](#data_type_compat)
4. [Passing D Array Arguments to C Functions](#passing_d_array)
5. [Calling `printf()`](#calling_printf)
6. [Structs and Unions](#structs_and_unions)
7. [Callbacks](#callbacks)
8. [Using Existing C Libraries](#using-c-libraries)
9. [Accessing C Globals](#c-globals)

 D is designed to fit comfortably with a C compiler for the target system. D makes up for not having its own VM by relying on the target environment's C runtime library. It would be senseless to attempt to port to D or write D wrappers for the vast array of C APIs available. How much easier it is to just call them directly. 

 This is done by matching the C compiler's data types, layouts, and function call/return sequences. 

 Calling C Functions
-------------------

 C functions can be called directly from D. There is no need for wrapper functions, argument swizzling, and the C functions do not need to be put into a separate DLL. 

 The C function must be declared and given a calling convention, most likely the "C" calling convention, for example: 

 
```
extern (C) int strcmp(const char* string1, const char* string2);

```
 and then it can be called within D code in the obvious way: 
```
import std.string;
int myDfunction(char[] s)
{
    return strcmp(std.string.toStringz(s), "foo");
}

```
 There are several things going on here:

 * D understands how C function names are "mangled" and the correct C function call/return sequence.
* C functions cannot be overloaded with another C function with the same name.
* There are no `__cdecl`, `__far`, `__stdcall`,  [`__declspec`](http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#declspec), or other such C [extended type modifiers](http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#extended) in D. These are handled by [linkage attributes](attribute#linkage), such as `extern (C)`.
* There is no volatile type modifier in D. To declare a C function that uses volatile, just drop the keyword from the declaration.
* Strings are not 0 terminated in D. See "Data Type Compatibility" for more information about this. However, string literals in D are 0 terminated.

 C code can correspondingly call D functions, if the D functions use an attribute that is compatible with the C compiler, most likely the extern (C):

 
```
// myfunc() can be called from any C function
extern (C)
{
    void myfunc(int a, int b)
    {
        ...
    }
}

```
 Storage Allocation
------------------

 C code explicitly manages memory with calls to [malloc()](http://www.digitalmars.com/rtl/stdlib.html#malloc) and [free()](http://www.digitalmars.com/rtl/stdlib.html#free). D allocates memory using the D garbage collector, so no explicit frees are necessary. 

 D can still explicitly allocate memory using core.stdc.stdlib.malloc() and core.stdc.stdlib.free(), these are useful for connecting to C functions that expect malloc'd buffers, etc. 

 If pointers to D garbage collector allocated memory are passed to C functions, it's critical to ensure that that memory will not be collected by the garbage collector before the C function is done with it. This is accomplished by: 

 * Making a copy of the data using core.stdc.stdlib.malloc() and passing the copy instead.
* Leaving a pointer to it on the stack (as a parameter or automatic variable), as the garbage collector will scan the stack.
* Leaving a pointer to it in the static data segment, as the garbage collector will scan the static data segment.
* Registering the pointer with the garbage collector with the [std.gc.addRoot()](https://dlang.org/phobos/core_memory.html#addRoot) or [std.gc.addRange()](https://dlang.org/phobos/core_memory.html#addRange) calls.

 An interior pointer to the allocated memory block is sufficient to let the GC know the object is in use; i.e. it is not necessary to maintain a pointer to the beginning of the allocated memory. 

 The garbage collector does not scan the stacks of threads not created by the D Thread interface. Nor does it scan the data segments of other DLLs, etc. 

 Data Type Compatibility
-----------------------

 

D And C Type Equivalence| D | C |
| 32 bit | 64 bit |
| `void` | `void` |
| `byte` | `signed char` |
| `ubyte` | `unsigned char` |
| `char` | `char` (chars are unsigned in D) |
| `wchar` | `wchar_t` (when `sizeof(wchar_t)` is 2) |
| `dchar` | `wchar_t` (when `sizeof(wchar_t)` is 4) |
| `short` | `short` |
| `ushort` | `unsigned short` |
| `int` | `int` |
| `uint` | `unsigned` |
| `ulong` | `unsigned long long` | `unsigned long` |
| `core.stdc.config.c_long` | `long` | `long` |
| `core.stdc.config.c_ulong` | `unsigned long` | `unsigned long` |
| `long` | `long long` | `long` (or `long long`) |
| `ulong` | `unsigned long long` | `unsigned long` (or `unsigned long long`) |
| `float` | `float` |
| `double` | `double` |
| `real` | `long double` |
| `cdouble` | `double _Complex` |
| `creal` | `long double _Complex` |
| `struct` | `struct` |
| `union` | `union` |
| `enum` | `enum` |
| `class` | 
 no equivalent |
| `type *` | `type *` |
| `type[dim]` | `type[dim]` |
| `type[dim]*, type()*[dim]` | `type[dim]*, type()*[dim]` |
| `type[]` | 
 no equivalent |
| `type1[type2]` | 
 no equivalent |
| `type function(params)` | `type(*)(params)` |
| `type delegate(params)` | 
 no equivalent |
| `size_t` | `size_t` |
| `ptrdiff_t` | `ptrdiff_t` |

 These equivalents hold for most C compilers. The C standard does not pin down the sizes of the types, so some care is needed. 

 Passing D Array Arguments to C Functions
----------------------------------------

 In C, arrays are passed to functions as pointers even if the function prototype says its an array. In D, static arrays are passed by value, not by reference. Thus, the function prototype must be adjusted to match what C expects.

 

D And C Function Prototype Equivalence| **D type** | **C type** |
| *T*\*  | *T*[] |
| ref *T*[*dim*]  | *T*[*dim*] |

 For example:

 
```
void foo(int a[3]) { ... } // C code
```
 
```
extern (C)
{
    void foo(ref int[3] a); // D prototype
}

```
 Calling `printf()`
------------------

 `printf` can be directly called from D code:

 
```
import core.stdc.stdio;

int main
{
    printf("hello world\n");
    return 0;
}

```
 Printing values works as it does in C:

 
```
int apples;
printf("there are %d apples\n", apples);

```
 Correctly matching the format specifier to the D type is necessary. The D compiler recognizes the printf formats and diagnoses mismatches with the supplied arguments. The specification for the formats used by D is the C99 specification 7.19.6.1. 

 A generous interpretation of what is a match between the argument and format specifier is taken, for example, an unsigned type can be printed with a signed format specifier. Diagnosed incompatibilites are: 

 * incompatible sizes which may cause argument misalignment
* dereferencing arguments that are not pointers
* insufficient number of arguments
* struct, array and slice arguments are not allowed
* non-pointer arguments to `s` specifier
* non-Standard formats
* undefined behavior per C99

 ### Strings

 A string cannot be printed directly. But `%.*s` can be used: 

 
```
string s = "betty";
printf("hello %.*s\n", cast(int) s.length, s.ptr);

```
 The cast to `int` is required. 

 ### 
`size_t` and `ptrdiff_t`

 These use the `zd` and `dt` format specifiers respectively: 

 
```
int* p, q;
printf("size of an int is %zt, pointer difference is %td\n", int.sizeof, p - q);

```
 ### Non-Standard Format Specifiers

 Non-Standard format specifiers will be rejected by the compiler. Since the checking is only done for formats as string literals, non-Standard ones can be used: 

 
```
const char* format = "value: %K\n";
printf(format, value);

```
 ### Modern Formatted Writing

 An improved D function for formatted output is `std.stdio.writef()`. 

 Structs and Unions
------------------

 D structs and unions are analogous to C's. 

 C code often adjusts the alignment and packing of struct members with a command line switch or with various implementation specific #pragmas. D supports explicit alignment attributes that correspond to the C compiler's rules. Check what alignment the C code is using, and explicitly set it for the D struct declaration. 

 D does not support bit fields. If needed, they can be emulated with shift and mask operations, or use the [std.bitmanip.bitfields](https://dlang.org/phobos/std_bitmanip.html#bitfields) library type. [htod](https://dlang.org/htod.html) will convert bit fields to inline functions that do the right shift and masks. 

 D does not support declaring variables of anonymous struct types. In such a case, define a named struct in D and make it private:

 
```
union Info  // C code
{
    struct
    {
        char *name;
    } file;
};

```
 
```
union Info  // D code
{
    private struct File
    {
        char* name;
    }
    File file;
}

```
 Callbacks
---------

 D can easily call C callbacks (function pointers), and C can call callbacks provided by D code if the callback is an `extern(C)` function, or some other linkage that both sides have agreed to (e.g. `extern(Windows)`).

 Here's an example of C code providing a callback to D code:

 
```
void someFunc(void *arg) { printf("Called someFunc!\n"); }  // C code
typedef void (*Callback)(void *);
extern "C" Callback getCallback(void)
{
    return someFunc;
}

```
 
```
extern(C) alias Callback = int function(int, int);  // D code
extern(C) Callback getCallback();
void main()
{
    Callback cb = getCallback();
    cb();  // invokes the callback
}

```
 And an example of D code providing a callback to C code:

 
```
extern "C" void printer(int (*callback)(int, int))  // C code
{
    printf("calling callback with 2 and 4 returns: %d\n", callback(2, 4));
}

```
 
```
extern(C) alias Callback = int function(int, int);  // D code
extern(C) void printer(Callback callback);
extern(C) int sum(int x, int y) { return x + y; }
void main()
{
    printer(&sum);
}

```
 For more info about callbacks read the [closures](function#closures) section.

 Using Existing C Libraries
--------------------------

 Since D can call C code directly, it can also call any C library functions, giving D access to the smorgasbord of existing C libraries. To do so, however, one needs to write a D interface (.di) file, which is a translation of the C .h header file for the C library into D. 

 For popular C libraries, the first place to look for the corresponding D interface file is the [Deimos Project](https://github.com/D-Programming-Deimos/). If it isn't there already, please write and contribute one to the Deimos Project. 

 Accessing C Globals
-------------------

 C globals can be accessed directly from D. C globals have the C naming convention, and so must be in an `extern (C)` block. Use the `extern` storage class to indicate that the global is allocated in the C code, not the D code. C globals default to being in global, not thread local, storage. To reference global storage from D, use the `__gshared` storage class. 

 
```
extern (C) extern __gshared int x;

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/interfaceToC.html>

Conditional Compilation
=======================

 **Contents** 1. [Version Condition](#version)
2. [Version Specification](#version-specification)
	1. [Predefined Versions](#predefined-versions)
3. [Debug Condition](#debug)
	1. [Debug Statement](#DebugStatement)
4. [Debug Specification](#debug_specification)
5. [Static If Condition](#staticif)
6. [Static Foreach](#staticforeach)
	1. [`break` and `continue`](#break-continue)
7. [Static Assert](#static-assert)

 *Conditional compilation* is the process of selecting which code to compile and which code to not compile. 

 
```
ConditionalDeclaration:
    Condition DeclarationBlock
    Condition DeclarationBlock else DeclarationBlock
    Condition : DeclDefsopt
    Condition DeclarationBlock else : DeclDefsopt

ConditionalStatement:
    Condition NoScopeNonEmptyStatement
    Condition NoScopeNonEmptyStatement else NoScopeNonEmptyStatement

```
 If the [*Condition*](#Condition) is satisfied, then the following *DeclarationBlock* or *Statement* is compiled in. If it is not satisfied, the *DeclarationBlock* or *Statement* after the optional `else` is compiled in. 

 Any *DeclarationBlock* or *Statement* that is not compiled in still must be syntactically correct. 

 No new scope is introduced, even if the *DeclarationBlock* or *Statement* is enclosed by `{ }`. 

 *ConditionalDeclaration*s and *ConditionalStatement*s can be nested. 

 The [*StaticAssert*](#StaticAssert) can be used to issue errors at compilation time for branches of the conditional compilation that are errors. 

 *Condition* comes in the following forms: 

 
```
Condition:
    VersionCondition
    DebugCondition
    StaticIfCondition

```
 Version Condition
-----------------

 
```
VersionCondition:
    version ( IntegerLiteral )
    version ( Identifier )
    version ( unittest )
    version ( assert )

```
 Versions enable multiple versions of a module to be implemented with a single source file. 

 The *VersionCondition* is satisfied if the *IntegerLiteral* is greater than or equal to the current *version level*, or if *Identifier* matches a *version identifier*. 

 The *version level* and *version identifier* can be set on the command line by the `-version` switch or in the module itself with a [*VersionSpecification*](#VersionSpecification), or they can be predefined by the compiler. 

 Version identifiers are in their own unique name space, they do not conflict with debug identifiers or other symbols in the module. Version identifiers defined in one module have no influence over other imported modules. 

 
```
int k;
version (Demo) // compile in this code block for the demo version
{
    int i;
    int k;    // error, k already defined

    i = 3;
}
x = i;      // uses the i declared above

```
 
```
version (X86)
{
    ... // implement custom inline assembler version
}
else
{
    ... // use default, but slow, version
}

```
 The `version(unittest)` is satisfied if and only if the code is compiled with unit tests enabled (the [*-unittest*](https://dlang.org/dmd.html#switch-unittest) option on *dmd*). 

 Version Specification
---------------------

 
```
VersionSpecification:
    version = Identifier ;
    version = IntegerLiteral ;

```
 The version specification makes it straightforward to group a set of features under one major version, for example: 

 
```
version (ProfessionalEdition)
{
    version = FeatureA;
    version = FeatureB;
    version = FeatureC;
}
version (HomeEdition)
{
    version = FeatureA;
}
...
version (FeatureB)
{
    ... implement Feature B ...
}

```
 Version identifiers or levels may not be forward referenced: 

 
```
version (Foo)
{
    int x;
}
version = Foo;  // error, Foo already used

```
 *VersionSpecification*s may only appear at module scope.

 While the debug and version conditions superficially behave the same, they are intended for very different purposes. Debug statements are for adding debug code that is removed for the release version. Version statements are to aid in portability and multiple release versions. 

 Here's an example of a *full* version as opposed to a *demo* version:

 
```
class Foo
{
    int a, b;

    version(full)
    {
        int extrafunctionality()
        {
            ...
            return 1;  // extra functionality is supported
        }
    }
    else // demo
    {
        int extrafunctionality()
        {
            return 0;  // extra functionality is not supported
        }
    }
}

```
 Various different version builds can be built with a parameter to version: 

 
```
version(n) // add in version code if version level is >= n
{
    ... version code ...
}

version(identifier) // add in version code if version
                         // keyword is identifier
{
    ... version code ...
}

```
 These are presumably set by the command line as `-version=n` and `-version=identifier`. 

 ### Predefined Versions

 Several environmental version identifiers and identifier name spaces are predefined for consistent usage. Version identifiers do not conflict with other identifiers in the code, they are in a separate name space. Predefined version identifiers are global, i.e. they apply to all modules being compiled and imported. 

 

Predefined Version Identifiers| **Version Identifier** | **Description** |
| `DigitalMars` | DMD (Digital Mars D) is the compiler |
| `GNU` | GDC (GNU D Compiler) is the compiler |
| `LDC` | LDC (LLVM D Compiler) is the compiler |
| `SDC` | SDC (Stupid D Compiler) is the compiler |
| `Windows` | Microsoft Windows systems |
| `Win32` | Microsoft 32-bit Windows systems |
| `Win64` | Microsoft 64-bit Windows systems |
| `linux` | All Linux systems |
| `OSX` | macOS |
| `iOS` | iOS |
| `TVOS` | tvOS |
| `WatchOS` | watchOS |
| `FreeBSD` | FreeBSD |
| `OpenBSD` | OpenBSD |
| `NetBSD` | NetBSD |
| `DragonFlyBSD` | DragonFlyBSD |
| `BSD` | All other BSDs |
| `Solaris` | Solaris |
| `Posix` | All POSIX systems (includes Linux, FreeBSD, OS X, Solaris, etc.) |
| `AIX` | IBM Advanced Interactive eXecutive OS |
| `Haiku` | The Haiku operating system |
| `SkyOS` | The SkyOS operating system |
| `SysV3` | System V Release 3 |
| `SysV4` | System V Release 4 |
| `Hurd` | GNU Hurd |
| `Android` | The Android platform |
| `Emscripten` | The Emscripten platform |
| `PlayStation` | The PlayStation platform |
| `PlayStation4` | The PlayStation 4 platform |
| `Cygwin` | The Cygwin environment |
| `MinGW` | The MinGW environment |
| `FreeStanding` | An environment without an operating system (such as Bare-metal targets) |
| `CRuntime_Bionic` | Bionic C runtime |
| `CRuntime_DigitalMars` | DigitalMars C runtime |
| `CRuntime_Glibc` | Glibc C runtime |
| `CRuntime_Microsoft` | Microsoft C runtime |
| `CRuntime_Musl` | musl C runtime |
| `CRuntime_Newlib` | newlib C runtime |
| `CRuntime_UClibc` | uClibc C runtime |
| `CRuntime_WASI` | WASI C runtime |
| `CppRuntime_Clang` | Clang Cpp runtime |
| `CppRuntime_DigitalMars` | DigitalMars Cpp runtime |
| `CppRuntime_Gcc` | Gcc Cpp runtime |
| `CppRuntime_Microsoft` | Microsoft Cpp runtime |
| `CppRuntime_Sun` | Sun Cpp runtime |
| `X86` | Intel and AMD 32-bit processors |
| `X86_64` | Intel and AMD 64-bit processors |
| `ARM` | The ARM architecture (32-bit) (AArch32 et al) |
| `ARM_Thumb` | ARM in any Thumb mode |
| `ARM_SoftFloat` | The ARM `soft` floating point ABI |
| `ARM_SoftFP` | The ARM `softfp` floating point ABI |
| `ARM_HardFloat` | The ARM `hardfp` floating point ABI |
| `AArch64` | The Advanced RISC Machine architecture (64-bit) |
| `AsmJS` | The asm.js intermediate programming language |
| `AVR` | 8-bit Atmel AVR Microcontrollers |
| `Epiphany` | The Epiphany architecture |
| `PPC` | The PowerPC architecture, 32-bit |
| `PPC_SoftFloat` | The PowerPC soft float ABI |
| `PPC_HardFloat` | The PowerPC hard float ABI |
| `PPC64` | The PowerPC architecture, 64-bit |
| `IA64` | The Itanium architecture (64-bit) |
| `MIPS32` | The MIPS architecture, 32-bit |
| `MIPS64` | The MIPS architecture, 64-bit |
| `MIPS_O32` | The MIPS O32 ABI |
| `MIPS_N32` | The MIPS N32 ABI |
| `MIPS_O64` | The MIPS O64 ABI |
| `MIPS_N64` | The MIPS N64 ABI |
| `MIPS_EABI` | The MIPS EABI |
| `MIPS_SoftFloat` | The MIPS `soft-float` ABI |
| `MIPS_HardFloat` | The MIPS `hard-float` ABI |
| `MSP430` | The MSP430 architecture |
| `NVPTX` | The Nvidia Parallel Thread Execution (PTX) architecture, 32-bit |
| `NVPTX64` | The Nvidia Parallel Thread Execution (PTX) architecture, 64-bit |
| `RISCV32` | The RISC-V architecture, 32-bit |
| `RISCV64` | The RISC-V architecture, 64-bit |
| `SPARC` | The SPARC architecture, 32-bit |
| `SPARC_V8Plus` | The SPARC v8+ ABI |
| `SPARC_SoftFloat` | The SPARC soft float ABI |
| `SPARC_HardFloat` | The SPARC hard float ABI |
| `SPARC64` | The SPARC architecture, 64-bit |
| `S390` | The System/390 architecture, 32-bit |
| `SystemZ` | The System Z architecture, 64-bit |
| `HPPA` | The HP PA-RISC architecture, 32-bit |
| `HPPA64` | The HP PA-RISC architecture, 64-bit |
| `SH` | The SuperH architecture, 32-bit |
| `WebAssembly` | The WebAssembly virtual ISA (instruction set architecture), 32-bit |
| `WASI` | The WebAssembly System Interface |
| `Alpha` | The Alpha architecture |
| `Alpha_SoftFloat` | The Alpha soft float ABI |
| `Alpha_HardFloat` | The Alpha hard float ABI |
| `LittleEndian` | Byte order, least significant first |
| `BigEndian` | Byte order, most significant first |
| `ELFv1` | The Executable and Linkable Format v1 |
| `ELFv2` | The Executable and Linkable Format v2 |
| `D_BetterC` | [D as Better C](betterc) code (command line switch [*-betterC*](https://dlang.org/dmd.html#switch-betterC)) is being generated |
| `D_Exceptions` | Exception handling is supported. Evaluates to `false` when compiling with command line switch [*-betterC*](https://dlang.org/dmd.html#switch-betterC) |
| `D_ModuleInfo` | `ModuleInfo` is supported. Evaluates to `false` when compiling with command line switch [*-betterC*](https://dlang.org/dmd.html#switch-betterC) |
| `D_TypeInfo` | Runtime type information (a.k.a `TypeInfo`) is supported. Evaluates to `false` when compiling with command line switch [*-betterC*](https://dlang.org/dmd.html#switch-betterC) |
| `D_Coverage` | [Code coverage analysis](https://dlang.org/code_coverage.html) instrumentation (command line switch [*-cov*](https://dlang.org/dmd.html#switch-cov)) is being generated |
| `D_Ddoc` | [Ddoc](ddoc) documentation (command line switch [*-D*](https://dlang.org/dmd.html#switch-D)) is being generated |
| `D_InlineAsm_X86` | [Inline assembler](iasm) for X86 is implemented |
| `D_InlineAsm_X86_64` | [Inline assembler](iasm) for X86-64 is implemented |
| `D_LP64` | Pointers are 64 bits (command line switch [*-m64*](https://dlang.org/dmd.html#switch-m64)). (Do not confuse this with C's LP64 model) |
| `D_X32` | Pointers are 32 bits, but words are still 64 bits (x32 ABI) (This can be defined in parallel to `X86_64`) |
| `D_HardFloat` | The target hardware has a floating point unit |
| `D_SoftFloat` | The target hardware does not have a floating point unit |
| `D_PIC` | Position Independent Code (command line switch [*-fPIC*](https://dlang.org/dmd-linux.html#switch-fPIC)) is being generated |
| `D_SIMD` | [Vector extensions](simd) (via `__simd`) are supported |
| `D_AVX` | AVX Vector instructions are supported |
| `D_AVX2` | AVX2 Vector instructions are supported |
| `D_Version2` | This is a D version 2 compiler |
| `D_NoBoundsChecks` | Array bounds checks are disabled (command line switch [*-boundscheck=off*](https://dlang.org/dmd.html#switch-boundscheck)) |
| `D_ObjectiveC` | The target supports interfacing with Objective-C |
| `Core` | Defined when building the standard runtime |
| `Std` | Define when building the standard library |
| `unittest` | [Unit tests](unittest) are enabled (command line switch [*-unittest*](https://dlang.org/dmd.html#switch-unittest)) |
| `assert` | Checks are being emitted for [*AssertExpression*](expression#AssertExpression)s |
| `none` | Never defined; used to just disable a section of code |
| `all` | Always defined; used as the opposite of `none` |

 The following identifiers are defined, but are deprecated: 

 

Predefined Version Identifiers (deprecated)| **Version Identifier** | **Description** |
| `darwin` | The Darwin operating system; use `OSX` instead |
| `Thumb` | ARM in Thumb mode; use `ARM_Thumb` instead |
| `S390X` | The System/390X architecture | 64-bit; use `SystemZ` instead |

 Others will be added as they make sense and new implementations appear. 

 It is inevitable that the D language will evolve over time. Therefore, the version identifier namespace beginning with "D\_" is reserved for identifiers indicating D language specification or new feature conformance. Further, all identifiers derived from the ones listed above by appending any character(s) are reserved. This means that e.g. `ARM_foo` and `Windows_bar` are reserved while `foo_ARM` and `bar_Windows` are not. 

 Furthermore, predefined version identifiers from this list cannot be set from the command line or from version statements. (This prevents things like both `Windows` and `linux` being simultaneously set.) 

 Compiler vendor specific versions can be predefined if the trademarked vendor identifier prefixes it, as in: 

 
```
version(DigitalMars_funky_extension)
{
    ...
}

```
 It is important to use the right version identifier for the right purpose. For example, use the vendor identifier when using a vendor specific feature. Use the operating system identifier when using an operating system specific feature, etc. 

 Debug Condition
---------------

 
```
DebugCondition:
    debug
    debug ( IntegerLiteral )
    debug ( Identifier )

```
 Two versions of programs are commonly built, a release build and a debug build. The debug build includes extra error checking code, test harnesses, pretty-printing code, etc. The debug statement conditionally compiles in its statement body. It is D's way of what in C is done with `#ifdef DEBUG` / `#endif` pairs. 

 The `debug` condition is satisfied when the `-debug` switch is passed to the compiler or when the debug level is >= 1. 

 The `debug (` *IntegerLiteral* `)` condition is satisfied when the debug level is `>=` *IntegerLiteral*. 

 The `debug (` *Identifier* `)` condition is satisfied when the debug identifier matches *Identifier*. 

 
```
class Foo
{
    int a, b;
debug:
    int flag;
}

```
 ### Debug Statement

 A [*ConditionalStatement*](#ConditionalStatement) that has a [*DebugCondition*](#DebugCondition) is called a *DebugStatement*. *DebugStatements* have relaxed semantic checks in that `pure`, `@nogc`, `nothrow` and `@safe` checks are not done. Neither do *DebugStatements* influence the inference of `pure`, `@nogc`, `nothrow` and `@safe` attributes.

 **Undefined Behavior:** Since these checks are bypassed, it is up to the programmer to ensure the code is correct. For example, throwing an exception in a `nothrow` function is undefined behavior. **Best Practices:** This enables the easy insertion of code to provide debugging help, by bypassing the otherwise stringent attribute checks. Never ship release code that has *DebugStatements* enabled. Debug Specification
-------------------

 
```
DebugSpecification:
    debug = Identifier ;
    debug = IntegerLiteral ;

```
 Debug identifiers and levels are set either by the command line switch `-debug` or by a *DebugSpecification*. 

 Debug specifications only affect the module they appear in, they do not affect any imported modules. Debug identifiers are in their own namespace, independent from version identifiers and other symbols. 

 It is illegal to forward reference a debug specification: 

 
```
debug(foo) writeln("Foo");
debug = foo;    // error, foo used before set

```
 *DebugSpecification*s may only appear at module scope.

 Various different debug builds can be built with a parameter to debug: 

 
```
debug(IntegerLiteral) { } // add in debug code if debug level is >= IntegerLiteral
debug(identifier) { } // add in debug code if debug keyword is identifier

```
 These are presumably set by the command line as `-debug=`*n* and `-debug=`*identifier*. 

 Static If Condition
-------------------

 
```
StaticIfCondition:
    static if ( AssignExpression )

```
 [*AssignExpression*](expression#AssignExpression) is implicitly converted to a boolean type, and is evaluated at compile time. The condition is satisfied if it evaluates to `true`. It is not satisfied if it evaluates to `false`. 

 It is an error if [*AssignExpression*](expression#AssignExpression) cannot be implicitly converted to a boolean type or if it cannot be evaluated at compile time. 

 *StaticIfCondition*s can appear in module, class, template, struct, union, or function scope. In function scope, the symbols referred to in the [*AssignExpression*](expression#AssignExpression) can be any that can normally be referenced by an expression at that point. 

 
```
const int i = 3;
int j = 4;

static if (i == 3)    // ok, at module scope
    int x;

class C
{
    const int k = 5;

    static if (i == 3) // ok
        int x;
    else
        long x;

    static if (j == 3) // error, j is not a constant
        int y;

    static if (k == 5) // ok, k is in current scope
        int z;
}

```
 
```
template Int(int i)
{
    static if (i == 32)
        alias Int = int;
    else static if (i == 16)
        alias Int = short;
    else
        static assert(0); // not supported
}

Int!(32) a;  // a is an int
Int!(16) b;  // b is a short
Int!(17) c;  // error, static assert trips

```
 A *StaticIfCondition* differs from an *IfStatement* in the following ways: 

 1. It can be used to conditionally compile declarations, not just statements.
2. It does not introduce a new scope even if `{ }` are used for conditionally compiled statements.
3. For unsatisfied conditions, the conditionally compiled code need only be syntactically correct. It does not have to be semantically correct.
4. It must be evaluatable at compile time.

 Static Foreach
--------------

 
```
StaticForeach:
    static AggregateForeach
    static RangeForeach

StaticForeachDeclaration:
    StaticForeach DeclarationBlock
    StaticForeach : DeclDefsopt

StaticForeachStatement:
    StaticForeach NoScopeNonEmptyStatement

```
 The aggregate/range bounds are evaluated at compile time and turned into a sequence of compile-time entities by evaluating corresponding code with a [*ForeachStatement*](statement#ForeachStatement)/[*ForeachRangeStatement*](statement#ForeachRangeStatement) at compile time. The body of the `static foreach` is then copied a number of times that corresponds to the number of elements of the sequence. Within the i-th copy, the name of the `static foreach` variable is bound to the i-th entry of the sequence, either as an `enum` variable declaration (for constants) or an `alias` declaration (for symbols). (In particular, `static foreach` variables are never runtime variables.) 

 
```
static foreach(i; [0, 1, 2, 3])
{
    pragma(msg, i);
}

```
 `static foreach` supports multiple variables in cases where the corresponding `foreach` statement supports them. (In this case, `static foreach` generates a compile-time sequence of tuples, and the tuples are subsequently unpacked during iteration). 

 
```
static foreach(i, v; ['a', 'b', 'c', 'd'])
{
    static assert(i + 'a' == v);
}

```
 Like bodies of [*ConditionalDeclaration*](#ConditionalDeclaration)s, a `static foreach` body does not introduce a new scope. Therefore, it can be used to generate declarations: 

 
```
import std.range : iota;

static foreach(i; iota(0, 3))
{
    mixin(`enum x`, i, ` = i;`);
}

pragma(msg, x0, " ", x1," ", x2); // 0 1 2

```
 If a new scope is desired for each expansion, use another set of braces:

 
```
static foreach(s; ["hi", "hey", "hello"])
{{
    enum len = s.length;    // local to each iteration
    static assert(len <= 5);
}}

static assert(!is(typeof(len)));

```
 ### 
`break` and `continue`

 As `static foreach` is a code generation construct and not a loop, `break` and `continue` cannot be used to change control flow within it. Instead of breaking or continuing a suitable enclosing statement, such an usage yields an error (this is to prevent misunderstandings). 

 
```
int test(int x)
{
    int r = -1;
    switch(x)
    {
        static foreach(i; 0 .. 100)
        {
            case i:
                r = i;
                break; // error
        }
        default: break;
    }
    return r;
}

static foreach(i; 0 .. 200)
{
    static assert(test(i) == (i < 100 ? i : -1));
}

```
 An explicit `break`/`continue` label can be used to avoid this limitation. (Note that `static foreach` itself cannot be broken nor continued even if it is explicitly labeled.) 

 
```
int test(int x)
{
    int r = -1;
    Lswitch: switch(x)
    {
        static foreach(i; 0 .. 100)
        {
            case i:
                r = i;
                break Lswitch;
        }
        default: break;
    }
    return r;
}

static foreach(i; 0 .. 200)
{
    static assert(test(i) == (i<100 ? i : -1));
}

```
 Static Assert
-------------

 
```
StaticAssert:
    static assert ( AssertArguments );

```
 The first [*AssignExpression*](expression#AssignExpression) is evaluated at compile time, and converted to a boolean value. If the value is true, the static assert is ignored. If the value is false, an error diagnostic is issued and the compile fails. 

 Unlike [*AssertExpression*](expression#AssertExpression)s, *StaticAssert*s are always checked and evaluated by the compiler unless they appear in an unsatisfied conditional. 

 
```
void foo()
{
    if (0)
    {
        assert(0);  // never trips
        static assert(0); // always trips
    }
    version (BAR)
    {
    }
    else
    {
        static assert(0); // trips when version BAR is not defined
    }
}

```
 *StaticAssert* is useful tool for drawing attention to conditional configurations not supported in the code. 

 The optional second [*AssignExpression*](expression#AssignExpression) can be used to supply additional information, such as a text string, that will be printed out along with the error diagnostic. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/version.html>

Portability
===========

 **Contents** 1. [32 to 64 Bit Portability](#32_to_64bit)
2. [Endianness](#endianness)
3. [OS Specific Code](#os_specific_code)

 It's good software engineering practice to minimize gratuitous portability problems in the code. Techniques to minimize potential portability problems are: 

 * The integral and floating type sizes should be considered as minimums. Algorithms should be designed to continue to work properly if the type size increases.
* Floating point computations can be carried out at a higher precision than the size of the floating point variable can hold. Floating point algorithms should continue to work properly if precision is arbitrarily increased.
* Avoid depending on the order of side effects in a computation that may get reordered by the compiler. For example: 
```
a + b + c

```
 can be evaluated as (a + b) + c, a + (b + c), (a + c) + b, (c + b) + a, etc. Parentheses control operator precedence, parentheses do not control order of evaluation. 

 If the operands of an associative operator + or \* are floating point values, the expression is not reordered.
* Avoid dependence on byte order; i.e. whether the CPU is big-endian or little-endian.
* Avoid dependence on the size of a pointer or reference being the same size as a particular integral type.
* If size dependencies are inevitable, put a `static assert` in the code to verify it: 
```
static assert(int.sizeof == (int*).sizeof);

```

 32 to 64 Bit Portability
------------------------

 64 bit processors and operating systems are here. With that in mind: 

 * Integral types will remain the same sizes between 32 and 64 bit code.
* Pointers and object references will increase in size from 4 bytes to 8 bytes going from 32 to 64 bit code.
* Use `size_t` as an alias for an unsigned integral type that can span the address space. Array indices should be of type `size_t`.
* Use `ptrdiff_t` as an alias for a signed integral type that can span the address space. A type representing the difference between two pointers should be of type `ptrdiff_t`.
* The `.length`, `.size`, `.sizeof`, `.offsetof` and `.alignof` properties will be of type `size_t`.

 Endianness
----------

 Endianness refers to the order in which multibyte types are stored. The two main orders are *big endian* and *little endian*. The compiler predefines the version identifier `BigEndian` or `LittleEndian` depending on the order of the target system. The x86 systems are all little endian. 

 The times when endianness matters are:

 * When reading data from an external source (like a file) written in a different endian format.
* When reading or writing individual bytes of a multibyte type like `long`s or `double`s.

 OS Specific Code
----------------

 System specific code is handled by isolating the differences into separate modules. At compile time, the correct system specific module is imported. 

 Minor differences can be handled by constant defined in a system specific import, and then using that constant in an *IfStatement* or *StaticIfStatement*. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/portability.html>

D Grammar
=========

 **Contents** 1. [Modules](#modules)
2. [Declarations](#declarations)
3. [Types](#types)
4. [Attributes](#attributes)
5. [Pragmas](#pragmas)
6. [Expressions](#expressions)
7. [Statements](#statements)
8. [Structs and Unions](#structs%20and%20unions)
9. [Classes](#classes)
10. [Interfaces](#interfaces)
11. [Enums](#enums)
12. [Functions](#functions)
13. [Templates](#templates)
14. [Template Mixins](#template%20mixins)
15. [Conditional Compilation](#conditional%20compilation)
16. [Traits](#traits)
17. [Unit Tests](#unit%20tests)
18. [D x86 Inline Assembler](#d%20x86%20inline%20assembler)
19. [Named Character Entities](#named%20character%20entities)
20. [Application Binary Interface](#application%20binary%20interface)

 Lexical Syntax
--------------

 Refer to the page for [lexical syntax](lex).

 Modules
-------

 
```
Module:
    ModuleDeclaration DeclDefs
    DeclDefs

DeclDefs:
    DeclDef
    DeclDef DeclDefs

DeclDef:
    AttributeSpecifier
    Declaration
    Constructor
    Destructor
    Postblit
    Allocator
    Deallocator
    ClassInvariant
    StructInvariant
    UnitTest
    AliasThis
    StaticConstructor
    StaticDestructor
    SharedStaticConstructor
    SharedStaticDestructor
    ConditionalDeclaration
    DebugSpecification
    VersionSpecification
    StaticAssert
    TemplateDeclaration
    TemplateMixinDeclaration
    TemplateMixin
    MixinDeclaration
    ;

```
 
```
ModuleDeclaration:
    ModuleAttributesopt module ModuleFullyQualifiedName ;

ModuleAttributes:
    ModuleAttribute
    ModuleAttribute ModuleAttributes

ModuleAttribute:
    DeprecatedAttribute
    UserDefinedAttribute

ModuleFullyQualifiedName:
    ModuleName
    Packages . ModuleName

ModuleName:
    Identifier

Packages:
    PackageName
    Packages . PackageName

PackageName:
    Identifier

```
 
```
ImportDeclaration:
    import ImportList ;
    static import ImportList ;

ImportList:
    Import
    ImportBindings
    Import , ImportList

Import:
    ModuleFullyQualifiedName
    ModuleAliasIdentifier = ModuleFullyQualifiedName

ImportBindings:
    Import : ImportBindList

ImportBindList:
    ImportBind
    ImportBind , ImportBindList

ImportBind:
    Identifier
    Identifier = Identifier

ModuleAliasIdentifier:
    Identifier

```
 
```
MixinDeclaration:
    mixin ( ArgumentList ) ;

```
 Declarations
------------

 
```
Declaration:
    FuncDeclaration
    VarDeclarations
    AliasDeclaration
    AggregateDeclaration
    EnumDeclaration
    ImportDeclaration
    ConditionalDeclaration
    StaticForeachDeclaration
    StaticAssert

```
 
```
VarDeclarations:
    StorageClassesopt BasicType Declarators ;
    AutoDeclaration

Declarators:
    DeclaratorInitializer
    DeclaratorInitializer , DeclaratorIdentifierList

DeclaratorInitializer:
    VarDeclarator
    VarDeclarator TemplateParametersopt = Initializer
    AltDeclarator
    AltDeclarator = Initializer

DeclaratorIdentifierList:
    DeclaratorIdentifier
    DeclaratorIdentifier , DeclaratorIdentifierList

DeclaratorIdentifier:
    VarDeclaratorIdentifier
    AltDeclaratorIdentifier

VarDeclaratorIdentifier:
    Identifier
    Identifier TemplateParametersopt = Initializer

AltDeclaratorIdentifier:
    TypeSuffixes Identifier AltDeclaratorSuffixesopt
    TypeSuffixes Identifier AltDeclaratorSuffixesopt = Initializer
    TypeSuffixesopt Identifier AltDeclaratorSuffixes
    TypeSuffixesopt Identifier AltDeclaratorSuffixes = Initializer

Declarator:
    VarDeclarator
    AltDeclarator

VarDeclarator:
    TypeSuffixesopt Identifier

AltDeclarator:
    TypeSuffixesopt Identifier AltDeclaratorSuffixes
    TypeSuffixesopt ( AltDeclaratorInner )
    TypeSuffixesopt ( AltDeclaratorInner ) AltFuncDeclaratorSuffix
    TypeSuffixesopt ( AltDeclaratorInner ) AltDeclaratorSuffixes

AltDeclaratorInner:
    TypeSuffixesopt Identifier
    TypeSuffixesopt Identifier AltFuncDeclaratorSuffix
    AltDeclarator

AltDeclaratorSuffixes:
    AltDeclaratorSuffix
    AltDeclaratorSuffix AltDeclaratorSuffixes

AltDeclaratorSuffix:
    [ ]
    [ AssignExpression ]
    [ Type ]

AltFuncDeclaratorSuffix:
    Parameters MemberFunctionAttributesopt

```
 
```
StorageClasses:
    StorageClass
    StorageClass StorageClasses

StorageClass:
    LinkageAttribute
    AlignAttribute
    deprecated
    enum
    static
    extern
    abstract
    final
    override
    synchronized
    auto
    scope
    const
    immutable
    inout
    shared
    __gshared
    Property
    nothrow
    pure
    ref

```
 
```
Initializer:
    VoidInitializer
    NonVoidInitializer

NonVoidInitializer:
    ExpInitializer
    ArrayInitializer
    StructInitializer

ExpInitializer:
    AssignExpression

ArrayInitializer:
    [ ArrayMemberInitializationsopt ]

ArrayMemberInitializations:
    ArrayMemberInitialization
    ArrayMemberInitialization ,
    ArrayMemberInitialization , ArrayMemberInitializations

ArrayMemberInitialization:
    NonVoidInitializer
    AssignExpression : NonVoidInitializer

StructInitializer:
    { StructMemberInitializersopt }

StructMemberInitializers:
    StructMemberInitializer
    StructMemberInitializer ,
    StructMemberInitializer , StructMemberInitializers

StructMemberInitializer:
    NonVoidInitializer
    Identifier : NonVoidInitializer

```
 
```
AutoDeclaration:
    StorageClasses AutoAssignments ;

AutoAssignments:
    AutoAssignment
    AutoAssignments , AutoAssignment

AutoAssignment:
    Identifier TemplateParametersopt = Initializer

```
 
```
AliasDeclaration:
    alias StorageClassesopt BasicType Declarators ;
    alias StorageClassesopt BasicType FuncDeclarator ;
    alias AliasAssignments ;

AliasAssignments:
    AliasAssignment
    AliasAssignments , AliasAssignment

AliasAssignment:
    Identifier TemplateParametersopt = StorageClassesopt Type
    Identifier TemplateParametersopt = FunctionLiteral
    Identifier TemplateParametersopt = StorageClassesopt BasicType Parameters MemberFunctionAttributesopt

```
 
```
VoidInitializer:
    void

```
 Types
-----

 
```
Type:
    TypeCtorsopt BasicType TypeSuffixesopt

TypeCtors:
    TypeCtor
    TypeCtor TypeCtors

TypeCtor:
    const
    immutable
    inout
    shared

BasicType:
    FundamentalType
    . QualifiedIdentifier
    QualifiedIdentifier
    Typeof
    Typeof . QualifiedIdentifier
    TypeCtor ( Type )
    Vector
    Traits
    MixinType

Vector:
    __vector ( VectorBaseType )

VectorBaseType:
    Type

FundamentalType:
    bool
    byte
    ubyte
    short
    ushort
    int
    uint
    long
    ulong
    cent
    ucent
    char
    wchar
    dchar
    float
    double
    real
    ifloat
    idouble
    ireal
    cfloat
    cdouble
    creal
    void

TypeSuffixes:
    TypeSuffix TypeSuffixesopt

TypeSuffix:
    *
    [ ]
    [ AssignExpression ]
    [ AssignExpression .. AssignExpression ]
    [ Type ]
    delegate Parameters MemberFunctionAttributesopt
    function Parameters FunctionAttributesopt

QualifiedIdentifier:
    Identifier
    Identifier . QualifiedIdentifier
    TemplateInstance
    TemplateInstance . QualifiedIdentifier
    Identifier [ AssignExpression ]
    Identifier [ AssignExpression ]. QualifiedIdentifier

```
 
```
Typeof:
    typeof ( Expression )
    typeof ( return )

```
 
```
MixinType:
    mixin ( ArgumentList )

```
 Attributes
----------

 
```
AttributeSpecifier:
    Attribute :
    Attribute DeclarationBlock

Attribute:
    LinkageAttribute
    AlignAttribute
    DeprecatedAttribute
    VisibilityAttribute
    Pragma
    static
    extern
    abstract
    final
    override
    synchronized
    auto
    scope
    const
    immutable
    inout
    shared
    __gshared
    AtAttribute
    FunctionAttributeKwd
    ref
    return

FunctionAttributeKwd:
    nothrow
    pure

AtAttribute:
    @ disable
    @ nogc
    @ live
    Property
    @ safe
    @ system
    @ trusted
    UserDefinedAttribute

Property:
    @ property

DeclarationBlock:
    DeclDef
    { DeclDefsopt }

```
 
```
LinkageAttribute:
    extern ( LinkageType )
    extern ( C++, QualifiedIdentifier )
    extern ( C++, NamespaceList )

LinkageType:
    C
    C++
    D
    Windows
    System
    Objective-C

NamespaceList:
    ConditionalExpression
    ConditionalExpression,
    ConditionalExpression, NamespaceList

```
 
```
AlignAttribute:
    align
    align ( AssignExpression )

```
 
```
DeprecatedAttribute:
    deprecated
    deprecated ( AssignExpression )

```
 
```
VisibilityAttribute:
    private
    package
    package ( QualifiedIdentifier )
    protected
    public
    export

```
 
```
UserDefinedAttribute:
    @ ( ArgumentList )
    @ Identifier
    @ Identifier ( ArgumentListopt )
    @ TemplateInstance
    @ TemplateInstance ( ArgumentListopt )

```
 Pragmas
-------

 
```
PragmaDeclaration:
    Pragma;
    Pragma DeclarationBlock

PragmaStatement:
    Pragma;
    Pragma NoScopeStatement

Pragma:
    pragma ( Identifier )
    pragma ( Identifier , ArgumentList )

```
 Expressions
-----------

 
```
Expression:
    CommaExpression

CommaExpression:
    AssignExpression
    AssignExpression , CommaExpression

```
 
```
AssignExpression:
    ConditionalExpression
    ConditionalExpression = AssignExpression
    ConditionalExpression += AssignExpression
    ConditionalExpression -= AssignExpression
    ConditionalExpression *= AssignExpression
    ConditionalExpression /= AssignExpression
    ConditionalExpression %= AssignExpression
    ConditionalExpression &= AssignExpression
    ConditionalExpression |= AssignExpression
    ConditionalExpression ^= AssignExpression
    ConditionalExpression ~= AssignExpression
    ConditionalExpression <<= AssignExpression
    ConditionalExpression >>= AssignExpression
    ConditionalExpression >>>= AssignExpression
    ConditionalExpression ^^= AssignExpression

```
 
```
ConditionalExpression:
    OrOrExpression
    OrOrExpression ? Expression : ConditionalExpression

```
 
```
OrOrExpression:
    AndAndExpression
    OrOrExpression || AndAndExpression

```
 
```
AndAndExpression:
    OrExpression
    AndAndExpression && OrExpression

```
 
```
OrExpression:
    XorExpression
    OrExpression | XorExpression

```
 
```
XorExpression:
    AndExpression
    XorExpression ^ AndExpression

```
 
```
AndExpression:
    CmpExpression
    AndExpression & CmpExpression

```
 
```
CmpExpression:
    ShiftExpression
    EqualExpression
    IdentityExpression
    RelExpression
    InExpression

```
 
```
EqualExpression:
    ShiftExpression == ShiftExpression
    ShiftExpression != ShiftExpression

```
 
```
IdentityExpression:
    ShiftExpression is ShiftExpression
    ShiftExpression !is ShiftExpression

```
 
```
RelExpression:
    ShiftExpression < ShiftExpression
    ShiftExpression <= ShiftExpression
    ShiftExpression > ShiftExpression
    ShiftExpression >= ShiftExpression

```
 
```
InExpression:
    ShiftExpression in ShiftExpression
    ShiftExpression !in ShiftExpression

```
 
```
ShiftExpression:
    AddExpression
    ShiftExpression << AddExpression
    ShiftExpression >> AddExpression
    ShiftExpression >>> AddExpression

```
 
```
AddExpression:
    MulExpression
    AddExpression + MulExpression
    AddExpression - MulExpression
    CatExpression

```
 
```
CatExpression:
    AddExpression ~ MulExpression

```
 
```
MulExpression:
    UnaryExpression
    MulExpression * UnaryExpression
    MulExpression / UnaryExpression
    MulExpression % UnaryExpression

```
 
```
UnaryExpression:
    & UnaryExpression
    ++ UnaryExpression
    -- UnaryExpression
    * UnaryExpression
    - UnaryExpression
    + UnaryExpression
    ! UnaryExpression
    ComplementExpression
    ( Type ) . Identifier
    ( Type ) . TemplateInstance
    DeleteExpression
    CastExpression
    PowExpression

```
 
```
ComplementExpression:
    ~ UnaryExpression

```
 
```
NewExpression:
    new AllocatorArgumentsopt Type
    NewExpressionWithArgs

NewExpressionWithArgs:
    new AllocatorArgumentsopt Type [ AssignExpression ]
    new AllocatorArgumentsopt Type ( ArgumentListopt )
    NewAnonClassExpression

AllocatorArguments:
    ( ArgumentListopt )

ArgumentList:
    AssignExpression
    AssignExpression ,
    AssignExpression , ArgumentList

```
 
```
DeleteExpression:
    delete UnaryExpression

```
 
```
CastExpression:
    cast ( Type ) UnaryExpression
    cast ( TypeCtorsopt ) UnaryExpression

```
 
```
PowExpression:
    PostfixExpression
    PostfixExpression ^^ UnaryExpression

```
 
```
PostfixExpression:
    PrimaryExpression
    PostfixExpression . Identifier
    PostfixExpression . TemplateInstance
    PostfixExpression . NewExpression
    PostfixExpression ++
    PostfixExpression --
    PostfixExpression ( ArgumentListopt )
    TypeCtorsopt BasicType ( ArgumentListopt )
    IndexExpression
    SliceExpression

```
 
```
IndexExpression:
    PostfixExpression [ ArgumentList ]

```
 
```
SliceExpression:
    PostfixExpression [ ]
    PostfixExpression [ Slice ,opt ]
Slice:
    AssignExpression
    AssignExpression , Slice
    AssignExpression .. AssignExpression
    AssignExpression .. AssignExpression , Slice

```
 
```
PrimaryExpression:
    Identifier
    . Identifier
    TemplateInstance
    . TemplateInstance
    this
    super
    null
    true
    false
    $
    IntegerLiteral
    FloatLiteral
    CharacterLiteral
    StringLiterals
    ArrayLiteral
    AssocArrayLiteral
    FunctionLiteral
    AssertExpression
    MixinExpression
    ImportExpression
    NewExpressionWithArgs
    FundamentalType . Identifier
    FundamentalType ( ArgumentListopt )
    TypeCtor ( Type ) . Identifier
    TypeCtor ( Type ) ( ArgumentListopt )
    Typeof
    TypeidExpression
    IsExpression
    ( Expression )
    SpecialKeyword
    TraitsExpression

```
 
```
StringLiterals:
    StringLiteral
    StringLiterals StringLiteral

```
 
```
ArrayLiteral:
    [ ArgumentListopt ]

```
 
```
AssocArrayLiteral:
    [ KeyValuePairs ]

KeyValuePairs:
    KeyValuePair
    KeyValuePair , KeyValuePairs

KeyValuePair:
    KeyExpression : ValueExpression

KeyExpression:
    AssignExpression

ValueExpression:
    AssignExpression

```
 
```
FunctionLiteral:
    function refopt Typeopt ParameterWithAttributes opt FunctionLiteralBody2
    delegate refopt Typeopt ParameterWithMemberAttributes opt FunctionLiteralBody2
    refopt ParameterWithMemberAttributes FunctionLiteralBody2
    FunctionLiteralBody
    Identifier => AssignExpression

ParameterWithAttributes:
    Parameters FunctionAttributesopt

ParameterWithMemberAttributes:
    Parameters MemberFunctionAttributesopt

FunctionLiteralBody2:
    => AssignExpression
    FunctionLiteralBody

FunctionLiteralBody:
    BlockStatement
    FunctionContractsopt BodyStatement

```
 
```
AssertExpression:
    assert ( AssertArguments )

AssertArguments:
    AssignExpression ,opt
    AssignExpression , AssignExpression ,opt

```
 
```
MixinExpression:
    mixin ( ArgumentList )

```
 
```
ImportExpression:
    import ( AssignExpression )

```
 
```
TypeidExpression:
    typeid ( Type )
    typeid ( Expression )

```
 
```
IsExpression:
    is ( Type )
    is ( Type : TypeSpecialization )
    is ( Type == TypeSpecialization )
    is ( Type : TypeSpecialization , TemplateParameterList )
    is ( Type == TypeSpecialization , TemplateParameterList )
    is ( Type Identifier )
    is ( Type Identifier : TypeSpecialization )
    is ( Type Identifier == TypeSpecialization )
    is ( Type Identifier : TypeSpecialization , TemplateParameterList )
    is ( Type Identifier == TypeSpecialization , TemplateParameterList )


TypeSpecialization:
    Type
    struct
    union
    class
    interface
    enum
    __vector
    function
    delegate
    super
    const
    immutable
    inout
    shared
    return
    __parameters
    module
    package

```
 
```
SpecialKeyword:
    __FILE__
    __FILE_FULL_PATH__
    __MODULE__
    __LINE__
    __FUNCTION__
    __PRETTY_FUNCTION__

```
 Statements
----------

 
```
Statement:
    ;
    NonEmptyStatement
    ScopeBlockStatement

NoScopeNonEmptyStatement:
    NonEmptyStatement
    BlockStatement

NoScopeStatement:
    ;
    NonEmptyStatement
    BlockStatement

NonEmptyOrScopeBlockStatement:
    NonEmptyStatement
    ScopeBlockStatement

NonEmptyStatement:
    NonEmptyStatementNoCaseNoDefault
    CaseStatement
    CaseRangeStatement
    DefaultStatement

NonEmptyStatementNoCaseNoDefault:
    LabeledStatement
    ExpressionStatement
    DeclarationStatement
    IfStatement
    WhileStatement
    DoStatement
    ForStatement
    ForeachStatement
    SwitchStatement
    FinalSwitchStatement
    ContinueStatement
    BreakStatement
    ReturnStatement
    GotoStatement
    WithStatement
    SynchronizedStatement
    TryStatement
    ScopeGuardStatement
    ThrowStatement
    AsmStatement
    MixinStatement
    ForeachRangeStatement
    PragmaStatement
    ConditionalStatement
    StaticForeachStatement
    StaticAssert
    TemplateMixin
    ImportDeclaration

```
 
```
ScopeStatement:
    NonEmptyStatement
    BlockStatement

```
 
```
ScopeBlockStatement:
    BlockStatement

```
 
```
LabeledStatement:
    Identifier :
    Identifier : NoScopeStatement
    Identifier : Statement

```
 
```
BlockStatement:
    { }
    { StatementList }

StatementList:
    Statement
    Statement StatementList

```
 
```
ExpressionStatement:
    Expression ;

```
 
```
DeclarationStatement:
    StorageClassesopt Declaration

```
 
```
IfStatement:
    if ( IfCondition ) ThenStatement
    if ( IfCondition ) ThenStatement else ElseStatement

IfCondition:
    Expression
    auto Identifier = Expression
    TypeCtors Identifier = Expression
    TypeCtorsopt BasicType Declarator = Expression

ThenStatement:
    ScopeStatement

ElseStatement:
    ScopeStatement

```
 
```
WhileStatement:
    while ( IfCondition ) ScopeStatement

```
 
```
DoStatement:
    do ScopeStatement  while ( Expression ) ;

```
 
```
ForStatement:
    for ( Initialize Testopt ; Incrementopt ) ScopeStatement

Initialize:
    ;
    NoScopeNonEmptyStatement

Test:
    Expression

Increment:
    Expression

```
 
```
AggregateForeach:
    Foreach ( ForeachTypeList ; ForeachAggregate )

ForeachStatement:
    AggregateForeach NoScopeNonEmptyStatement

Foreach:
    foreach
    foreach_reverse

ForeachTypeList:
    ForeachType
    ForeachType , ForeachTypeList

ForeachType:
    ForeachTypeAttributesopt BasicType Declarator
    ForeachTypeAttributesopt Identifier
    ForeachTypeAttributesopt alias Identifier

ForeachTypeAttributes
    ForeachTypeAttribute
    ForeachTypeAttribute ForeachTypeAttributesopt

ForeachTypeAttribute:
    ref
    TypeCtor
    enum

ForeachAggregate:
    Expression

```
 
```
RangeForeach:
    Foreach ( ForeachType ; LwrExpression .. UprExpression )

LwrExpression:
    Expression

UprExpression:
    Expression

ForeachRangeStatement:
    RangeForeach ScopeStatement

```
 
```
SwitchStatement:
    switch ( Expression ) ScopeStatement

CaseStatement:
    case ArgumentList : ScopeStatementList

CaseRangeStatement:
    case FirstExp : .. case LastExp : ScopeStatementList

FirstExp:
    AssignExpression

LastExp:
    AssignExpression

DefaultStatement:
    default : ScopeStatementList

ScopeStatementList:
    StatementListNoCaseNoDefault

StatementListNoCaseNoDefault:
    StatementNoCaseNoDefault
    StatementNoCaseNoDefault StatementListNoCaseNoDefault

StatementNoCaseNoDefault:
    ;
    NonEmptyStatementNoCaseNoDefault
    ScopeBlockStatement

```
 
```
FinalSwitchStatement:
    final switch ( Expression ) ScopeStatement

```
 
```
ContinueStatement:
    continue Identifieropt ;

```
 
```
BreakStatement:
    break Identifieropt ;

```
 
```
ReturnStatement:
    return Expressionopt ;

```
 
```
GotoStatement:
    goto Identifier ;
    goto default ;
    goto case ;
    goto case Expression ;

```
 
```
WithStatement:
    with ( Expression ) ScopeStatement
    with ( Symbol ) ScopeStatement
    with ( TemplateInstance ) ScopeStatement

```
 
```
SynchronizedStatement:
    synchronized ScopeStatement
    synchronized ( Expression ) ScopeStatement

```
 
```
TryStatement:
    try ScopeStatement Catches
    try ScopeStatement Catches FinallyStatement
    try ScopeStatement FinallyStatement

Catches:
    Catch
    Catch Catches

Catch:
    catch ( CatchParameter ) NoScopeNonEmptyStatement

CatchParameter:
    BasicType Identifieropt

FinallyStatement:
    finally NoScopeNonEmptyStatement

```
 
```
ThrowStatement:
    throw Expression ;

```
 
```
ScopeGuardStatement:
    scope(exit) NonEmptyOrScopeBlockStatement
    scope(success) NonEmptyOrScopeBlockStatement
    scope(failure) NonEmptyOrScopeBlockStatement

```
 
```
AsmStatement:
    asm FunctionAttributesopt { AsmInstructionListopt }

AsmInstructionList:
    AsmInstruction ;
    AsmInstruction ; AsmInstructionList

```
 
```
PragmaStatement

```
 
```
MixinStatement:
    mixin ( ArgumentList ) ;

```
 Structs and Unions
------------------

 
```
AggregateDeclaration:
    ClassDeclaration
    InterfaceDeclaration
    StructDeclaration
    UnionDeclaration

StructDeclaration:
    struct Identifier ;
    struct Identifier AggregateBody
    StructTemplateDeclaration
    AnonStructDeclaration

AnonStructDeclaration:
    struct AggregateBody

UnionDeclaration:
    union Identifier ;
    union Identifier AggregateBody
    UnionTemplateDeclaration
    AnonUnionDeclaration

AnonUnionDeclaration:
    union AggregateBody

AggregateBody:
    { DeclDefsopt }

```
 
```
Postblit:
    this ( this ) MemberFunctionAttributesopt ;
    this ( this ) MemberFunctionAttributesopt FunctionBody

```
 
```
StructInvariant:
    invariant ( ) BlockStatement
    invariant BlockStatement
    invariant ( AssertArguments ) ;

```
 Classes
-------

 
```
ClassDeclaration:
    class Identifier ;
    class Identifier BaseClassListopt AggregateBody
    ClassTemplateDeclaration

BaseClassList:
    : SuperClass
    : SuperClass , Interfaces
    : Interfaces

SuperClass:
    BasicType

Interfaces:
    Interface
    Interface , Interfaces

Interface:
    BasicType

```
 
```
Constructor:
    this Parameters MemberFunctionAttributesopt ;
    this Parameters MemberFunctionAttributesopt FunctionBody
    ConstructorTemplate

```
 
```
Destructor:
    ~ this ( ) MemberFunctionAttributesopt ;
    ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 
```
StaticConstructor:
    static this ( ) MemberFunctionAttributesopt ;
    static this ( ) MemberFunctionAttributesopt FunctionBody

```
 
```
StaticDestructor:
    static ~ this ( ) MemberFunctionAttributesopt ;
    static ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 
```
SharedStaticConstructor:
    shared static this ( ) MemberFunctionAttributesopt ;
    shared static this ( ) MemberFunctionAttributesopt FunctionBody

```
 
```
SharedStaticDestructor:
    shared static ~ this ( ) MemberFunctionAttributesopt ;
    shared static ~ this ( ) MemberFunctionAttributesopt FunctionBody

```
 
```
ClassInvariant:
    invariant ( ) BlockStatement
    invariant BlockStatement
    invariant ( AssertArguments ) ;

```
 
```
Allocator:
    new Parameters ;
    new Parameters FunctionBody

```
 
```
Deallocator:
    delete Parameters ;
    delete Parameters FunctionBody

```
 
```
AliasThis:
    alias Identifier this ;

```
 
```
NewAnonClassExpression:
    new AllocatorArgumentsopt class ConstructorArgsopt SuperClassopt Interfacesopt AggregateBody

ConstructorArgs:
    ( ArgumentListopt )

```
 
```
class Identifier : SuperClass Interfaces AggregateBody
// ...
new AllocatorArguments Identifier ConstructorArgs

```
 Interfaces
----------

 
```
InterfaceDeclaration:
    interface Identifier ;
    interface Identifier BaseInterfaceListopt AggregateBody
    InterfaceTemplateDeclaration

BaseInterfaceList:
    : Interfaces

```
 Enums
-----

 
```
EnumDeclaration:
    enum Identifier EnumBody
    enum Identifier : EnumBaseType EnumBody
    AnonymousEnumDeclaration

EnumBaseType:
    Type

EnumBody:
    { EnumMembers }
    ;

EnumMembers:
    EnumMember
    EnumMember ,
    EnumMember , EnumMembers

EnumMemberAttributes:
    EnumMemberAttribute
    EnumMemberAttribute EnumMemberAttributes

EnumMemberAttribute:
    DeprecatedAttribute
    UserDefinedAttribute
    @disable

EnumMember:
    EnumMemberAttributesopt Identifier
    EnumMemberAttributesopt Identifier = AssignExpression

AnonymousEnumDeclaration:
    enum : EnumBaseType { EnumMembers }
    enum { EnumMembers }
    enum { AnonymousEnumMembers }

AnonymousEnumMembers:
    AnonymousEnumMember
    AnonymousEnumMember ,
    AnonymousEnumMember , AnonymousEnumMembers

AnonymousEnumMember:
    EnumMember
    Type Identifier = AssignExpression

```
 Functions
---------

 
```
FuncDeclaration:
    StorageClassesopt BasicType FuncDeclarator FunctionBody
    AutoFuncDeclaration

AutoFuncDeclaration:
    StorageClasses Identifier FuncDeclaratorSuffix FunctionBody

FuncDeclarator:
    TypeSuffixesopt Identifier FuncDeclaratorSuffix

FuncDeclaratorSuffix:
    Parameters MemberFunctionAttributesopt
    TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt

```
 
```
Parameters:
    ( ParameterListopt )

ParameterList:
    Parameter
    Parameter , ParameterList
    VariadicArgumentsAttributes ...

Parameter:
    ParameterAttributesopt BasicType Declarator
    ParameterAttributesopt BasicType Declarator ...
    ParameterAttributesopt BasicType Declarator = AssignExpression
    ParameterAttributesopt Type
    ParameterAttributesopt Type ...

ParameterAttributes:
    InOut
    UserDefinedAttribute
    ParameterAttributes InOut
    ParameterAttributes UserDefinedAttribute
    ParameterAttributes

InOut:
    auto
    TypeCtor
    final
    in
    lazy
    out
    ref
    return ref
    scope

VariadicArgumentsAttributes:
    VariadicArgumentsAttribute
    VariadicArgumentsAttribute VariadicArgumentsAttributes

VariadicArgumentsAttribute:
    const
    immutable
    return
    scope
    shared

```
 
```
FunctionAttributes:
    FunctionAttribute
    FunctionAttribute FunctionAttributes

FunctionAttribute:
    FunctionAttributeKwd
    Property

MemberFunctionAttributes:
    MemberFunctionAttribute
    MemberFunctionAttribute MemberFunctionAttributes

MemberFunctionAttribute:
    const
    immutable
    inout
    return
    shared
    FunctionAttribute

```
 
```
FunctionBody:
    SpecifiedFunctionBody
    MissingFunctionBody
    ShortenedFunctionBody

FunctionLiteralBody:
    SpecifiedFunctionBody

SpecifiedFunctionBody:
    doopt BlockStatement
    FunctionContractsopt InOutContractExpression doopt BlockStatement
    FunctionContractsopt InOutStatement do BlockStatement

MissingFunctionBody:
    ;
    FunctionContractsopt InOutContractExpression ;
    FunctionContractsopt InOutStatement

ShortenedFunctionBody:
    => AssignExpression ;

```
 
```
FunctionContracts:
    FunctionContract
    FunctionContract FunctionContracts

FunctionContract:
    InOutContractExpression
    InOutStatement

InOutContractExpression:
    InContractExpression
    OutContractExpression

InOutStatement:
    InStatement
    OutStatement

InContractExpression:
    in ( AssertArguments )

OutContractExpression:
    out ( ; AssertArguments )
    out ( Identifier ; AssertArguments )

InStatement:
    in BlockStatement

OutStatement:
    out BlockStatement
    out ( Identifier ) BlockStatement

```
 Templates
---------

 
```
TemplateDeclaration:
    template Identifier TemplateParameters Constraintopt { DeclDefsopt }

TemplateParameters:
    ( TemplateParameterListopt )

TemplateParameterList:
    TemplateParameter
    TemplateParameter ,
    TemplateParameter , TemplateParameterList

TemplateParameter:
    TemplateTypeParameter
    TemplateValueParameter
    TemplateAliasParameter
    TemplateSequenceParameter
    TemplateThisParameter

```
 
```
TemplateInstance:
    Identifier TemplateArguments

TemplateArguments:
    ! ( TemplateArgumentListopt )
    ! TemplateSingleArgument

TemplateArgumentList:
    TemplateArgument
    TemplateArgument ,
    TemplateArgument , TemplateArgumentList

TemplateArgument:
    Type
    AssignExpression
    Symbol

Symbol:
    SymbolTail
    . SymbolTail

SymbolTail:
    Identifier
    Identifier . SymbolTail
    TemplateInstance
    TemplateInstance . SymbolTail

TemplateSingleArgument:
    Identifier
    FundamentalType
    CharacterLiteral
    StringLiteral
    IntegerLiteral
    FloatLiteral
    true
    false
    null
    this
    SpecialKeyword

```
 
```
TemplateTypeParameter:
    Identifier
    Identifier TemplateTypeParameterSpecialization
    Identifier TemplateTypeParameterDefault
    Identifier TemplateTypeParameterSpecialization TemplateTypeParameterDefault

TemplateTypeParameterSpecialization:
    : Type

TemplateTypeParameterDefault:
    = Type

```
 
```
TemplateThisParameter:
    this TemplateTypeParameter

```
 
```
TemplateValueParameter:
    BasicType Declarator
    BasicType Declarator TemplateValueParameterSpecialization
    BasicType Declarator TemplateValueParameterDefault
    BasicType Declarator TemplateValueParameterSpecialization TemplateValueParameterDefault

TemplateValueParameterSpecialization:
    : ConditionalExpression

TemplateValueParameterDefault:
    = AssignExpression
    = SpecialKeyword

```
 
```
TemplateAliasParameter:
    alias Identifier TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt
    alias BasicType Declarator TemplateAliasParameterSpecializationopt TemplateAliasParameterDefaultopt

TemplateAliasParameterSpecialization:
    : Type
    : ConditionalExpression

TemplateAliasParameterDefault:
    = Type
    = ConditionalExpression

```
 
```
TemplateSequenceParameter:
    Identifier ...

```
 
```
ConstructorTemplate:
    this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt :
    this TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt FunctionBody

```
 
```
ClassTemplateDeclaration:
    class Identifier TemplateParameters ;
    class Identifier TemplateParameters Constraintopt BaseClassListopt AggregateBody
    class Identifier TemplateParameters BaseClassListopt Constraintopt AggregateBody

InterfaceTemplateDeclaration:
    interface Identifier TemplateParameters ;
    interface Identifier TemplateParameters Constraintopt BaseInterfaceListopt AggregateBody
    interface Identifier TemplateParameters BaseInterfaceList Constraint AggregateBody

StructTemplateDeclaration:
    struct Identifier TemplateParameters ;
    struct Identifier TemplateParameters Constraintopt AggregateBody

UnionTemplateDeclaration:
    union Identifier TemplateParameters ;
    union Identifier TemplateParameters Constraintopt AggregateBody

```
 
```
Constraint:
    if ( Expression )

```
 Template Mixins
---------------

 
```
TemplateMixinDeclaration:
    mixin template Identifier TemplateParameters Constraintopt { DeclDefsopt }

TemplateMixin:
    mixin MixinTemplateName TemplateArgumentsopt Identifieropt ;

MixinTemplateName:
    . MixinQualifiedIdentifier
    MixinQualifiedIdentifier
    Typeof . MixinQualifiedIdentifier

MixinQualifiedIdentifier:
    Identifier
    Identifier . MixinQualifiedIdentifier
    TemplateInstance . MixinQualifiedIdentifier

```
 Conditional Compilation
-----------------------

 
```
ConditionalDeclaration:
    Condition DeclarationBlock
    Condition DeclarationBlock else DeclarationBlock
    Condition : DeclDefsopt
    Condition DeclarationBlock else : DeclDefsopt

ConditionalStatement:
    Condition NoScopeNonEmptyStatement
    Condition NoScopeNonEmptyStatement else NoScopeNonEmptyStatement

```
 
```
Condition:
    VersionCondition
    DebugCondition
    StaticIfCondition

```
 
```
VersionCondition:
    version ( IntegerLiteral )
    version ( Identifier )
    version ( unittest )
    version ( assert )

```
 
```
VersionSpecification:
    version = Identifier ;
    version = IntegerLiteral ;

```
 
```
DebugCondition:
    debug
    debug ( IntegerLiteral )
    debug ( Identifier )

```
 
```
DebugSpecification:
    debug = Identifier ;
    debug = IntegerLiteral ;

```
 
```
StaticIfCondition:
    static if ( AssignExpression )

```
 
```
StaticForeach:
    static AggregateForeach
    static RangeForeach

StaticForeachDeclaration:
    StaticForeach DeclarationBlock
    StaticForeach : DeclDefsopt

StaticForeachStatement:
    StaticForeach NoScopeNonEmptyStatement

```
 
```
StaticAssert:
    static assert ( AssertArguments );

```
 Traits
------

 
```
TraitsExpression:
    __traits ( TraitsKeyword , TraitsArguments )

TraitsKeyword:
    isAbstractClass
    isArithmetic
    isAssociativeArray
    isFinalClass
    isPOD
    isNested
    isFuture
    isDeprecated
    isFloating
    isIntegral
    isScalar
    isStaticArray
    isUnsigned
    isDisabled
    isVirtualFunction
    isVirtualMethod
    isAbstractFunction
    isFinalFunction
    isStaticFunction
    isOverrideFunction
    isTemplate
    isRef
    isOut
    isLazy
    isReturnOnStack
    isZeroInit
    isModule
    isPackage
    hasMember
    hasCopyConstructor
    hasPostblit
    identifier
    getAliasThis
    getAttributes
    getFunctionAttributes
    getFunctionVariadicStyle
    getLinkage
    getLocation
    getMember
    getOverloads
    getParameterStorageClasses
    getPointerBitmap
    getCppNamespaces
    getVisibility
    getProtection
    getTargetInfo
    getVirtualFunctions
    getVirtualMethods
    getUnitTests
    parent
    child
    classInstanceSize
    getVirtualIndex
    allMembers
    derivedMembers
    isSame
    compiles

TraitsArguments:
    TraitsArgument
    TraitsArgument , TraitsArguments

TraitsArgument:
    AssignExpression
    Type

```
 Unit Tests
----------

 
```
UnitTest:
    unittest BlockStatement

```
 D x86 Inline Assembler
----------------------

 
```
AsmStatement:
    asm FunctionAttributesopt { AsmInstructionListopt }

    AsmInstructionList:
        AsmInstruction ;
        AsmInstruction ; AsmInstructionList
    
```
 
```
AsmInstruction:
    Identifier : AsmInstruction
    align IntegerExpression
    even
    naked
    db Operands
    ds Operands
    di Operands
    dl Operands
    df Operands
    dd Operands
    de Operands
    db StringLiteral
    ds StringLiteral
    di StringLiteral
    dl StringLiteral
    dw StringLiteral
    dq StringLiteral
    Opcode
    Opcode Operands

Operands:
    Operand
    Operand , Operands

```
 
```
IntegerExpression:
    IntegerLiteral
    Identifier

```
 
```
Register:
    AL AH AX EAX
    BL BH BX EBX
    CL CH CX ECX
    DL DH DX EDX
    BP EBP
    SP ESP
    DI EDI
    SI ESI
    ES CS SS DS GS FS
    CR0 CR2 CR3 CR4
    DR0 DR1 DR2 DR3 DR6 DR7
    TR3 TR4 TR5 TR6 TR7
    ST
    ST(0) ST(1) ST(2) ST(3) ST(4) ST(5) ST(6) ST(7)
    MM0  MM1  MM2  MM3  MM4  MM5  MM6  MM7
    XMM0 XMM1 XMM2 XMM3 XMM4 XMM5 XMM6 XMM7

```
 
```
Register64:
    RAX  RBX  RCX  RDX
    BPL  RBP
    SPL  RSP
    DIL  RDI
    SIL  RSI
    R8B  R8W  R8D  R8
    R9B  R9W  R9D  R9
    R10B R10W R10D R10
    R11B R11W R11D R11
    R12B R12W R12D R12
    R13B R13W R13D R13
    R14B R14W R14D R14
    R15B R15W R15D R15
    XMM8 XMM9 XMM10 XMM11 XMM12 XMM13 XMM14 XMM15
    YMM0 YMM1 YMM2  YMM3  YMM4  YMM5  YMM6  YMM7
    YMM8 YMM9 YMM10 YMM11 YMM12 YMM13 YMM14 YMM15

```
 
```
Operand:
    AsmExp

AsmExp:
    AsmLogOrExp
    AsmLogOrExp ? AsmExp : AsmExp

AsmLogOrExp:
    AsmLogAndExp
    AsmLogOrExp || AsmLogAndExp

AsmLogAndExp:
    AsmOrExp
    AsmLogAndExp && AsmOrExp

AsmOrExp:
    AsmXorExp
    AsmOrExp | AsmXorExp

AsmXorExp:
    AsmAndExp
    AsmXorExp ^ AsmAndExp

AsmAndExp:
    AsmEqualExp
    AsmAndExp & AsmEqualExp

AsmEqualExp:
    AsmRelExp
    AsmEqualExp == AsmRelExp
    AsmEqualExp != AsmRelExp

AsmRelExp:
    AsmShiftExp
    AsmRelExp < AsmShiftExp
    AsmRelExp <= AsmShiftExp
    AsmRelExp > AsmShiftExp
    AsmRelExp >= AsmShiftExp

AsmShiftExp:
    AsmAddExp
    AsmShiftExp << AsmAddExp
    AsmShiftExp >> AsmAddExp
    AsmShiftExp >>> AsmAddExp

AsmAddExp:
    AsmMulExp
    AsmAddExp + AsmMulExp
    AsmAddExp - AsmMulExp

AsmMulExp:
    AsmBrExp
    AsmMulExp * AsmBrExp
    AsmMulExp / AsmBrExp
    AsmMulExp % AsmBrExp

AsmBrExp:
    AsmUnaExp
    AsmBrExp [ AsmExp ]

AsmUnaExp:
    AsmTypePrefix AsmExp
    offsetof AsmExp
    seg AsmExp
    + AsmUnaExp
    - AsmUnaExp
    ! AsmUnaExp
    ~ AsmUnaExp
    AsmPrimaryExp

AsmPrimaryExp:
    IntegerLiteral
    FloatLiteral
    __LOCAL_SIZE
    $
    Register
    Register : AsmExp
    Register64
    Register64 : AsmExp
    DotIdentifier
    this

DotIdentifier:
    Identifier
    Identifier . DotIdentifier
    FundamentalType . Identifier

```
 
```
AsmTypePrefix:
    near ptr
    far ptr
    word ptr
    dword ptr
    qword ptr
    FundamentalType ptr

```
 Named Character Entities
------------------------

 
```
NamedCharacterEntity:
    & Identifier ;

```
 Application Binary Interface
----------------------------

 
```
MangledName:
    _D QualifiedName Type
    _D QualifiedName Z        // Internal

```
 
```
QualifiedName:
    SymbolFunctionName
    SymbolFunctionName QualifiedName

SymbolFunctionName:
    SymbolName
    SymbolName TypeFunctionNoReturn
    SymbolName M TypeModifiersopt TypeFunctionNoReturn

```
 
```
SymbolName:
    LName
    TemplateInstanceName
    IdentifierBackRef
    0                         // anonymous symbols

```
 
```
TemplateInstanceName:
    TemplateID LName TemplateArgs Z

TemplateID:
    __T
    __U        // for symbols declared inside template constraint

TemplateArgs:
    TemplateArg
    TemplateArg TemplateArgs

TemplateArg:
    TemplateArgX
    H TemplateArgX

```
 
```
TemplateArgX:
    T Type
    V Type Value
    S QualifiedName
    X Number ExternallyMangledName

```
 
```
Value:
    n
    i Number
    N Number
    e HexFloat
    c HexFloat c HexFloat
    CharWidth Number _ HexDigits
    A Number Value...
    S Number Value...

HexFloat:
    NAN
    INF
    NINF
    N HexDigits P Exponent
    HexDigits P Exponent

Exponent:
    N Number
    Number

HexDigits:
    HexDigit
    HexDigit HexDigits

HexDigit:
    Digit
    A
    B
    C
    D
    E
    F

CharWidth:
    a
    w
    d

```
 
```
Name:
    Namestart
    Namestart Namechars

Namestart:
    _
    Alpha

Namechar:
    Namestart
    Digit

Namechars:
    Namechar
    Namechar Namechars

```
 
```
LName:
    Number Name

Number:
    Digit
    Digit Number

Digit:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

```
 
```
TypeBackRef:
    Q NumberBackRef

IdentifierBackRef:
    Q NumberBackRef

NumberBackRef:
    lower-case-letter
    upper-case-letter NumberBackRef

```
 
```
Type:
    TypeModifiersopt TypeX
    TypeBackRef

TypeX:
    TypeArray
    TypeStaticArray
    TypeAssocArray
    TypePointer
    TypeFunction
    TypeIdent
    TypeClass
    TypeStruct
    TypeEnum
    TypeTypedef
    TypeDelegate
    TypeVoid
    TypeByte
    TypeUbyte
    TypeShort
    TypeUshort
    TypeInt
    TypeUint
    TypeLong
    TypeUlong
    TypeCent
    TypeUcent
    TypeFloat
    TypeDouble
    TypeReal
    TypeIfloat
    TypeIdouble
    TypeIreal
    TypeCfloat
    TypeCdouble
    TypeCreal
    TypeBool
    TypeChar
    TypeWchar
    TypeDchar
    TypeNull
    TypeTuple
    TypeVector

TypeModifiers:
    Const
    Wild
    Wild Const
    Shared
    Shared Const
    Shared Wild
    Shared Wild Const
    Immutable

Shared:
    O

Const:
    x

Immutable:
    y

Wild:
    Ng

TypeArray:
    A Type

TypeStaticArray:
    G Number Type

TypeAssocArray:
    H Type Type

TypePointer:
    P Type

TypeVector:
    Nh Type

TypeFunction:
    TypeFunctionNoReturn Type

TypeFunctionNoReturn:
    CallConvention FuncAttrsopt Parametersopt ParamClose

CallConvention:
    F       // D
    U       // C
    W       // Windows
    R       // C++
    Y       // Objective-C

FuncAttrs:
    FuncAttr
    FuncAttr FuncAttrs

FuncAttr:
    FuncAttrPure
    FuncAttrNothrow
    FuncAttrRef
    FuncAttrProperty
    FuncAttrNogc
    FuncAttrReturn
    FuncAttrScope
    FuncAttrTrusted
    FuncAttrSafe
    FuncAttrLive

```
 
```
FuncAttrPure:
    Na

FuncAttrNogc:
    Ni

FuncAttrNothrow:
    Nb

FuncAttrProperty:
    Nd

FuncAttrRef:
    Nc

FuncAttrReturn:
    Nj

FuncAttrScope:
    Nl

FuncAttrTrusted:
    Ne

FuncAttrSafe:
    Nf

FuncAttrLive:
    Nm

Parameters:
    Parameter
    Parameter Parameters

Parameter:
    Parameter2
    M Parameter2     // scope
    Nk Parameter2    // return

Parameter2:
    Type
    I Type     // in
    J Type     // out
    K Type     // ref
    L Type     // lazy

ParamClose
    X     // variadic T t...) style
    Y     // variadic T t,...) style
    Z     // not variadic

TypeIdent:
    I QualifiedName

TypeClass:
    C QualifiedName

TypeStruct:
    S QualifiedName

TypeEnum:
    E QualifiedName

TypeTypedef:
    T QualifiedName

TypeDelegate:
    D TypeModifiersopt TypeFunction

TypeVoid:
    v

TypeByte:
    g

TypeUbyte:
    h

TypeShort:
    s

TypeUshort:
    t

TypeInt:
    i

TypeUint:
    k

TypeLong:
    l

TypeUlong:
    m

TypeCent:
    zi

TypeUcent:
    zk

TypeFloat:
    f

TypeDouble:
    d

TypeReal:
    e

TypeIfloat:
    o

TypeIdouble:
    p

TypeIreal:
    j

TypeCfloat:
    q

TypeCdouble:
    r

TypeCreal:
    c

TypeBool:
    b

TypeChar:
    a

TypeWchar:
    u

TypeDchar:
    w

TypeNull:
    n

TypeTuple:
    B Parameters Z

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/grammar.html>

Structs, Unions
===============

 **Contents** 1. [Struct Layout](#struct_layout)
2. [Plain Old Data](#POD)
3. [Opaque Structs and Unions](#opaque_struct_unions)
4. [Default Initialization of Structs](#default_struct_init)
5. [Static Initialization of Structs](#static_struct_init)
6. [Default Initialization of Unions](#default_union_init)
7. [Static Initialization of Unions](#static_union_init)
8. [Dynamic Initialization of Structs](#dynamic_struct_init)
9. [Struct Literals](#struct-literal)
10. [Struct Properties](#struct_properties)
11. [Struct Instance Properties](#struct_instance_properties)
12. [Struct Field Properties](#struct_field_properties)
13. [Const, Immutable and Shared Structs](#const-struct)
14. [Union Constructors](#UnionConstructor)
15. [Struct Constructors](#struct-constructor)
	1. [Delegating Constructors](#delegating-constructor)
	2. [Struct Instantiation](#struct-instantiation)
	3. [Constructor Attributes](#constructor-attributes)
	4. [Disabling Default Struct Construction](#disable_default_construction)
	5. [Field initialization inside a constructor](#field-init)
	6. [Struct Copy Constructors](#struct-copy-constructor)
16. [Struct Postblits](#struct-postblit)
17. [Struct Destructors](#struct-destructor)
18. [Struct Invariants](#StructInvariant)
19. [Identity Assignment Overload](#assign-overload)
20. [Nested Structs](#nested)
21. [Unions and Special Member Functions](#unions_and_special_memb_funct)

 Whereas classes are reference types, structs are value types. Structs and unions are simple aggregations of data and their associated operations on that data. 

 
```
AggregateDeclaration:
    ClassDeclaration
    InterfaceDeclaration
    StructDeclaration
    UnionDeclaration

StructDeclaration:
    struct Identifier ;
    struct Identifier AggregateBody
    StructTemplateDeclaration
    AnonStructDeclaration

AnonStructDeclaration:
    struct AggregateBody

UnionDeclaration:
    union Identifier ;
    union Identifier AggregateBody
    UnionTemplateDeclaration
    AnonUnionDeclaration

AnonUnionDeclaration:
    union AggregateBody

AggregateBody:
    { DeclDefsopt }

```
 A struct is defined to not have an identity; that is, the implementation is free to make bit copies of the struct as convenient.

 Structs and unions may not contain an instance of themselves, however, they may contain a pointer to the same type. 

 **Best Practices:** 1. Bit fields are supported with the [bitfields](https://dlang.org/phobos/std_bitmanip.html#bitfields) template.

 Struct Layout
-------------

 The non-static data members of a struct are called *fields*. Fields are laid out in lexical order. Fields are aligned according to the [Align Attribute](attribute#align) in effect. Unnamed padding is inserted between fields to align fields. There is no padding between the first field and the start of the object. 

 Structs with no fields of non-zero size (aka *Empty Structs*) have a size of one byte.

 Non-static [function-nested D structs](#nested), which access the context of their enclosing scope, have an extra field. 

 **Implementation Defined:** 1. The default layout of the fields of a struct is an exact match with the *associated C compiler*.
2. g++ and clang++ differ in how empty structs are handled. Both return `1` from `sizeof`, however, clang++ does not push them onto the parameter stack while g++ does. This is a binary incompatibility between g++ and clang++. dmd follows clang++ behavior for OSX and FreeBSD, and g++ behavior for Linux and other Posix platforms.
3. clang and gcc both return `0` from `sizeof` for empty structs. Using `extern "C++"` in clang++ and g++ does not cause them to conform to the behavior of their respective C compilers.

 **Undefined Behavior:** 1. The padding data can be accessed, but its contents are undefined.
2. Do not pass or return structs with no fields of non-zero size to `extern (C)` functions. According to C11 6.7.2.1p8 this is undefined behavior.

 **Best Practices:** 1. When laying out a struct to match an externally defined layout, use align attributes to describe an exact match. Using a [Static Assert](version#static-assert) to ensure the result is as expected.
2. Although the contents of the padding are often zero, do not rely on that.
3. Avoid using empty structs when interfacing with C and C++ code.
4. Avoid using empty structs as parameters or arguments to variadic functions.

 Plain Old Data
--------------

 A struct or union is *Plain Old Data* (POD) if it meets the following criteria:

 1. it is not nested
2. it has no postblits, copy constructors, destructors, or assignment operators
3. it has no `ref` fields or fields that are themselves non-POD

 **Best Practices:** Structs or unions that interface with C code should be POD. Opaque Structs and Unions
-------------------------

 Opaque struct and union declarations do not have a [*AggregateBody*](#AggregateBody):

 
```
struct S;
union U;
struct V(T);
union W(T);

```
 The members are completely hidden to the user, and so the only operations on those types are ones that do not require any knowledge of the contents of those types. For example:

 
```
struct S;
S.sizeof; // error, size is not known
S s;      // error, cannot initialize unknown contents
S* p;     // ok, knowledge of members is not necessary

```
 **Best Practices:** They can be used to implement the [PIMPL idiom](https://en.wikipedia.org/wiki/Opaque_pointer). Default Initialization of Structs
---------------------------------

 Struct fields are by default initialized to whatever the [*Initializer*](declaration#Initializer) for the field is, and if none is supplied, to the default initializer for the field's type. 

 
```
struct S { int a = 4; int b; }
S x; // x.a is set to 4, x.b to 0

```
 The default initializers are evaluated at compile time.

 The default initializers may not contain references to mutable data.

 Static Initialization of Structs
--------------------------------

 If a [*StructInitializer*](declaration#StructInitializer) is supplied, the fields are initialized by the [*StructMemberInitializer*](declaration#StructMemberInitializer) syntax. *StructMemberInitializers* with the *Identifier : NonVoidInitializer* syntax may be appear in any order, where *Identifier* is the field identifier. *StructMemberInitializer*s with the [*NonVoidInitializer*](declaration#NonVoidInitializer) syntax appear in the lexical order of the fields in the [*StructDeclaration*](#StructDeclaration). 

 Fields not specified in the *StructInitializer* are default initialized.

 
```
struct S { int a, b, c, d = 7; }
S r;                          // r.a = 0, r.b = 0, r.c = 0, r.d = 7
S s = { a:1, b:2 };           // s.a = 1, s.b = 2, s.c = 0, s.d = 7
S t = { c:4, b:5, a:2, d:5 }; // t.a = 2, t.b = 5, t.c = 4, t.d = 5
S u = { 1, 2 };               // u.a = 1, u.b = 2, u.c = 0, u.d = 7
S v = { 1, d:3 };             // v.a = 1, v.b = 0, v.c = 0, v.d = 3
S w = { b:1, 3 };             // w.a = 0, w.b = 1, w.c = 3, w.d = 7

```
 Initializing a field more than once is an error:

 
```
S x = { 1, a:2 };  // error: duplicate initializer for field `a`

```
 Default Initialization of Unions
--------------------------------

 Unions are by default initialized to whatever the [*Initializer*](declaration#Initializer) for the first field is, and if none is supplied, to the default initializer for the first field's type. 

 If the union is larger than the first field, the remaining bits are set to 0.

 
```
union U { int a = 4; long b; }
U x; // x.a is set to 4, x.b to an implementation-defined value

union V { int a; long b = 4; }
V y; // y.a is set to 0, y.b to an implementation-defined value

```
 
```
union W { int a = 4; long b = 5; } // error: overlapping default initialization for `a` and `b`

```
 The default initializer is evaluated at compile time.

 **Implementation Defined:** The values the fields other than the default initialized field are set to. Static Initialization of Unions
-------------------------------

 Unions are initialized similarly to structs, except that only one initializer is allowed.

 
```
union U { int a; double b; }
U u = { 2 };       // u.a = 2
U v = { b : 5.0 }; // v.b = 5.0

```
 
```
U w = { 2, 3 };    // error: overlapping initialization for field `a` and `b`

```
 If the union is larger than the initialized field, the remaining bits are set to 0.

 **Implementation Defined:** The values the fields other than the initialized field are set to. Dynamic Initialization of Structs
---------------------------------

 The [static initializer syntax](#static_struct_init) can also be used to initialize non-static variables. The initializer need not be evaluable at compile time.

 
```
struct S { int a, b, c, d = 7; }

void test(int i)
{
    S q = { 1, b:i }; // q.a = 1, q.b = i, q.c = 0, q.d = 7
}

```
 Structs can be dynamically initialized from another value of the same type:

 
```
struct S { int a; }
S t;      // default initialized
t.a = 3;
S s = t;  // s.a is set to 3

```
 If `opCall` is overridden for the struct, and the struct is initialized with a value that is of a different type, then the `opCall` operator is called:

 
```
struct S
{
    int a;

    static S opCall(int v)
    {
        S s;
        s.a = v;
        return s;
    }

    static S opCall(S v)
    {
        assert(0);
    }
}

S s = 3; // sets s.a to 3 using S.opCall(int)
S t = s; // sets t.a to 3, S.opCall(S) is not called

```
 Struct Literals
---------------

 Struct literals consist of the name of the struct followed by a parenthesized argument list:

 
```
struct S { int x; float y; }

int foo(S s) { return s.x; }

foo( S(1, 2) ); // set field x to 1, field y to 2

```
 Struct literals are syntactically like function calls. If a struct has a member function named `opCall`, then struct literals for that struct are not possible. See also [opCall operator overloading](operatoroverloading#FunctionCall) for the issue workaround. It is an error if there are more arguments than fields of the struct. If there are fewer arguments than fields, the remaining fields are initialized with their respective default initializers. If there are anonymous unions in the struct, only the first member of the anonymous union can be initialized with a struct literal, and all subsequent non-overlapping fields are default initialized. 

 Struct Properties
-----------------

 

Struct Properties| **Name** | **Description** |
| `.sizeof` | Size in bytes of struct |
| `.alignof` | Size boundary struct needs to be aligned on |

 Struct Instance Properties
--------------------------

 

Struct Instance Properties| **Name** | **Description** |
| `.tupleof` | An [expression sequence](template#variadic-templates) of all struct fields - see [Class Properties](class#class_properties) for a class-based example. |

 Struct Field Properties
-----------------------

 

Struct Field Properties| **Name** | **Description** |
| `.offsetof` | Offset in bytes of field from beginning of struct |

 Const, Immutable and Shared Structs
-----------------------------------

 A struct declaration can have a storage class of `const`, `immutable` or `shared`. It has an equivalent effect as declaring each member of the struct as `const`, `immutable` or `shared`. 

 
```
const struct S { int a; int b = 2; }
void main()
{
    S s = S(3); // initializes s.a to 3
    S t;        // initializes t.a to 0
    t = s;      // error, t.a and t.b are const, so cannot modify them.
    t.a = 4;    // error, t.a is const
}

```
 Union Constructors
------------------

 Unions are constructed in the same way as structs.

 Struct Constructors
-------------------

 Struct constructors are used to initialize an instance of a struct when a more complex construction is needed than is allowed by [static initialization](#static_struct_init) or a [struct literal](#struct-literal). 

 Constructors are defined with a function name of `this` and have no return value. The grammar is the same as for the class [*Constructor*](class#Constructor). 

 A struct constructor is called by the name of the struct followed by [*Parameters*](function#Parameters). 

 If the [*ParameterList*](function#ParameterList) is empty, the struct instance is default initialized.

 
```
struct S
{
    int x, y = 4, z = 6;
    this(int a, int b)
    {
        x = a;
        y = b;
    }
}

void main()
{
    S a = S(4, 5); // calls S.this(4, 5):  a.x = 4, a.y = 5, a.z = 6
    S b = S();  // default initialized:    b.x = 0, b.y = 4, b.z = 6
    S c = S(1); // error, matching this(int) not found
}

```
 A *default constructor* (i.e. one with an empty [*ParameterList*](function#ParameterList)) is not allowed.

 
```
struct S
{
    int x;
    this() { } // error, struct default constructor not allowed
}

```
 ### Delegating Constructors

 A constructor can call another constructor for the same struct in order to share common initializations. This is called a *delegating constructor*: 

 
```
struct S
{
    int j = 1;
    long k = 2;
    this(long k)
    {
        this.k = k;
    }
    this(int i)
    {
        // At this point: j=1, k=2
        this(6); // delegating constructor call
        // At this point: j=1, k=6
        j = i;
        // At this point: j=i, k=6
    }
}

```
 The following restrictions apply:

 1. If a constructor's code contains a delegating constructor call, all possible execution paths through the constructor must make exactly one delegating constructor call: 
```
struct S
{
    int a;
    this(int i) { }

    this(char c)
    {
        c || this(1); // error, not on all paths
    }

    this(wchar w)
    {
        (w) ? this(1) : this('c'); } // ok

    this(byte b)
    {
        foreach (i; 0 .. b)
        {
            this(1);  // error, inside loop
        }
    }
}

```
2. It is illegal to refer to `this` implicitly or explicitly prior to making a delegating constructor call.
3. Once the delegating constructor returns, all fields are considered constructed.
4. Delegating constructor calls cannot appear after labels.

 See also: [delegating class constructors](class#delegating-constructors).

 ### Struct Instantiation

 When an instance of a struct is created, the following steps happen:

 1. The raw data is statically initialized using the values provided in the struct definition. This operation is equivalent to doing a memory copy of a static version of the object onto the newly allocated one.
2. If there is a constructor defined for the struct, the constructor matching the argument list is called.
3. If struct invariant checking is turned on, the struct invariant is called at the end of the constructor.

 ### Constructor Attributes

 A constructor qualifier (`const`, `immutable` or `shared`) constructs the object instance with that specific qualifier. 

 
```
struct S1
{
    int[] a;
    this(int n) { a = new int[](n); }
}
struct S2
{
    int[] a;
    this(int n) immutable { a = new int[](n); }
}
void main()
{
    // Mutable constructor creates mutable object.
    S1 m1 = S1(1);

    // Constructed mutable object is implicitly convertible to const.
    const S1 c1 = S1(1);

    // Constructed mutable object is not implicitly convertible to immutable.
    immutable i1 = S1(1); // error

    // Mutable constructor cannot construct immutable object.
    auto x1 = immutable S1(1); // error


    // Immutable constructor creates immutable object.
    immutable i2 = immutable S2(1);

    // Immutable constructor cannot construct mutable object.
    auto x2 = S2(1); // error

    // Constructed immutable object is not implicitly convertible to mutable.
    S2 m2 = immutable S2(1); // error

    // Constructed immutable object is implicitly convertible to const.
    const S2 c2 = immutable S2(1);
}

```
 Constructors can be overloaded with different attributes.

 
```
struct S
{
    this(int);           // non-shared mutable constructor
    this(int) shared;    // shared mutable constructor
    this(int) immutable; // immutable constructor
}

S m = S(1);
shared s = shared S(2);
immutable i = immutable S(3);

```
 #### Pure Constructors

 If the constructor can create a unique object (i.e. if it is `pure`), the object is implicitly convertible to any qualifiers. 

 
```
struct S
{
    this(int) pure;
    // Based on the definition, this creates a mutable object. But the
    // created object cannot contain any mutable global data.
    // Therefore the created object is unique.

    this(int[] arr) immutable pure;
    // Based on the definition, this creates an immutable object. But
    // the argument int[] never appears in the created object so it
    // isn't implicitly convertible to immutable. Also, it cannot store
    // any immutable global data.
    // Therefore the created object is unique.
}

immutable i = immutable S(1); // this(int) pure is called
shared s = shared S(1);       // this(int) pure is called
S m = S([1,2,3]);             // this(int[]) immutable pure is called

```
 ### Disabling Default Struct Construction

 If a struct constructor is annotated with `@disable` and has an empty [*ParameterList*](function#ParameterList), the struct has disabled default construction. The only way it can be constructed is via a call to another constructor with a non-empty *ParameterList*. 

 A struct with a disabled default constructor, and no other constructors, cannot be instantiated other than via a [*VoidInitializer*](declaration#VoidInitializer).

 A disabled default constructor may not have a [*FunctionBody*](function#FunctionBody).

 If any fields have disabled default construction, struct default construction is also disabled.

 
```
struct S
{
    int x;

    // Disables default construction
    @disable this();

    this(int v) { x = v; }
}
struct T
{
    int y;
    S s;
}
void main()
{
    S s;          // error: default construction is disabled
    S t = S();    // error: also disabled
    S u = S(1);   // constructed by calling `S.this(1)`
    S v = void;   // not initialized, but allowed
    S w = { 1 };  // error: cannot use { } since constructor exists
    S[3] a;       // error: default construction is disabled
    S[3] b = [S(1), S(20), S(-2)]; // ok
    T t;          // error: default construction is disabled
}

```
 **Best Practices:** Disabling default construction is useful when the default value, such as `null`, is not acceptable. ### Field initialization inside a constructor

 In a constructor body, if a delegating constructor is called, all field assignments are considered assignments. Otherwise, the first instance of field assignment is its initialization, and assignments of the form `field = expression` are treated as equivalent to `typeof(field)(expression)`. The values of fields may be read before initialization or construction with a delegating constructor. 

 
```
struct S
{
    int num;
    int ber;
    this(int i)
    {
        num = i + 1;   // initialization
        num = i + 2;   // assignment
        ber = ber + 1; // ok to read before initialization
    }
    this(int i, int j)
    {
        this(i);
        num = i + 1;  // assignment
    }
}

```
 If the field type has an [`opAssign`](operatoroverloading#assignment) method, it will not be used for initialization.

 
```
struct A
{
    this(int n) {}
    void opAssign(A rhs) {}
}
struct S
{
    A val;
    this(int i)
    {
        val = A(i);  // val is initialized to the value of A(i)
        val = A(2);  // rewritten to val.opAssign(A(2))
    }
}

```
 If the field type is not mutable, multiple initialization will be rejected.

 
```
struct S
{
    immutable int num;
    this(int)
    {
        num = 1;  // OK
        num = 2;  // Error: assignment to immutable
    }
}

```
 If the field is initialized on one path, it must be initialized on all paths.

 
```
struct S
{
    immutable int num;
    immutable int ber;
    this(int i)
    {
        if (i)
            num = 3;   // initialization
        else
            num = 4;   // initialization
    }
    this(long j)
    {
        j ? (num = 3) : (num = 4); // ok
        j || (ber = 3);  // Error: initialized on only one path
        j && (ber = 3);  // Error: initialized on only one path
    }
}

```
 A field initialization may not appear in a loop or after a label.

 
```
struct S
{
    immutable int num;
    immutable string str;
    this(int j)
    {
        foreach (i; 0..j)
        {
            num = 1;    // Error: field initialization not allowed in loops
        }
        size_t i = 0;
    Label:
        str = "hello";  // Error: field initialization not allowed after labels
        if (i++ < 2)
            goto Label;
    }
    this(int j, int k)
    {
        switch (j)
        {
            case 1: ++j; break;
            default: break;
        }
        num = j;        // Error: `case` and `default` are also labels
    }
}

```
 If a field's type has disabled default construction, then it must be initialized in the constructor.

 
```
struct S { int y; @disable this(); }

struct T
{
    S s;
    this(S t) { s = t; }       // ok
    this(int i) { this('c'); } // ok
    this(char) { }             // Error: s not initialized
}

```
 ### Struct Copy Constructors

 Copy constructors are used to initialize a `struct` instance from another `struct` of the same type.

 A constructor declaration is a copy constructor declaration if and only if it is a constructor declaration that takes only one non-default parameter by reference that is of the same type as `typeof(this)`, followed by any number of default parameters:

 
```
struct A
{
    this(ref return scope A rhs) {}                        // copy constructor
    this(ref return scope const A rhs, int b = 7) {}       // copy constructor with default parameter
}

```
 The copy constructor is type checked as a normal constructor.

 If a copy constructor is defined, implicit calls to it will be inserted in the following situations:

 1. When a variable is explicitly initialized:

```
struct A
{
    this(ref return scope A rhs) {}
}

void main()
{
    A a;
    A b = a; // copy constructor gets called
}

```
3. When a parameter is passed by value to a function:

```
struct A
{
    this(ref return scope A another) {}
}

void fun(A a) {}

void main()
{
    A a;
    fun(a);    // copy constructor gets called
}

```
5. When a parameter is returned by value from a function and Named Returned Value Optiomization (NRVO) cannot be performed:

```
struct A
{
    this(ref return scope A another) {}
}

A fun()
{
    A a;
    return a;       // NRVO, no copy constructor call
}

A a;
A gun()
{
    return a;       // cannot perform NRVO, rewrite to: return (A __tmp; __tmp.copyCtor(a));
}

void main()
{
    A a = fun();
    A b = gun();
}

```

 When a copy constructor is defined for a `struct` (or marked `@disable`), the compiler no longer implicitly generates default copy/blitting constructors for that `struct`: 

 
```
struct A
{
    int[] a;
    this(ref return scope A rhs) {}
}

void fun(immutable A) {}

void main()
{
    immutable A a;
    fun(a);        // error: copy constructor cannot be called with types (immutable) immutable
}

```
 If a `union S` has fields that define a copy constructor, whenever an object of type `S` is initialized by copy, an error will be issued. The same rule applies to overlapped fields (anonymous unions).

 A `struct` that defines a copy constructor is not a POD.

 #### Copy Constructor Attributes

 The copy constructor can be overloaded with different qualifiers applied to the parameter (copying from a qualified source) or to the copy constructor itself (copying to a qualified destination): 

 
```
struct A
{
    this(ref return scope A another) {}                        // 1 - mutable source, mutable destination
    this(ref return scope immutable A another) {}              // 2 - immutable source, mutable destination
    this(ref return scope A another) immutable {}              // 3 - mutable source, immutable destination
    this(ref return scope immutable A another) immutable {}    // 4 - immutable source, immutable destination
}

void main()
{
    A a;
    immutable A ia;

    A a2 = a;      // calls 1
    A a3 = ia;     // calls 2
    immutable A a4 = a;     // calls 3
    immutable A a5 = ia;    // calls 4
}

```
 The `inout` qualifier may be applied to the copy constructor parameter in order to specify that mutable, `const`, or `immutable` types are treated the same: 

 
```
struct A
{
    this(ref return scope inout A rhs) immutable {}
}

void main()
{
    A r1;
    const(A) r2;
    immutable(A) r3;

    // All call the same copy constructor because `inout` acts like a wildcard
    immutable(A) a = r1;
    immutable(A) b = r2;
    immutable(A) c = r3;
}

```
 #### Implicit Copy Constructors

 A copy constructor is generated implicitly by the compiler for a `struct S` if all of the following conditions are met:

 1. `S` does not explicitly declare any copy constructors;
2. `S` defines at least one direct member that has a copy constructor, and that member is not overlapped (by means of `union`) with any other member.

 If the restrictions above are met, the following copy constructor is generated:

 
```
this(ref return scope inout(S) src) inout
{
    foreach (i, ref inout field; src.tupleof)
        this.tupleof[i] = field;
}

```
 If the generated copy constructor fails to type check, it will receive the `@disable` attribute.

 Struct Postblits
----------------

 
```
Postblit:
    this ( this ) MemberFunctionAttributesopt ;
    this ( this ) MemberFunctionAttributesopt FunctionBody

```
 WARNING: The postblit is considered legacy and is not recommended for new code. Code should use [copy constructors](#struct-copy-constructor) defined in the previous section. For backward compatibility reasons, a `struct` that explicitly defines both a copy constructor and a postblit will only use the postblit for implicit copying. However, if the postblit is disabled, the copy constructor will be used. If a struct defines a copy constructor (user-defined or generated) and has fields that define postblits, a deprecation will be issued, informing that the postblit will have priority over the copy constructor.

 *Copy construction* is defined as initializing a struct instance from another struct of the same type. Copy construction is divided into two parts:

 1. blitting the fields, i.e. copying the bits
2. running *postblit* on the result

 The first part is done automatically by the language, the second part is done if a postblit function is defined for the struct. The postblit has access only to the destination struct object, not the source. Its job is to ‘fix up’ the destination as necessary, such as making copies of referenced data, incrementing reference counts, etc. For example: 

 
```
struct S
{
    int[] a;    // array is privately owned by this instance
    this(this)
    {
        a = a.dup;
    }
}

```
 Disabling struct postblit makes the object not copyable. 

 
```
struct T
{
    @disable this(this);  // disabling makes T not copyable
}
struct S
{
    T t;   // uncopyable member makes S also not copyable
}

void main()
{
    S s;
    S t = s; // error, S is not copyable
}

```
 Depending on the struct layout, the compiler may generate the following internal postblit functions:

 1. `void __postblit()`. The compiler assigns this name to the explicitly defined postblit `this(this)` so that it can be treated exactly as a normal function. Note that if a struct defines a postblit, it cannot define a function named `__postblit` - no matter the signature - as this would result in a compilation error due to the name conflict.
2. `void __fieldPostblit()`. If a struct `X` has at least one `struct` member that in turn defines (explicitly or implicitly) a postblit, then a field postblit is generated for `X` that calls all the underlying postblits of the struct fields in declaration order.
3. `void __aggrPostblit()`. If a struct has an explicitly defined postblit and at least 1 struct member that has a postblit (explicit or implicit) an aggregated postblit is generated which calls `__fieldPostblit` first and then `__postblit`.
4. `void __xpostblit()`. The field and aggregated postblits, although generated for a struct, are not actual struct members. In order to be able to call them, the compiler internally creates an alias, called `__xpostblit` which is a member of the struct and which points to the generated postblit that is the most inclusive.

 
```
// struct with alias __xpostblit = __postblit
struct X
{
    this(this) {}
}

// struct with alias __xpostblit = __fieldPostblit
// which contains a call to X.__xpostblit
struct Y
{
    X a;
}

// struct with alias __xpostblit = __aggrPostblit which contains
// a call to Y.__xpostblit and a call to Z.__postblit
struct Z
{
    Y a;
    this(this) {}
}

void main()
{
    // X has __postblit and __xpostblit (pointing to __postblit)
    static assert(__traits(hasMember, X, "__postblit"));
    static assert(__traits(hasMember, X, "__xpostblit"));

    // Y does not have __postblit, but has __xpostblit (pointing to __fieldPostblit)
    static assert(!__traits(hasMember, Y, "__postblit"));
    static assert(__traits(hasMember, Y, "__xpostblit"));
    // __fieldPostblit is not a member of the struct
    static assert(!__traits(hasMember, Y, "__fieldPostblit"));

    // Z has  __postblit and __xpostblit (pointing to __aggrPostblit)
    static assert(__traits(hasMember, Z, "__postblit"));
    static assert(__traits(hasMember, Z, "__xpostblit"));
    // __aggrPostblit is not a member of the struct
    static assert(!__traits(hasMember, Z, "__aggrPostblit"));
}

```
 Neither of the above postblits is defined for structs that don't define `this(this)` and don't have fields that transitively define it. If a struct does not define a postblit (implicit or explicit) but defines functions that use the same name/signature as the internally generated postblits, the compiler is able to identify that the functions are not actual postblits and does not insert calls to them when the struct is copied. Example:

 
```
struct X
{}

int a;

struct Y
{
    int a;
    X b;
    void __fieldPostPostblit()
    {
        a = 42;
    }
}

void main()
{
    static assert(!__traits(hasMember, X, "__postblit"));
    static assert(!__traits(hasMember, X, "__xpostblit"));

    static assert(!__traits(hasMember, Y, "__postblit"));
    static assert(!__traits(hasMember, Y, "__xpostblit"));

    Y y;
    auto y2 = y;
    assert(a == 0); // __fieldPostBlit does not get called
}

```
 Postblits cannot be overloaded. If two or more postblits are defined, even if the signatures differ, the compiler assigns the `__postblit` name to both and later issues a conflicting function name error:

 
```
struct X
{
    this(this) {}
    this(this) const {} // error: function X.__postblit conflicts with function X.__postblit
}

```
 The following describes the behavior of the qualified postblit definitions:

 1. `const`. When a postblit is qualified with `const` as in `this(this) const;` or `const this(this);` then the postblit is successfully called on mutable (unqualified), `const`, and `immutable` objects, but the postblit cannot modify the object because it regards it as `const`; hence `const` postblits are of limited usefulness. Example:

```
struct S
{
    int n;
    this(this) const
    {
        import std.stdio : writeln;
        writeln("postblit called");
        //++n; // error: cannot modify this.n in `const` function
    }
}

void main()
{
    S s1;
    auto s2 = s1;
    const S s3;
    auto s4 = s3;
    immutable S s5;
    auto s6 = s5;
}

```
3. `immutable`. When a postblit is qualified with `immutable` as in `this(this) immutable` or `immutable this(this)` the code is ill-formed. The `immutable` postblit passes the compilation phase but cannot be invoked. Example:

```
struct Y
{
    // not invoked anywhere, no error is issued
    this(this) immutable
    { }
}

struct S
{
    this(this) immutable
    { }
}

void main()
{
    S s1;
    auto s2 = s1;    // error: immutable method `__postblit` is not callable using a mutable object
    const S s3;
    auto s4 = s3;    // error: immutable method `__postblit` is not callable using a mutable object
    immutable S s5;
    auto s6 = s5;    // error: immutable method `__postblit` is not callable using a mutable object
}

```
5. `shared`. When a postblit is qualified with `shared` as in `this(this) shared` or `shared this(this)` solely `shared` objects may invoke the postblit; attempts of postbliting unshared objects will result in compile time errors:

```
struct S
{
    this(this) shared
    { }
}

void main()
{
    S s1;
    auto s2 = s1;    // error: shared method `__postblit` is not callable using a non-shared object
    const S s3;
    auto s4 = s3;    // error: shared method `__postblit` is not callable using a non-shared object
    immutable S s5;
    auto s6 = s5;    // error: shared method `__postblit` is not callable using a non-shared object

    // calling the shared postblit on a shared object is accepted
    shared S s7;
    auto s8 = s7;
}

```

 An unqualified postblit will get called even if the struct is instantiated as `immutable` or `const`, but the compiler issues an error if the struct is instantiated as `shared`:

 
```
struct S
{
    int n;
    this(this) { ++n; }
}

void main()
{
    immutable S a;      // shared S a; => error : non-shared method is not callable using a shared object
    auto a2 = a;
    import std.stdio: writeln;
    writeln(a2.n);     // prints 1
}

```
 From a postblit perspective, qualifiying the struct definition yields the same result as explicitly qualifying the postblit.

 The following table lists all the possibilities of grouping qualifiers for a postblit associated with the type of object that needs to be used in order to successfully invoke the postblit:

 

Qualifier Groups| object type to be invoked on | `const` | `immutable` | `shared` |
| any object type |  ✔ |  |  |
| uncallable |  |  ✔ |  |
| shared object |  |  |  ✔ |
| uncallable |  ✔ |  ✔ |  |
| shared object |  ✔ |  |  ✔ |
| uncallable |  |  ✔ |  ✔ |
| uncallable |  ✔ |  ✔ |  ✔ |

 Note that when `const` and `immutable` are used to explicitly qualify a postblit as in `this(this) const immutable;` or `const immutable this(this);` - the order in which the qualifiers are declared does not matter - the compiler generates a conflicting attribute error, however declaring the struct as `const`/`immutable` and the postblit as `immutable`/`const` achieves the effect of applying both qualifiers to the postblit. In both cases the postblit is qualified with the more restrictive qualifier, which is `immutable`. 

 The postblits `__fieldPostblit` and `__aggrPostblit` are generated without any implicit qualifiers and are not considered struct members. This leads to the situation where qualifying an entire struct declaration with `const` or `immutable` does not have any impact on the above-mentioned postblits. However, since `__xpostblit` is a member of the struct and an alias of one of the other postblits, the qualifiers applied to the struct will affect the aliased postblit.

 
```
struct S
{
    this(this)
    { }
}

// `__xpostblit` aliases the aggregated postblit so the `const` applies to it.
// However, the aggregated postblit calls the field postblit which does not have
// any qualifier applied, resulting in a qualifier mismatch error
const struct B
{
    S a;        // error : mutable method B.__fieldPostblit is not callable using a const object
    this(this)
    { }
}

// `__xpostblit` aliases the field postblit; no error
const struct B2
{
    S a;
}

// Similar to B
immutable struct C
{
    S a;        // error : mutable method C.__fieldPostblit is not callable using a immutable object
    this(this)
    { }
}

// Similar to B2, compiles
immutable struct C2
{
    S a;
}

```
 In the above situations the errors do not contain line numbers because the errors are regarding generated code. 

 Qualifying an entire struct as `shared` correctly propagates the attribute to the generated postblits:

 
```
shared struct A
{
    this(this)
    {
        import std.stdio : writeln;
        writeln("the shared postblit was called");
    }
}

struct B
{
    A a;
}

void main()
{
    shared B b1;
    auto b2 = b1;
}

```
 Unions may have fields that have postblits. However, a union itself never has a postblit. Copying a union does not result in postblit calls for any fields. If those calls are desired, they must be inserted explicitly by the programmer:

 
```
struct S
{
    int count;
    this(this)
    {
        ++count;
    }
}

union U
{
    S s;
}

void main()
{
    U a = U.init;
    U b = a;
    assert(b.s.count == 0);
    b.s.__postblit;
    assert(b.s.count == 1);
}

```
 Struct Destructors
------------------

 Destructors are called when an object goes out of scope. Their purpose is to free up resources owned by the struct object. 

 Unions may have fields that have destructors. However, a union itself never has a destructor. When a union goes out of scope, destructors for it's fields are not called. If those calls are desired, they must be inserted explicitly by the programmer:

 
```
struct S
{
    ~this()
    {
        import std.stdio;
        writeln("S is being destructed");
    }
}

union U
{
    S s;
}

void main()
{
    import std.stdio;
    {
        writeln("entering first scope");
        U u = U.init;
        scope (exit) writeln("exiting first scope");
    }
    {
        writeln("entering second scope");
        U u = U.init;
        scope (exit)
        {
            writeln("exiting second scope");
            destroy(u.s);
        }
    }
}

```
 Struct Invariants
-----------------

 
```
StructInvariant:
    invariant ( ) BlockStatement
    invariant BlockStatement
    invariant ( AssertArguments ) ;

```
 *StructInvariant*s specify the relationships among the members of a struct instance. Those relationships must hold for any interactions with the instance from its public interface. 

 The invariant is in the form of a `const` member function. The invariant is defined to *hold* if all the [*AssertExpression*](expression#AssertExpression)s within the invariant that are executed succeed. 

 If the invariant does not hold, then the program enters an invalid state.

 Any invariants for fields are applied before the struct invariant.

 There may be multiple invariants in a struct. They are applied in lexical order.

 *StructInvariant*s must hold at the exit of the struct constructor (if any), and at the entry of the struct destructor (if any).

 *StructInvariant*s must hold at the entry and exit of all public or exported non-static member functions. The order of application of invariants is: 


1. preconditions
2. invariant
3. function body
4. invariant
5. postconditions

 The invariant need not hold if the struct instance is implicitly constructed using the default `.init` value.

 
```
struct Date
{
    this(int d, int h)
    {
        day = d;    // days are 1..31
        hour = h;   // hours are 0..23
    }

    invariant
    {
        assert(1 <= day && day <= 31);
        assert(0 <= hour && hour < 24);
    }

  private:
    int day;
    int hour;
}

```
 Public or exported non-static member functions cannot be called from within an invariant.

 
```
struct Foo
{
    public void f() { }
    private void g() { }

    invariant
    {
        f();  // error, cannot call public member function from invariant
        g();  // ok, g() is not public
    }
}

```
 **Undefined Behavior:** happens if the invariant does not hold and execution continues. **Implementation Defined:** 1. Whether the *StructInvariant* is executed at runtime or not. This is typically controlled with a compiler switch.
2. The behavior when the invariant does not hold is typically the same as for when [*AssertExpression*](expression#AssertExpression)s fail.

 **Best Practices:** 1. Do not indirectly call exported or public member functions within a struct invariant, as this can result in infinite recursion.
2. Avoid reliance on side effects in the invariant. as the invariant may or may not be executed.
3. Avoid having mutable public fields of structs with invariants, as then the invariant cannot verify the public interface.

 Identity Assignment Overload
----------------------------

 While copy construction takes care of initializing an object from another object of the same type, assignment is defined as copying the contents of a source object over those of a destination object, calling the destination object's destructor if it has one in the process: 

 
```
struct S { ... }  // S has postblit or destructor
S s;      // default construction of s
S t = s;  // t is copy-constructed from s
t = s;    // t is assigned from s

```
 Struct assignment `t=s` is defined to be semantically equivalent to: 

 
```
t.opAssign(s);

```
 where `opAssign` is a member function of S:

 
```
ref S opAssign(ref S s)
{
    S tmp = this;   // bitcopy this into tmp
    this = s;       // bitcopy s into this
    tmp.__dtor();   // call destructor on tmp
    return this;
}

```
 An identity assignment overload is required for a struct if one or more of these conditions hold:

 * it has a [destructor](#struct-destructor)
* it has a [postblit](#struct-postblit)
* it has a field with an identity assignment overload

 If an identity assignment overload is required and does not exist, an identity assignment overload function of the type `ref S opAssign(ref S)` will be automatically generated.

 A user-defined one can implement the equivalent semantics, but can be more efficient. 

 One reason a custom `opAssign` might be more efficient is if the struct has a reference to a local buffer: 

 
```
struct S
{
    int[] buf;
    int a;

    ref S opAssign(ref const S s) return
    {
        a = s.a;
        return this;
    }

    this(this)
    {
        buf = buf.dup;
    }
}

```
 Here, `S` has a temporary workspace `buf[]`. The normal postblit will pointlessly free and reallocate it. The custom `opAssign` will reuse the existing storage. 

 Nested Structs
--------------

 A *nested struct* is a struct that is declared inside the scope of a function or a templated struct that has aliases to local functions as a template argument. Nested structs have member functions. It has access to the context of its enclosing scope (via an added hidden field).

 
```
void foo()
{
    int i = 7;
    struct SS
    {
        int x,y;
        int bar() { return x + i + 1; }
    }
    SS s;
    s.x = 3;
    s.bar(); // returns 11
}

```
 A struct can be prevented from being nested by using the static attribute, but then of course it will not be able to access variables from its enclosing scope.

 
```
void foo()
{
    int i = 7;
    static struct SS
    {
        int x, y;
        int bar()
        {
            return i; // error, SS is not a nested struct
        }
    }
}

```
 Unions and Special Member Functions
-----------------------------------

 Unions may not have postblits, destructors, or invariants.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/struct.html>

Inline Assembler
================

 **Contents** 1. [Asm statement](#asmstatements)
2. [Asm instruction](#asminstruction)
3. [Labels](#labels)
4. [align *IntegerExpression*](#align)
5. [even](#even)
6. [naked](#naked)
7. [db, ds, di, dl, df, dd, de](#raw_data)
8. [Opcodes](#opcodes)
	1. [Special Cases](#special_cases)
9. [Operands](#operands)
	1. [Operand Types](#operand_types)
	2. [Struct/Union/Class Member Offsets](#agregate_member_offsets)
	3. [Stack Variables](#stack_variables)
	4. [Special Symbols](#special_symbols)
10. [Opcodes Supported](#supported_opcodes)
	1. [Pentium 4 (Prescott) Opcodes Supported](#P4_opcode_support)
	2. [AMD Opcodes Supported](#amd_opcode_support)
	3. [SIMD](#simd)
	4. [Other](#other)

  [![Some Assembly Required]  D, being a systems programming language, provides an inline assembler. The inline assembler is standardized for D implementations across the same CPU family, for example, the Intel Pentium inline assembler for a Win32 D compiler will be syntax compatible with the inline assembler for Linux running on an Intel Pentium. 

 Implementations of D on different architectures, however, are free to innovate upon the memory model, function call/return conventions, argument passing conventions, etc. 

 This document describes the `x86` and `x86_64` implementations of the inline assembler. The inline assembler platform support that a compiler provides is indicated by the `D_InlineAsm_X86` and `D_InlineAsm_X86_64` version identifiers, respectively. 

 Asm statement
-------------

 
```
AsmStatement:
    asm FunctionAttributesopt { AsmInstructionListopt }

    AsmInstructionList:
        AsmInstruction ;
        AsmInstruction ; AsmInstructionList
    
```
 Assembler instructions must be located inside an `asm` block. Like functions, `asm` statements must be anotated with adequate function attributes to be compatible with the caller. Asm statements attributes must be explicitly defined, they are not infered. 

 
```
void func1() pure nothrow @safe @nogc
{
    asm pure nothrow @trusted @nogc
    {}
}

void func2() @safe @nogc
{
    asm @nogc // Error: asm statement is assumed to be @system - mark it with '@trusted' if it is not
    {}
}

```
 Asm instruction
---------------

 
```
AsmInstruction:
    Identifier : AsmInstruction
    align IntegerExpression
    even
    naked
    db Operands
    ds Operands
    di Operands
    dl Operands
    df Operands
    dd Operands
    de Operands
    db StringLiteral
    ds StringLiteral
    di StringLiteral
    dl StringLiteral
    dw StringLiteral
    dq StringLiteral
    Opcode
    Opcode Operands

Operands:
    Operand
    Operand , Operands

```
 Labels
------

 Assembler instructions can be labeled just like other statements. They can be the target of goto statements. For example: 

 
```
void *pc;
asm
{
    call L1          ;
  L1:                ;
    pop  EBX         ;
    mov  pc[EBP],EBX ; // pc now points to code at L1
}

```
 align *IntegerExpression*
-------------------------

 
```
IntegerExpression:
    IntegerLiteral
    Identifier

```
 Causes the assembler to emit NOP instructions to align the next assembler instruction on an *IntegerExpression* boundary. *IntegerExpression* must evaluate at compile time to an integer that is a power of 2. 

 Aligning the start of a loop body can sometimes have a dramatic effect on the execution speed. 

 even
----

 Causes the assembler to emit NOP instructions to align the next assembler instruction on an even boundary. 

 naked
-----

 Causes the compiler to not generate the function prolog and epilog sequences. This means such is the responsibility of inline assembly programmer, and is normally used when the entire function is to be written in assembler. 

 db, ds, di, dl, df, dd, de
--------------------------

 These pseudo ops are for inserting raw data directly into the code. `db` is for bytes, `ds` is for 16 bit words, `di` is for 32 bit words, `dl` is for 64 bit words, `df` is for 32 bit floats, `dd` is for 64 bit doubles, and `de` is for 80 bit extended reals. Each can have multiple operands. If an operand is a string literal, it is as if there were *length* operands, where *length* is the number of characters in the string. One character is used per operand. For example:

 
```
asm
{
    db 5,6,0x83;   // insert bytes 0x05, 0x06, and 0x83 into code
    ds 0x1234;     // insert bytes 0x34, 0x12
    di 0x1234;     // insert bytes 0x34, 0x12, 0x00, 0x00
    dl 0x1234;     // insert bytes 0x34, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    df 1.234;      // insert float 1.234
    dd 1.234;      // insert double 1.234
    de 1.234;      // insert real 1.234
    db "abc";      // insert bytes 0x61, 0x62, and 0x63
    ds "abc";      // insert bytes 0x61, 0x00, 0x62, 0x00, 0x63, 0x00
}

```
 Opcodes
-------

 A list of supported opcodes is at the end. 

 The following registers are supported. Register names are always in upper case. 

 
```
Register:
    AL AH AX EAX
    BL BH BX EBX
    CL CH CX ECX
    DL DH DX EDX
    BP EBP
    SP ESP
    DI EDI
    SI ESI
    ES CS SS DS GS FS
    CR0 CR2 CR3 CR4
    DR0 DR1 DR2 DR3 DR6 DR7
    TR3 TR4 TR5 TR6 TR7
    ST
    ST(0) ST(1) ST(2) ST(3) ST(4) ST(5) ST(6) ST(7)
    MM0  MM1  MM2  MM3  MM4  MM5  MM6  MM7
    XMM0 XMM1 XMM2 XMM3 XMM4 XMM5 XMM6 XMM7

```
 `x86_64` adds these additional registers.

 
```
Register64:
    RAX  RBX  RCX  RDX
    BPL  RBP
    SPL  RSP
    DIL  RDI
    SIL  RSI
    R8B  R8W  R8D  R8
    R9B  R9W  R9D  R9
    R10B R10W R10D R10
    R11B R11W R11D R11
    R12B R12W R12D R12
    R13B R13W R13D R13
    R14B R14W R14D R14
    R15B R15W R15D R15
    XMM8 XMM9 XMM10 XMM11 XMM12 XMM13 XMM14 XMM15
    YMM0 YMM1 YMM2  YMM3  YMM4  YMM5  YMM6  YMM7
    YMM8 YMM9 YMM10 YMM11 YMM12 YMM13 YMM14 YMM15

```
 ### Special Cases

  
`lock`, `rep`, `repe`, `repne`, `repnz`, `repz`
 These prefix instructions do not appear in the same statement as the instructions they prefix; they appear in their own statement. For example: 
```
asm
{
    rep   ;
    movsb ;
}

```
 `pause` This opcode is not supported by the assembler, instead use 
```
asm
{
    rep  ;
    nop  ;
}

```
 which produces the same result.  `floating point ops` Use the two operand form of the instruction format; 
```
fdiv ST(1);     // wrong
fmul ST;        // wrong
fdiv ST,ST(1);  // right
fmul ST,ST(0);  // right

```
   Operands
--------

 
```
Operand:
    AsmExp

AsmExp:
    AsmLogOrExp
    AsmLogOrExp ? AsmExp : AsmExp

AsmLogOrExp:
    AsmLogAndExp
    AsmLogOrExp || AsmLogAndExp

AsmLogAndExp:
    AsmOrExp
    AsmLogAndExp && AsmOrExp

AsmOrExp:
    AsmXorExp
    AsmOrExp | AsmXorExp

AsmXorExp:
    AsmAndExp
    AsmXorExp ^ AsmAndExp

AsmAndExp:
    AsmEqualExp
    AsmAndExp & AsmEqualExp

AsmEqualExp:
    AsmRelExp
    AsmEqualExp == AsmRelExp
    AsmEqualExp != AsmRelExp

AsmRelExp:
    AsmShiftExp
    AsmRelExp < AsmShiftExp
    AsmRelExp <= AsmShiftExp
    AsmRelExp > AsmShiftExp
    AsmRelExp >= AsmShiftExp

AsmShiftExp:
    AsmAddExp
    AsmShiftExp << AsmAddExp
    AsmShiftExp >> AsmAddExp
    AsmShiftExp >>> AsmAddExp

AsmAddExp:
    AsmMulExp
    AsmAddExp + AsmMulExp
    AsmAddExp - AsmMulExp

AsmMulExp:
    AsmBrExp
    AsmMulExp * AsmBrExp
    AsmMulExp / AsmBrExp
    AsmMulExp % AsmBrExp

AsmBrExp:
    AsmUnaExp
    AsmBrExp [ AsmExp ]

AsmUnaExp:
    AsmTypePrefix AsmExp
    offsetof AsmExp
    seg AsmExp
    + AsmUnaExp
    - AsmUnaExp
    ! AsmUnaExp
    ~ AsmUnaExp
    AsmPrimaryExp

AsmPrimaryExp:
    IntegerLiteral
    FloatLiteral
    __LOCAL_SIZE
    $
    Register
    Register : AsmExp
    Register64
    Register64 : AsmExp
    DotIdentifier
    this

DotIdentifier:
    Identifier
    Identifier . DotIdentifier
    FundamentalType . Identifier

```
 The operand syntax more or less follows the Intel CPU documentation conventions. In particular, the convention is that for two operand instructions the source is the right operand and the destination is the left operand. The syntax differs from that of Intel's in order to be compatible with the D language tokenizer and to simplify parsing. 

 The `seg` means load the segment number that the symbol is in. This is not relevant for flat model code. Instead, do a move from the relevant segment register. 

 A dotted expression is evaluated during the compilation and then must either give a constant or indicate a higher level variable that fits in the target register or variable. 

 ### Operand Types

 
```
AsmTypePrefix:
    near ptr
    far ptr
    word ptr
    dword ptr
    qword ptr
    FundamentalType ptr

```
 In cases where the operand size is ambiguous, as in:

 
```
add [EAX],3     ;

```
 it can be disambiguated by using an [*AsmTypePrefix*](#AsmTypePrefix): 
```
add  byte ptr [EAX],3 ;
add  int ptr [EAX],7  ;

```
 `far ptr` is not relevant for flat model code. 

 ### Struct/Union/Class Member Offsets

 To access members of an aggregate, given a pointer to the aggregate is in a register, use the `.offsetof` property of the qualified name of the member:

 
```
struct Foo { int a,b,c; }
int bar(Foo *f)
{
    asm
    {
        mov EBX,f                   ;
        mov EAX,Foo.b.offsetof[EBX] ;
    }
}
void main()
{
    Foo f = Foo(0, 2, 0);
    assert(bar(&f) == 2);
}

```
 Alternatively, inside the scope of an aggregate, only the member name is needed:

 
```
struct Foo   // or class
{
    int a,b,c;
    int bar()
    {
        asm
        {
            mov EBX, this   ;
            mov EAX, b[EBX] ;
        }
    }
}
void main()
{
    Foo f = Foo(0, 2, 0);
    assert(f.bar() == 2);
}

```
 ### Stack Variables

 Stack variables (variables local to a function and allocated on the stack) are accessed via the name of the variable indexed by EBP:

 
```
int foo(int x)
{
    asm
    {
        mov EAX,x[EBP] ; // loads value of parameter x into EAX
        mov EAX,x      ; // does the same thing
    }
}

```
 If the [EBP] is omitted, it is assumed for local variables. If `naked` is used, this no longer holds. 

 ### Special Symbols

  &dollar; Represents the program counter of the start of the next instruction. So, 
```
jmp  $  ;

```
 branches to the instruction following the jmp instruction. The &dollar; can only appear as the target of a jmp or call instruction.  `__LOCAL_SIZE` This gets replaced by the number of local bytes in the local stack frame. It is most handy when the `naked` is invoked and a custom stack frame is programmed.   Opcodes Supported
-----------------

 

Opcodes| *aaa* | *aad* | *aam* | *aas* | *adc* |
| *add* | *addpd* | *addps* | *addsd* | *addss* |
| *and* | *andnpd* | *andnps* | *andpd* | *andps* |
| *arpl* | *bound* | *bsf* | *bsr* | *bswap* |
| *bt* | *btc* | *btr* | *bts* | *call* |
| *cbw* | *cdq* | *clc* | *cld* | *clflush* |
| *cli* | *clts* | *cmc* | *cmova* | *cmovae* |
| *cmovb* | *cmovbe* | *cmovc* | *cmove* | *cmovg* |
| *cmovge* | *cmovl* | *cmovle* | *cmovna* | *cmovnae* |
| *cmovnb* | *cmovnbe* | *cmovnc* | *cmovne* | *cmovng* |
| *cmovnge* | *cmovnl* | *cmovnle* | *cmovno* | *cmovnp* |
| *cmovns* | *cmovnz* | *cmovo* | *cmovp* | *cmovpe* |
| *cmovpo* | *cmovs* | *cmovz* | *cmp* | *cmppd* |
| *cmpps* | *cmps* | *cmpsb* | *cmpsd* | *cmpss* |
| *cmpsw* | *cmpxchg* | *cmpxchg8b* | *cmpxchg16b* |  |
| *comisd* | *comiss* |  |  |  |
| *cpuid* | *cvtdq2pd* | *cvtdq2ps* | *cvtpd2dq* | *cvtpd2pi* |
| *cvtpd2ps* | *cvtpi2pd* | *cvtpi2ps* | *cvtps2dq* | *cvtps2pd* |
| *cvtps2pi* | *cvtsd2si* | *cvtsd2ss* | *cvtsi2sd* | *cvtsi2ss* |
| *cvtss2sd* | *cvtss2si* | *cvttpd2dq* | *cvttpd2pi* | *cvttps2dq* |
| *cvttps2pi* | *cvttsd2si* | *cvttss2si* | *cwd* | *cwde* |
| *da* | *daa* | *das* | *db* | *dd* |
| *de* | *dec* | *df* | *di* | *div* |
| *divpd* | *divps* | *divsd* | *divss* | *dl* |
| *dq* | *ds* | *dt* | *dw* | *emms* |
| *enter* | *f2xm1* | *fabs* | *fadd* | *faddp* |
| *fbld* | *fbstp* | *fchs* | *fclex* | *fcmovb* |
| *fcmovbe* | *fcmove* | *fcmovnb* | *fcmovnbe* | *fcmovne* |
| *fcmovnu* | *fcmovu* | *fcom* | *fcomi* | *fcomip* |
| *fcomp* | *fcompp* | *fcos* | *fdecstp* | *fdisi* |
| *fdiv* | *fdivp* | *fdivr* | *fdivrp* | *feni* |
| *ffree* | *fiadd* | *ficom* | *ficomp* | *fidiv* |
| *fidivr* | *fild* | *fimul* | *fincstp* | *finit* |
| *fist* | *fistp* | *fisub* | *fisubr* | *fld* |
| *fld1* | *fldcw* | *fldenv* | *fldl2e* | *fldl2t* |
| *fldlg2* | *fldln2* | *fldpi* | *fldz* | *fmul* |
| *fmulp* | *fnclex* | *fndisi* | *fneni* | *fninit* |
| *fnop* | *fnsave* | *fnstcw* | *fnstenv* | *fnstsw* |
| *fpatan* | *fprem* | *fprem1* | *fptan* | *frndint* |
| *frstor* | *fsave* | *fscale* | *fsetpm* | *fsin* |
| *fsincos* | *fsqrt* | *fst* | *fstcw* | *fstenv* |
| *fstp* | *fstsw* | *fsub* | *fsubp* | *fsubr* |
| *fsubrp* | *ftst* | *fucom* | *fucomi* | *fucomip* |
| *fucomp* | *fucompp* | *fwait* | *fxam* | *fxch* |
| *fxrstor* | *fxsave* | *fxtract* | *fyl2x* | *fyl2xp1* |
| *hlt* | *idiv* | *imul* | *in* | *inc* |
| *ins* | *insb* | *insd* | *insw* | *int* |
| *into* | *invd* | *invlpg* | *iret* | *iretd* |
| *iretq* | *ja* | *jae* | *jb* | *jbe* |
| *jc* | *jcxz* | *je* | *jecxz* | *jg* |
| *jge* | *jl* | *jle* | *jmp* | *jna* |
| *jnae* | *jnb* | *jnbe* | *jnc* | *jne* |
| *jng* | *jnge* | *jnl* | *jnle* | *jno* |
| *jnp* | *jns* | *jnz* | *jo* | *jp* |
| *jpe* | *jpo* | *js* | *jz* | *lahf* |
| *lar* | *ldmxcsr* | *lds* | *lea* | *leave* |
| *les* | *lfence* | *lfs* | *lgdt* | *lgs* |
| *lidt* | *lldt* | *lmsw* | *lock* | *lods* |
| *lodsb* | *lodsd* | *lodsw* | *loop* | *loope* |
| *loopne* | *loopnz* | *loopz* | *lsl* | *lss* |
| *ltr* | *maskmovdqu* | *maskmovq* | *maxpd* | *maxps* |
| *maxsd* | *maxss* | *mfence* | *minpd* | *minps* |
| *minsd* | *minss* | *mov* | *movapd* | *movaps* |
| *movd* | *movdq2q* | *movdqa* | *movdqu* | *movhlps* |
| *movhpd* | *movhps* | *movlhps* | *movlpd* | *movlps* |
| *movmskpd* | *movmskps* | *movntdq* | *movnti* | *movntpd* |
| *movntps* | *movntq* | *movq* | *movq2dq* | *movs* |
| *movsb* | *movsd* | *movss* | *movsw* | *movsx* |
| *movupd* | *movups* | *movzx* | *mul* | *mulpd* |
| *mulps* | *mulsd* | *mulss* | *neg* | *nop* |
| *not* | *or* | *orpd* | *orps* | *out* |
| *outs* | *outsb* | *outsd* | *outsw* | *packssdw* |
| *packsswb* | *packuswb* | *paddb* | *paddd* | *paddq* |
| *paddsb* | *paddsw* | *paddusb* | *paddusw* | *paddw* |
| *pand* | *pandn* | *pavgb* | *pavgw* | *pcmpeqb* |
| *pcmpeqd* | *pcmpeqw* | *pcmpgtb* | *pcmpgtd* | *pcmpgtw* |
| *pextrw* | *pinsrw* | *pmaddwd* | *pmaxsw* | *pmaxub* |
| *pminsw* | *pminub* | *pmovmskb* | *pmulhuw* | *pmulhw* |
| *pmullw* | *pmuludq* | *pop* | *popa* | *popad* |
| *popf* | *popfd* | *por* | *prefetchnta* | *prefetcht0* |
| *prefetcht1* | *prefetcht2* | *psadbw* | *pshufd* | *pshufhw* |
| *pshuflw* | *pshufw* | *pslld* | *pslldq* | *psllq* |
| *psllw* | *psrad* | *psraw* | *psrld* | *psrldq* |
| *psrlq* | *psrlw* | *psubb* | *psubd* | *psubq* |
| *psubsb* | *psubsw* | *psubusb* | *psubusw* | *psubw* |
| *punpckhbw* | *punpckhdq* | *punpckhqdq* | *punpckhwd* | *punpcklbw* |
| *punpckldq* | *punpcklqdq* | *punpcklwd* | *push* | *pusha* |
| *pushad* | *pushf* | *pushfd* | *pxor* | *rcl* |
| *rcpps* | *rcpss* | *rcr* | *rdmsr* | *rdpmc* |
| *rdtsc* | *rep* | *repe* | *repne* | *repnz* |
| *repz* | *ret* | *retf* | *rol* | *ror* |
| *rsm* | *rsqrtps* | *rsqrtss* | *sahf* | *sal* |
| *sar* | *sbb* | *scas* | *scasb* | *scasd* |
| *scasw* | *seta* | *setae* | *setb* | *setbe* |
| *setc* | *sete* | *setg* | *setge* | *setl* |
| *setle* | *setna* | *setnae* | *setnb* | *setnbe* |
| *setnc* | *setne* | *setng* | *setnge* | *setnl* |
| *setnle* | *setno* | *setnp* | *setns* | *setnz* |
| *seto* | *setp* | *setpe* | *setpo* | *sets* |
| *setz* | *sfence* | *sgdt* | *shl* | *shld* |
| *shr* | *shrd* | *shufpd* | *shufps* | *sidt* |
| *sldt* | *smsw* | *sqrtpd* | *sqrtps* | *sqrtsd* |
| *sqrtss* | *stc* | *std* | *sti* | *stmxcsr* |
| *stos* | *stosb* | *stosd* | *stosw* | *str* |
| *sub* | *subpd* | *subps* | *subsd* | *subss* |
| *syscall* | *sysenter* | *sysexit* | *sysret* | *test* |
| *ucomisd* | *ucomiss* | *ud2* | *unpckhpd* | *unpckhps* |
| *unpcklpd* | *unpcklps* | *verr* | *verw* | *wait* |
| *wbinvd* | *wrmsr* | *xadd* | *xchg* | *xlat* |
| *xlatb* | *xor* | *xorpd* | *xorps* |  |

 ### Pentium 4 (Prescott) Opcodes Supported

 

Pentium 4 Opcodes| *addsubpd* | *addsubps* | *fisttp* | *haddpd* | *haddps* |
| *hsubpd* | *hsubps* | *lddqu* | *monitor* | *movddup* |
| *movshdup* | *movsldup* | *mwait* |  |  |

 ### AMD Opcodes Supported

 

AMD Opcodes| *pavgusb* | *pf2id* | *pfacc* | *pfadd* | *pfcmpeq* |
| *pfcmpge* | *pfcmpgt* | *pfmax* | *pfmin* | *pfmul* |
| *pfnacc* | *pfpnacc* | *pfrcp* | *pfrcpit1* | *pfrcpit2* |
| *pfrsqit1* | *pfrsqrt* | *pfsub* | *pfsubr* | *pi2fd* |
| *pmulhrw* | *pswapd* |  |  |  |

 ### SIMD

 SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2 and AVX are supported.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/iasm.html>

Documentation Generator
=======================

 **Contents** 1. [Specification](#specifications)
	1. [Phases of Processing](#phases_of_processing)
	2. [Lexical](#lexical)
	3. [Parsing](#parsing)
	4. [Sections](#sections)
	5. [Standard Sections](#standard_sections)
	6. [Special Sections](#special_sections)
2. [Highlighting](#highlighting)
	1. [Embedded Comments](#embedded_comments)
	2. [Embedded Code](#embedded_code)
	3. [Inline Code](#inline_code)
	4. [Embedded HTML](#embedded_html)
	5. [Headings](#headings)
	6. [Links](#links)
	7. [Lists](#lists)
	8. [Tables](#tables)
	9. [Quotes](#quotes)
	10. [Horizontal Rules](#hrules)
	11. [Text Emphasis](#text_emphasis)
	12. [Identifier Emphasis](#emphasis)
	13. [Character Entities](#character_entities)
	14. [Punctuation Escapes](#punctuation_escapes)
	15. [No Documentation](#no_documentation)
3. [Macros](#macros)
	1. [Predefined Macros](#predefined_macros)
	2. [Macro Definitions from `sc.ini`'s DDOCFILE](#macro_def_scini)
	3. [Macro Definitions from .ddoc Files on the Command Line](#macro_def_ddoc_file)
	4. [Macro Definitions Generated by Ddoc](#macro_def_ddocgenerated)
4. [Using Ddoc to generate examples from unit tests](#using_ddoc_to_generate_examples)
5. [Using Ddoc for other Documentation](#using_ddoc_for_other_documentation)
6. [Security considerations](#security)
7. [Links to D documentation generators](#links_to_d_documentation_generators)

 The D programming language enables embedding both contracts and test code along side the actual code, which helps to keep them all consistent with each other. One thing lacking is the documentation, as ordinary comments are usually unsuitable for automated extraction and formatting into manual pages. Embedding the user documentation into the source code has important advantages, such as not having to write the documentation twice, and the likelihood of the documentation staying consistent with the code. 

 Some existing approaches to this are: 

 * [Doxygen](http://www.stack.nl/~dimitri/doxygen) which already has some support for D
* Java's [Javadoc](https://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/index.html), probably the most well-known
* C#'s [embedded XML](https://msdn.microsoft.com/en-us/library/b2s063f7.aspx)
* Other [documentation tools](https://python.org/sigs/doc-sig/otherlangs.html)

 D's goals for embedded documentation are: 

 1. It looks good as embedded documentation, not just after it is extracted and processed.
2. It's easy and natural to write, i.e. minimal reliance on <tags> and other clumsy forms one would never see in a finished document.
3. It does not repeat information that the compiler already knows from parsing the code.
4. It doesn't rely on embedded HTML, as such will impede extraction and formatting for other purposes.
5. It's based on existing D comment forms, so it is completely independent of parsers only interested in D code.
6. It should look and feel different from code, so it won't be visually confused with code.
7. It should be possible for the user to use Doxygen or other documentation extractor if desired.

 Specification
-------------

 The specification for the form of embedded documentation comments only specifies how information is to be presented to the compiler. It is implementation-defined how that information is used and the form of the final presentation. Whether the final presentation form is an HTML web page, a man page, a PDF file, etc. is not specified as part of the D Programming Language. 

 ### Phases of Processing

 Embedded documentation comments are processed in a series of phases: 

 1. Lexical - documentation comments are identified and attached to tokens.
2. Parsing - documentation comments are associated with specific declarations and combined.
3. Sections - each documentation comment is divided up into a sequence of sections.
4. Special sections are processed.
5. Highlighting of non-special sections is done.
6. All sections for the module are combined.
7. Macro and Escape text substitution is performed to produce the final result.

 ### Lexical

 Embedded documentation comments are one of the following forms: 

 1. /\*\* ... \*/ The two \*'s after the opening /
2. /++ ... +/ The two +'s after the opening /
3. /// The three slashes

 The following are all embedded documentation comments:

 
```
/// This is a one line documentation comment.

/** So is this. */

/++ And this. +/

/**
   This is a brief documentation comment.
 */

/**
 * The leading * on this line is not part of the documentation comment.
 */

/*********************************
   The extra *'s immediately following the /** are not
   part of the documentation comment.
 */

/++
   This is a brief documentation comment.
 +/

/++
 + The leading + on this line is not part of the documentation comment.
 +/

/+++++++++++++++++++++++++++++++++
   The extra +'s immediately following the / ++ are not
   part of the documentation comment.
 +/

/**************** Closing *'s are not part *****************/

```
 The extra \*'s and +'s on the comment opening, closing and left margin are ignored and are not part of the embedded documentation. Comments not following one of those forms are not documentation comments. 

 ### Parsing

 Each documentation comment is associated with a declaration. If the documentation comment is on a line by itself or with only whitespace to the left, it refers to the next declaration. Multiple documentation comments applying to the same declaration are concatenated. Documentation comments not associated with a declaration are ignored. Documentation comments preceding the *ModuleDeclaration* apply to the entire module. If the documentation comment appears on the same line to the right of a declaration, it applies to that. 

 If a documentation comment for a declaration consists only of the identifier `ditto` then the documentation comment for the previous declaration at the same declaration scope is applied to this declaration as well. 

 If there is no documentation comment for a declaration, that declaration may not appear in the output. To ensure it does appear in the output, put an empty declaration comment for it. 

 
```
int a;  /// documentation for a; b has no documentation
int b;

/** documentation for c and d */
/** more documentation for c and d */
int c;
/** ditto */
int d;

/** documentation for e and f */ int e;
int f;  /// ditto

/** documentation for g */
int g; /// more documentation for g

/// documentation for C and D
class C
{
    int x; /// documentation for C.x

    /** documentation for C.y and C.z */
    int y;
    int z; /// ditto
}

/// ditto
class D { }

```
 ### Sections

 The document comment is a series of *Section*s. A *Section* is a name that is the first non-blank character on a line immediately followed by a ':'. This name forms the section name. The section name is not case sensitive. 

 Section names starting with 'http://' or 'https://' are not recognized as section names. 

 #### Summary

 The first section is the *Summary*, and does not have a section name. It is first paragraph, up to a blank line or a section name. While the summary can be any length, try to keep it to one line. The *Summary* section is optional. 

 #### Description

 The next unnamed section is the *Description*. It consists of all the paragraphs following the *Summary* until a section name is encountered or the end of the comment. 

 While the *Description* section is optional, there cannot be a *Description* without a *Summary* section. 

 
```
/***********************************
 * Brief summary of what
 * myfunc does, forming the summary section.
 *
 * First paragraph of synopsis description.
 *
 * Second paragraph of
 * synopsis description.
 */

void myfunc() { }

```
 Named sections follow the *Summary* and *Description* unnamed sections. 

 ### Standard Sections

 For consistency and predictability, there are several standard sections. None of these are required to be present. 

 
**Authors:** Lists the author(s) of the declaration. 
```
/**
 * Authors: Melvin D. Nerd, melvin@mailinator.com
 */

```
  **Bugs:**
 Lists any known bugs. 
```
/**
 * Bugs: Doesn't work for negative values.
 */

```
  **Date:**
 Specifies the date of the current revision. The date should be in a form parseable by std.date. 
```
/**
 * Date: March 14, 2003
 */

```
  **Deprecated:**
 Provides an explanation for and corrective action to take if the associated declaration is marked as deprecated. 
```
/**
 * Deprecated: superseded by function bar().
 */

deprecated void foo() { ... }

```
  **Examples:**
 Any usage examples 
```
/**
 * Examples:
 * --------------------
 * writeln("3"); // writes '3' to stdout
 * --------------------
 */

```
  **History:**
 Revision history. 
```
/**
 * History:
 *      V1 is initial version
 *
 *      V2 added feature X
 */

```
  **License:**
 Any license information for copyrighted code. 
```
/**
 * License: use freely for any purpose
 */

void bar() { ... }

```
  **Returns:**
 Explains the return value of the function. If the function returns **void**, don't redundantly document it. 
```
/**
 * Read the file.
 * Returns: The contents of the file.
 */

void[] readFile(const(char)[] filename) { ... }

```
  **See\_Also:**
 List of other symbols and URLs to related items. 
```
/**
 * See_Also:
 *    foo, bar, http://www.digitalmars.com/d/phobos/index.html
 */

```
  **Standards:**
 If this declaration is compliant with any particular standard, the description of it goes here. 
```
/**
 * Standards: Conforms to DSPEC-1234
 */

```
 **Throws:** Lists exceptions thrown and under what circumstances they are thrown. 
```
/**
 * Write the file.
 * Throws: WriteException on failure.
 */

void writeFile(string filename) { ... }

```
  **Version:**
 Specifies the current version of the declaration. 
```
/**
 * Version: 1.6a
 */

```
  ### Special Sections

 Some sections have specialized meanings and syntax. 

 
 **Copyright:**
 This contains the copyright notice. The macro COPYRIGHT is set to the contents of the section when it documents the module declaration. The copyright section only gets this special treatment when it is for the module declaration. 
```
/** Copyright: Public Domain */

module foo;

```
  **Params:**
 Function parameters can be documented by listing them in a params section. Each line that starts with an identifier followed by an '=' starts a new parameter description. A description can span multiple lines. 
```
/***********************************
 * foo does this.
 * Params:
 *      x =     is for this
 *              and not for that
 *      y =     is for that
 */

void foo(int x, int y)
{
}

```
  **Macros:**
 The macros section follows the same syntax as the **Params:** section. It's a series of *NAME*=*value* pairs. The *NAME* is the macro name, and *value* is the replacement text. 
```
/**
 * Macros:
 *      FOO =   now is the time for
 *              all good men
 *      BAR =   bar
 *      MAGENTA =   <font color="magenta">&dollar;0</font>
 */

```
  **Escapes=**
 The escapes section is a series of substitutions which replace special characters with a string. It's useful when the output format requires escaping of certain characters, for example in HTML **&** should be escaped with **&amp;**. The syntax is **/c/string/**, where **c** is either a single character, or multiple characters separated by whitespace or commas, and **string** is the replacement text. 
```
/**
 * ESCAPES = /&/AddressOf!/
 *           /!/Exclamation/
 *           /?/QuestionMark/
 *           /,/Comma/
 *           /{ }/Parens/
 *           /<,>/Arrows/
 */

```
  Highlighting
------------

 ### Embedded Comments

  The documentation comments can themselves be commented using the &dollar;`(DDOC_COMMENT comment text)` syntax. These comments do not nest. 

 ### Embedded Code

  D code can be embedded using lines beginning with at least three hyphens `-`, backticks ``` or tildes `~` (ignoring whitespace) to delineate the code section: 

 
```
/++
 + Our function.
 +
 + Example:
 + ---
 + import std.stdio;
 +
 + void foo()
 + {
 +     writeln("foo!");  /* print the string */
 + }
 + ---
 +/

```
  Note that in the above example the documentation comment uses the /++ ... +/ form so that /\* ... \*/ can be used inside the code section. 

  D code gets automatic syntax highlighting. To include code in another language without syntax highlighting, add a language string at the end of the top delimiter line: 

 
```
/++
 + Some C++
 + ``` cpp
 + #include <iostream>
 +
 + void foo()
 + {
 +     std::cout << "foo!";
 + }
 + ```
 +/

```
 ### Inline Code

  Inline code can be written between backtick characters (`), similarly to the syntax used on GitHub, Reddit, Stack Overflow, and other websites. Both the opening and closing ` character must appear on the same line to trigger this behavior. 

  Text inside these sections will be escaped according to the rules described above, then wrapped in a `&dollar;(DDOC_BACKQUOTED)` macro. By default, this macro expands to be displayed as an inline text span, formatted as code. 

  A literal backtick character can be output either as a non-paired ` on a single line or by using the `&dollar;(BACKTICK)` macro. 

 
```
 /// Returns `true` if `a == b`.
 void foo() {}

 /// Backquoted `<html>` will be displayed to the user instead
 /// of passed through as embedded HTML (see below).
 void bar() {}

```
 ### Embedded HTML

 HTML can be embedded into the documentation comments, and it will be passed through to the HTML output unchanged. However, since it is not necessarily true that HTML will be the desired output format of the embedded documentation comment extractor, it is best to avoid using it where practical. 

 
```
/**
 * Example of embedded HTML:
 *
 * <ol>
 *   <li><a href="http://www.digitalmars.com">Digital Mars</a></li>
 *   <li><a href="http://www.classicempire.com">Empire</a></li>
 * </ol>
 */

```
 ### Headings

 A long documentation section can be subdivided by adding headings. A heading is a line of text that starts with one to six `#` characters followed by whitespace and then the heading text. The number of `#` characters determines the heading level. Headings may optionally end with any number of trailing `#` characters. 

 
```
/**
 * # H1
 * ## H2
 * ### H3
 * #### H4 ###
 * ##### H5 ##
 * ###### H6 #
 */

```
 ### Links

 Documentation may link to other documentation or to a URL. There are four styles of links: 

 
```
/**
 * Some links:
 *
 * 1. A [reference link][ref] and bare reference links: [ref] or [Object]
 * 2. An [inline link](https://dlang.org)
 * 3. A bare URL: https://dlang.org
 * 4. An ![image](https://dlang.org/images/d3.png)
 *
 * [ref]: https://dlang.org "The D Language Website"
 */

```
 #### Reference Links

 Reference-style links enclose a reference label in square brackets. They may optionally be preceded by some link text, also enclosed in square brackets. 

 The reference label must match a reference defined elsewhere. This may be a D symbol in scope of the source code being documented, like `[Object]` in the example above, or it may be an explicit reference that is defined in the same documentation comment, like `[ref]` in the example above. In the example both instances of `[ref]` in item `1.` will be replaced with the URL and title text from the matching definition at the bottom of the example. The first link will read `reference link` and the second will read `ref`. 

 Reference definitions start with a label in square brackets, followed by a colon, a URL and an optional title wrapped in single or double quotes, or in parentheses. If a reference label would match both a D symbol and a reference definition then the reference definition is used. 

 The generated links to D symbols are relative if they have the same root package as the module being documented. If not, their URLs are preceded by a `&dollar;(DDOC_ROOT_pkg)` macro, where `pkg` is the root package of the symbol being linked to. Links to D symbols are generated with a `&dollar;(DOC_EXTENSION)` macro after the module name. Then the generated URL for `[Object]` in the above example is as if it had been written: 

 
```
&dollar;(DOC_ROOT_object)object&dollar;(DOC_EXTENSION)#.Object

```
 `DOC_ROOT_` macros can be defined for any external packages to link to using a [Macros section](#macros). 

 #### Inline Links

 Inline-style links enclose link text in square brackets and the link URL in parentheses. Like reference links, the URL may optionally be followed by title text wrapped in single or double quotes, or in parentheses: 

 
```
/// [a link with title text](https://dlang.org 'Some title text')

```
 #### Bare URLs

 Bare URLs are sequences of characters that start with `http://` or `https://`, continue with one or more characters from the set of letters, digits and `-_?=%&/+#~.`, and contain at least one period. URL recognition happens before all macro text substitution. The URL is wrapped in a `&dollar;(DDOC_LINK_AUTODETECT)` macro and is otherwise left untouched. 

 #### Images

 Images have the same form as reference or inline links, but add an exclamation point `!` before the initial square bracket. What would be the link text in a normal link is used as the image's alt text. 

 ### Lists

 Documentation may contain lists. Start an ordered list with a number followed by a period: 

 
```
/**
 * 1. First this
 * 2. Then this
 *    1. A sub-item
 */

```
 Start an unordered list with a hyphen (`-`), an asterisk (`*`) or a plus (`+`). Subsequent items in the same list must also start with the same symbol: 

 
```
/**
 * - A list
 * - With a second item
 *
 * + A different list
 *   - With a sub-item
 *
 * * A third list (note the double asterisks)
 */

```
 Note the double asterisks in the example above. This is because the list is inside a documentation comment that is delimited with asterisks, so the initial asterisk is considered part of the documentation comment, not a list item. This is even true when other lines don't start with an asterisk: 

 
```
/**
 - A list
 * Not a list because the asterisk is part of the documentation comment
 */

/++
 + + The caveat also applies to plus-delimited documentation comments
 +/

```
 List items can include content like new paragraphs, headings, embedded code, or child list items. Simply indent the content to match the indent of the text after the list symbol: 

 
```
/**
 * - A parent list item
 *
 *   With a second paragraph
 *
 *   - A sub-item
 *     ---
 *     // A code example inside the sub-item
 *     ---
 */

```
 ### Tables

 Data may be placed into a table. Tables consist of a single header row, a delimiter row, and zero or more data rows. Cells in each row are separated by pipe (`|`) characters. Initial and trailing `|`'s are optional. The number of cells in the delimiter row must match the number of cells in the header row: 

 
```
/**
 *  | Item | Price |
 *  | ---- | ----: |
 *  | Wigs | &dollar;10 |
 *    Wheels | &dollar;13
 *  | Widgets | &dollar;200 |
 */

```
 Cells in the delimiter row contain hyphens (`-`) and optional colons (`:`). A `:` to the left of the hyphens creates a left-aligned column, a `:` to the right of the hyphens creates a right-aligned column (like the example above), and `:`'s on both sides of the hyphens create a center-aligned column. 

 ### Quotes

 Documentation may include a section of quoted material by prefixing each line of the section with a `>`. Quotes may include headings, lists, embedded code, etc. 

 
```
/**
 * > To D, or not to D. -- Willeam NerdSpeare
 */

```
 Lines of text that directly follow a quoted line are considered part of the quote: 

 
```
/**
 * > This line
 * and this line are both part of the quote
 *
 * This line is not part of the quote.
 */

```
 ### Horizontal Rules

 Create a horizontal rule by adding a line containing three or more asterisks, underscores or hyphens: 

 
```
/**
 * ***
 * ___
 */

```
 As with [lists](#lists), note that the initial `*` in the example above will be stripped because it is part of a documentation comment that is delimited with asterisks. At least three subsequent asterisks are needed. 

 To create a horizontal rule with hyphens, add spaces between the hyphens. Without the spaces they would be treated as the start or end of an [embedded code block](#embedded_code). Note that any horizontal rule may contain spaces: 

 
```
/**
 * - - -
 * _ _ _
 * * * *
 */

```
 ### Text Emphasis

 A span of text wrapped in asterisks (`*`) is emphasized, and text wrapped in two asterisks (`**`) is strongly emphasized: 

 `*single asterisks*` is rendered as *single asterisks*. 

 `**double asterisks**` is rendered as **double asterisks**. 

 Insert a literal asterisk by [backslash-escaping](#punctuation_escapes) it: `\*` is rendered as \*. 

 Unlike [Markdown](https://daringfireball.net/projects/markdown/syntax), underscores (`_`) are not supported for emphasizing text because it would break snake\_case names and underscore prefix processing in [identifier emphasis](#emphasis). 

 ### Identifier Emphasis

 Identifiers in documentation comments that are function parameters or are names that are in scope at the associated declaration are emphasized in the output. This emphasis can take the form of italics, boldface, a hyperlink, etc. How it is emphasized depends on what it is  —  a function parameter, type, D keyword, etc. To prevent unintended emphasis of an identifier, it can be preceded by an underscore (\_). The underscore will be stripped from the output. 

 ### Character Entities

  Some characters have special meaning to the documentation processor, to avoid confusion it can be best to replace them with their corresponding character entities: 

 

Characters and Entities| **Character** | **Entity** |
| `<` | &lt; |
| `>` | &gt; |
| `&` | &amp; |

  It is not necessary to do this inside a code section, or if the special character is not immediately followed by a # or a letter. 

 ### Punctuation Escapes

  Escape any ASCII punctuation symbol with a backslash `\`. Doing so outputs the original character without the backslash, except for the following characters which output predefined macros instead: 

 

Characters and Escape Macros| **Character** | **Macro** |
| `(` | &dollar;(LPAREN) |
| `)` | &dollar;(RPAREN) |
| `,` | &dollar;(COMMA) |
| `&dollar;` | &dollar;(DOLLAR) |

  To output a backslash, simply use two backslashes in a row: `\\`. Note that backslashes inside embedded or inline code do *not* escape punctuation and are included in the output as-is. Backslashes before non-punctation are also included in the output as-is. For example, `C:\dmd2\bin\dmd.exe` does not require escaping its embedded backslashes. 

 ### No Documentation

  No documentation is generated for the following constructs, even if they have a documentation comment: 

 * Invariants
* Postblits
* Destructors
* Static constructors and static destructors
* Class info, type info, and module info

 Macros
------

  The documentation comment processor includes a simple macro text preprocessor. When a &dollar;(*NAME*) appears in section text it is replaced with *NAME*s corresponding replacement text.

 For example: 
```
/**
Macros:
 PARAM = <u>&dollar;1</u>
 MATH_DOCS = <a href="https://dlang.org/phobos/std_math.html">Math Docs</a>
*/
module math;

/**
 * This function returns the sum of &dollar;(PARAM a) and &dollar;(PARAM b).
 * See also the &dollar;(MATH_DOCS).
 */
int sum(int a, int b) { return a + b; }

```
  The above would generate the following output:

 
```
<h1>test</h1>
<dl><dt><big><a name="sum"></a>int <u>sum</u>(int <i>a</i>, int <i>b</i>);
</big></dt>
<dd>This function returns the <u>sum</u> of <u><i>a</i></u> and <u><i>b</i></u>.
 See also the <a href="https://dlang.org/phobos/std_math.html">Math Docs</a>.
</dd>
</dl>

```
  The replacement text is recursively scanned for more macros. If a macro is recursively encountered, with no argument or with the same argument text as the enclosing macro, it is replaced with no text. Macro invocations that cut across replacement text boundaries are not expanded. If the macro name is undefined, the replacement text has no characters in it. If a &dollar;(NAME) is desired to exist in the output without being macro expanded, the &dollar; should be  [backslash-escaped](#punctuation_escapes): `\$`. 

  Macros can have arguments. Any text from the end of the identifier to the closing ‘)’ is the &dollar;0 argument. A &dollar;0 in the replacement text is replaced with the argument text. If there are commas in the argument text, &dollar;1 will represent the argument text up to the first comma, &dollar;2 from the first comma to the second comma, etc., up to &dollar;9. &dollar;+ represents the text from the first comma to the closing ‘)’. The argument text can contain nested parentheses, "" or '' strings, `<``!--` `...` `--``>` comments, or tags. If stray, unnested parentheses are used, they can be [backslash-escaped](#punctuation_escapes): `\(` or `\)`. 

  Macro definitions come from the following sources, in the specified order: 

 1. Predefined macros.
2. Definitions from file specified by [sc.ini](https://dlang.org/dmd-windows.html)'s or [dmd.conf](https://dlang.org/dmd-linux.html#dmd_conf) DDOCFILE setting.
3. Definitions from \*.ddoc files specified on the command line.
4. Runtime definitions generated by Ddoc.
5. Definitions from any Macros: sections.

  Macro redefinitions replace previous definitions of the same name. This means that the sequence of macro definitions from the various sources forms a hierarchy. 

  Macro names beginning with "D\_" and "DDOC\_" are reserved. 

 ### Predefined Macros

  A number of macros are predefined Ddoc, and represent the minimal definitions needed by Ddoc to format and highlight the presentation. The definitions are for simple HTML.

 The implementations of all predefined macros are implementation-defined. The reference implementation's macro definitions can be found [here](https://github.com/dlang/dmd/blob/master/res/default_ddoc_theme.ddoc).

  Ddoc does not generate HTML code. It formats into the basic formatting macros, which (in their predefined form) are then expanded into HTML. If output other than HTML is desired, then these macros need to be redefined. 

 

Predefined Formatting Macros| **Name** | **Description** |
| `B` | boldface the argument |
| `I` | italicize the argument |
| `U` | underline the argument |
| `P` | argument is a paragraph |
| `DL` | argument is a definition list |
| `DT` | argument is a definition in a definition list |
| `DD` | argument is a description of a definition |
| `TABLE` | argument is a table |
| `TR` | argument is a row in a table |
| `TH` | argument is a header entry in a row |
| `TD` | argument is a data entry in a row |
| `OL` | argument is an ordered list |
| `UL` | argument is an unordered list |
| `LI` | argument is an item in a list |
| `BIG` | argument is one font size bigger |
| `SMALL` | argument is one font size smaller |
| `BR` | start new line |
| `LINK` | generate clickable link on argument |
| `LINK2` | generate clickable link, first arg is address |
| `RED` | argument is set to be red |
| `BLUE` | argument is set to be blue |
| `GREEN` | argument is set to be green |
| `YELLOW` | argument is set to be yellow |
| `BLACK` | argument is set to be black |
| `WHITE` | argument is set to be white |
| `D_CODE` | argument is D code |
| `D_INLINECODE` | argument is inline D code |
| `LF` | Insert a line feed (newline) |
| `LPAREN` | Insert a left parenthesis |
| `RPAREN` | Insert a right parenthesis |
| `BACKTICK` | Insert a backtick |
| `DOLLAR` | Insert a dollar sign |
| `DDOC` | overall template for output |

  **DDOC** is special in that it specifies the boilerplate into which the entire generated text is inserted (represented by the Ddoc generated macro **BODY**). For example, in order to use a style sheet, **DDOC** would be redefined as: 

 
```
DDOC = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
    <html><head>
    <META http-equiv="content-type" content="text/html; charset=utf-8">
    <title>&dollar;(TITLE)</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    </head><body>
    <h1>&dollar;(TITLE)</h1>
    &dollar;(BODY)
    </body></html>

```
  Highlighting of D code is performed by the following macros: 

 

D Code Formatting Macros| **Name** | **Description** |
| `D_COMMENT` | Highlighting of comments |
| `D_STRING` | Highlighting of string literals |
| `D_KEYWORD` | Highlighting of D keywords |
| `D_PSYMBOL` | Highlighting of current declaration name |
| `D_PARAM` | Highlighting of current function declaration parameters |

  The highlighting macros start with `DDOC_`. They control the formatting of individual parts of the presentation. 

 

Ddoc Section Formatting Macros| **Name** | **Description** |
| `DDOC_CONSTRAINT` | Highlighting of a template constraint. |
| `DDOC_COMMENT` | Inserts a comment in the output. |
| `DDOC_DECL` | Highlighting of the declaration. |
| `DDOC_DECL_DD` | Highlighting of the description of a declaration. |
| `DDOC_DITTO` | Highlighting of ditto declarations. |
| `DDOC_SECTIONS` | Highlighting of all the sections. |
| `DDOC_SUMMARY` | Highlighting of the summary section. |
| `DDOC_DESCRIPTION` | Highlighting of the description section. |
| `DDOC_AUTHORS` | Highlighting of the authors section. |
| `DDOC_BUGS` | Highlighting of the bugs section. |
| `DDOC_COPYRIGHT` | Highlighting of the copyright section. |
| `DDOC_DATE` | Highlighting of the date section. |
| `DDOC_DEPRECATED` | Highlighting of the deprecated section. |
| `DEPRECATED` | Wrapper for deprecated declarations. |
| `DDOC_EXAMPLES` | Highlighting of the examples section. |
| `DDOC_HISTORY` | Highlighting of the history section. |
| `DDOC_LICENSE` | Highlighting of the license section. |
| `DDOC_OVERLOAD_SEPARATOR` | Inserts a separator between overloads of a given name. |
| `DDOC_RETURNS` | Highlighting of the returns section. |
| `DDOC_SEE_ALSO` | Highlighting of the see-also section. |
| `DDOC_STANDARDS` | Highlighting of the standards section. |
| `DDOC_THROWS` | Highlighting of the throws section. |
| `DDOC_VERSION` | Highlighting of the version section. |
| `DDOC_SECTION_H` | Highlighting of the section name of a non-standard section. |
| `DDOC_SECTION` | Highlighting of the contents of a non-standard section. |
| `DDOC_MEMBERS` | Default highlighting of all the members of a class, struct, etc. |
| `DDOC_MODULE_MEMBERS` | Highlighting of all the members of a module. |
| `DDOC_CLASS_MEMBERS` | Highlighting of all the members of a class. |
| `DDOC_STRUCT_MEMBERS` | Highlighting of all the members of a struct. |
| `DDOC_ENUM_MEMBERS` | Highlighting of all the members of an enum. |
| `DDOC_TEMPLATE_PARAM` | Highlighting of a template's individual parameters. |
| `DDOC_TEMPLATE_PARAM_LIST` | Highlighting of a template's parameter list. |
| `DDOC_TEMPLATE_MEMBERS` | Highlighting of all the members of a template. |
| `DDOC_ENUM_BASETYPE` | Highlighting of the type an enum is based upon |
| `DDOC_PARAMS` | Highlighting of a function parameter section. |
| `DDOC_PARAM_ROW` | Highlighting of a name=value function parameter. |
| `DDOC_PARAM_ID` | Highlighting of the parameter name. |
| `DDOC_PARAM_DESC` | Highlighting of the parameter value. |
| `DDOC_BLANKLINE` | Inserts a blank line. |
| `DDOC_ANCHOR` | Expands to a named anchor used for hyperlinking to a particular declaration section. Argument &dollar;1 expands to the qualified declaration name. |
| `DDOC_PSYMBOL` | Highlighting of declaration name to which a particular section is referring. |
| `DDOC_PSUPER_SYMBOL` | Highlighting of the base type of a class. |
| `DDOC_KEYWORD` | Highlighting of D keywords. |
| `DDOC_PARAM` | Highlighting of function parameters. |
| `DDOC_BACKQUOTED` | Inserts inline code. |
| `DDOC_AUTO_PSYMBOL_SUPPRESS` | Highlighting of auto-detected symbol that starts with underscore |
| `DDOC_AUTO_PSYMBOL` | Highlighting of auto-detected symbol |
| `DDOC_AUTO_KEYWORD` | Highlighting of auto-detected keywords |
| `DDOC_AUTO_PARAM` | Highlighting of auto-detected parameters |

  For example, one could redefine `DDOC_SUMMARY`: 

 
```
DDOC_SUMMARY = &dollar;(GREEN &dollar;0)

```
  And all the summary sections will now be green. 

 ### Macro Definitions from `sc.ini`'s DDOCFILE

  A text file of macro definitions can be created, and specified in `sc.ini`: 

 
```
DDOCFILE=myproject.ddoc

```
 ### Macro Definitions from .ddoc Files on the Command Line

  File names on the DMD command line with the extension .ddoc are text files that are read and processed in order. 

 ### Macro Definitions Generated by Ddoc

 

Generated Macro Definitions| **Macro Name** | **Content** |
|  BODY |  Set to the generated document text.  |
|  TITLE |  Set to the module name.  |
|  DATETIME |  Set to the current date and time.  |
|  YEAR |  Set to the current year.  |
|  COPYRIGHT |  Set to the contents of any Copyright: section that is part of the module comment.  |
|  DOCFILENAME |  Set to the name of the generated output file.  |
|  SRCFILENAME |  Set to the name of the source file the documentation is being generated from.  |

 Using Ddoc to generate examples from unit tests
-----------------------------------------------

  Ddoc can automatically generate usage examples for declarations using unit tests. If a declaration is followed by a documented unit test, the code from the test will be inserted into the example section of the declaration. This avoids the frequent problem of having outdated documentation for pieces of code. 

  To create a documented unit test just add three forward slashes before the unittest block, like this:

 
```
///
unittest
{
    ...
}

```
 For more information please see the full section on [documented unit tests](unittest#documented-unittests). 

 Using Ddoc for other Documentation
----------------------------------

  Ddoc is primarily designed for use in producing documentation from embedded comments. It can also, however, be used for processing other general documentation. The reason for doing this would be to take advantage of the macro capability of Ddoc and the D code syntax highlighting capability. 

  If the .d source file starts with the string "Ddoc" then it is treated as general purpose documentation, not as a D code source file. From immediately after the "Ddoc" string to the end of the file or any "Macros:" section forms the document. No automatic highlighting is done to that text, other than highlighting of D code embedded between lines delineated with --- lines. Only macro processing is done. 

  Much of the D documentation itself is generated this way, including this page. Such documentation is marked at the bottom as being generated by Ddoc. 

 Security considerations
-----------------------

  Note that DDoc comments may embed raw HTML, including <script> tags. Be careful when publishing or distributing rendered DDoc HTML generated from untrusted sources, as this may allow  [cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting). 

 Links to D documentation generators
-----------------------------------

  A list of current D documentation generators which use Ddoc can be found on our [wiki page](https://wiki.dlang.org/Open_Source_Projects#Documentation_Generators). 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/ddoc.html>

Interfacing to Objective-C
==========================

 **Contents** 1. [Classes](#classes)
	1. [Declaring an External Class](#external-class)
	2. [Defining a Class](#defining-class)
2. [Protocols](#protocols)
	1. [Declaring a Protocol](#declaring-protocol)
	2. [Optional Methods](#optional-methods)
3. [Instance Variables](#instance-variables)
4. [Calling an Instance Method](#instance-method)
5. [The `@selector` Attribute](#selector-attribute)
	1. [Compiler Checks](#compiler-checks)
6. [The `@optional` Attribute](#optional-attribute)
	1. [Compiler Checks](#compiler-checks)
7. [Objective-C Linkage](#objc-linkage)
8. [Memory Management](#memory-management)
9. [Frameworks](#frameworks)
	1. [Framework Paths](#framework-paths)
10. [Full Usage Example](#usage-example)

  D supports interfacing with Objective-C. It supports protocols, classes, subclasses, instance variables, instance methods and class methods. Platform support might vary between different compilers. 

  Fully working example is available at [the bottom](#usage-example). 

 Classes
-------

 ### Declaring an External Class

 
```
import core.attribute : selector;

extern (Objective-C)
extern class NSString
{
    const(char)* UTF8String() @selector("UTF8String");
}

```
  All Objective-C classes that should be accessible from within D need to be declared with the [Objective-C linkage](#objc-linkage). If the class is declared as `extern` (in addition to `extern (Objective-C)`) it is expected to be defined externally. 

  The [`@selector`](#selector-attribute) attribute indicates which Objective-C selector should be used when calling this method. This attribute needs to be attached to all methods with the `Objective-C` linkage. 

 ### Defining a Class

 
```
import core.attribute : selector;

// externally defined
extern (Objective-C)
extern class NSObject
{
    static NSObject alloc() @selector("alloc");
    NSObject init() @selector("init");
}

extern (Objective-C)
class Foo : NSObject
{
    override static Foo alloc() @selector("alloc");
    override Foo init() @selector("init");

    final int bar(int a) @selector("bar:")
    {
        return a;
    }
}

void main()
{
    assert(Foo.alloc.init.bar(3) == 3);
}

```
  Defining an Objective-C class is exactly the same as declaring an external class but it should not be declared as `extern`. 

  To match the Objective-C semantics, `static` and `final` methods are virtual. `static` methods are overridable as well. 

 Protocols
---------

 ### Declaring a Protocol

 
```
import core.attribute : selector;
import core.stdc.stdio : printf;

extern (Objective-C)
interface Foo
{
    static void foo() @selector("foo");
    void bar() @selector("bar");
}

extern (Objective-C)
class Bar : Foo
{
    static void foo() @selector("foo")
    {
        printf("foo\n");
    }

    void bar() @selector("bar")
    {
        printf("bar\n");
    }
}

```
  Objective-C protocols are represented as interfaces in D and are declared using the `interface` keyword. 

  All Objective-C protocols that should be accessible from within D need to be declared with the [Objective-C linkage](#objc-linkage). 

  Objective-C protocols support virtual class (static) methods. These methods must be implemented by the class that implements the protocol (unless they are [optional](#optional-methods)). To match these semantics, `static` methods are virtual. That also means that static methods with Objective-C linkage, inside an interface cannot have a body. 

 ### Optional Methods

 
```
import core.attribute : optional, selector;
import core.stdc.stdio : printf;

struct objc_selector;
alias SEL = objc_selector*;

extern (C) SEL sel_registerName(in char* str);

extern (Objective-C)
extern class NSObject
{
    static NSObject alloc() @selector("alloc");
    NSObject init() @selector("init");
}

extern (Objective-C)
interface Foo
{
    bool respondsToSelector(SEL sel) @selector("respondsToSelector:");
    void foo() @selector("foo");

    // this is an optional method
    @optional void bar() @selector("bar");
}

extern (Objective-C)
class Bar : NSObject, Foo
{
    override static Bar alloc() @selector("alloc");
    override Bar init() @selector("init");

    bool respondsToSelector(SEL sel) @selector("respondsToSelector:");

    void foo() @selector("foo")
    {
        printf("foo\n");
    }
}

void main()
{
    Foo f = Bar.alloc.init;

    // check, at runtime, if the instance `f` implements the method `bar`
    if (f.respondsToSelector(sel_registerName("bar")))
        f.bar();
    else
        f.foo();
}

```
  Objective-C protocols support optional methods. Optional methods are **not** required to be implemented by the class that implements the protocol. To safely call an optional method, a runtime check should be performed to make sure the receiver implements the method. 

  In D, optional methods are represented using the [`@optional`](#optional-attribute) attribute. 

 Instance Variables
------------------

 
```
import core.attribute : selector;

// externally defined
extern (Objective-C)
extern class NSObject
{
    static NSObject alloc() @selector("alloc");
    NSObject init() @selector("init");
}

extern (Objective-C)
class Foo : NSObject
{
    int bar_;

    override static Foo alloc() @selector("alloc");
    override Foo init() @selector("init");

    int bar() @selector("bar")
    {
        return bar_;
    }
}

void main()
{
    auto foo = Foo.alloc.init;
    foo.bar_ = 3;
    assert(foo.bar == 3);
}

```
  Declaring an instance variable looks exactly the same as for a regular D class. 

  To solve the fragile base class problem, instance variables in Objective-C has a dynamic offset. That means that the base class can change (add or remove instance variables) without the subclasses needing to recompile or relink. Thanks to this feature it's not necessary to declare instance variables when creating bindings to Objective-C classes. 

 Calling an Instance Method
--------------------------

  Calling an Objective-C instance method uses the same syntax as calling regular D methods: 

 
```
const(char)* result = object.UTF8String();

```
  When the compiler sees a call to a method with Objective-C linkage it will generate a call similar to how an Objective-C compiler would call the method. 

 The `@selector` Attribute
-------------------------

  The `@selector` attribute is a compiler recognized [UDA](attribute#uda). It is used to tell the compiler which selector to use when calling an Objective-C method. 

  Selectors in Objective-C can contain the colon character, which is not valid in D identifiers. D supports method overloading while Objective-C achieves something similar by using different selectors. For these two reasons it is better to be able to specify the selectors manually in D, instead of trying to infer it. This allows to have a more natural names for the methods in D. Example: 

 
```
import core.attribute : selector;

extern (Objective-C)
extern class NSString
{
    NSString initWith(in char*) @selector("initWithUTF8String:");
    NSString initWith(NSString) @selector("initWithString:");
}

```
  Here the method `initWith` is overloaded with two versions, one accepting `in char*`, the other one `NSString`. These two methods are mapped to two different Objective-C selectors, `initWithUTF8String:` and `initWithString:`. 

  The attribute is defined in druntime in [`core.attribute`](https://dlang.org/phobos/core_attribute.html). The attribute is only defined when the version identifier [`D_ObjectiveC`](#objc-version-identifier) is enabled. 

 ### Compiler Checks

  The compiler performs the following checks to enforce the correct usage of the `@selector` attribute: 

 * The attribute can only be attached to methods with Objective-C linkage
* The attribute can only be attached once to a method
* The attribute cannot be attached to a template method
* The number of colons in the selector needs to match the number of parameters the method is declared with

 If any of the checks fail, a compile error will occur.

 The `@optional` Attribute
-------------------------

  The `@optional` attribute is a compiler recognized [UDA](attribute#uda). It is used to tell the compiler that a method, with Objective-C linkage, declared inside an interface is optional. That means that the class that implements the interface does **not** have to implement the method. 

  To safely call an optional method, a runtime check should be performed to make sure the receiver implements the method. 

  The attribute is defined in druntime in [`core.attribute`](https://dlang.org/phobos/core_attribute.html). The attribute is only defined when the version identifier [`D_ObjectiveC`](#objc-version-identifier) is enabled. 

 ### Compiler Checks

  The compiler performs the following checks to enforce the correct usage of the `@optional` attribute: 

 * The attribute can only be attached to methods with Objective-C linkage
* The attribute can only be attached to a method inside an interface
* The attribute can only be attached once to a method
* The attribute cannot be attached to a template method

 If any of the checks fail, a compile error will occur.

  The `D_ObjectiveC` Version Identifier
--------------------------------------

  The `D_ObjectiveC` version identifier is a predefined version identifier. It is enabled if Objective-C support is available for the target. 

 Objective-C Linkage
-------------------

  Objective-C linkage is achieved by attaching the `extern (Objective-C)` attribute to a class. Example: 

 
```
import core.attribute : selector;

extern (Objective-C)
extern class NSObject
{
    NSObject init() @selector("init");
}

```
  All methods inside a class declared as `extern (Objective-C)` will get implicit Objective-C linkage. 

  The linkage is recognized on all platforms but will issue a compile error if it is used on a platform where Objective-C support is not available. This allows to easily hide Objective-C declarations from platforms where it is not available using the [`version`](version#version) statement, without resorting to string mixins or other workarounds. 

 Memory Management
-----------------

  The preferred way to do memory management in Objective-C is to use Automatic Reference Counting, [ARC](https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html). This is not supported in D, therefore manual memory management is required to be used instead. This is achieved by calling [`release`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/release) on an Objective-C instance, like in the old days of Objective-C. 

 Frameworks
----------

  Most Objective-C code is bundled in something called a "Framework". This is basically a regular directory, with the `.framework` extension and a specific directory layout. A framework contains a dynamic library, all public header files and any resources (images, sounds and so on) required by the framework. 

  These directories are recognized by some tools, like the Objective-C compiler and linker, to be frameworks. To link with a framework from DMD, use the following flags: 

 
```
-L-framework -L<Framework>

```
 where `<Framework>` is the name of the framework to link with, without the `.framework` extension. The two `-L` flags are required because the linker expects a space between the `-framework` flag and the name of the framework. DMD cannot handle this and will instead interpret the name of the framework as a separate flag. ### Framework Paths

  Using the above flag, the linker will search in the standard framework paths. The standard search paths for frameworks are: 

 * `/System/Library/Frameworks`
* `/Library/Frameworks`

  The following flag from DMD can be used to add a new path in which to search for frameworks: 

 
```
-L-F<framework_path>

```
  For more information see the [reference documentation](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPFrameworks/Tasks/IncludingFrameworks.html) and the `ld` man page. 

 Full Usage Example
------------------

  This example will create an Objective-C string, `NSString`, and log the message using `NSLog` to stderr. 

 
```
import core.attribute : selector;

extern (Objective-C)
extern class NSString
{
    static NSString alloc() @selector("alloc");
    NSString initWithUTF8String(in char* str) @selector("initWithUTF8String:");
    void release() @selector("release");
}

```
  This is a simplified declaration of the [`NSString`](https://developer.apple.com/documentation/foundation/nsstring?language=objc) class. The [`alloc`](https://developer.apple.com/documentation/objectivec/nsobject/1571958-alloc?language=objc) method allocates an instance of the class. The [`initWithUTF8String:`](https://developer.apple.com/documentation/foundation/nsstring/1412128-initwithutf8string?language=objc) method will be used to convert a C string in UTF-8 to an Objective-C string, `NSString`. The [`release`](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1571957-release?language=objc) method is used to release an deallocate the string. Since D doesn't support [ARC](https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html) it's needed to manually release Objective-C instances. 

 
```
extern (C) void NSLog(NSString, ...);

```
  This [`NSLog`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/index.html#//apple_ref/c/func/NSLog) function prints a message to the System Log facility, i.e. to stderr and Console. 

 
```
auto str = NSString.alloc();

```
 Allocate an instance of the class, `NSString`.

 
```
str = str.initWithUTF8String("Hello World!")

```
 Initialize the Objective-C string using a C string.

 
```
NSLog(str);

```
  Log the string to stderr, this will print something like this in the terminal: 

 
```
2015-07-18 13:14:27.978 main[11045:2934950] Hello World!

```
 
```
str.release();

```
 Release and deallocate the string.

 All steps combined look like this:

 
```
module main;

import core.attribute : selector;

extern (Objective-C)
extern class NSString
{
    static NSString alloc() @selector("alloc");
    NSString initWithUTF8String(in char* str) @selector("initWithUTF8String:");
    void release() @selector("release");
}

extern (C) void NSLog(NSString, ...);

void main()
{
    auto str = NSString.alloc().initWithUTF8String("Hello World!");
    NSLog(str);
    str.release();
}

```
  When compiling the application remember to link with the required libraries, in this case the Foundation framework. Example: 

 
```
dmd -L-framework -LFoundation main.d

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/objc_interface.html>

Statements
==========

 **Contents** 1. [Scope Statements](#scope-statement)
2. [Scope Block Statements](#scope-block-statement)
3. [Labeled Statements](#labeled-statement)
4. [Block Statement](#block-statement)
5. [Expression Statement](#expression-statement)
6. [Declaration Statement](#declaration-statement)
7. [If Statement](#if-statement)
8. [While Statement](#while-statement)
9. [Do Statement](#do-statement)
10. [For Statement](#for-statement)
11. [Foreach Statement](#foreach-statement)
	1. [Foreach over Arrays](#foreach_over_arrays)
	2. [Foreach over Arrays of Characters](#foreach_over_arrays_of_characters)
	3. [Foreach over Associative Arrays](#foreach_over_associative_arrays)
	4. [Foreach over Structs and Classes with opApply](#foreach_over_struct_and_classes)
	5. [Foreach over Structs and Classes with Ranges](#foreach-with-ranges)
	6. [Foreach over Delegates](#foreach_over_delegates)
	7. [Foreach over Sequences](#foreach_over_tuples)
	8. [Foreach Ref Parameters](#foreach_ref_parameters)
	9. [Foreach Restrictions](#foreach_restrictions)
12. [Foreach Range Statement](#foreach-range-statement)
	1. [Break and Continue out of Foreach](#break_and_continue_out_of_foreach)
13. [Switch Statement](#switch-statement)
14. [Final Switch Statement](#final-switch-statement)
15. [Continue Statement](#continue-statement)
16. [Break Statement](#break-statement)
17. [Return Statement](#return-statement)
18. [Goto Statement](#goto-statement)
19. [With Statement](#with-statement)
20. [Synchronized Statement](#synchronized-statement)
21. [Try Statement](#try-statement)
22. [Throw Statement](#throw-statement)
23. [Scope Guard Statement](#scope-guard-statement)
	1. [Catching C++ Class Objects](#catching_cpp_class_objects)
24. [Asm Statement](#asm)
25. [Pragma Statement](#pragma-statement)
26. [Mixin Statement](#mixin-statement)

 The order of execution within a function is controlled by [*Statement*](#Statement)s. A function's body consists of a sequence of zero or more *Statement*s. Execution occurs in lexical order, though certain statements may have deferred effects. A *Statement* has no value; it is executed for its effects. 

 
```
Statement:
    ;
    NonEmptyStatement
    ScopeBlockStatement

NoScopeNonEmptyStatement:
    NonEmptyStatement
    BlockStatement

NoScopeStatement:
    ;
    NonEmptyStatement
    BlockStatement

NonEmptyOrScopeBlockStatement:
    NonEmptyStatement
    ScopeBlockStatement

NonEmptyStatement:
    NonEmptyStatementNoCaseNoDefault
    CaseStatement
    CaseRangeStatement
    DefaultStatement

NonEmptyStatementNoCaseNoDefault:
    LabeledStatement
    ExpressionStatement
    DeclarationStatement
    IfStatement
    WhileStatement
    DoStatement
    ForStatement
    ForeachStatement
    SwitchStatement
    FinalSwitchStatement
    ContinueStatement
    BreakStatement
    ReturnStatement
    GotoStatement
    WithStatement
    SynchronizedStatement
    TryStatement
    ScopeGuardStatement
    ThrowStatement
    AsmStatement
    MixinStatement
    ForeachRangeStatement
    PragmaStatement
    ConditionalStatement
    StaticForeachStatement
    StaticAssert
    TemplateMixin
    ImportDeclaration

```
 Any ambiguities in the grammar between *Statement*s and [*Declaration*](declaration#Declaration)s are resolved by the declarations taking precedence. Wrapping such a statement in parentheses will disambiguate it in favor of being a *Statement*. 

 Scope Statements
----------------

 
```
ScopeStatement:
    NonEmptyStatement
    BlockStatement

```
 A new scope for local symbols is introduced for the *NonEmptyStatement* or [*BlockStatement*](#BlockStatement). 

 Even though a new scope is introduced, local symbol declarations cannot shadow (hide) other local symbol declarations in the same function. 

 
```
void func1(int x)
{
    int x;    // illegal, x shadows parameter x

    int y;

    { int y; } // illegal, y shadows enclosing scope's y

    void delegate() dg;
    dg = { int y; }; // ok, this y is not in the same function

    struct S
    {
        int y;    // ok, this y is a member, not a local
    }

    { int z; }
    { int z; }  // ok, this z is not shadowing the other z

    { int t; }
    { t++;   }  // illegal, t is undefined
}

```
 **Best Practices:** Local declarations within a function should all have unique names, even if they are in non-overlapping scopes. Scope Block Statements
----------------------

 
```
ScopeBlockStatement:
    BlockStatement

```
 A scope block statement introduces a new scope for the [*BlockStatement*](#BlockStatement). 

 Labeled Statements
------------------

  Statements can be labeled. A label is an identifier that precedes a statement. 

 
```
LabeledStatement:
    Identifier :
    Identifier : NoScopeStatement
    Identifier : Statement

```
  Any statement can be labeled, including empty statements, and so can serve as the target of a goto statement. Labeled statements can also serve as the target of a break or continue statement. 

  A label can appear without a following statement at the end of a block. 

  Labels are in a name space independent of declarations, variables, types, etc. Even so, labels cannot have the same name as local declarations. The label name space is the body of the function they appear in. Label name spaces do not nest, i.e. a label inside a block statement is accessible from outside that block. 

 Labels in one function cannot be referenced from another function.

 Block Statement
---------------

 
```
BlockStatement:
    { }
    { StatementList }

StatementList:
    Statement
    Statement StatementList

```
 A block statement is a sequence of statements enclosed by `{ }`. The statements are executed in lexical order, until the end of the block is reached or a statement transfers control elsewhere. 

 Expression Statement
--------------------

 
```
ExpressionStatement:
    Expression ;

```
 The expression is evaluated.

 Expressions that have no effect, like `(x + x)`, are illegal as expression statements unless they are cast to void.

 
```
int x;
x++;               // ok
x;                 // illegal
1+1;               // illegal
cast(void)(x + x); // ok

```
 Declaration Statement
---------------------

 Declaration statements define variables, and declare types, templates, functions, imports, conditionals, static foreaches, and static asserts. 

 
```
DeclarationStatement:
    StorageClassesopt Declaration

```
 Some declaration statements:

 
```
int a;        // declare a as type int and initialize it to 0
struct S { }  // declare struct s
alias myint = int;

```
 If Statement
------------

 If statements provide simple conditional execution of statements.

 
```
IfStatement:
    if ( IfCondition ) ThenStatement
    if ( IfCondition ) ThenStatement else ElseStatement

IfCondition:
    Expression
    auto Identifier = Expression
    TypeCtors Identifier = Expression
    TypeCtorsopt BasicType Declarator = Expression

ThenStatement:
    ScopeStatement

ElseStatement:
    ScopeStatement

```
 [*Expression*](expression#Expression) is evaluated and must have a type that can be converted to a boolean. If it's true the *ThenStatement* is transferred to, else the *ElseStatement* is transferred to.

 The *ElseStatement*is associated with the innermost if statement which does not already have an associated *ElseStatement*.

 If an `auto` *Identifier* is provided, it is declared and initialized to the value and type of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*.

 If a *TypeCtors* *Identifier* is provided, it is declared to be of the type specified by *TypeCtors* and is initialized with the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*.

 If a *Declarator* is provided, it is declared and initialized to the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the *ThenStatement*.

 
```
import std.regex;
...
if (auto m = std.regex.matchFirst("abcdef", "b(c)d"))
{
    writefln("[%s]", m.pre);    // prints [a]
    writefln("[%s]", m.post);   // prints [ef]
    writefln("[%s]", m[0]);     // prints [bcd]
    writefln("[%s]", m[1]);     // prints [c]
}
else
{
    writeln(m.post); // Error: undefined identifier 'm'
}
writeln(m.pre);      // Error: undefined identifier 'm'

```
 While Statement
---------------

 
```
WhileStatement:
    while ( IfCondition ) ScopeStatement

```
 A *While Statement* implements a simple loop.

 If the [*IfCondition*](#IfCondition) is an [*Expression*](expression#Expression), it is evaluated and must have a type that can be converted to a boolean. If it's true the [*ScopeStatement*](#ScopeStatement) is executed. After the [*ScopeStatement*](#ScopeStatement) is executed, the [*Expression*](expression#Expression) is evaluated again, and if true the [*ScopeStatement*](#ScopeStatement) is executed again. This continues until the [*Expression*](expression#Expression) evaluates to false.

 
```
int i = 0;
while (i < 10)
{
    foo(i);
    ++i;
}

```
 If an `auto` *Identifier* is provided, it is declared and initialized to the value and type of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement).

 If a *TypeCtors* *Identifier* is provided, it is declared to be of the type specified by *TypeCtors* and is initialized with the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement).

 If a *Declarator* is provided, it is declared and initialized to the value of the [*Expression*](expression#Expression). Its scope extends from when it is initialized to the end of the [*ScopeStatement*](#ScopeStatement).

 A [*BreakStatement*](#BreakStatement) will exit the loop.

 A [*ContinueStatement*](#ContinueStatement) will transfer directly to evaluating [*IfCondition*](#IfCondition) again.

 Do Statement
------------

 
```
DoStatement:
    do ScopeStatement  while ( Expression ) ;

```
 Do while statements implement simple loops.

 [*ScopeStatement*](#ScopeStatement) is executed. Then [*Expression*](expression#Expression) is evaluated and must have a type that can be converted to a boolean. If it's true the loop is iterated again. This continues until the [*Expression*](expression#Expression) evaluates to false.

 
```
int i = 0;
do
{
    foo(i);
} while (++i < 10);

```
 A [*BreakStatement*](#BreakStatement) will exit the loop. A [*ContinueStatement*](#ContinueStatement) will transfer directly to evaluating [*Expression*](expression#Expression) again.

 For Statement
-------------

 For statements implement loops with initialization, test, and increment clauses.

 
```
ForStatement:
    for ( Initialize Testopt ; Incrementopt ) ScopeStatement

Initialize:
    ;
    NoScopeNonEmptyStatement

Test:
    Expression

Increment:
    Expression

```
 *Initialize* is executed. *Test* is evaluated and must have a type that can be converted to a boolean. If it's true the statement is executed. After the statement is executed, the *Increment* is executed. Then *Test* is evaluated again, and if true the statement is executed again. This continues until the *Test* evaluates to false. 

 A [*BreakStatement*](#BreakStatement) will exit the loop. A [*ContinueStatement*](#ContinueStatement) will transfer directly to the *Increment*. 

 A *ForStatement* creates a new scope. If *Initialize* declares a variable, that variable's scope extends through the end of the for statement. For example: 

 
```
for (int i = 0; i < 10; i++)
    foo(i);

```
 is equivalent to: 
```
{
    int i;
    for (i = 0; i < 10; i++)
        foo(i);
}

```
 Function bodies cannot be empty:

 
```
for (int i = 0; i < 10; i++)
    ;       // illegal

```
 Use instead: 
```
for (int i = 0; i < 10; i++)
{
}

```
 The *Initialize* may be omitted (although the trailing `;` is still required). *Test* may also be omitted, and if so, it is treated as if it evaluated to true.

 **Best Practices:** Consider replacing *ForStatements* with [Foreach Statements](statement#foreach-statement) or [Foreach Range Statements](statement#ForeachRangeStatement). Foreach loops are easier to understand, less prone to error, and easier to refactor. Foreach Statement
-----------------

 A `foreach` statement loops over the contents of an aggregate.

 
```
AggregateForeach:
    Foreach ( ForeachTypeList ; ForeachAggregate )

ForeachStatement:
    AggregateForeach NoScopeNonEmptyStatement

Foreach:
    foreach
    foreach_reverse

ForeachTypeList:
    ForeachType
    ForeachType , ForeachTypeList

ForeachType:
    ForeachTypeAttributesopt BasicType Declarator
    ForeachTypeAttributesopt Identifier
    ForeachTypeAttributesopt alias Identifier

ForeachTypeAttributes
    ForeachTypeAttribute
    ForeachTypeAttribute ForeachTypeAttributesopt

ForeachTypeAttribute:
    ref
    TypeCtor
    enum

ForeachAggregate:
    Expression

```
  *ForeachAggregate* is evaluated. It must evaluate to an expression of type static array, dynamic array, associative array, struct, class, delegate, or sequence. The [*NoScopeNonEmptyStatement*](#NoScopeNonEmptyStatement) is executed, once for each element of the aggregate. At the start of each iteration, the variables declared by the *ForeachTypeList* are set to be a copy of the elements of the aggregate. If the variable is `ref`, it is a reference to the contents of that aggregate. 

  The aggregate must be loop invariant, meaning that elements to the aggregate cannot be added or removed from it in the [*NoScopeNonEmptyStatement*](#NoScopeNonEmptyStatement). 

 ### Foreach over Arrays

  If the aggregate is a static or dynamic array, there can be one or two variables declared. If one, then the variable is said to be the *value* set to the elements of the array, one by one. The type of the variable must match the type of the array contents, except for the special cases outlined below. If there are two variables declared, the first is said to be the *index* and the second is said to be the *value*. The *index* must be of type `size_t` for dynamic arrays. Static arrays may use any integral type that spans the length of the array. *index* cannot be `ref`. It is set to be the index of the array element. 

 
```
char[] a;
...
foreach (int i, char c; a)
{
    writefln("a[%d] = '%c'", i, c);
}

```
 For `foreach`, the elements for the array are iterated over starting at index 0 and continuing to the maximum of the array. For `foreach_reverse`, the array elements are visited in the reverse order. 

 **Note:** The *ForeachTypeAttribute* is implicit, and when a type is not specified, it is inferred. In that case, `auto` is implied, and it is not necessary (and actually forbidden) to use it. 

 
```
int[] arr;
...
foreach (n; arr) // ok, n is an int
    writeln(n);

foreach (auto n; arr) // error, auto is redundant
    writeln(n);

```
 ### Foreach over Arrays of Characters

 If the aggregate expression is a static or dynamic array of `char`s, `wchar`s, or `dchar`s, then the *Type* of the *value* can be any of `char`, `wchar`, or `dchar`. In this manner any UTF array can be decoded into any UTF type: 

 
```
char[] a = "\xE2\x89\xA0".dup;  // \u2260 encoded as 3 UTF-8 bytes

foreach (dchar c; a)
{
    writefln("a[] = %x", c); // prints 'a[] = 2260'
}

dchar[] b = "\u2260"d.dup;

foreach (char c; b)
{
    writef("%x, ", c);  // prints 'e2, 89, a0, '
}

```
 Aggregates can be string literals, which can be accessed as char, wchar, or dchar arrays: 

 
```
void test()
{
    foreach (char c; "ab")
    {
        writefln("'%s'", c);
    }
    foreach (wchar w; "xy")
    {
        writefln("'%s'", w);
    }
}

```
 which would print: 

 
```
'a'
'b'
'x'
'y'

```
 ### Foreach over Associative Arrays

 If the aggregate expression is an associative array, there can be one or two variables declared. If one, then the variable is said to be the *value* set to the elements of the array, one by one. The type of the variable must match the type of the array contents. If there are two variables declared, the first is said to be the *index* and the second is said to be the *value*. The *index* must be of the same type as the indexing type of the associative array. It cannot be `ref`, and it is set to be the index of the array element. The order in which the elements of the array are iterated over is unspecified for `foreach`. `foreach_reverse` for associative arrays is illegal. 

 
```
double[string] a; // index type is string, value type is double
...
foreach (string s, double d; a)
{
    writefln("a['%s'] = %g", s, d);
}

```
 ### Foreach over Structs and Classes with opApply

 If the aggregate expression is a struct or class object, the `foreach` is defined by the special `opApply` member function, and the `foreach_reverse` behavior is defined by the special `opApplyReverse` member function. These functions have the type: 

 
```
int opApply(scope int delegate(ref Type [, ...]) dg);

int opApplyReverse(scope int delegate(ref Type [, ...]) dg);

```
 where *Type* matches the *Type* used in the *ForeachType* declaration of *Identifier*. Multiple *ForeachType*s correspond with multiple *Type*s in the delegate type passed to `opApply` or `opApplyReverse`. There can be multiple `opApply` and `opApplyReverse` functions, one is selected by matching the type of *dg* to the *ForeachType*s of the *ForeachStatement*. The body of the apply function iterates over the elements it aggregates, passing them each to the *dg* function. If the *dg* returns 0, then apply goes on to the next element. If the *dg* returns a nonzero value, apply must cease iterating and return that value. Otherwise, after done iterating across all the elements, apply will return 0. 

 For example, consider a class that is a container for two elements:

 
```
class Foo
{
    uint[2] array;

    int opApply(scope int delegate(ref uint) dg)
    {
        int result = 0;

        for (int i = 0; i < array.length; i++)
        {
            result = dg(array[i]);
            if (result)
                break;
        }
        return result;
    }
}

```
 An example using this might be:

 
```
void test()
{
    Foo a = new Foo();

    a.array[0] = 73;
    a.array[1] = 82;

    foreach (uint u; a)
    {
        writefln("%d", u);
    }
}

```
 which would print:

 
```
73
82

```
 The `scope` storage class on the *dg* parameter means that the parameter's value does not escape the scope of the *opApply* function (an example would be assigning *dg* to a global). If it cannot be statically guaranteed that *dg* does not escape, a closure may be allocated for it on the heap instead of the stack. Best practice is to annotate delegate parameters with `scope` when possible. 

 *opApply* can also be a templated function, which will infer the types of parameters based on the *ForeachStatement*. 

 For example:

 
```
struct S
{
    import std.traits : ParameterTypeTuple;  // introspection template

    int opApply(Dg)(scope Dg dg)
    if (ParameterTypeTuple!Dg.length == 2) // foreach with 2 parameters
    {
        return 0;
    }

    int opApply(Dg)(scope Dg dg)
    if (ParameterTypeTuple!Dg.length == 3) // foreach with takes 3 parameters
    {
        return 0;
    }
}

void main()
{
    foreach (int a, int b; S()) { }  // calls first opApply function
    foreach (int a, int b, float c; S()) { }  // calls second opApply function
}

```
 It is important to make sure that, if `opApply` catches any exceptions, that those exceptions did not originate from the delegate passed to *opApply*. The user would expect exceptions thrown from a `foreach` body to both terminate the loop, and propagate outside the `foreach` body. 

 ### Foreach over Structs and Classes with Ranges

 If the aggregate expression is a struct or class object, but the `opApply` for `foreach`, or `opApplyReverse` `foreach_reverse` do not exist, then iteration over struct and class objects can be done with range primitives. For `foreach`, this means the following properties and methods must be defined: 

 

Foreach Range Properties| **Property** | **Purpose** |
| `.empty` | returns true if no more elements |
| `.front` | return the leftmost element of the range |

 

Foreach Range Methods| **Method** | **Purpose** |
| `.popFront()` | move the left edge of the range right by one |

 Meaning:

 
```
foreach (e; range) { ... }

```
 translates to:

 
```
for (auto __r = range; !__r.empty; __r.popFront())
{
    auto e = __r.front;
    ...
}

```
 Similarly, for `foreach_reverse`, the following properties and methods must be defined: 

 

Foreach\_reverse Range Properties| **Property** | **Purpose** |
| `.empty` | returns true if no more elements |
| `.back` | return the rightmost element of the range |

 

Foreach\_reverse Range Methods| **Method** | **Purpose** |
| `.popBack()` | move the right edge of the range left by one |

 Meaning:

 
```
foreach_reverse (e; range) { ... }

```
 translates to:

 
```
for (auto __r = range; !__r.empty; __r.popBack())
{
    auto e = __r.back;
    ...
}

```
 ### Foreach over Delegates

 If *ForeachAggregate* is a delegate, the type signature of the delegate is of the same as for `opApply`. This enables many different named looping strategies to coexist in the same class or struct.

 For example:

 
```
void main()
{
    // Custom loop implementation, that iterates over powers of 2 with
    // alternating sign. The loop body is passed in dg.
    int myLoop(int delegate(ref int) dg)
    {
        for (int z = 1; z < 128; z *= -2)
        {
            auto ret = dg(z);

            // If the loop body contains a break, ret will be non-zero.
            if (ret != 0)
                return ret;
        }
        return 0;
    }

    // This example loop simply collects the loop index values into an array.
    int[] result;
    foreach (ref x; &myLoop)
    {
        result ~= x;
    }
    assert(result == [1, -2, 4, -8, 16, -32, 64, -128]);
}

```
 **Note:** When *ForeachAggregate* is a delegate, the compiler does not try to implement reverse traversal of the results returned by the delegate when `foreach_reverse` is used. This may result in code that is confusing to read. Therefore, using `foreach_reverse` with a delegate is now deprecated, and will be rejected in the future.

 ### Foreach over Sequences

  If the aggregate expression is a sequence, there can be one or two iteration symbols declared. If one, then the symbol is an *element alias* of each element in the sequence in turn. 


 If the sequence is a *TypeSeq*, then the foreach statement is executed once for each type, and the element alias is set to each type. 


 When the sequence is a *ValueSeq*, the element alias is a variable and is set to each value in the sequence. If the type of the variable is given, it must match the type of the sequence contents. If no type is given, the type of the variable is set to the type of the sequence element, which may change from iteration to iteration. 


 If there are two symbols declared, the first is the *index variable* and the second is the *element alias*. The index must be of `int`, `uint`, `long` or `ulong` type, it cannot be `ref`, and it is set to the index of each sequence element. 

 Example:

 
```
import std.meta : AliasSeq;

void main()
{
    alias Seq = AliasSeq!(int, "literal", main);

    foreach (sym; Seq)
    {
        pragma(msg, sym.stringof);
    }
}

```
 Output:

 
```
int
"literal"
main()

```
 See also: [Static Foreach](version#staticforeach).

 ### Foreach Ref Parameters

 `ref` can be used to update the original elements: 

 
```
void test()
{
    static uint[2] a = [7, 8];

    foreach (ref uint u; a)
    {
        u++;
    }
    foreach (uint u; a)
    {
        writefln("%d", u);
    }
}

```
 which would print: 
```
8
9

```
 `ref` can not be applied to the index values.

 If not specified, the *Type*s in the *ForeachType* can be inferred from the type of the *ForeachAggregate*. 

 ### Foreach Restrictions

 The aggregate itself must not be resized, reallocated, free'd, reassigned or destructed while the foreach is iterating over the elements. 

 
```
int[] a;
int[] b;
foreach (int i; a)
{
    a = null;       // error
    a.length += 10; // error
    a = b;          // error
}
a = null;         // ok

```
 Foreach Range Statement
-----------------------

 A foreach range statement loops over the specified range.

 
```
RangeForeach:
    Foreach ( ForeachType ; LwrExpression .. UprExpression )

LwrExpression:
    Expression

UprExpression:
    Expression

ForeachRangeStatement:
    RangeForeach ScopeStatement

```
  *ForeachType* declares a variable with either an explicit type, or a type inferred from *LwrExpression* and *UprExpression*. The *ScopeStatement* is then executed *n* times, where *n* is the result of *UprExpression* - *LwrExpression*. If *UprExpression* is less than or equal to *LwrExpression*, the *ScopeStatement* is executed zero times. If *Foreach* is `foreach`, then the variable is set to *LwrExpression*, then incremented at the end of each iteration. If *Foreach* is `foreach_reverse`, then the variable is set to *UprExpression*, then decremented before each iteration. *LwrExpression* and *UprExpression* are each evaluated exactly once, regardless of how many times the *ScopeStatement* is executed. 

 
```
import std.stdio;

int foo()
{
    write("foo");
    return 10;
}

void main()
{
    foreach (i; 0 .. foo())
    {
        write(i);
    }
}

```
 prints: 
```
foo0123456789

```
 ### Break and Continue out of Foreach

 A [*BreakStatement*](#BreakStatement) in the body of the foreach will exit the foreach, a [*ContinueStatement*](#ContinueStatement) will immediately start the next iteration. 

 Switch Statement
----------------

 A switch statement goes to one of a collection of case statements depending on the value of the switch expression. 
```
SwitchStatement:
    switch ( Expression ) ScopeStatement

CaseStatement:
    case ArgumentList : ScopeStatementList

CaseRangeStatement:
    case FirstExp : .. case LastExp : ScopeStatementList

FirstExp:
    AssignExpression

LastExp:
    AssignExpression

DefaultStatement:
    default : ScopeStatementList

ScopeStatementList:
    StatementListNoCaseNoDefault

StatementListNoCaseNoDefault:
    StatementNoCaseNoDefault
    StatementNoCaseNoDefault StatementListNoCaseNoDefault

StatementNoCaseNoDefault:
    ;
    NonEmptyStatementNoCaseNoDefault
    ScopeBlockStatement

```
 [*Expression*](expression#Expression) is evaluated. The result type T must be of integral type or `char[]`, `wchar[]` or `dchar[]`. The result is compared against each of the case expressions. If there is a match, the corresponding case statement is transferred to. 

 The case expressions, [*ArgumentList*](expression#ArgumentList), are a comma separated list of expressions. 

 A *CaseRangeStatement* is a shorthand for listing a series of case statements from *FirstExp* to *LastExp*. 

 If none of the case expressions match, and there is a default statement, the default statement is transferred to. 

 A switch statement must have a default statement.

 The case expressions must all evaluate to a constant value or array, or a runtime initialized const or immutable variable of integral type. They must be implicitly convertible to the type of the switch [*Expression*](expression#Expression). 

 Case expressions must all evaluate to distinct values. Const or immutable variables must all have different names. If they share a value, the first case statement with that value gets control. There must be exactly one default statement.

 The [*ScopeStatementList*](#ScopeStatementList) introduces a new scope. 

 Case statements and default statements associated with the switch can be nested within block statements; they do not have to be in the outermost block. For example, this is allowed: 

 
```
switch (i)
{
    case 1:
    {
        case 2:
    }
    break;
}

```
 A [*ScopeStatementList*](#ScopeStatementList) must either be empty, or be ended with a [*ContinueStatement*](#ContinueStatement), [*BreakStatement*](#BreakStatement), [*ReturnStatement*](#ReturnStatement), [*GotoStatement*](#GotoStatement), [*ThrowStatement*](#ThrowStatement) or assert(0) expression unless this is the last case. This is to set apart with C's error-prone implicit fall-through behavior. `goto case;` could be used for explicit fall-through: 

 
```
int number;
string message;
switch (number)
{
    default:    // valid: ends with 'throw'
        throw new Exception("unknown number");

    case 3:     // valid: ends with 'break' (break out of the 'switch' only)
        message ~= "three ";
        break;

    case 4:     // valid: ends with 'continue' (continue the enclosing loop)
        message ~= "four ";
        continue;

    case 5:     // valid: ends with 'goto' (explicit fall-through to next case.)
        message ~= "five ";
        goto case;

    case 6:     // ERROR: implicit fall-through
        message ~= "six ";

    case 1:     // valid: the body is empty
    case 2:     // valid: this is the last case in the switch statement.
        message = "one or two";
}

```
 A break statement will exit the switch *BlockStatement*.

 Strings can be used in switch expressions. For example: 

 
```
string name;
...
switch (name)
{
    case "fred":
    case "sally":
        ...
}

```
 For applications like command line switch processing, this can lead to much more straightforward code, being clearer and less error prone. char, wchar and dchar strings are allowed. 

 `Implementation Note:` The compiler's code generator may assume that the case statements are sorted by frequency of use, with the most frequent appearing first and the least frequent last. Although this is irrelevant as far as program correctness is concerned, it is of performance interest. 

 Final Switch Statement
----------------------

 
```
FinalSwitchStatement:
    final switch ( Expression ) ScopeStatement

```
 A final switch statement is just like a switch statement, except that:

 * No [*DefaultStatement*](#DefaultStatement) is allowed.
* No [*CaseRangeStatement*](#CaseRangeStatement)s are allowed.
* If the switch [*Expression*](expression#Expression) is of enum type, all the enum members must appear in the [*CaseStatement*](#CaseStatement)s.
* The case expressions cannot evaluate to a run time initialized value.

 **Implementation Defined:** If the [*Expression*](expression#Expression) value does not match any of the *CaseRangeStatements*, whether that is diagnosed at compile time or at runtime. Continue Statement
------------------

 
```
ContinueStatement:
    continue Identifieropt ;

```
 `continue` aborts the current iteration of its enclosing loop statement, and starts the next iteration.

 continue executes the next iteration of its innermost enclosing while, for, foreach, or do loop. The increment clause is executed.

 If continue is followed by *Identifier*, the *Identifier* must be the label of an enclosing while, for, or do loop, and the next iteration of that loop is executed. It is an error if there is no such statement.

 Any intervening finally clauses are executed, and any intervening synchronization objects are released.

 `Note:` If a finally clause executes a throw out of the finally clause, the continue target is never reached.

 
```
for (i = 0; i < 10; i++)
{
    if (foo(i))
        continue;
    bar();
}

```
 Break Statement
---------------

 
```
BreakStatement:
    break Identifieropt ;

```
 `break` exits the innermost enclosing while, for, foreach, do, or switch statement, resuming execution at the statement following it.

 If break is followed by *Identifier*, the *Identifier* must be the label of an enclosing while, for, do or switch statement, and that statement is exited. It is an error if there is no such statement.

 Any intervening finally clauses are executed, and any intervening synchronization objects are released.

 `Note:` If a finally clause executes a throw out of the finally clause, the break target is never reached.

 
```
for (i = 0; i < 10; i++)
{
    if (foo(i))
        break;
}

```
 Return Statement
----------------

 
```
ReturnStatement:
    return Expressionopt ;

```
 `return` exits the current function and supplies its return value.

 [*Expression*](expression#Expression) is required if the function specifies a return type that is not void. The [*Expression*](expression#Expression) is implicitly converted to the function return type.

 At least one return statement, throw statement, or assert(0) expression is required if the function specifies a return type that is not void, unless the function contains inline assembler code.

 Before the function actually returns, any objects with scope storage duration are destroyed, any enclosing finally clauses are executed, any scope(exit) statements are executed, any scope(success) statements are executed, and any enclosing synchronization objects are released.

 The function will not return if any enclosing finally clause does a return, goto or throw that exits the finally clause.

 If there is an out postcondition (see [Contract Programming](contracts)), that postcondition is executed after the [*Expression*](expression#Expression) is evaluated and before the function actually returns.

 
```
int foo(int x)
{
    return x + 3;
}

```
 Goto Statement
--------------

 
```
GotoStatement:
    goto Identifier ;
    goto default ;
    goto case ;
    goto case Expression ;

```
 `goto` transfers to the statement labeled with *Identifier*.

 
```
    if (foo)
        goto L1;
    x = 3;
L1:
    x++;

```
 The second form, `goto default;`, transfers to the innermost [*DefaultStatement*](#DefaultStatement) of an enclosing [*SwitchStatement*](#SwitchStatement).

 The third form, `goto case;`, transfers to the next [*CaseStatement*](#CaseStatement) of the innermost enclosing [*SwitchStatement*](#SwitchStatement).

 The fourth form, `goto case` [*Expression*](expression#Expression)`;`, transfers to the [*CaseStatement*](#CaseStatement) of the innermost enclosing [*SwitchStatement*](#SwitchStatement) with a matching [*Expression*](expression#Expression).

 
```
switch (x)
{
    case 3:
        goto case;
    case 4:
        goto default;
    case 5:
        goto case 4;
    default:
        x = 4;
        break;
}

```
 Any intervening finally clauses are executed, along with releasing any intervening synchronization mutexes.

 It is illegal for a *GotoStatement* to be used to skip initializations.

 With Statement
--------------

 The `with` statement is a way to simplify repeated references to the same object.

 
```
WithStatement:
    with ( Expression ) ScopeStatement
    with ( Symbol ) ScopeStatement
    with ( TemplateInstance ) ScopeStatement

```
 where [*Expression*](expression#Expression) evaluates to a class reference or struct instance. Within the with body the referenced object is searched first for identifier symbols. The *WithStatement*

 
```
with (expression)
{
    ...
    ident;
}

```
 is semantically equivalent to: 
```
{
    Object tmp;
    tmp = expression;
    ...
    tmp.ident;
}

```
 Note that [*Expression*](expression#Expression) only gets evaluated once and is not copied. The with statement does not change what `this` or `super` refer to. 

 For *Symbol* which is a scope or *TemplateInstance*, the corresponding scope is searched when looking up symbols. For example: 

 
```
struct Foo
{
    alias Y = int;
}
...
Y y;        // error, Y undefined
with (Foo)
{
    Y y;    // same as Foo.Y y;
}

```
 Use of with object symbols that shadow local symbols with the same identifier are not allowed. This is to reduce the risk of inadvertent breakage of with statements when new members are added to the object declaration. 

 
```
struct S
{
    float x;
}

void main()
{
    int x;
    S s;
    with (s)
    {
        x++;  // error, shadows the int x declaration
    }
}

```
 In nested *WithStatement*s, the inner-most scope takes precedence. If a symbol cannot be resolved at the inner-most scope, resolution is forwarded incrementally up the scope hierarchy.

 
```
import std.stdio;

struct Foo
{
    void f() { writeln("Foo.f"); }
}

struct Bar
{
    void f() { writeln("Bar.f"); }
}

struct Baz
{
    // f() is not implemented
}

void f()
{
    writeln("f");
}

void main()
{
    Foo foo;
    Bar bar;
    Baz baz;

    f();               // prints "f"

    with(foo)
    {
        f();           // prints "Foo.f"

        with(bar)
        {
            f();       // prints "Bar.f"

            with(baz)
            {
                f();   // prints "Bar.f".  `Baz` does not implement `f()` so
                       // resolution is forwarded to `with(bar)`'s scope
            }
        }
        with(baz)
        {
            f();       // prints "Foo.f".  `Baz` does not implement `f()` so
                       // resolution is forwarded to `with(foo)`'s scope
        }
    }
    with(baz)
    {
        f();           // prints "f".  `Baz` does not implement `f()` so
                       // resolution is forwarded to `main`'s scope. `f()` is
                       // not implemented in `main`'s scope, so resolution is
                       // subsequently forward to module scope.
    }
}


```
 Synchronized Statement
----------------------

 The synchronized statement wraps a statement with a mutex to synchronize access among multiple threads. 

 
```
SynchronizedStatement:
    synchronized ScopeStatement
    synchronized ( Expression ) ScopeStatement

```
 Synchronized allows only one thread at a time to execute *ScopeStatement* by using a mutex. 

 What mutex is used is determined by the [*Expression*](expression#Expression). If there is no [*Expression*](expression#Expression), then a global mutex is created, one per such synchronized statement. Different synchronized statements will have different global mutexes. 

 If there is an [*Expression*](expression#Expression), it must evaluate to either an Object or an instance of an *Interface*, in which case it is cast to the Object instance that implemented that *Interface*. The mutex used is specific to that Object instance, and is shared by all synchronized statements referring to that instance. 

 The synchronization gets released even if *ScopeStatement* terminates with an exception, goto, or return. 

 Example: 

 
```
synchronized { ... }

```
 This implements a standard critical section. 

 Synchronized statements support recursive locking; that is, a function wrapped in synchronized is allowed to recursively call itself and the behavior will be as expected: The mutex will be locked and unlocked as many times as there is recursion. 

 Try Statement
-------------

 Exception handling is done with the try-catch-finally statement.

 
```
TryStatement:
    try ScopeStatement Catches
    try ScopeStatement Catches FinallyStatement
    try ScopeStatement FinallyStatement

Catches:
    Catch
    Catch Catches

Catch:
    catch ( CatchParameter ) NoScopeNonEmptyStatement

CatchParameter:
    BasicType Identifieropt

FinallyStatement:
    finally NoScopeNonEmptyStatement

```
 *CatchParameter* declares a variable v of type T, where T is Throwable or derived from Throwable. v is initialized by the throw expression if T is of the same type or a base class of the throw expression. The catch clause will be executed if the exception object is of type T or derived from T.

 If just type T is given and no variable v, then the catch clause is still executed. 

 It is an error if any *CatchParameter* type T1 hides a subsequent *Catch* with type T2, i.e. it is an error if T1 is the same type as or a base class of T2. 

 The *FinallyStatement* is always executed, whether the `try` *ScopeStatement* exits with a goto, break, continue, return, exception, or fall-through. 

 If an exception is raised in the *FinallyStatement* and is not caught before the original exception is caught, it is chained to the previous exception via the *next* member of *Throwable*. Note that, in contrast to most other programming languages, the new exception does not replace the original exception. Instead, later exceptions are regarded as 'collateral damage' caused by the first exception. The original exception must be caught, and this results in the capture of the entire chain. 

 Thrown objects derived from [`class $Error`](https://dlang.org/phobos/object.html#Error) are treated differently. They bypass the normal chaining mechanism, such that the chain can only be caught by catching the first `Error`. In addition to the list of subsequent exceptions, `Error` also contains a pointer that points to the original exception (the head of the chain) if a bypass occurred, so that the entire exception history is retained.

 
```
import std.stdio;

int main()
{
    try
    {
        try
        {
            throw new Exception("first");
        }
        finally
        {
            writeln("finally");
            throw new Exception("second");
        }
    }
    catch (Exception e)
    {
        writeln("catch %s", e.msg);
    }
    writeln("done");
    return 0;
}

```
 prints: 
```
finally
catch first
done

```
 A *FinallyStatement* may not exit with a goto, break, continue, or return; nor may it be entered with a goto. 

 A *FinallyStatement* may not contain any *Catches*. This restriction may be relaxed in future versions. 

 Throw Statement
---------------

 Throws an exception.

 
```
ThrowStatement:
    throw Expression ;

```
 [*Expression*](expression#Expression) is evaluated and must be a `Throwable` reference. The `Throwable` reference is thrown as an exception.

 
```
throw new Exception("message");

```
 **Best Practices:** Use [Assert Expressions](expression#assert_expressions) rather than [Error](https://dlang.org/library/object#Error) to report program bugs and abort the program. Scope Guard Statement
---------------------

 
```
ScopeGuardStatement:
    scope(exit) NonEmptyOrScopeBlockStatement
    scope(success) NonEmptyOrScopeBlockStatement
    scope(failure) NonEmptyOrScopeBlockStatement

```
 The *ScopeGuardStatement* executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) at the close of the current scope, rather than at the point where the *ScopeGuardStatement* appears. `scope(exit)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits normally or when it exits due to exception unwinding. `scope(failure)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits due to exception unwinding. `scope(success)` executes [*NonEmptyOrScopeBlockStatement*](#NonEmptyOrScopeBlockStatement) when the scope exits normally.

 If there are multiple *ScopeGuardStatement*s in a scope, they will be executed in the reverse lexical order in which they appear. If any scope instances are to be destroyed upon the close of the scope, their destructions will be interleaved with the *ScopeGuardStatement*s in the reverse lexical order in which they appear.

 
```
write("1");
{
    write("2");
    scope(exit) write("3");
    scope(exit) write("4");
    write("5");
}
writeln();

```
 writes: 
```
12543

```
 
```
{
    scope(exit) write("1");
    scope(success) write("2");
    scope(exit) write("3");
    scope(success) write("4");
}
writeln();

```
 writes: 
```
4321

```
 
```
struct Foo
{
    this(string s) { write(s); }
    ~this() { write("1"); }
}

try
{
    scope(exit) write("2");
    scope(success) write("3");
    Foo f = Foo("0");
    scope(failure) write("4");
    throw new Exception("msg");
    scope(exit) write("5");
    scope(success) write("6");
    scope(failure) write("7");
}
catch (Exception e)
{
}
writeln();

```
 writes: 
```
0412

```
 A `scope(exit)` or `scope(success)` statement may not exit with a throw, goto, break, continue, or return; nor may it be entered with a goto. ### Catching C++ Class Objects

  On many platforms, catching C++ class objects is supported. Catching C++ objects and D objects cannot both be done in the same *TryStatement*. Upon exit from the *Catch*, any destructors for the C++ object will be run and the storage used for it reclaimed. C++ objects cannot be caught in `@safe` code. 

 Asm Statement
-------------

 Inline assembler is supported with the asm statement:

 
```
AsmStatement:
    asm FunctionAttributesopt { AsmInstructionListopt }

AsmInstructionList:
    AsmInstruction ;
    AsmInstruction ; AsmInstructionList

```
 An asm statement enables the direct use of assembly language instructions. This makes it easy to obtain direct access to special CPU features without resorting to an external assembler. The D compiler will take care of the function calling conventions, stack setup, etc.

 The format of the instructions is, of course, highly dependent on the native instruction set of the target CPU, and so is [implementation defined](iasm). But, the format will follow the following conventions:

 * It must use the same tokens as the D language uses.
* The comment form must match the D language comments.
* Asm instructions are terminated by a ;, not by an end of line.

 These rules exist to ensure that D source code can be tokenized independently of syntactic or semantic analysis. For example, for the Intel Pentium:

 
```
int x = 3;
asm
{
    mov EAX,x; // load x and put it in register EAX
}

```
 Inline assembler can be used to access hardware directly:

 
```
int gethardware()
{
    asm
    {
        mov EAX, dword ptr 0x1234;
    }
}

```
 For some D implementations, such as a translator from D to C, an inline assembler makes no sense, and need not be implemented. The version statement can be used to account for this:

 
```
version (D_InlineAsm_X86)
{
    asm
    {
        ...
    }
}
else
{
    /* ... some workaround ... */
}

```
 Semantically consecutive *AsmStatement*s shall not have any other instructions (such as register save or restores) inserted between them by the compiler. 

 Pragma Statement
----------------

 
```
PragmaStatement

```
 Mixin Statement
---------------

 
```
MixinStatement:
    mixin ( ArgumentList ) ;

```
 Each [*AssignExpression*](expression#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*StatementList*](#StatementList), and is compiled as such. 

 
```
import std.stdio;

void main()
{
    int j;
    mixin("
        int x = 3;
        for (int i = 0; i < 3; i++)
            writeln(x + i, ++j);
        ");    // ok

    string s = "int y;";
    mixin(s);  // ok
    y = 4;     // ok, mixin declared y

    string t = "y = 3;";
    mixin(t);  // error, t is not evaluatable at compile time

    mixin("y =") 4; // error, string must be complete statement

    mixin("y =" ~ "4;");  // ok

    mixin("y =", 2+2, ";");  // ok
}

```
 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/statement.html>

Traits
======

 **Contents** 1. [isArithmetic](#isArithmetic)
2. [isFloating](#isFloating)
3. [isIntegral](#isIntegral)
4. [isScalar](#isScalar)
5. [isUnsigned](#isUnsigned)
6. [isStaticArray](#isStaticArray)
7. [isAssociativeArray](#isAssociativeArray)
8. [isAbstractClass](#isAbstractClass)
9. [isFinalClass](#isFinalClass)
10. [isPOD](#isPOD)
11. [isNested](#isNested)
12. [isFuture](#isFuture)
13. [isDeprecated](#isDeprecated)
14. [isDisabled](#isDisabled)
15. [isVirtualFunction](#isVirtualFunction)
16. [isVirtualMethod](#isVirtualMethod)
17. [isAbstractFunction](#isAbstractFunction)
18. [isFinalFunction](#isFinalFunction)
19. [isOverrideFunction](#isOverrideFunction)
20. [isStaticFunction](#isStaticFunction)
21. [isRef](#isRef)
22. [isTemplate](#isTemplate)
23. [isZeroInit](#isZeroInit)
24. [isReturnOnStack](#isReturnOnStack)
25. [isModule](#isModule)
26. [isPackage](#isPackage)
27. [hasMember](#hasMember)
28. [hasCopyConstructor](#hasCopyConstructor)
29. [hasPostblit](#hasPostblit)
30. [identifier](#identifier)
31. [getAliasThis](#getAliasThis)
32. [getAttributes](#getAttributes)
33. [getFunctionVariadicStyle](#getFunctionVariadicStyle)
34. [getFunctionAttributes](#getFunctionAttributes)
35. [getLinkage](#getLinkage)
36. [getLocation](#getLocation)
37. [getMember](#getMember)
38. [getOverloads](#getOverloads)
39. [getParameterStorageClasses](#getParameterStorageClasses)
40. [getPointerBitmap](#getPointerBitmap)
41. [getCppNamespaces](#getCppNamespaces)
42. [getVisibility](#getVisibility)
43. [getProtection](#getProtection)
44. [getTargetInfo](#getTargetInfo)
45. [getVirtualFunctions](#getVirtualFunctions)
46. [getVirtualMethods](#getVirtualMethods)
47. [getUnitTests](#getUnitTests)
48. [parent](#parent)
49. [child](#child)
50. [classInstanceSize](#classInstanceSize)
51. [getVirtualIndex](#getVirtualIndex)
52. [allMembers](#allMembers)
53. [derivedMembers](#derivedMembers)
54. [isSame](#isSame)
55. [compiles](#compiles)

 Traits are extensions to the language to enable programs, at compile time, to get at information internal to the compiler. This is also known as compile time reflection. It is done as a special, easily extended syntax (similar to Pragmas) so that new capabilities can be added as required. 

 
```
TraitsExpression:
    __traits ( TraitsKeyword , TraitsArguments )

TraitsKeyword:
    isAbstractClass
    isArithmetic
    isAssociativeArray
    isFinalClass
    isPOD
    isNested
    isFuture
    isDeprecated
    isFloating
    isIntegral
    isScalar
    isStaticArray
    isUnsigned
    isDisabled
    isVirtualFunction
    isVirtualMethod
    isAbstractFunction
    isFinalFunction
    isStaticFunction
    isOverrideFunction
    isTemplate
    isRef
    isOut
    isLazy
    isReturnOnStack
    isZeroInit
    isModule
    isPackage
    hasMember
    hasCopyConstructor
    hasPostblit
    identifier
    getAliasThis
    getAttributes
    getFunctionAttributes
    getFunctionVariadicStyle
    getLinkage
    getLocation
    getMember
    getOverloads
    getParameterStorageClasses
    getPointerBitmap
    getCppNamespaces
    getVisibility
    getProtection
    getTargetInfo
    getVirtualFunctions
    getVirtualMethods
    getUnitTests
    parent
    child
    classInstanceSize
    getVirtualIndex
    allMembers
    derivedMembers
    isSame
    compiles

TraitsArguments:
    TraitsArgument
    TraitsArgument , TraitsArguments

TraitsArgument:
    AssignExpression
    Type

```
 isArithmetic
------------

 If the arguments are all either types that are arithmetic types, or expressions that are typed as arithmetic types, then `true` is returned. Otherwise, `false` is returned. If there are no arguments, `false` is returned.

 
```
import std.stdio;

void main()
{
    int i;
    writeln(__traits(isArithmetic, int));
    writeln(__traits(isArithmetic, i, i+1, int));
    writeln(__traits(isArithmetic));
    writeln(__traits(isArithmetic, int*));
}

```
 Prints: 
```
true
true
false
false

```
 isFloating
----------

 Works like `isArithmetic`, except it's for floating point types (including imaginary and complex types).

 
```
import core.simd : float4;

enum E : float { a, b }

static assert(__traits(isFloating, float));
static assert(__traits(isFloating, idouble));
static assert(__traits(isFloating, creal));
static assert(__traits(isFloating, E));
static assert(__traits(isFloating, float4));

static assert(!__traits(isFloating, float[4]));

```
 isIntegral
----------

 Works like `isArithmetic`, except it's for integral types (including character types).

 
```
import core.simd : int4;

enum E { a, b }

static assert(__traits(isIntegral, bool));
static assert(__traits(isIntegral, char));
static assert(__traits(isIntegral, int));
static assert(__traits(isIntegral, E));
static assert(__traits(isIntegral, int4));

static assert(!__traits(isIntegral, float));
static assert(!__traits(isIntegral, int[4]));
static assert(!__traits(isIntegral, void*));

```
 isScalar
--------

 Works like `isArithmetic`, except it's for scalar types.

 
```
import core.simd : int4, void16;

enum E { a, b }

static assert(__traits(isScalar, bool));
static assert(__traits(isScalar, char));
static assert(__traits(isScalar, int));
static assert(__traits(isScalar, float));
static assert(__traits(isScalar, E));
static assert(__traits(isScalar, int4));
static assert(__traits(isScalar, void*)); // Includes pointers!

static assert(!__traits(isScalar, int[4]));
static assert(!__traits(isScalar, void16));
static assert(!__traits(isScalar, void));
static assert(!__traits(isScalar, typeof(null)));
static assert(!__traits(isScalar, Object));

```
 isUnsigned
----------

 Works like `isArithmetic`, except it's for unsigned types.

 
```
import core.simd : uint4;

enum SignedEnum { a, b }
enum UnsignedEnum : uint { a, b }

static assert(__traits(isUnsigned, bool));
static assert(__traits(isUnsigned, char));
static assert(__traits(isUnsigned, uint));
static assert(__traits(isUnsigned, UnsignedEnum));
static assert(__traits(isUnsigned, uint4));

static assert(!__traits(isUnsigned, int));
static assert(!__traits(isUnsigned, float));
static assert(!__traits(isUnsigned, SignedEnum));
static assert(!__traits(isUnsigned, uint[4]));
static assert(!__traits(isUnsigned, void*));

```
 isStaticArray
-------------

 Works like `isArithmetic`, except it's for static array types.

 
```
import core.simd : int4;

enum E : int[4] { a = [1, 2, 3, 4] }

static array = [1, 2, 3]; // Not a static array: the type is inferred as int[] not int[3].

static assert(__traits(isStaticArray, void[0]));
static assert(__traits(isStaticArray, E));
static assert(!__traits(isStaticArray, int4));
static assert(!__traits(isStaticArray, array));

```
 isAssociativeArray
------------------

 Works like `isArithmetic`, except it's for associative array types.

 isAbstractClass
---------------

 If the arguments are all either types that are abstract classes, or expressions that are typed as abstract classes, then `true` is returned. Otherwise, `false` is returned. If there are no arguments, `false` is returned.

 
```
import std.stdio;

abstract class C { int foo(); }

void main()
{
    C c;
    writeln(__traits(isAbstractClass, C));
    writeln(__traits(isAbstractClass, c, C));
    writeln(__traits(isAbstractClass));
    writeln(__traits(isAbstractClass, int*));
}

```
 Prints: 
```
true
true
false
false

```
 isFinalClass
------------

 Works like `isAbstractClass`, except it's for final classes.

 isPOD
-----

 Takes one argument, which must be a type. It returns `true` if the type is a [POD](https://dlang.org/glossary.html#pod) type, otherwise `false`.

 isNested
--------

 Takes one argument. It returns `true` if the argument is a nested type which internally stores a context pointer, otherwise it returns `false`. Nested types can be [classes](class#nested), [structs](struct#nested), and [functions](function#variadicnested).

 isFuture
--------

 Takes one argument. It returns `true` if the argument is a symbol marked with the `@future` keyword, otherwise `false`. Currently, only functions and variable declarations have support for the `@future` keyword.

 isDeprecated
------------

 Takes one argument. It returns `true` if the argument is a symbol marked with the `deprecated` keyword, otherwise `false`.

 isDisabled
----------

 Takes one argument and returns `true` if it's a function declaration marked with `@disable`.

 
```
struct Foo
{
    @disable void foo();
    void bar(){}
}

static assert(__traits(isDisabled, Foo.foo));
static assert(!__traits(isDisabled, Foo.bar));

```
 For any other declaration even if `@disable` is a syntactically valid attribute `false` is returned because the annotation has no effect.

 
```
@disable struct Bar{}

static assert(!__traits(isDisabled, Bar));

```
 isVirtualFunction
-----------------

 The same as [*isVirtualMethod*](#isVirtualMethod), except that final functions that don't override anything return true. 

 isVirtualMethod
---------------

 Takes one argument. If that argument is a virtual function, `true` is returned, otherwise `false`. Final functions that don't override anything return false. 

 
```
import std.stdio;

struct S
{
    void bar() { }
}

class C
{
    void bar() { }
}

void main()
{
    writeln(__traits(isVirtualMethod, C.bar));  // true
    writeln(__traits(isVirtualMethod, S.bar));  // false
}

```
 isAbstractFunction
------------------

 Takes one argument. If that argument is an abstract function, `true` is returned, otherwise `false`. 

 
```
import std.stdio;

struct S
{
    void bar() { }
}

class C
{
    void bar() { }
}

class AC
{
    abstract void foo();
}

void main()
{
    writeln(__traits(isAbstractFunction, C.bar));   // false
    writeln(__traits(isAbstractFunction, S.bar));   // false
    writeln(__traits(isAbstractFunction, AC.foo));  // true
}

```
 isFinalFunction
---------------

 Takes one argument. If that argument is a final function, `true` is returned, otherwise `false`. 

 
```
import std.stdio;

struct S
{
    void bar() { }
}

class C
{
    void bar() { }
    final void foo();
}

final class FC
{
    void foo();
}

void main()
{
    writeln(__traits(isFinalFunction, C.bar));  // false
    writeln(__traits(isFinalFunction, S.bar));  // false
    writeln(__traits(isFinalFunction, C.foo));  // true
    writeln(__traits(isFinalFunction, FC.foo)); // true
}

```
 isOverrideFunction
------------------

 Takes one argument. If that argument is a function marked with override, `true` is returned, otherwise `false`. 

 
```
import std.stdio;

class Base
{
    void foo() { }
}

class Foo : Base
{
    override void foo() { }
    void bar() { }
}

void main()
{
    writeln(__traits(isOverrideFunction, Base.foo)); // false
    writeln(__traits(isOverrideFunction, Foo.foo));  // true
    writeln(__traits(isOverrideFunction, Foo.bar));  // false
}

```
 isStaticFunction
----------------

 Takes one argument. If that argument is a static function, meaning it has no context pointer, `true` is returned, otherwise `false`. 

 
```
struct A
{
    int foo() { return 3; }
    static int boo(int a) { return a; }
}

void main()
{
    assert(__traits(isStaticFunction, A.boo));
    assert(!__traits(isStaticFunction, A.foo));
    assert(__traits(isStaticFunction, main));
}

```
 
isRef, isOut, isLazy
---------------------

 Takes one argument. If that argument is a declaration, `true` is returned if it is ref, out, or lazy, otherwise `false`. 

 
```
void fooref(ref int x)
{
    static assert(__traits(isRef, x));
    static assert(!__traits(isOut, x));
    static assert(!__traits(isLazy, x));
}

void fooout(out int x)
{
    static assert(!__traits(isRef, x));
    static assert(__traits(isOut, x));
    static assert(!__traits(isLazy, x));
}

void foolazy(lazy int x)
{
    static assert(!__traits(isRef, x));
    static assert(!__traits(isOut, x));
    static assert(__traits(isLazy, x));
}

```
 isTemplate
----------

 Takes one argument. If that argument is a template then `true` is returned, otherwise `false`. 

 
```
void foo(T)(){}
static assert(__traits(isTemplate,foo));
static assert(!__traits(isTemplate,foo!int()));
static assert(!__traits(isTemplate,"string"));

```
 isZeroInit
----------

 Takes one argument which must be a type. If the type's [default initializer](property#init) is all zero bits then `true` is returned, otherwise `false`.

 
```
struct S1 { int x; }
struct S2 { int x = -1; }

static assert(__traits(isZeroInit, S1));
static assert(!__traits(isZeroInit, S2));

void test()
{
    int x = 3;
    static assert(__traits(isZeroInit, typeof(x)));
}

// `isZeroInit` will always return true for a class C
// because `C.init` is null reference.

class C { int x = -1; }

static assert(__traits(isZeroInit, C));

// For initializing arrays of element type `void`.
static assert(__traits(isZeroInit, void));

```
 isReturnOnStack
---------------

  Takes one argument which must either be a function symbol, function literal, a delegate, or a function pointer. It returns a `bool` which is `true` if the return value of the function is returned on the stack via a pointer to it passed as a hidden extra parameter to the function. 

 
```
struct S { int[20] a; }
int test1();
S test2();

static assert(__traits(isReturnOnStack, test1) == false);
static assert(__traits(isReturnOnStack, test2) == true);

```
 **Implementation Defined:** This is determined by the function ABI calling convention in use, which is often complex. **Best Practices:** This has applications in: 1. Returning values in registers is often faster, so this can be used as a check on a hot function to ensure it is using the fastest method.
2. When using inline assembly to correctly call a function.
3. Testing that the compiler does this correctly is normally hackish and awkward, this enables efficient, direct, and simple testing.

 isModule
--------

 Takes one argument. If that argument is a symbol that refers to a [spec/module, module](module) then `true` is returned, otherwise `false`. [Package modules](module#package-module) are considered to be modules even if they have not been directly imported as modules. 

 
```
import std.algorithm.sorting;

// A regular package (no package.d)
static assert(!__traits(isModule, std));
// A package module (has a package.d file)
// Note that we haven't imported std.algorithm directly.
// (In other words, we don't have an "import std.algorithm;" directive.)
static assert(__traits(isModule, std.algorithm));
// A regular module
static assert(__traits(isModule, std.algorithm.sorting));

```
 isPackage
---------

 Takes one argument. If that argument is a symbol that refers to a [spec/module, package](module) then `true` is returned, otherwise `false`. 

 
```
import std.algorithm.sorting;
static assert(__traits(isPackage, std));
static assert(__traits(isPackage, std.algorithm));
static assert(!__traits(isPackage, std.algorithm.sorting));

```
 hasMember
---------

 The first argument is a type that has members, or is an expression of a type that has members. The second argument is a string. If the string is a valid property of the type, `true` is returned, otherwise `false`. 

 
```
import std.stdio;

struct S
{
    int m;

    import std.stdio; // imports write
}

void main()
{
    S s;

    writeln(__traits(hasMember, S, "m")); // true
    writeln(__traits(hasMember, s, "m")); // true
    writeln(__traits(hasMember, S, "y")); // false
    writeln(__traits(hasMember, S, "write")); // true
    writeln(__traits(hasMember, int, "sizeof")); // true
}

```
 hasCopyConstructor
------------------

 The argument is a type. If it is a struct with a copy constructor, returns `true`. Otherwise, return `false`. Note that a copy constructor is distinct from a postblit. 

 
```

import std.stdio;

struct S
{
}

class C
{
}

struct P
{
    this(ref P rhs) {}
}

struct B
{
    this(this) {}
}

void main()
{
    writeln(__traits(hasCopyConstructor, S)); // false
    writeln(__traits(hasCopyConstructor, C)); // false
    writeln(__traits(hasCopyConstructor, P)); // true
    writeln(__traits(hasCopyConstructor, B)); // false, this is a postblit
}

```
 hasPostblit
-----------

 The argument is a type. If it is a struct with a postblit, returns `true`. Otherwise, return `false`. Note a postblit is distinct from a copy constructor. 

 
```

import std.stdio;

struct S
{
}

class C
{
}

struct P
{
    this(ref P rhs) {}
}

struct B
{
    this(this) {}
}


void main()
{
    writeln(__traits(hasPostblit, S)); // false
    writeln(__traits(hasPostblit, C)); // false
    writeln(__traits(hasPostblit, P)); // false, this is a copy ctor
    writeln(__traits(hasPostblit, B)); // true
}

```
 identifier
----------

 Takes one argument, a symbol. Returns the identifier for that symbol as a string literal. 

 
```
import std.stdio;

int var = 123;
pragma(msg, typeof(var));                       // int
pragma(msg, typeof(__traits(identifier, var))); // string
writeln(var);                                   // 123
writeln(__traits(identifier, var));             // "var"

```
 getAliasThis
------------

 Takes one argument, a type. If the type has `alias this` declarations, returns a sequence of the names (as `string`s) of the members used in those declarations. Otherwise returns an empty sequence. 

 
```
alias AliasSeq(T...) = T;

struct S1
{
    string var;
    alias var this;
}
static assert(__traits(getAliasThis, S1) == AliasSeq!("var"));
static assert(__traits(getAliasThis, int).length == 0);

pragma(msg, __traits(getAliasThis, S1));
pragma(msg, __traits(getAliasThis, int));

```
 Prints: 
```
tuple("var")
tuple()

```
 getAttributes
-------------

  Takes one argument, a symbol. Returns a tuple of all attached user-defined attributes. If no UDAs exist it will return an empty tuple. 

  For more information, see: [User-Defined Attributes](attribute#uda) 

 
```
@(3) int a;
@("string", 7) int b;

enum Foo;
@Foo int c;

pragma(msg, __traits(getAttributes, a));
pragma(msg, __traits(getAttributes, b));
pragma(msg, __traits(getAttributes, c));

```
 Prints: 
```
tuple(3)
tuple("string", 7)
tuple((Foo))

```
 getFunctionVariadicStyle
------------------------

  Takes one argument which must either be a function symbol, or a type that is a function, delegate or a function pointer. It returns a string identifying the kind of [variadic arguments](function#variadic) that are supported. 

 

getFunctionVariadicStyle| **result** | **kind** | **access** | **example** |
| `"none"` | not a variadic function |  | `void foo();` |
| `"argptr"` | D style variadic function | `_argptr` and `_arguments` | `void bar(...)` |
| `"stdarg"` | C style variadic function | [`core.stdc.stdarg`](https://dlang.org/phobos/core_stdc_stdarg.html) | `extern (C) void abc(int, ...)` |
| `"typesafe"` | typesafe variadic function | array on stack | `void def(int[] ...)` |

 
```
import core.stdc.stdarg;

void novar() {}
extern(C) void cstyle(int, ...) {}
extern(C++) void cppstyle(int, ...) {}
void dstyle(...) {}
void typesafe(int[]...) {}

static assert(__traits(getFunctionVariadicStyle, novar) == "none");
static assert(__traits(getFunctionVariadicStyle, cstyle) == "stdarg");
static assert(__traits(getFunctionVariadicStyle, cppstyle) == "stdarg");
static assert(__traits(getFunctionVariadicStyle, dstyle) == "argptr");
static assert(__traits(getFunctionVariadicStyle, typesafe) == "typesafe");

static assert(__traits(getFunctionVariadicStyle, (int[] a...) {}) == "typesafe");
static assert(__traits(getFunctionVariadicStyle, typeof(cstyle)) == "stdarg");

```
 getFunctionAttributes
---------------------

  Takes one argument which must either be a function symbol, function literal, or a function pointer. It returns a string tuple of all the attributes of that function **excluding** any user-defined attributes (UDAs can be retrieved with the [getAttributes](#get-attributes) trait). If no attributes exist it will return an empty tuple. 

 **Note:** The order of the attributes in the returned tuple is implementation-defined and should not be relied upon.  A list of currently supported attributes are:

 * `pure`, `nothrow`, `@nogc`, `@property`, `@system`, `@trusted`, `@safe`, `ref` and `@live`

 **Note:** `ref` is a function attribute even though it applies to the return type.  Additionally the following attributes are only valid for non-static member functions:

 * `const`, `immutable`, `inout`, `shared`

 For example: 
```
int sum(int x, int y) pure nothrow { return x + y; }

pragma(msg, __traits(getFunctionAttributes, sum));

struct S
{
    void test() const @system { }
}

pragma(msg, __traits(getFunctionAttributes, S.test));

void main(){}

```
 Prints: 
```
tuple("pure", "nothrow", "@system")
tuple("const", "@system")

```
 Note that some attributes can be inferred. For example:

 
```
pragma(msg, __traits(getFunctionAttributes, (int x) @trusted { return x * 2; }));

void main(){}

```
 Prints: 
```
tuple("pure", "nothrow", "@nogc", "@trusted")

```
 getLinkage
----------

 Takes one argument, which is a declaration symbol, or the type of a function, delegate, pointer to function, struct, class, or interface. Returns a string representing the [LinkageAttribute](attribute#LinkageAttribute) of the declaration. The string is one of: 

 * `"D"`
* `"C"`
* `"C++"`
* `"Windows"`
* `"Objective-C"`
* `"System"`

 
```
extern (C) int fooc();
alias aliasc = fooc;

static assert(__traits(getLinkage, fooc) == "C");
static assert(__traits(getLinkage, aliasc) == "C");

extern (C++) struct FooCPPStruct {}
extern (C++) class FooCPPClass {}
extern (C++) interface FooCPPInterface {}

static assert(__traits(getLinkage, FooCPPStruct) == "C++");
static assert(__traits(getLinkage, FooCPPClass) == "C++");
static assert(__traits(getLinkage, FooCPPInterface) == "C++");

```
 getLocation
-----------

 Takes one argument which is a symbol. To disambiguate between overloads, pass the result of [*getOverloads*](#getOverloads) with the desired index, to `getLocation`. Returns a `tuple(string, int, int)` whose entries correspond to the filename, line number and column number where the argument was declared. 

 getMember
---------

 Takes two arguments, the second must be a string. The result is an expression formed from the first argument, followed by a ‘.’, followed by the second argument as an identifier. 

 
```
import std.stdio;

struct S
{
    int mx;
    static int my;
}

void main()
{
    S s;

    __traits(getMember, s, "mx") = 1;  // same as s.mx=1;
    writeln(__traits(getMember, s, "m" ~ "x")); // 1

    // __traits(getMember, S, "mx") = 1;  // error, no this for S.mx
    __traits(getMember, S, "my") = 2;  // ok
}

```
 getOverloads
------------

 The first argument is an aggregate (e.g. struct/class/module). The second argument is a `string` that matches the name of the member(s) to return. The third argument is a `bool`, and is optional. If `true`, the result will also include template overloads. The result is a tuple of all the overloads of the supplied name. 

 
```
import std.stdio;

class D
{
    this() { }
    ~this() { }
    void foo() { }
    int foo(int) { return 2; }
    void bar(T)() { return T.init; }
    class bar(int n) {}
}

void main()
{
    D d = new D();

    foreach (t; __traits(getOverloads, D, "foo"))
        writeln(typeid(typeof(t)));

    alias b = typeof(__traits(getOverloads, D, "foo"));
    foreach (t; b)
        writeln(typeid(t));

    auto i = __traits(getOverloads, d, "foo")[1](1);
    writeln(i);

    foreach (t; __traits(getOverloads, D, "bar", true))
        writeln(t.stringof);
}

```
 Prints: 
```
void()
int()
void()
int()
2
bar(T)()
bar(int n)

```
 getParameterStorageClasses
--------------------------

  Takes two arguments. The first must either be a function symbol, or a type that is a function, delegate or a function pointer. The second is an integer identifying which parameter, where the first parameter is 0. It returns a tuple of strings representing the storage classes of that parameter. 

 
```
ref int foo(return ref const int* p, scope int* a, out int b, lazy int c);

static assert(__traits(getParameterStorageClasses, foo, 0)[0] == "return");
static assert(__traits(getParameterStorageClasses, foo, 0)[1] == "ref");

static assert(__traits(getParameterStorageClasses, foo, 1)[0] == "scope");
static assert(__traits(getParameterStorageClasses, foo, 2)[0] == "out");
static assert(__traits(getParameterStorageClasses, typeof(&foo), 3)[0] == "lazy");

```
 getPointerBitmap
----------------

 The argument is a type. The result is an array of `size_t` describing the memory used by an instance of the given type. 

 The first element of the array is the size of the type (for classes it is the [*classInstanceSize*](#classInstanceSize)).

 The following elements describe the locations of GC managed pointers within the memory occupied by an instance of the type. For type T, there are `T.sizeof / size_t.sizeof` possible pointers represented by the bits of the array values.

 This array can be used by a precise GC to avoid false pointers.

 
```
void main()
{
    static class C
    {
        // implicit virtual function table pointer not marked
        // implicit monitor field not marked, usually managed manually
        C next;
        size_t sz;
        void* p;
        void function () fn; // not a GC managed pointer
    }

    static struct S
    {
        size_t val1;
        void* p;
        C c;
        byte[] arr;          // { length, ptr }
        void delegate () dg; // { context, func }
    }

    static assert (__traits(getPointerBitmap, C) == [6*size_t.sizeof, 0b010100]);
    static assert (__traits(getPointerBitmap, S) == [7*size_t.sizeof, 0b0110110]);
}

```
 getCppNamespaces
----------------

 The argument is a symbol. The result is a tuple of strings, possibly empty, that correspond to the namespaces the symbol resides in. 

 
```
extern(C++, "ns")
struct Foo {}
struct Bar {}
extern(C++, __traits(getCppNamespaces, Foo)) struct Baz {}
static assert(__traits(getCppNamespaces, Foo) ==  __traits(getCppNamespaces, Baz));
void main()
{
    static assert(__traits(getCppNamespaces, Foo)[0] == "ns");
    static assert(!__traits(getCppNamespaces, Bar).length);
    static assert(__traits(getCppNamespaces, Foo) ==  __traits(getCppNamespaces, Baz));
}

```
 getVisibility
-------------

 The argument is a symbol. The result is a string giving its visibility level: "public", "private", "protected", "export", or "package". 

 
```
import std.stdio;

class D
{
    export void foo() { }
    public int bar;
}

void main()
{
    D d = new D();

    auto i = __traits(getVisibility, d.foo);
    writeln(i);

    auto j = __traits(getVisibility, d.bar);
    writeln(j);
}

```
 Prints: 
```
export
public

```
 getProtection
-------------

 A backward-compatible alias for [*getVisibility*](#getVisibility).

 getTargetInfo
-------------

 Receives a string key as argument. The result is an expression describing the requested target information. 

 
```
version (CppRuntime_Microsoft)
    static assert(__traits(getTargetInfo, "cppRuntimeLibrary") == "libcmt");

```
 Keys are implementation defined, allowing relevant data for exotic targets. A reliable subset exists which are always available: 

 * `"cppRuntimeLibrary"` - The C++ runtime library affinity for this toolchain
* `"cppStd"` - The version of the C++ standard supported by `extern(C++)` code, equivalent to the `__cplusplus` macro in a C++ compiler
* `"floatAbi"` - Floating point ABI; may be `"hard"`, `"soft"`, or `"softfp"`
* `"objectFormat"` - Target object format

 getVirtualFunctions
-------------------

 The same as [*getVirtualMethods*](#getVirtualMethods), except that final functions that do not override anything are included. 

 getVirtualMethods
-----------------

 The first argument is a class type or an expression of class type. The second argument is a string that matches the name of one of the functions of that class. The result is a tuple of the virtual overloads of that function. It does not include final functions that do not override anything. 

 
```
import std.stdio;

class D
{
    this() { }
    ~this() { }
    void foo() { }
    int foo(int) { return 2; }
}

void main()
{
    D d = new D();

    foreach (t; __traits(getVirtualMethods, D, "foo"))
        writeln(typeid(typeof(t)));

    alias b = typeof(__traits(getVirtualMethods, D, "foo"));
    foreach (t; b)
        writeln(typeid(t));

    auto i = __traits(getVirtualMethods, d, "foo")[1](1);
    writeln(i);
}

```
 Prints: 
```
void()
int()
void()
int()
2

```
 getUnitTests
------------

  Takes one argument, a symbol of an aggregate (e.g. struct/class/module). The result is a tuple of all the unit test functions of that aggregate. The functions returned are like normal nested static functions, [CTFE](https://dlang.org/glossary.html#ctfe) will work and [UDAs](attribute#uda) will be accessible. 

 ### Note:

  The -unittest flag needs to be passed to the compiler. If the flag is not passed `__traits(getUnitTests)` will always return an empty tuple. 

 
```
module foo;

import core.runtime;
import std.stdio;

struct name { string name; }

class Foo
{
    unittest
    {
        writeln("foo.Foo.unittest");
    }
}

@name("foo") unittest
{
    writeln("foo.unittest");
}

template Tuple (T...)
{
    alias Tuple = T;
}

shared static this()
{
  // Override the default unit test runner to do nothing. After that, "main" will
  // be called.
  Runtime.moduleUnitTester = { return true; };
}

void main()
{
    writeln("start main");

    alias tests = Tuple!(__traits(getUnitTests, foo));
    static assert(tests.length == 1);

    alias attributes = Tuple!(__traits(getAttributes, tests[0]));
    static assert(attributes.length == 1);

    foreach (test; tests)
        test();

    foreach (test; __traits(getUnitTests, Foo))
        test();
}

```
 By default, the above will print:

 
```
start main
foo.unittest
foo.Foo.unittest

```
 parent
------

 Takes a single argument which must evaluate to a symbol. The result is the symbol that is the parent of it. 

 child
-----

 Takes two arguments. The first must be a symbol or expression. The second is a symbol, such as an alias to a member of the first argument. The result is the second argument interpreted with its `this` context set to the value of the first argument. 

 
```
import std.stdio;

struct A
{
    int i;
    int foo(int j) {
        return i * j;
    }
    T bar(T)(T t) {
        return i + t;
    }
}

alias Ai = A.i;
alias Abar = A.bar!int;

void main()
{
    A a;

    __traits(child, a, Ai) = 3;
    writeln(a.i);
    writeln(__traits(child, a, A.foo)(2));
    writeln(__traits(child, a, Abar)(5));
}

```
 Prints: 
```
3
6
7

```
 classInstanceSize
-----------------

 Takes a single argument, which must evaluate to either a class type or an expression of class type. The result is of type `size_t`, and the value is the number of bytes in the runtime instance of the class type. It is based on the static type of a class, not the polymorphic type. 

 getVirtualIndex
---------------

 Takes a single argument which must evaluate to a function. The result is a `ptrdiff_t` containing the index of that function within the vtable of the parent type. If the function passed in is final and does not override a virtual function, `-1` is returned instead. 

 allMembers
----------

 Takes a single argument, which must evaluate to either a type or an expression of type. A tuple of string literals is returned, each of which is the name of a member of that type combined with all of the members of the base classes (if the type is a class). No name is repeated. Builtin properties are not included. 

 
```
import std.stdio;

class D
{
    this() { }
    ~this() { }
    void foo() { }
    int foo(int) { return 0; }
}

void main()
{
    auto b = [ __traits(allMembers, D) ];
    writeln(b);
    // ["__ctor", "__dtor", "foo", "toString", "toHash", "opCmp", "opEquals",
    // "Monitor", "factory"]
}

```
 The order in which the strings appear in the result is not defined.

 derivedMembers
--------------

 Takes a single argument, which must evaluate to either a type or an expression of type. A tuple of string literals is returned, each of which is the name of a member of that type. No name is repeated. Base class member names are not included. Builtin properties are not included. 

 
```
import std.stdio;

class D
{
    this() { }
    ~this() { }
    void foo() { }
    int foo(int) { return 0; }
}

void main()
{
    auto a = [__traits(derivedMembers, D)];
    writeln(a);    // ["__ctor", "__dtor", "foo"]
}

```
 The order in which the strings appear in the result is not defined.

 isSame
------

 Takes two arguments and returns bool `true` if they are the same symbol, `false` if not.

 
```
import std.stdio;

struct S { }

int foo();
int bar();

void main()
{
    writeln(__traits(isSame, foo, foo)); // true
    writeln(__traits(isSame, foo, bar)); // false
    writeln(__traits(isSame, foo, S));   // false
    writeln(__traits(isSame, S, S));     // true
    writeln(__traits(isSame, std, S));   // false
    writeln(__traits(isSame, std, std)); // true
}

```
 If the two arguments are expressions made up of literals or enums that evaluate to the same value, true is returned.

 If the two arguments are both [lambda functions](expression#function_literals) (or aliases to lambda functions), then they are compared for equality. For the comparison to be computed correctly, the following conditions must be met for both lambda functions:

 1. The lambda function arguments must not have a template instantiation as an explicit argument type. Any other argument types (basic, user-defined, template) are supported.
2. The lambda function body must contain a single expression (no return statement) which contains only numeric values, manifest constants, enum values, function arguments and function calls. If the expression contains local variables or return statements, the function is considered incomparable.

 If these constraints aren't fulfilled, the function is considered incomparable and `isSame` returns `false`.

 
```
int f() { return 2; }
void test(alias pred)()
{
    // f() from main is a different function from top-level f()
    static assert(!__traits(isSame, (int a) => a + f(), pred));
}

void main()
{
    static assert(__traits(isSame, (a, b) => a + b, (c, d) => c + d));
    static assert(__traits(isSame, a => ++a, b => ++b));
    static assert(!__traits(isSame, (int a, int b) => a + b, (a, b) => a + b));
    static assert(__traits(isSame, (a, b) => a + b + 10, (c, d) => c + d + 10));

    // lambdas accessing local variables are considered incomparable
    int b;
    static assert(!__traits(isSame, a => a + b, a => a + b));

    // lambdas calling other functions are comparable
    int f() { return 3;}
    static assert(__traits(isSame, a => a + f(), a => a + f()));
    test!((int a) => a + f())();

    class A
    {
        int a;
        this(int a)
        {
            this.a = a;
        }
    }

    class B
    {
        int a;
        this(int a)
        {
            this.a = a;
        }
    }

    static assert(__traits(isSame, (A a) => ++a.a, (A b) => ++b.a));
    // lambdas with different data types are considered incomparable,
    // even if the memory layout is the same
    static assert(!__traits(isSame, (A a) => ++a.a, (B a) => ++a.a));
}

```
 If the two arguments are tuples then `isSame` returns `true` if the two tuples, after expansion, have the same length and if each pair of nth argument respects the constraints previously specified.

 
```
import std.stdio;
import std.meta;

struct S { }

void main()
{
    // true, like __traits(isSame(0,0)) && __traits(isSame(1,1))
    writeln(__traits(isSame, AliasSeq!(0,1), AliasSeq!(0,1)));
    // false, like __traits(isSame(S,std.meta)) && __traits(isSame(1,1))
    writeln(__traits(isSame, AliasSeq!(S,1), AliasSeq!(std.meta,1)));
    // false, the length of the sequences is different
    writeln(__traits(isSame, AliasSeq!(1), AliasSeq!(1,2)));
}

```
 compiles
--------

 Returns a bool `true` if all of the arguments compile (are semantically correct). The arguments can be symbols, types, or expressions that are syntactically correct. The arguments cannot be statements or declarations. 

 If there are no arguments, the result is `false`.

 
```
import std.stdio;

struct S
{
    static int s1;
    int s2;
}

int foo();
int bar();

void main()
{
    writeln(__traits(compiles));                      // false
    writeln(__traits(compiles, foo));                 // true
    writeln(__traits(compiles, foo + 1));             // true
    writeln(__traits(compiles, &foo + 1));            // false
    writeln(__traits(compiles, typeof(1)));           // true
    writeln(__traits(compiles, S.s1));                // true
    writeln(__traits(compiles, S.s3));                // false
    writeln(__traits(compiles, 1,2,3,int,long,std));  // true
    writeln(__traits(compiles, 3[1]));                // false
    writeln(__traits(compiles, 1,2,3,int,long,3[1])); // false
}

```
 This is useful for:

 * Giving better error messages inside generic code than the sometimes hard to follow compiler ones.
* Doing a finer grained specialization than template partial specialization allows for.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/traits.html>

Interfacing to C++
==================

 **Contents** 1. [The General Idea](#general_idea)
2. [Global Functions](#global-functions)
	1. [Calling C++ Global Functions from D](#calling_cpp_global_from_d)
	2. [Calling Global D Functions From C++](#calling_global_d_functions_from_cpp)
3. [C++ Namespaces](#cpp-namespaces)
4. [Classes](#classes)
	1. [Using C++ Classes From D](#using_cpp_classes_from_d)
	2. [Using D Classes From C++](#using_d_classes_from_cpp)
5. [Structs](#structs)
6. [C++ Templates](#cpp-templates)
7. [Function Overloading](#function-overloading)
8. [Memory Allocation](#memory-allocation)
9. [Data Type Compatibility](#data-type-compatibility)
10. [Packing and Alignment](#packing-and-alignment)
11. [Lifetime Management](#lifetime-management)
12. [Special Member Functions](#special-member-functions)
13. [Runtime Type Identification](#rtti)
14. [Exception Handling](#exception-handling)
15. [Comparing D Immutable and Const with C++ Const](#comparing-d-immutable-and-const-with-cpp-const)

 This document specifies how to interface with C++ directly.

 It is also possible to indirectly interface with C++ code, either through a [C interface](interfacetoc) or a COM interface.

 The General Idea
----------------

 Being 100% compatible with C++ means more or less adding a fully functional C++ compiler front end to D. Anecdotal evidence suggests that writing such is a minimum of a 10 man-year project, essentially making a D compiler with such capability unimplementable. Other languages looking to hook up to C++ face the same problem, and the solutions have been: 

 1. Support the COM interface (but that only works for Windows).
2. Laboriously construct a C wrapper around the C++ code.
3. Use an automated tool such as SWIG to construct a C wrapper.
4. Reimplement the C++ code in the other language.
5. Give up.

 D takes a pragmatic approach that assumes a couple modest accommodations can solve a significant chunk of the problem: 

 * matching C++ name mangling conventions
* matching C++ function calling conventions
* matching C++ virtual function table layout for single inheritance

 Global Functions
----------------

 C++ global functions, including those in namespaces, can be declared and called in D, or defined in D and called in C++.

 ### Calling C++ Global Functions from D

 Given a C++ function in a C++ source file:

 
```
#include <iostream>

using namespace std;

int foo(int i, int j, int k)
{
    cout << "i = " << i << endl;
    cout << "j = " << j << endl;
    cout << "k = " << k << endl;

    return 7;
}

```
 In the corresponding D code, `foo` is declared as having C++ linkage and function calling conventions: 

 
```
extern (C++) int foo(int i, int j, int k);

```
 and then it can be called within the D code:

 
```
extern (C++) int foo(int i, int j, int k);

void main()
{
    foo(1, 2, 3);
}

```
 Compiling the two files, the first with a C++ compiler, the second with a D compiler, linking them together, and then running it yields:

 
```
> g++ -c foo.cpp
> dmd bar.d foo.o -L-lstdc++ && ./bar
i = 1
j = 2
k = 3

```
 There are several things going on here:

 * D understands how C++ function names are "mangled" and the correct C++ function call/return sequence.
* Because modules are not part of C++, each function with C++ linkage in the global namespace must be globally unique within the program.
* There are no `__cdecl`, `__far`, `__stdcall`, `__declspec`, or other such nonstandard C++ extensions in D.
* There are no volatile type modifiers in D.
* Strings are not 0 terminated in D. See "Data Type Compatibility" for more information about this. However, string literals in D are 0 terminated.

 ### Calling Global D Functions From C++

 To make a D function accessible from C++, give it C++ linkage:

 
```
import std.stdio;

extern (C++) int foo(int i, int j, int k)
{
    writefln("i = %s", i);
    writefln("j = %s", j);
    writefln("k = %s", k);
    return 1;
}

extern (C++) void bar();

void main()
{
    bar();
}

```
 The C++ end looks like:

 
```
int foo(int i, int j, int k);

void bar()
{
    foo(6, 7, 8);
}

```
 Compiling, linking, and running produces the output:

 
```
> dmd -c foo.d
> g++ bar.cpp foo.o -lphobos2 -pthread -o bar && ./bar
i = 6
j = 7
k = 8

```
 C++ Namespaces
--------------

 C++ symbols that reside in namespaces can be accessed from D. A [namespace](attribute#namespace) can be added to the `extern (C++)` [LinkageAttribute](attribute#linkage): 

 
```
extern (C++, N) int foo(int i, int j, int k);

void main()
{
    N.foo(1, 2, 3);   // foo is in C++ namespace 'N'
}

```
 C++ can open the same namespace in the same file and multiple files. In D, this can be done as follows:

 
```
module ns;
extern (C++, `ns`)
{
    int foo() { return 1; }
}

```
 Any expression that resolves to either a tuple of strings or an empty tuple is accepted. When the expression resolves to an empty tuple, it is equivalent to `extern (C++)`

 
```
extern(C++, (expression))
{
    int bar() { return 2; }
}

```
 or in multiple files, by organizing them in a package consisting of several modules:

 
```
ns/
|-- a.d
|-- b.d
|-- package.d

```
 File `ns/a.d`:

 
```
module a; extern (C++, `ns`) { int foo() { return 1; } }

```
 File `ns/b.d`:

 
```
module b; extern (C++, `ns`) { int bar() { return 2; } }

```
 File `ns/package.d`:

 
```
module ns;
public import a, b;

```
 Then import the package containing the extern C++ declarations as follows:

 
```
import ns;
static assert(foo() == 1 && bar() == 2);

```
 Note that the `extern (C++,` ns`)` linkage attribute affects only the ABI (name mangling and calling convention) of these declarations. Importing them follows the usual [D module import semantics](spec/module).

 Alternatively, the non-string form can be used to introduce a scope. Note that the enclosing module already provides a scope for the symbols declared in the namespace. This form does not allow closing and reopening the same namespace with in the same module. That is:

 
```
module a; extern (C++, ns1) { int foo() { return 1; } }

```
 
```
module b; extern (C++, ns1) { int bar() { return 2; } }

```
 
```
import a, b;
static assert(foo() == 1 && bar() == 2);

```
 works, but:

 
```
extern (C++, ns1) { int foo() { return 1; } }
extern (C++, ns1) { int bar() { return 2; } }

```
 does not. Additionally, aliases can be used to avoid collision of symbols:

 
```
module a; extern (C++, ns) { int foo() { return 1; } }

```
 
```
module b; extern (C++, ns) { int bar() { return 2; } }

```
 
```
module ns;
import a, b;
alias foo = a.ns.foo;
alias bar = b.ns.bar;

```
 
```
import ns;
static assert(foo() == 1 && bar() == 2);

```
 Classes
-------

 C++ classes can be declared in D by using the `extern (C++)` attribute on `class`, `struct` and `interface` declarations. `extern (C++)` interfaces have the same restrictions as D interfaces, which means that Multiple Inheritance is supported to the extent that only one base class can have member fields.

 `extern (C++)` structs do not support virtual functions but can be used to map C++ value types.

 Unlike classes and interfaces with D linkage, `extern (C++)` classes and interfaces are not rooted in `Object` and cannot be used with `typeid`.

 D structs and classes have different semantics whereas C++ structs and classes are basically the same. The use of a D struct or class depends on the C++ implementation and not on the used C++ keyword. When mapping a D `class` onto a C++ `struct`, use `extern(C++, struct)` to avoid linking problems with C++ compilers (notably MSVC) that distinguish between C++'s `class` and `struct` when mangling. Conversely, use `extern(C++, class)` to map a D `struct` onto a C++ `class`.

 `extern(C++, class)` and `extern(C++, struct)` can be combined with C++ namespaces:

 
```
extern (C++, struct) extern (C++, foo)
class Bar
{
}

```
 ### Using C++ Classes From D

 The following example shows binding of a pure virtual function, its implementation in a derived class, a non-virtual member function, and a member field:

 
```
#include <iostream>

using namespace std;

class Base
{
    public:
        virtual void print3i(int a, int b, int c) = 0;
};

class Derived : public Base
{
    public:
        int field;
        Derived(int field) : field(field) {}

        void print3i(int a, int b, int c)
        {
            cout << "a = " << a << endl;
            cout << "b = " << b << endl;
            cout << "c = " << c << endl;
        }

        int mul(int factor);
};

int Derived::mul(int factor)
{
    return field * factor;
}

Derived *createInstance(int i)
{
    return new Derived(i);
}

void deleteInstance(Derived *&d)
{
    delete d;
    d = 0;
}

```
 We can use it in D code like:

 
```
extern(C++)
{
    abstract class Base
    {
        void print3i(int a, int b, int c);
    }

    class Derived : Base
    {
        int field;
        @disable this();
        override void print3i(int a, int b, int c);
        final int mul(int factor);
    }

    Derived createInstance(int i);
    void deleteInstance(ref Derived d);
}

void main()
{
    import std.stdio;

    auto d1 = createInstance(5);
    writeln(d1.field);
    writeln(d1.mul(4));

    Base b1 = d1;
    b1.print3i(1, 2, 3);

    deleteInstance(d1);
    assert(d1 is null);

    auto d2 = createInstance(42);
    writeln(d2.field);

    deleteInstance(d2);
    assert(d2 is null);
}

```
 Compiling, linking, and running produces the output:

 
```
> g++ base.cpp
> dmd main.d base.o -L-lstdc++ && ./main
5
20
a = 1
b = 2
c = 3
42

```
 Note how in the above example, the constructor is not bindable and is instead disabled on the D side; an alternative would be to reimplement the constructor in D. See the [section below on lifetime management](cpp_interface#lifetime-management) for more information.

 ### Using D Classes From C++

 Given D code like:

 
```
extern (C++) int callE(E);

extern (C++) interface E
{
    int bar(int i, int j, int k);
}

class F : E
{
    extern (C++) int bar(int i, int j, int k)
    {
        import std.stdio : writefln;
        writefln("i = %s", i);
        writefln("j = %s", j);
        writefln("k = %s", k);
        return 8;
    }
}

void main()
{
    F f = new F();
    callE(f);
}

```
 The C++ code to access it looks like:

 
```
class E
{
  public:
    virtual int bar(int i, int j, int k);
};


int callE(E *e)
{
    return e->bar(11, 12, 13);
}

```
 
```
> dmd -c base.d
> g++ klass.cpp base.o -lphobos2 -pthread -o klass && ./klass
i = 11
j = 12
k = 13

```
 Structs
-------

 C++ allows a struct to inherit from a base struct. This is done in D using `alias this`:

 
```
struct Base { ... members ... };

struct Derived
{
    Base base;       // make it the first field
    alias base this;

    ... members ...
}

```
 In both C++ and D, if a struct has zero fields, the struct still has a size of 1 byte. But, in C++ if the struct with zero fields is used as a base struct, its size is zero (called the [Empty Base Optimization](https://en.cppreference.com/w/cpp/language/ebo)). There are two methods for emulating this behavior in D. The first forwards references to a function returning a faked reference to the base:

 
```
struct Base { ... members ... };

struct DerivedStruct
{
    static if (Base.tupleof.length > 0)
        Base base;
    else
        ref inout(Base) base() inout
        {
            return *cast(inout(Base)*)&this;
        }
    alias base this;

    ... members ...
}

```
 The second makes use of template mixins:

 
```
mixin template BaseMembers()
{
    void memberFunction() { ... }
}

struct Base
{
    mixin BaseMembers!();
}

struct Derived
{
    mixin BaseMembers!();

    ... members ...
}

```
 Note that the template mixin is evaluated in the context of its instantiation, not declaration. If this is a problem, the template mixin can use local imports, or have the member functions forward to the actual functions.

 C++ Templates
-------------

 C++ function and type templates can be bound by using the `extern (C++)` attribute on a function or type template declaration.

 Note that all instantiations used in D code must be provided by linking to C++ object code or shared libraries containing the instantiations.

 For example:

 
```
#include <iostream>

template<class T>
struct Foo
{
    private:
    T field;

    public:
    Foo(T t) : field(t) {}
    T get();
    void set(T t);
};

template<class T>
T Foo<T>::get()
{
    return field;
}

template<class T>
void Foo<T>::set(T t)
{
    field = t;
}

Foo<int> makeIntFoo(int i)
{
    return Foo<int>(i);
}

Foo<char> makeCharFoo(char c)
{
    return Foo<char>(c);
}

template<class T>
void increment(Foo<T> &foo)
{
    foo.set(foo.get() + 1);
}

template<class T>
void printThreeNext(Foo<T> foo)
{
    for(size_t i = 0; i < 3; ++i)
    {
        std::cout << foo.get() << std::endl;
        increment(foo);
    }
}

// The following two functions ensure that the required instantiations of
// printThreeNext are provided by this code module
void printThreeNexti(Foo<int> foo)
{
    printThreeNext(foo);
}

void printThreeNextc(Foo<char> foo)
{
    printThreeNext(foo);
}

```
 
```
extern(C++):
struct Foo(T)
{
    private:
    T field;

    public:
    @disable this();
    T get();
    void set(T t);
}

Foo!int makeIntFoo(int i);
Foo!char makeCharFoo(char c);
void increment(T)(ref Foo!T foo);
void printThreeNext(T)(Foo!T foo);

extern(D) void main()
{
    auto i = makeIntFoo(42);
    assert(i.get() == 42);
    i.set(1);
    increment(i);
    assert(i.get() == 2);

    auto c = makeCharFoo('a');
    increment(c);
    assert(c.get() == 'b');

    c.set('A');
    printThreeNext(c);
}

```
 Compiling, linking, and running produces the output:

 
```
> g++ -c template.cpp
> dmd main.d template.o -L-lstdc++ && ./main
A
B
C

```
 Function Overloading
--------------------

 C++ and D follow different rules for function overloading. D source code, even when calling `extern (C++)` functions, will still follow D overloading rules. 

 Memory Allocation
-----------------

 C++ code explicitly manages memory with calls to `::operator new()` and `::operator delete()`. D's `new` operator allocates memory using the D garbage collector, so no explicit delete is necessary. D's `new` operator is not compatible with C++'s `::operator new` and `::operator delete`. Attempting to allocate memory with D's `new` and deallocate with C++ `::operator delete` will result in miserable failure. 

 D can explicitly manage memory using a variety of library tools, such as with [`std.experimental.allocator`](https://dlang.org/phobos/std_experimental_allocator.html). Additionally, `core.stdc.stdlib.malloc` and `core.stdc.stdlib.free` can be used directly for connecting to C++ functions that expect `malloc`'d buffers. 

 If pointers to memory allocated on the D garbage collector heap are passed to C++ functions, it's critical to ensure that the referenced memory will not be collected by the D garbage collector before the C++ function is done with it. This is accomplished by: 

 * Making a copy of the data using [`std.experimental.allocator`](https://dlang.org/phobos/std_experimental_allocator.html) or `core.stdc.stdlib.malloc` and passing the copy instead.
* Leaving a pointer to it on the stack (as a parameter or automatic variable), as the garbage collector will scan the stack.
* Leaving a pointer to it in the static data segment, as the garbage collector will scan the static data segment.
* Registering the pointer with the garbage collector using the `core.memory.GC.addRoot` or `core.memory.GC.addRange` functions.

 An interior pointer to the allocated memory block is sufficient to let the GC know the object is in use; i.e. it is not necessary to maintain a pointer to the *beginning* of the allocated memory. 

 The garbage collector does not scan the stacks of threads not registered with the D runtime, nor does it scan the data segments of shared libraries that aren't registered with the D runtime. 

 Data Type Compatibility
-----------------------

 

D And C++ Type Equivalence| **D type** | **C++ type** |
|  void |  void  |
|  byte |  signed char  |
|  ubyte |  unsigned char  |
|  char |  char (chars are unsigned in D)  |
| `core.stdc.stddef.wchar_t` | `wchar_t` |
|  short |  short  |
|  ushort |  unsigned short  |
|  int |  int  |
|  uint |  unsigned  |
|  long |  long long  |
|  ulong |  unsigned long long  |
| `core.stdc.config.cpp_long` |  long  |
| `core.stdc.config.cpp_ulong` |  unsigned long  |
|  float |  float  |
|  double |  double  |
|  real |  long double  |
| `extern (C++)` struct |  struct or class  |
| `extern (C++)` class |  struct or class  |
| `extern (C++)` interface |  struct or class with no member fields  |
|  union |  union  |
|  enum |  enum  |
| *type*\* | *type* \*  |
|  ref *type* (in parameter lists only) | *type* `&` |
| *type*[*dim*] | *type*[*dim*]  |
| *type*[*dim*]\* | *type*(\*)[*dim*]  |
| *type*[] |  no equivalent  |
| *type*[*type*] |  no equivalent  |
| *type* function(*parameters*) | *type*(\*)(*parameters*)  |
| *type* delegate(*parameters*) |  no equivalent  |

 These equivalents hold when the D and C++ compilers used are companions on the host platform.

 Packing and Alignment
---------------------

 D structs and unions are analogous to C's. 

 C code often adjusts the alignment and packing of struct members with a command line switch or with various implementation specific #pragmas. D supports explicit alignment attributes that correspond to the C compiler's rules. Check what alignment the C code is using, and explicitly set it for the D struct declaration. 

 D supports bitfields in the standard library: see [`std.bitmanip.bitfields`](https://dlang.org/phobos/std_bitmanip.html#bitfields). 

 Lifetime Management
-------------------

 C++ constructors, copy constructors, move constructors and destructors cannot be called directly in D code, and D constructors, postblit operators and destructors cannot be directly exported to C++ code. Interoperation of types with these special operators is possible by either 1) disabling the operator in the client language and only using it in the host language, or 2) faithfully reimplementing the operator in the client language. With the latter approach, care needs to be taken to ensure observable semantics remain the same with both implementations, which can be difficult, or in some edge cases impossible, due to differences in how the operators work in the two languages. For example, in D all objects are movable and there is no move constructor.

 Special Member Functions
------------------------

 D cannot directly call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators. 

 Runtime Type Identification
---------------------------

 D runtime type identification uses completely different techniques than C++. The two are incompatible.

 Exception Handling
------------------

 Exception interoperability is a work in progress.

 At present, C++ exceptions cannot be caught in or thrown from D, and D exceptions cannot be caught in or thrown from C++. Additionally, objects in C++ stack frames are not guaranteed to be destroyed when unwinding the stack due to a D exception, and vice versa.

 The plan is to support all of the above except throwing D exceptions directly in C++ code (but they will be throwable indirectly by calling into a D function with C++ linkage).

 Comparing D Immutable and Const with C++ Const
----------------------------------------------

 

Const, Immutable Comparison| **Feature** | **D** | **C++98** |
| `const` keyword | Yes | Yes |
| `immutable` keyword | Yes | No |
| const notation | 
```
// Functional:
//ptr to const ptr to const int
const(int*)* p;

```
 | 
```
// Postfix:
//ptr to const ptr to const int
const int *const *p;

```
 |
| transitive const | 
```
// Yes:
//const ptr to const ptr to const int
const int** p;
**p = 3; // error

```
 | 
```
// No:
// const ptr to ptr to int
int** const p;
**p = 3;    // ok

```
 |
| cast away const | 
```
// Yes:
// ptr to const int
const(int)* p;
int* q = cast(int*)p; // ok

```
 | 
```
// Yes:
// ptr to const int
const int* p;
int* q = const_cast<int*>p; //ok

```
 |
| cast+mutate | 
```
// No:
// ptr to const int
const(int)* p;
int* q = cast(int*)p;
*q = 3;   // undefined behavior

```
 | 
```
// Yes:
// ptr to const int
const int* p;
int* q = const_cast<int*>p;
*q = 3;   // ok

```
 |
| overloading | 
```
// Yes:
void foo(int x);
void foo(const int x);  //ok

```
 | 
```
// No:
void foo(int x);
void foo(const int x);  //error

```
 |
| const/mutable aliasing | 
```
// Yes:
void foo(const int* x, int* y)
{
    bar(*x); // bar(3)
    *y = 4;
    bar(*x); // bar(4)
}
...
int i = 3;
foo(&i, &i);

```
 | 
```
// Yes:
void foo(const int* x, int* y)
{
    bar(*x); // bar(3)
    *y = 4;
    bar(*x); // bar(4)
}
...
int i = 3;
foo(&i, &i);

```
 |
| immutable/mutable aliasing | 
```
// No:
void foo(immutable int* x, int* y)
{
    bar(*x); // bar(3)
    *y = 4;  // undefined behavior
    bar(*x); // bar(??)
}
...
int i = 3;
foo(cast(immutable)&i, &i);

```
 |  No immutables  |
| type of string literal | `immutable(char)[]` | `const char*` |
| string literal to non-const |  not allowed |  allowed, but deprecated  |

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/cpp_interface.html>

Memory-Safe-D-Spec
==================

 **Contents** 1. [Usage](#usage)
	1. [Scope and Return Parameters](#scope-return-params)
2. [Limitations](#limitations)

 ![D-Man in rain] for a rationale. 

 Memory-safe code [cannot use certain language features](function#function-safety), such as:

 * Casts that break the type system.
* Modification of pointer values.
* Taking the address of a local variable or function parameter.

 Usage
-----

 There are three categories of functions from the perspective of memory safety:

 * [`@safe`](function#safe-functions) functions
* [`@trusted`](function#trusted-functions) functions
* [`@system`](function#system-functions) functions

 `@system` functions may perform any operation legal from the perspective of the language including inherently memory unsafe operations like returning pointers to expired stackframes. These functions may not be called directly from `@safe` functions.

 `@trusted` functions have all the capabilities of `@system` functions but may be called from `@safe` functions. For this reason they should be very limited in the scope of their use. Typical uses of `@trusted` functions include wrapping system calls that take buffer pointer and length arguments separately so that @safe` functions may call them with arrays.

 `@safe` functions have a number of restrictions on what they may do and are intended to disallow operations that may cause memory corruption. See [`@safe` functions](function#safe-functions).

 These attributes may be inferred when the compiler has the function body available, such as with templates.

 Array bounds checks are necessary to enforce memory safety, so these are enabled (by default) for `@safe` code even in **-release** mode. 

 ### Scope and Return Parameters

 The function parameter attributes `return` and `scope` are used to track what happens to low-level pointers passed to functions. Such pointers include: raw pointers, arrays, `this`, classes, `ref` parameters, delegate/lazy parameters, and aggregates containing a pointer.

 `scope` ensures that no references to the pointed-to object are retained, in global variables or pointers passed to the function (and recursively to other functions called in the function), as a result of calling the function. Variables in the function body and parameter list that are `scope` may have their allocations elided as a result.

 `return` indicates that either the return value of the function or the first parameter is a pointer derived from the `return` parameter or any other parameters also marked `return`. For constructors, `return` applies to the (implicitly returned) `this` reference. For void functions, `return` applies to the first parameter *iff* it is `ref`; this is to support UFCS, property setters and non-member functions (e.g. `put` used like `put(dest, source)`).

 These attributes may appear after the formal parameter list, in which case they apply either to a method's `this` parameter, or to a free function's first parameter *iff* it is `ref`. `return` or `scope` is ignored when applied to a type that is not a low-level pointer.

 **Note:** Checks for `scope` parameters are currently enabled only for `@safe` code compiled with the `-dip1000` command-line flag.

 Limitations
-----------

 Memory safety does not imply that code is portable, uses only sound programming practices, is free of byte order dependencies, or other bugs. It is focussed only on eliminating memory corruption possibilities. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/memory-safe-d.html>

Better C
========

 **Contents** 1. [Retained Features](#retained)
	1. [Running unittests in `-betterC`](#unittests)
2. [Unavailable Features](#consequences)

 It is straightforward to link C functions and libraries into D programs. But linking D functions and libraries into C programs is not straightforward. 

 D programs generally require:

 1. The D runtime library to be linked in, because many features of the core language require runtime library support.
2. The `main()` function to be written in D, to ensure that the required runtime library support is properly initialized.

 To link D functions and libraries into C programs, it's necessary to only require the C runtime library to be linked in. This is accomplished by defining a subset of D that fits this requirement, called **BetterC**. 

 **Implementation Defined:** **BetterC** is typically enabled by setting the *-betterC* command line flag for the implementation. When **BetterC** is enabled, the predefined <version> `D_BetterC` can be used for conditional compilation. 

 An entire program can be written in **BetterC** by supplying a C `main()` function:

 
```
extern(C) void main()
{
    import core.stdc.stdio : printf;
    printf("Hello betterC\n");
}

```
 
```
> dmd -betterC hello.d && ./hello
Hello betterC

```
 Limiting a program to this subset of runtime features is useful when targeting constrained environments where the use of such features is not practical or possible. 

 **BetterC** makes embedding D libraries in existing larger projects easier by: 

 1. Simplifying the process of integration at the build-system level
2. Removing the need to ensure that Druntime is properly initialized on calls to the library, for situations when an initialization step is not performed or would be difficult to insert before the library is used.
3. Mixing memory management strategies (GC + manual memory management) can be tricky, hence removing D's GC from the equation may be worthwhile sometimes.

 Retained Features
-----------------

 Nearly the full language remains available. Highlights include:

 1. Unrestricted use of compile-time features
2. Full metaprogramming facilities
3. Nested functions, nested structs, delegates and [lambdas](expression#function_literals)
4. Member functions, constructors, destructors, operating overloading, etc.
5. The full module system
6. Array slicing, and array bounds checking
7. RAII (yes, it can work without exceptions)
8. `scope(exit)`
9. Memory safety protections
10. Interfacing with C++
11. COM classes and C++ classes
12. `assert` failures are directed to the C runtime library
13. `switch` with strings
14. `final switch`
15. `unittest`
16. [`printf` format validation](interfacetoc#calling_printf)

 ### Running unittests in `-betterC`

 While, testing can be done without the *-betterC* flag, it is sometimes desirable to run the testsuite in `-betterC` too. `unittest` blocks can be listed with the [`getUnitTests`](traits#getUnitTests) trait: 
```
unittest
{
   assert(0);
}

extern(C) void main()
{
    static foreach(u; __traits(getUnitTests, __traits(parent, main)))
        u();
}

```
 
```
> dmd -betterC -unittest -run test.d
dmd_runpezoXK: foo.d:3: Assertion `0' failed.

```
 However, in `-betterC` `assert` expressions don't use Druntime's assert and are directed to `assert` of the C runtime library instead. Unavailable Features
--------------------

 D features not available with **BetterC**:

 1. Garbage Collection
2. TypeInfo and ModuleInfo
3. Classes
4. Built-in threading (e.g. [`core.thread`](https://dlang.org/phobos/core_thread.html))
5. Dynamic arrays (though slices of static arrays work) and associative arrays
6. Exceptions
7. `synchronized` and [`core.sync`](https://dlang.org/phobos/core_sync.html)
8. Static module constructors or destructors

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/betterc.html>

Named Character Entities
========================

 **Contents** 
```
NamedCharacterEntity:
    & Identifier ;

```
 The full list of named character entities from the [HTML 5 Spec](https://w3.org/TR/html5/syntax.html#named-character-references) is supported except for the named entities which contain multiple code points. Below is a *partial* list of the named character entities. 

 **Note:** Not all glyphs will display properly in the **Glyph** column in all browsers. 

 

Named Character Entities| **Name** | **Value** | **Glyph** |
| `quot` | 34 | " |
| `amp` | 38 | & |
| `lt` | 60 | `<` |
| `gt` | 62 | `>` |
| `OElig` | 338 | Œ |
| `oelig` | 339 | œ |
| `Scaron` | 352 | Š |
| `scaron` | 353 | š |
| `Yuml` | 376 | ÿ |
| `circ` | 710 | ˆ |
| `tilde` | 732 | ˜ |
| `ensp` | 8194 |  |
| `emsp` | 8195 |  |
| `thinsp` | 8201 |  |
| `zwnj` | 8204 | ‌ |
| `zwj` | 8205 | ‍ |
| `lrm` | 8206 | ‎ |
| `rlm` | 8207 | ‏ |
| `ndash` | 8211 | – |
| `mdash` | 8212 |  —  |
| `lsquo` | 8216 | ‘ |
| `rsquo` | 8217 | ’ |
| `sbquo` | 8218 | ‚ |
| `ldquo` | 8220 | “ |
| `rdquo` | 8221 | ” |
| `bdquo` | 8222 | „ |
| `dagger` | 8224 | † |
| `Dagger` | 8225 | ‡ |
| `permil` | 8240 | ‰ |
| `lsaquo` | 8249 | ‹ |
| `rsaquo` | 8250 | › |
| `euro` | 8364 | € |

   
 

Latin-1 (ISO-8859-1) Entities| **Name** | **Value** | **Glyph** |
| `nbsp` | 160 |  |
| `iexcl` | 161 | ¡ |
| `cent` | 162 | ¢ |
| `pound` | 163 | £ |
| `curren` | 164 | ¤ |
| `yen` | 165 | ¥ |
| `brvbar` | 166 | ¦ |
| `sect` | 167 | § |
| `uml` | 168 | ¨ |
| `copy` | 169 | © |
| `ordf` | 170 | ª |
| `laquo` | 171 | « |
| `not` | 172 | ¬ |
| `shy` | 173 | ­ |
| `reg` | 174 | ® |
| `macr` | 175 | ¯ |
| `deg` | 176 | ° |
| `plusmn` | 177 | ± |
| `sup2` | 178 | ² |
| `sup3` | 179 | ³ |
| `acute` | 180 | ´ |
| `micro` | 181 | µ |
| `para` | 182 | ¶ |
| `middot` | 183 | · |
| `cedil` | 184 | ¸ |
| `sup1` | 185 | ¹ |
| `ordm` | 186 | º |
| `raquo` | 187 | » |
| `frac14` | 188 | ¼ |
| `frac12` | 189 | ½ |
| `frac34` | 190 | ¾ |
| `iquest` | 191 | ¿ |
| `Agrave` | 192 | À |
| `Aacute` | 193 | Á |
| `Acirc` | 194 | Â |
| `Atilde` | 195 | Ã |
| `Auml` | 196 | Ä |
| `Aring` | 197 | Å |
| `AElig` | 198 | Æ |
| `Ccedil` | 199 | Ç |
| `Egrave` | 200 | È |
| `Eacute` | 201 | É |
| `Ecirc` | 202 | Ê |
| `Euml` | 203 | Ë |
| `Igrave` | 204 | Ì |
| `Iacute` | 205 | Í |
| `Icirc` | 206 | Î |
| `Iuml` | 207 | Ï |
| `ETH` | 208 | Ð |
| `Ntilde` | 209 | Ñ |
| `Ograve` | 210 | Ò |
| `Oacute` | 211 | Ó |
| `Ocirc` | 212 | Ô |
| `Otilde` | 213 | Õ |
| `Ouml` | 214 | Ö |
| `times` | 215 | × |
| `Oslash` | 216 | Ø |
| `Ugrave` | 217 | Ù |
| `Uacute` | 218 | Ú |
| `Ucirc` | 219 | Û |
| `Uuml` | 220 | Ü |
| `Yacute` | 221 | Ý |
| `THORN` | 222 | Þ |
| `szlig` | 223 | ß |
| `agrave` | 224 | à |
| `aacute` | 225 | á |
| `acirc` | 226 | â |
| `atilde` | 227 | ã |
| `auml` | 228 | ä |
| `aring` | 229 | å |
| `aelig` | 230 | æ |
| `ccedil` | 231 | ç |
| `egrave` | 232 | è |
| `eacute` | 233 | é |
| `ecirc` | 234 | ê |
| `euml` | 235 | ë |
| `igrave` | 236 | ì |
| `iacute` | 237 | í |
| `icirc` | 238 | î |
| `iuml` | 239 | ï |
| `eth` | 240 | ð |
| `ntilde` | 241 | ñ |
| `ograve` | 242 | ò |
| `oacute` | 243 | ó |
| `ocirc` | 244 | ô |
| `otilde` | 245 | õ |
| `ouml` | 246 | ö |
| `divide` | 247 | ÷ |
| `oslash` | 248 | ø |
| `ugrave` | 249 | ù |
| `uacute` | 250 | ú |
| `ucirc` | 251 | û |
| `uuml` | 252 | ü |
| `yacute` | 253 | ý |
| `thorn` | 254 | þ |
| `yuml` | 255 | ÿ |

   
 

Symbols and Greek letter entities| **Name** | **Value** | **Glyph** |
| `fnof` | 402 | ƒ |
| `Alpha` | 913 | Α |
| `Beta` | 914 | Β |
| `Gamma` | 915 | Γ |
| `Delta` | 916 | Δ |
| `Epsilon` | 917 | Ε |
| `Zeta` | 918 | Ζ |
| `Eta` | 919 | Η |
| `Theta` | 920 | Θ |
| `Iota` | 921 | Ι |
| `Kappa` | 922 | Κ |
| `Lambda` | 923 | Λ |
| `Mu` | 924 | Μ |
| `Nu` | 925 | Ν |
| `Xi` | 926 | Ξ |
| `Omicron` | 927 | Ο |
| `Pi` | 928 | Π |
| `Rho` | 929 | Ρ |
| `Sigma` | 931 | Σ |
| `Tau` | 932 | Τ |
| `Upsilon` | 933 | Υ |
| `Phi` | 934 | Φ |
| `Chi` | 935 | Χ |
| `Psi` | 936 | Ψ |
| `Omega` | 937 | Ω |
| `alpha` | 945 | α |
| `beta` | 946 | β |
| `gamma` | 947 | γ |
| `delta` | 948 | δ |
| `epsilon` | 949 | ε |
| `zeta` | 950 | ζ |
| `eta` | 951 | η |
| `theta` | 952 | θ |
| `iota` | 953 | ι |
| `kappa` | 954 | κ |
| `lambda` | 955 | λ |
| `mu` | 956 | μ |
| `nu` | 957 | ν |
| `xi` | 958 | ξ |
| `omicron` | 959 | ο |
| `pi` | 960 | π |
| `rho` | 961 | ρ |
| `sigmaf` | 962 | ς |
| `sigma` | 963 | σ |
| `tau` | 964 | τ |
| `upsilon` | 965 | υ |
| `phi` | 966 | φ |
| `chi` | 967 | χ |
| `psi` | 968 | ψ |
| `omega` | 969 | ω |
| `thetasym` | 977 | ϑ |
| `upsih` | 978 | ϒ |
| `piv` | 982 | ϖ |
| `bull` | 8226 | • |
| `hellip` | 8230 | … |
| `prime` | 8242 | ′ |
| `Prime` | 8243 | ″ |
| `oline` | 8254 | ‾ |
| `frasl` | 8260 | ⁄ |
| `weierp` | 8472 | ℘ |
| `image` | 8465 | ℑ |
| `real` | 8476 | ℜ |
| `trade` | 8482 | ™ |
| `alefsym` | 8501 | ℵ |
| `larr` | 8592 | ← |
| `uarr` | 8593 | ↑ |
| `rarr` | 8594 | → |
| `darr` | 8595 | ↓ |
| `harr` | 8596 | ↔ |
| `crarr` | 8629 | ↵ |
| `lArr` | 8656 | ⇐ |
| `uArr` | 8657 | ⇑ |
| `rArr` | 8658 | ⇒ |
| `dArr` | 8659 | ⇓ |
| `hArr` | 8660 | ⇔ |
| `forall` | 8704 | ∀ |
| `part` | 8706 | ∂ |
| `exist` | 8707 | ∃ |
| `empty` | 8709 | ∅ |
| `nabla` | 8711 | ∇ |
| `isin` | 8712 | ∈ |
| `notin` | 8713 | ∉ |
| `ni` | 8715 | ∋ |
| `prod` | 8719 | ∏ |
| `sum` | 8721 | ∑ |
| `minus` | 8722 | − |
| `lowast` | 8727 | ∗ |
| `radic` | 8730 | √ |
| `prop` | 8733 | ∝ |
| `infin` | 8734 | ∞ |
| `ang` | 8736 | ∠ |
| `and` | 8743 | ∧ |
| `or` | 8744 | ∨ |
| `cap` | 8745 | ∩ |
| `cup` | 8746 | ∪ |
| `int` | 8747 | ∫ |
| `there4` | 8756 | ∴ |
| `sim` | 8764 | ∼ |
| `cong` | 8773 | ≅ |
| `asymp` | 8776 | ≈ |
| `ne` | 8800 | ≠ |
| `equiv` | 8801 | ≡ |
| `le` | 8804 | ≤ |
| `ge` | 8805 | ≥ |
| `sub` | 8834 | ⊂ |
| `sup` | 8835 | ⊃ |
| `nsub` | 8836 | ⊄ |
| `sube` | 8838 | ⊆ |
| `supe` | 8839 | ⊇ |
| `oplus` | 8853 | ⊕ |
| `otimes` | 8855 | ⊗ |
| `perp` | 8869 | ⊥ |
| `sdot` | 8901 | ⋅ |
| `lceil` | 8968 | ⌈ |
| `rceil` | 8969 | ⌉ |
| `lfloor` | 8970 | ⌊ |
| `rfloor` | 8971 | ⌋ |
| `loz` | 9674 | ◊ |
| `spades` | 9824 | ♠ |
| `clubs` | 9827 | ♣ |
| `hearts` | 9829 | ♥ |
| `diams` | 9830 | ♦ |
| `lang` | 10216 | 〈 |
| `rang` | 10217 | 〉 |

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/entity.html>

Vector Extensions
=================

 **Contents** 1. [`core.simd`](#core_simd)
	1. [Properties](#properties)
	2. [Conversions](#conversions)
	3. [Accessing Individual Vector Elements](#accessing_individual_elems)
	4. [Conditional Compilation](#conditional_compilation)
2. [X86 And X86\_64 Vector Extension Implementation](#x86_64_vec)
	1. [Vector Operation Intrinsics](#vector_op_intrinsics)

 CPUs often support specialized vector types and vector operations (a.k.a. *media instructions*). Vector types are a fixed array of floating or integer types, and vector operations operate simultaneously on them.

 Specialized [*Vector*](type#Vector) types provide access to them.

 The [*VectorBaseType*](type#VectorBaseType) must be a [Static Array](https://dlang.org/arrays.html#static-arrays). The VectorElementType is the unqualified element type of the static array. The dimension of the static array is the number of elements in the vector. 

 **Implementation Defined:** Which vector types are supported depends on the target. The implementation is expected to only support the vector types that are implemented in the target's hardware. **Best Practices:** Use the declarations in [`core.simd`](https://dlang.org/phobos/core_simd.html) instead of the language [*Vector*](type#Vector) grammar. `core.simd`
-----------

 Vector types and operations are introduced by importing [`core.simd`](https://dlang.org/phobos/core_simd.html):

 
```
import core.simd;

```
 **Implementation Defined:** These types and operations will be the ones defined for the architecture the compiler is targeting. If a particular CPU family has varying support for vector types, an additional runtime check may be necessary. The compiler does not emit runtime checks; those must be done by the programmer. 

 Depending on the architecture, compiler flags may be required to activate support for SIMD types. 

 The types defined will all follow the naming convention:

 
```
typeNN

```
 where *type* is the vector element type and *NN* is the number of those elements in the vector type. The type names will not be keywords. ### Properties

 Vector types have the property:

 

Vector Type Properties| **Property** | **Description** |
| .array | Returns static array representation |

 Vectors support the following properties based on the vector element type. The value produced is that of a vector of the same type with each element set to the value corresponding to the property value for the element type.

 

Integral Vector Type Properties| **Property** | **Description** |
| .min | minimum value |
| .max | maximum value |

 

Floating Point Vector Type Properties| **Property** | **Description** |
| .epsilon | smallest increment to the value 1 |
| .infinity | infinity value |
| .max | largest representable value that is not infinity |
| .min\_normal | smallest representable value that is not 0 |
| .nan | NaN value |

 ### Conversions

 Vector types of the same size can be implicitly converted among each other, this is done as a reinterpret cast (a type paint). Vector types can be cast to their [*VectorBaseType*](type#VectorBaseType).

 Integers and floating point values can be implicitly converted to their vector equivalents:

 
```
int4 v = 7;
v = 3 + v;   // add 3 to each element in v

```
 ### Accessing Individual Vector Elements

 They cannot be accessed directly, but can be when converted to an array type:

 
```
int4 v;
(cast(int*)&v)[3] = 2;   // set 3rd element of the 4 int vector
(cast(int[4])v)[3] = 2;  // set 3rd element of the 4 int vector
v.array[3] = 2;          // set 3rd element of the 4 int vector
v.ptr[3] = 2;            // set 3rd element of the 4 int vector

```
 ### Conditional Compilation

 If vector extensions are implemented, the [version identifier](version#PredefinedVersions) `D_SIMD` is set.

 Whether a type exists or not can be tested at compile time with an [*IsExpression*](expression#IsExpression): 

 
```
static if (is(typeNN))
    ... yes, it is supported ...
else
    ... nope, use workaround ...

```
 Whether a particular operation on a type is supported can be tested at compile time with: 

 
```
float4 a,b;
static if (__traits(compiles, a+b))
    ... yes, it is supported ...
else
    ... nope, use workaround ...

```
 For runtime testing to see if certain vector instructions are available, see the functions in [core.cpuid](https://dlang.org/phobos/core_cpuid.html). 

 A typical workaround would be to use array vector operations instead:

 
```
float4 a,b;
static if (__traits(compiles, a/b))
    c = a / b;
else
    c[] = a[] / b[];

```
 X86 And X86\_64 Vector Extension Implementation
-----------------------------------------------

 **Implementation Defined:** The following describes the specific implementation of the vector types for the X86 and X86\_64 architectures. 

 The vector extensions are currently implemented for the OS X 32 bit target, and all 64 bit targets.

 [`core.simd`](https://dlang.org/phobos/core_simd.html) defines the following types: 

 

Vector Types| **Type Name** | **Description** | **gcc Equivalent** |
| void16 | 16 bytes of untyped data | *no equivalent* |
| byte16 | 16 `byte`s | `signed char __attribute__((vector_size(16)))` |
| ubyte16 | 16 `ubyte`s | `unsigned char __attribute__((vector_size(16)))` |
| short8 | 8 `short`s | `short __attribute__((vector_size(16)))` |
| ushort8 | 8 `ushort`s | `ushort __attribute__((vector_size(16)))` |
| int4 | 4 `int`s | `int __attribute__((vector_size(16)))` |
| uint4 | 4 `uint`s | `unsigned __attribute__((vector_size(16)))` |
| long2 | 2 `long`s | `long __attribute__((vector_size(16)))` |
| ulong2 | 2 `ulong`s | `unsigned long __attribute__((vector_size(16)))` |
| float4 | 4 `float`s | `float __attribute__((vector_size(16)))` |
| double2 | 2 `double`s | `double __attribute__((vector_size(16)))` |
| void32 | 32 bytes of untyped data | *no equivalent* |
| byte32 | 32 `byte`s | `signed char __attribute__((vector_size(32)))` |
| ubyte32 | 32 `ubyte`s | `unsigned char __attribute__((vector_size(32)))` |
| short16 | 16 `short`s | `short __attribute__((vector_size(32)))` |
| ushort16 | 16 `ushort`s | `ushort __attribute__((vector_size(32)))` |
| int8 | 8 `int`s | `int __attribute__((vector_size(32)))` |
| uint8 | 8 `uint`s | `unsigned __attribute__((vector_size(32)))` |
| long4 | 4 `long`s | `long __attribute__((vector_size(32)))` |
| ulong4 | 4 `ulong`s | `unsigned long __attribute__((vector_size(32)))` |
| float8 | 8 `float`s | `float __attribute__((vector_size(32)))` |
| double4 | 4 `double`s | `double __attribute__((vector_size(32)))` |

 Note: for 32 bit gcc, it's `long long` instead of `long`.

 

Supported 128-bit Vector Operators| **Operator** | **void16** | **byte16** | **ubyte16** | **short8** | **ushort8** | **int4** | **uint4** | **long2** | **ulong2** | **float4** | **double2** |
| = | × | × | × | × | × | × | × | × | × | × | × |
| + | – | × | × | × | × | × | × | × | × | × | × |
| - | – | × | × | × | × | × | × | × | × | × | × |
| \* | – | – | – | × | × | – | – | – | – | × | × |
| / | – | – | – | – | – | – | – | – | – | × | × |
| `&` | – | × | × | × | × | × | × | × | × | – | – |
| | | – | × | × | × | × | × | × | × | × | – | – |
| `^` | – | × | × | × | × | × | × | × | × | – | – |
| += | – | × | × | × | × | × | × | × | × | × | × |
| -= | – | × | × | × | × | × | × | × | × | × | × |
| \*= | – | – | – | × | × | – | – | – | – | × | × |
| /= | – | – | – | – | – | – | – | – | – | × | × |
| `&`= | – | × | × | × | × | × | × | × | × | – | – |
| |= | – | × | × | × | × | × | × | × | × | – | – |
| `^=` | – | × | × | × | × | × | × | × | × | – | – |
| *unary*`~` | – | × | × | × | × | × | × | × | × | – | – |
| *unary*+ | – | × | × | × | × | × | × | × | × | × | × |
| *unary*- | – | × | × | × | × | × | × | × | × | × | × |

 

Supported 256-bit Vector Operators| **Operator** | **void32** | **byte32** | **ubyte32** | **short16** | **ushort16** | **int8** | **uint8** | **long4** | **ulong4** | **float8** | **double4** |
| = | × | × | × | × | × | × | × | × | × | × | × |
| + | – | × | × | × | × | × | × | × | × | × | × |
| - | – | × | × | × | × | × | × | × | × | × | × |
| \* | – | – | – | – | – | – | – | – | – | × | × |
| / | – | – | – | – | – | – | – | – | – | × | × |
| `&` | – | × | × | × | × | × | × | × | × | – | – |
| | | – | × | × | × | × | × | × | × | × | – | – |
| `^` | – | × | × | × | × | × | × | × | × | – | – |
| += | – | × | × | × | × | × | × | × | × | × | × |
| -= | – | × | × | × | × | × | × | × | × | × | × |
| \*= | – | – | – | – | – | – | – | – | – | × | × |
| /= | – | – | – | – | – | – | – | – | – | × | × |
| `&`= | – | × | × | × | × | × | × | × | × | – | – |
| |= | – | × | × | × | × | × | × | × | × | – | – |
| `^=` | – | × | × | × | × | × | × | × | × | – | – |
| *unary*`~` | – | × | × | × | × | × | × | × | × | – | – |
| *unary*+ | – | × | × | × | × | × | × | × | × | × | × |
| *unary*- | – | × | × | × | × | × | × | × | × | × | × |

 Operators not listed are not supported at all.

 ### Vector Operation Intrinsics

 See [`core.simd`](https://dlang.org/phobos/core_simd.html) for the supported intrinsics.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/simd.html>

Live Functions
==============

 **Contents** 1. [Ownership/Borrowing](#ob)
	1. [Tracked Pointers](#tracked)
	2. [Pointer States](#state)
	3. [Lifetimes](#lifetime)
	4. [Pointer State Transitions](#transition)
	5. [Borrowers can be Owners](#borrower)
	6. [Exceptions](#exception)
	7. [Lazy Parameters](#lazy)
	8. [Mixing Memory Pools](#mempool)
	9. [Variadic Function Arguments](#vargs)

 **Experimental, Subject to Change** If a memory object has only one pointer to it, that pointer is the *owner* of the memory object. With the single owner, it becomes straightforward to manage the memory for the object. It also becomes trivial to synchronize access to that memory object among multiple threads, because it can only be accessed by the thread that controls that single pointer. 

 This can be generalized to a graph of memory objects interconnected by pointers, where only a single pointer connects to that graph from elsewhere. That single pointer becomes the *owner* of all the memory objects in that graph. 

 When the owner of the graph is no longer needed, then the graph of memory objects it points to is no longer needed and can be safely disposed of. If the owner itself is no longer in use (i.e. is no longer *live*) and the owned memory objects are not disposed of, an error can be diagnosed. 

 Hence, the following errors can be statically detected: 

 
```
int* allocate();    // allocate a memory object
void release(int*); // deallocate a memory object

@live void test()
{
    auto p = allocate();
}   // error: p is not disposed of

@live void test()
{
    auto p = allocate();
    release(p);
    release(p); // error: p was already disposed of
}

@live void test()
{
    int* p = void;
    release(p); // error, p does not have a defined value
}

@live void test()
{
    auto p = allocate();
    p = allocate(); // error: p was not disposed of
    release(p);
}

```
 Functions with the `@live` attribute enable diagnosing these sorts of errors by tracking the status of owner pointers. 

 Ownership/Borrowing
-------------------

 Tracking the ownership status of a pointer can be safely extended by adding the capability of temporarilly *borrowing* ownership of a pointer from the *owner*. The *owner* can no longer use the pointer as long as the *borrower* is still using the pointer value (i.e. is *live*). Once the *borrower* is no longer *live*, the *owner* and resume using it. Only one *borrower* can be live at any point. 

 Multiple *borrower* pointers can simultaneously exist if all of them are pointers to read only (`const` or `immutable`) data, i.e. none of them can modify the memory object(s) pointed to. 

 This is collectively called an *Ownership/Borrowing* system. It can be state as: 

 
> At any point in the program, for each memory object, there is exactly one live mutable pointer to it or all the live pointers to it are read-only.
> 
> 

 Function declarations annotated with the `@live` attribute are checked for compliance with the Ownership/Borrowing rules. The checks are run after other semantic processing is complete. The checking does not influence code generation. 

 Whether a pointer is allocated memory using the GC or some other storage allocator is immaterial to OB, they are not distinguished and are handled identically. 

 Class references are assumed to be allocated using either the GC or are allocated on the stack as `scope` classes, and are not tracked. 

 If `@live` functions call non-`@live` functions, those called functions are expected to present an `@live` compatible interface, although it is not checked. if non-`@live` functions call `@live` functions, arguments passed are expected to follow `@live` conventions. 

 It will not detect attempts to dereference `null` pointers or possibly `null` pointers. This is unworkable because there is no current method of annotating a type as a non-`null` pointer. 

 ### Tracked Pointers

 The only pointers that are tracked are those declared in the `@live` function as `this`, function parameters or local variables. Variables from other functions are not tracked, even `@live` ones, as the analysis of interactions with other functions depends entirely on that function signature, not its internals. Parameters that are `const` are not tracked. 

 ### Pointer States

 Each tracked pointer is in one of the following states: 

 
Undefined The pointer is in an invalid state. Dereferencing such a pointer is an error. Owner The owner is the sole pointer to a memory object graph. An Owner pointer normally does not have a `scope` attribute. If a pointer with the `scope` attribute is initialized with an expression not derived from a tracked pointer, it is an Owner. If an Owner pointer is assigned to another Owner pointer, the former enters the Undefined state.  Borrowed A Borrowed pointer is one that temporarily becomes the sole pointer to a memory object graph. It enters that state via assignment from an owner pointer, and stays in that state until its last use. A Borrowed pointer must have the `scope` attribute and must be a pointer to mutable.  Readonly A Readonly pointer acquires its value from an Owner. While the Readonly pointer is live, only Readonly pointers can be acquired from that Owner. A Readonly pointer must have the `scope` attribute and also must not be a pointer to mutable.   ### Lifetimes

 The lifetime of a Borrowed or Readonly pointer value starts when it is assigned a value from an Owner or another Borrowed pointer, and ends at the last read of that value. 

 This is also known as *Non-Lexical Lifetimes*. 

 ### Pointer State Transitions

 A pointer changes its state when one of these operations is done to it: 

 * storage is allocated for it (such as a local variable on the stack), which places the pointer in the Undefined state
* initialization (treated as assignment)
* assignment - the source and target pointers change state based on what states they are in and their types and storage classes
* passed to an `out` function parameter (changes state after the function returns), treated the same as initialization
* passed by `ref` to a function parameter, treated as an assignment to a Borrow or a Readonly depending on the storage class and type of the parameter
* returned from a function
* it is passed by value to a function parameter, which is treated as an assignment to that parameter.
* it is implicitly passed by ref as a closure variable to a nested function
* the address of the pointer is taken, which is treated as assignment to whoever receives the address
* the address of any part of the memory object graph is taken, which is treated as assignment to whoever receives that address
* a pointer value is read from any part of the memory object graph, which is treated as assignment to whoever receives that pointer
* merging of control flow reconciles the state of each variable based on the states they have from each edge

 ### Borrowers can be Owners

 Borrowers are considered Owners if they are initialized from other than a pointer. 

 
```
@live void uhoh()
{
    scope p = malloc();  // p is considered an Owner
    scope const pc = malloc(); // pc is not considered an Owner
} // dangling pointer pc is not detected on exit


```
 ### Exceptions

 The analysis assumes no exceptions are thrown. 

 
```
@live void leaky()
{
    auto p = malloc();
    pitcher();  // throws exception, p leaks
    free(p);
}

```
 One solution is to use `scope(exit)`: 

 
```
@live void waterTight()
{
    auto p = malloc();
    scope(exit) free(p);
    pitcher();
}

```
 or use RAII objects or call only `nothrow` functions. 

 ### Lazy Parameters

 Lazy parameters are not considered. 

 ### Mixing Memory Pools

 Conflation of different memory pools: 

 
```
void* xmalloc(size_t);
void xfree(void*);

void* ymalloc(size_t);
void yfree(void*);

auto p = xmalloc(20);
yfree(p);  // should call xfree() instead

```
 is not detected. 

 This can be mitigated by using type-specific pools: 

 
```
U* umalloc();
void ufree(U*);

V* vmalloc();
void vfree(V*);

auto p = umalloc();
vfree(p);  // type mismatch

```
 and perhaps disabling implicit conversions to `void*` in `@live` functions. 

 ### Variadic Function Arguments

 Arguments to variadic functions (such as `printf`) are considered to be consumed. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/ob.html>

Application Binary Interface
============================

 **Contents** 1. [C ABI](#c_abi)
2. [Endianness](#endianness)
3. [Basic Types](#basic_types)
4. [Delegates](#delegates)
5. [Structs](#structs)
6. [Classes](#classes)
7. [Interfaces](#interfaces)
8. [Arrays](#arrays)
9. [Associative Arrays](#associative_arrays)
10. [Reference Types](#references_types)
11. [Name Mangling](#name_mangling)
	1. [Back references](#back_ref)
	2. [Type Mangling](#type_mangling)
12. [Function Calling Conventions](#function_calling_conventions)
	1. [Register Conventions](#register_conventions)
	2. [Return Value](#return_value)
	3. [Parameters](#parameters)
13. [Exception Handling](#exception_handling)
	1. [Windows](#windows_eh)
	2. [Linux, FreeBSD and OS X](#ninux_fbsd_osx_eh)
14. [Garbage Collection](#garbage_collection)
15. [Runtime Helper Functions](#runtime_helper_functions)
16. [Module Initialization and Termination](#module_init_and_fina)
17. [Unit Testing](#unit_testing)
18. [Symbolic Debugging](#symbolic_debugging)
	1. [Codeview Debugger Extensions](#codeview)

 A D implementation that conforms to the D ABI (Application Binary Interface) will be able to generate libraries, DLLs, etc., that can interoperate with D binaries built by other implementations. 

 C ABI
-----

 The C ABI referred to in this specification means the C Application Binary Interface of the target system. C and D code should be freely linkable together, in particular, D code shall have access to the entire C ABI runtime library. 

 Endianness
----------

 The [endianness](https://en.wikipedia.org/wiki/Endianness) (byte order) of the layout of the data will conform to the endianness of the target machine. The Intel x86 CPUs are *little endian* meaning that the value 0x0A0B0C0D is stored in memory as: `0D 0C 0B 0A`. 

 Basic Types
-----------

 

|  |  |
| --- | --- |
| bool | 8 bit byte with the values 0 for false and 1 for true |
| byte | 8 bit signed value |
| ubyte | 8 bit unsigned value |
| short | 16 bit signed value |
| ushort | 16 bit unsigned value |
| int | 32 bit signed value |
| uint | 32 bit unsigned value |
| long | 64 bit signed value |
| ulong | 64 bit unsigned value |
| cent | 128 bit signed value |
| ucent | 128 bit unsigned value |
| float | 32 bit IEEE 754 floating point value |
| double | 64 bit IEEE 754 floating point value |
| real | implementation defined floating point value, for x86 it is 80 bit IEEE 754 extended real |

 Delegates
---------

 Delegates are *fat pointers* with two parts:

 

Delegate Layout| **offset** | **property** | **contents** |
| `0` | `.ptr` | context pointer |
| *ptrsize* | `.funcptr` | pointer to function |

 The *context pointer* can be a class *this* reference, a struct *this* pointer, a pointer to a closure (nested functions) or a pointer to an enclosing function's stack frame (nested functions). 

 Structs
-------

 Conforms to the target's C ABI struct layout.

 Classes
-------

 An object consists of:

 

Class Object Layout| **size** | **property** | **contents** |
| *ptrsize* | `.__vptr` | pointer to vtable |
| *ptrsize* | `.__monitor` | monitor |
| *ptrsize*... |  | vptrs for any interfaces implemented by this class in left to right, most to least derived, order |
| `...` | `...` | super's non-static fields and super's interface vptrs, from least to most derived |
| `...` | named fields | non-static fields |

 The vtable consists of:

 

Virtual Function Pointer Table Layout| **size** | **contents** |
| *ptrsize* | pointer to instance of TypeInfo |
| *ptrsize*... | pointers to virtual member functions |

 Casting a class object to an interface consists of adding the offset of the interface's corresponding vptr to the address of the base of the object. Casting an interface ptr back to the class type it came from involves getting the correct offset to subtract from it from the object.Interface entry at vtbl[0]. Adjustor thunks are created and pointers to them stored in the method entries in the vtbl[] in order to set the this pointer to the start of the object instance corresponding to the implementing method. 

 An adjustor thunk looks like:

 
```
  ADD EAX,offset
  JMP method

```
 The leftmost side of the inheritance graph of the interfaces all share their vptrs, this is the single inheritance model. Every time the inheritance graph forks (for multiple inheritance) a new vptr is created and stored in the class' instance. Every time a virtual method is overridden, a new vtbl[] must be created with the updated method pointers in it. 

 The class definition:

 
```
class XXXX
{
    ....
};

```
 Generates the following:

 * An instance of Class called ClassXXXX.
* A type called StaticClassXXXX which defines all the static members.
* An instance of StaticClassXXXX called StaticXXXX for the static members.

 Interfaces
----------

 An interface is a pointer to a pointer to a vtbl[]. The vtbl[0] entry is a pointer to the corresponding instance of the object.Interface class. The rest of the `vtbl[1..$]` entries are pointers to the virtual functions implemented by that interface, in the order that they were declared. 

 A COM interface differs from a regular interface in that there is no object.Interface entry in `vtbl[0]`; the entries `vtbl[0..$]` are all the virtual function pointers, in the order that they were declared. This matches the COM object layout used by Windows. 

 A C++ interface differs from a regular interface in that it matches the layout of a C++ class using single inheritance on the target machine. 

 Arrays
------

 A dynamic array consists of:

 

Dynamic Array Layout| **offset** | **property** | **contents** |
| `0` | `.length` | array dimension |
| `size_t` | `.ptr` | pointer to array data |

 A dynamic array is declared as:

 
```
type[] array;

```
 whereas a static array is declared as: 
```
type[dimension] array;

```
 Thus, a static array always has the dimension statically available as part of the type, and so it is implemented like in C. Static arrays and Dynamic arrays can be easily converted back and forth to each other. 

 Associative Arrays
------------------

 Associative arrays consist of a pointer to an opaque, implementation defined type.

 The current implementation is contained in and defined by [rt/aaA.d](https://github.com/dlang/druntime/blob/master/src/rt/aaA.d). 

 Reference Types
---------------

 D has reference types, but they are implicit. For example, classes are always referred to by reference; this means that class instances can never reside on the stack or be passed as function parameters. 

 Name Mangling
-------------

 D accomplishes typesafe linking by *mangling* a D identifier to include scope and type information. 

 
```
MangledName:
    _D QualifiedName Type
    _D QualifiedName Z        // Internal

```
 The [*Type*](#Type) above is the type of a variable or the return type of a function. This is never a [*TypeFunction*](#TypeFunction), as the latter can only be bound to a value via a pointer to a function or a delegate.

 
```
QualifiedName:
    SymbolFunctionName
    SymbolFunctionName QualifiedName

SymbolFunctionName:
    SymbolName
    SymbolName TypeFunctionNoReturn
    SymbolName M TypeModifiersopt TypeFunctionNoReturn

```
 The **M** means that the symbol is a function that requires a `this` pointer. Class or struct fields are mangled without **M**. To disambiguate **M** from being a [*Parameter*](#Parameter) with modifier `scope`, the following type needs to be checked for being a [*TypeFunction*](#TypeFunction).

 
```
SymbolName:
    LName
    TemplateInstanceName
    IdentifierBackRef
    0                         // anonymous symbols

```
 Template Instance Names have the types and values of its parameters encoded into it: 

 
```
TemplateInstanceName:
    TemplateID LName TemplateArgs Z

TemplateID:
    __T
    __U        // for symbols declared inside template constraint

TemplateArgs:
    TemplateArg
    TemplateArg TemplateArgs

TemplateArg:
    TemplateArgX
    H TemplateArgX

```
 If a template argument matches a specialized template parameter, the argument is mangled with prefix **H**.

 
```
TemplateArgX:
    T Type
    V Type Value
    S QualifiedName
    X Number ExternallyMangledName

```
 *ExternallyMangledName* can be any series of characters allowed on the current platform, e.g. generated by functions with C++ linkage or annotated with `pragma(mangle,...)`.

 
```
Value:
    n
    i Number
    N Number
    e HexFloat
    c HexFloat c HexFloat
    CharWidth Number _ HexDigits
    A Number Value...
    S Number Value...

HexFloat:
    NAN
    INF
    NINF
    N HexDigits P Exponent
    HexDigits P Exponent

Exponent:
    N Number
    Number

HexDigits:
    HexDigit
    HexDigit HexDigits

HexDigit:
    Digit
    A
    B
    C
    D
    E
    F

CharWidth:
    a
    w
    d

```
  **n** is for **null** arguments. 
**i** [*Number*](#Number)
 is for positive numeric literals (including character literals). 
**N** [*Number*](#Number)
 is for negative numeric literals. 
**e** [*HexFloat*](#HexFloat)
 is for real and imaginary floating point literals. 
**c** [*HexFloat*](#HexFloat) **c** [*HexFloat*](#HexFloat)
 is for complex floating point literals. 
[*CharWidth*](#CharWidth) [*Number*](#Number) `_` [*HexDigits*](#HexDigits)
 
[*CharWidth*](#CharWidth) is whether the characters are 1 byte (**a**), 2 bytes (**w**) or 4 bytes (**d**) in size. [*Number*](#Number) is the number of characters in the string. The [*HexDigits*](#HexDigits) are the hex data for the string.  
**A** [*Number*](#Number) [*Value*](#Value)... An array or asssociative array literal. [*Number*](#Number) is the length of the array. [*Value*](#Value) is repeated [*Number*](#Number) times for a normal array, and 2 \* [*Number*](#Number) times for an associative array.  
**S** [*Number*](#Number) [*Value*](#Value)... A struct literal. [*Value*](#Value) is repeated [*Number*](#Number) times.   
```
Name:
    Namestart
    Namestart Namechars

Namestart:
    _
    Alpha

Namechar:
    Namestart
    Digit

Namechars:
    Namechar
    Namechar Namechars

```
 A [*Name*](#Name) is a standard D [identifier](lex#identifiers).

 
```
LName:
    Number Name

Number:
    Digit
    Digit Number

Digit:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

```
 An [*LName*](#LName) is a name preceded by a [*Number*](#Number) giving the number of characters in the [*Name*](#Name). 

 ### Back references

 Any [*LName*](#LName) or non-basic [*Type*](#Type) (i.e. any type that does not encode as a fixed one or two character sequence) that has been emitted to the mangled symbol before will not be emitted again, but is referenced by a special sequence encoding the relative position of the original occurrence in the mangled symbol name.

 Numbers in back references are encoded with base 26 by upper case letters **A** - **Z** for higher digits but lower case letters **a** - **z** for the last digit.

 
```
TypeBackRef:
    Q NumberBackRef

IdentifierBackRef:
    Q NumberBackRef

NumberBackRef:
    lower-case-letter
    upper-case-letter NumberBackRef

```
 To distinguish between the type of the back reference a look-up of the back referenced character is necessary: An identifier back reference always points to a digit **0** to **9**, while a type back reference always points to a letter.

 ### Type Mangling

 Types are mangled using a simple linear scheme:

 
```
Type:
    TypeModifiersopt TypeX
    TypeBackRef

TypeX:
    TypeArray
    TypeStaticArray
    TypeAssocArray
    TypePointer
    TypeFunction
    TypeIdent
    TypeClass
    TypeStruct
    TypeEnum
    TypeTypedef
    TypeDelegate
    TypeVoid
    TypeByte
    TypeUbyte
    TypeShort
    TypeUshort
    TypeInt
    TypeUint
    TypeLong
    TypeUlong
    TypeCent
    TypeUcent
    TypeFloat
    TypeDouble
    TypeReal
    TypeIfloat
    TypeIdouble
    TypeIreal
    TypeCfloat
    TypeCdouble
    TypeCreal
    TypeBool
    TypeChar
    TypeWchar
    TypeDchar
    TypeNull
    TypeTuple
    TypeVector

TypeModifiers:
    Const
    Wild
    Wild Const
    Shared
    Shared Const
    Shared Wild
    Shared Wild Const
    Immutable

Shared:
    O

Const:
    x

Immutable:
    y

Wild:
    Ng

TypeArray:
    A Type

TypeStaticArray:
    G Number Type

TypeAssocArray:
    H Type Type

TypePointer:
    P Type

TypeVector:
    Nh Type

TypeFunction:
    TypeFunctionNoReturn Type

TypeFunctionNoReturn:
    CallConvention FuncAttrsopt Parametersopt ParamClose

CallConvention:
    F       // D
    U       // C
    W       // Windows
    R       // C++
    Y       // Objective-C

FuncAttrs:
    FuncAttr
    FuncAttr FuncAttrs

FuncAttr:
    FuncAttrPure
    FuncAttrNothrow
    FuncAttrRef
    FuncAttrProperty
    FuncAttrNogc
    FuncAttrReturn
    FuncAttrScope
    FuncAttrTrusted
    FuncAttrSafe
    FuncAttrLive

```
 Function attributes are emitted in the order as listed above.

 
```
FuncAttrPure:
    Na

FuncAttrNogc:
    Ni

FuncAttrNothrow:
    Nb

FuncAttrProperty:
    Nd

FuncAttrRef:
    Nc

FuncAttrReturn:
    Nj

FuncAttrScope:
    Nl

FuncAttrTrusted:
    Ne

FuncAttrSafe:
    Nf

FuncAttrLive:
    Nm

Parameters:
    Parameter
    Parameter Parameters

Parameter:
    Parameter2
    M Parameter2     // scope
    Nk Parameter2    // return

Parameter2:
    Type
    I Type     // in
    J Type     // out
    K Type     // ref
    L Type     // lazy

ParamClose
    X     // variadic T t...) style
    Y     // variadic T t,...) style
    Z     // not variadic

TypeIdent:
    I QualifiedName

TypeClass:
    C QualifiedName

TypeStruct:
    S QualifiedName

TypeEnum:
    E QualifiedName

TypeTypedef:
    T QualifiedName

TypeDelegate:
    D TypeModifiersopt TypeFunction

TypeVoid:
    v

TypeByte:
    g

TypeUbyte:
    h

TypeShort:
    s

TypeUshort:
    t

TypeInt:
    i

TypeUint:
    k

TypeLong:
    l

TypeUlong:
    m

TypeCent:
    zi

TypeUcent:
    zk

TypeFloat:
    f

TypeDouble:
    d

TypeReal:
    e

TypeIfloat:
    o

TypeIdouble:
    p

TypeIreal:
    j

TypeCfloat:
    q

TypeCdouble:
    r

TypeCreal:
    c

TypeBool:
    b

TypeChar:
    a

TypeWchar:
    u

TypeDchar:
    w

TypeNull:
    n

TypeTuple:
    B Parameters Z

```
 Function Calling Conventions
----------------------------

 The `extern (C)` and `extern (D)` calling convention matches the C calling convention used by the supported C compiler on the host system. Except that the extern (D) calling convention for Windows x86 is described here. 

 ### Register Conventions

 * EAX, ECX, EDX are scratch registers and can be destroyed by a function.
* EBX, ESI, EDI, EBP must be preserved across function calls.
* EFLAGS is assumed destroyed across function calls, except for the direction flag which must be forward.
* The FPU stack must be empty when calling a function.
* The FPU control word must be preserved across function calls.
* Floating point return values are returned on the FPU stack. These must be cleaned off by the caller, even if they are not used.

 ### Return Value

 * The types bool, byte, ubyte, short, ushort, int, uint, pointer, Object, and interfaces are returned in EAX.
* long and ulong are returned in EDX,EAX, where EDX gets the most significant half.
* float, double, real, ifloat, idouble, ireal are returned in ST0.
* cfloat, cdouble, creal are returned in ST1,ST0 where ST1 is the real part and ST0 is the imaginary part.
* Dynamic arrays are returned with the pointer in EDX and the length in EAX.
* Associative arrays are returned in EAX.
* References are returned as pointers in EAX.
* Delegates are returned with the pointer to the function in EDX and the context pointer in EAX.
* 1, 2 and 4 byte structs and static arrays are returned in EAX.
* 8 byte structs and static arrays are returned in EDX,EAX, where EDX gets the most significant half.
* For other sized structs and static arrays, the return value is stored through a hidden pointer passed as an argument to the function.
* Constructors return the this pointer in EAX.

 ### Parameters

 The parameters to the non-variadic function:

 
```
foo(a1, a2, ..., an);

```
 are passed as follows: 

|  |
| --- |
| a1 |
| a2 |
| ... |
| an |
| hidden |
| this |

 where *hidden* is present if needed to return a struct value, and *this* is present if needed as the this pointer for a member function or the context pointer for a nested function.

 The last parameter is passed in EAX rather than being pushed on the stack if the following conditions are met:

 * It fits in EAX.
* It is not a 3 byte struct.
* It is not a floating point type.

 Parameters are always pushed as multiples of 4 bytes, rounding upwards, so the stack is always aligned on 4 byte boundaries. They are pushed most significant first. **out** and **ref** are passed as pointers. Static arrays are passed as pointers to their first element. On Windows, a real is pushed as a 10 byte quantity, a creal is pushed as a 20 byte quantity. On Linux, a real is pushed as a 12 byte quantity, a creal is pushed as two 12 byte quantities. The extra two bytes of pad occupy the ‘most significant’ position. 

 The callee cleans the stack.

 The parameters to the variadic function:

 
```
void foo(int p1, int p2, int[] p3...)
foo(a1, a2, ..., an);

```
 are passed as follows: 

|  |
| --- |
| p1 |
| p2 |
| a3 |
| hidden |
| this |

 The variadic part is converted to a dynamic array and the rest is the same as for non-variadic functions.

 The parameters to the variadic function:

 
```
void foo(int p1, int p2, ...)
foo(a1, a2, a3, ..., an);

```
 are passed as follows: 

|  |
| --- |
| an |
| ... |
| a3 |
| a2 |
| a1 |
| `_`arguments |
| hidden |
| this |

 The caller is expected to clean the stack. `_argptr` is not passed, it is computed by the callee.

 Exception Handling
------------------

 ### Windows

 Conforms to the Microsoft Windows Structured Exception Handling conventions. 

 ### Linux, FreeBSD and OS X

 Uses static address range/handler tables. It is not compatible with the ELF/Mach-O exception handling tables. The stack is walked assuming it uses the EBP/RBP stack frame convention. The EBP/RBP convention must be used for every function that has an associated EH (Exception Handler) table. 

 For each function that has exception handlers, an EH table entry is generated. 

 

EH Table Entry| **field** | **description** |
| `void*` | pointer to start of function |
| `DHandlerTable*` | pointer to corresponding EH data |
| `uint` | size in bytes of the function |

 The EH table entries are placed into the following special segments, which are concatenated by the linker. 

 

EH Table Segment| **Operating System** | **Segment Name** |
| Windows | `FI` |
| Linux | `.deh_eh` |
| FreeBSD | `.deh_eh` |
| OS X | `__deh_eh`, `__DATA` |

   
 The rest of the EH data can be placed anywhere, it is immutable.

 

DHandlerTable| **field** | **description** |
| `void*` | pointer to start of function |
| `uint` | offset of ESP/RSP from EBP/RBP |
| `uint` | offset from start of function to return code |
| `uint` | number of entries in `DHandlerInfo[]` |
| `DHandlerInfo[]` | array of handler information |

   
 

DHandlerInfo| **field** | **description** |
| `uint` | offset from function address to start of guarded section |
| `uint` | offset of end of guarded section |
| `int` | previous table index |
| `uint` | if != 0 offset to DCatchInfo data from start of table |
| `void*` | if not null, pointer to finally code to execute |

   
 

DCatchInfo| **field** | **description** |
| `uint` | number of entries in `DCatchBlock[]` |
| `DCatchBlock[]` | array of catch information |

   
 

DCatchBlock| **field** | **description** |
| `ClassInfo` | catch type |
| `uint` | offset from EBP/RBP to catch variable |
|`void*`, catch handler code

 Garbage Collection
------------------

 The interface to this is found in Druntime's [gc/gcinterface.d](https://github.com/dlang/druntime/blob/master/src/gc/gcinterface.d).

 Runtime Helper Functions
------------------------

 These are found in Druntime's [rt/](https://github.com/dlang/druntime/blob/master/src/rt/).

 Module Initialization and Termination
-------------------------------------

 All the static constructors for a module are aggregated into a single function, and a pointer to that function is inserted into the ctor member of the ModuleInfo instance for that module. 

 All the static denstructors for a module are aggregated into a single function, and a pointer to that function is inserted into the dtor member of the ModuleInfo instance for that module. 

 Unit Testing
------------

 All the unit tests for a module are aggregated into a single function, and a pointer to that function is inserted into the unitTest member of the ModuleInfo instance for that module. 

 Symbolic Debugging
------------------

 D has types that are not represented in existing C or C++ debuggers. These are dynamic arrays, associative arrays, and delegates. Representing these types as structs causes problems because function calling conventions for structs are often different than that for these types, which causes C/C++ debuggers to misrepresent things. For these debuggers, they are represented as a C type which does match the calling conventions for the type. 

 

Types for C Debuggers| **D type** | **C representation** |
| dynamic array | `unsigned long long` |
| associative array | `void*` |
| delegate | `long long` |
| `dchar` | `unsigned long` |

 For debuggers that can be modified to accept new types, the following extensions help them fully support the types. 

 ### Codeview Debugger Extensions

 The D **dchar** type is represented by the special primitive type 0x78.

 D makes use of the Codeview OEM generic type record indicated by `LF_OEM` (0x0015). The format is:

 

Codeview OEM Extensions for D| field size | 2 | 2 | 2 | 2 | 2 | 2 |
| **D Type** | **Leaf Index** | **OEM Identifier** | **recOEM** | **num indices** |  **type index** | **type index** |
| dynamic array | `LF_OEM` | *OEM* | 1 | 2 | @*index* | @*element* |
| associative array | `LF_OEM` | *OEM* | 2 | 2 | @*key* | @*element* |
| delegate | `LF_OEM` | *OEM* | 3 | 2 | @*this* | @*function* |

 where: 

|  |  |
| --- | --- |
| *OEM* | 0x42 |
| *index* | type index of array index |
| *key* | type index of key |
| *element* | type index of array element |
| *this* | type index of context pointer |
| *function* | type index of function |

 These extensions can be pretty-printed by [obj2asm](http://www.digitalmars.com/ctg/obj2asm.html). The [Ddbg](http://ddbg.mainia.de/releases.html) debugger supports them.

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/abi.html>

Expressions
===========

 **Contents** 1. [Definitions and Terms](#definitions-and-terms)
2. [Order Of Evaluation](#order-of-evaluation)
3. [Lifetime of Temporaries](#temporary-lifetime)
4. [Expressions](#expression)
5. [Assign Expressions](#assign_expressions)
	1. [Simple Assignment Expression](#simple_assignment_expressions)
	2. [Assignment Operator Expressions](#assignment_operator_expressions)
6. [Conditional Expressions](#conditional_expressions)
7. [OrOr Expressions](#oror_expressions)
8. [AndAnd Expressions](#andand_expressions)
9. [Bitwise Expressions](#bitwise_expressions)
	1. [Or Expressions](#or_expressions)
	2. [Xor Expressions](#xor_expressions)
	3. [And Expressions](#and_expressions)
10. [Compare Expressions](#compare_expressions)
11. [Equality Expressions](#equality_expressions)
	1. [Identity Expressions](#identity_expressions)
12. [Relational Expressions](#relation_expressions)
	1. [Integer comparisons](#integer_comparisons)
	2. [Floating point comparisons](#floating-point-comparisons)
	3. [Class comparisons](#class-comparisons)
13. [In Expressions](#in_expressions)
14. [Shift Expressions](#shift_expressions)
15. [Add Expressions](#add_expressions)
16. [Cat Expressions](#cat_expressions)
17. [Mul Expressions](#mul_expressions)
18. [Unary Expressions](#unary-expression)
	1. [Complement Expressions](#complement_expressions)
	2. [New Expressions](#new_expressions)
	3. [Delete Expressions](#delete_expressions)
	4. [Cast Expressions](#cast_expressions)
19. [Pow Expressions](#pow_expressions)
20. [Postfix Expressions](#postfix_expressions)
21. [Index Expressions](#index_expressions)
22. [Slice Expressions](#slice_expressions)
23. [Primary Expressions](#primary_expressions)
	1. [.Identifier](#identifier)
	2. [this](#this)
	3. [super](#super)
	4. [null](#null)
	5. [true, false](#true_false)
	6. [Character Literals](#character-literal)
	7. [String Literals](#string_literals)
	8. [Array Literals](#array_literals)
	9. [Associative Array Literals](#associative_array_literals)
	10. [Function Literals](#function_literals)
	11. [Uniform construction syntax for built-in scalar types](#uniform_construction_syntax)
	12. [Assert Expressions](#assert_expressions)
	13. [Mixin Expressions](#mixin_expressions)
	14. [Import Expressions](#import_expressions)
	15. [Typeid Expressions](#typeid_expressions)
	16. [IsExpression](#is_expression)
24. [Special Keywords](#specialkeywords)
25. [Associativity and Commutativity](#associativity)

 An expression is a sequence of operators and operands that specifies an evaluation. The syntax, order of evaluation, and semantics of expressions are as follows.

 Expressions are used to compute values with a resulting type. These values can then be assigned, tested, or ignored. Expressions can also have side effects. 

 Definitions and Terms
---------------------

 **Definition** (“Full expression”): For any expression *expr*, the full expression of *expr* is defined as follows. If *expr* parses as a subexpression of another expression *expr1*, then the full expression of *expr* is the full expression of *expr1*. Otherwise, *expr* is its own full expression.

 Each expression has a unique full expression.

 Example: in the statement `return f() + g() * 2;`, the full expression of `g() * 2` is `f() + g() * 2`, but not the full expression of `f() + g()` because the latter is not parsed as a subexpression.

 Note: Although the definition is straightforward, a few subtleties exist related to function literals. In the statement `return (() => x + f())() * g();`, the full expression of `f()` is `x + f()`, not the expression passed to `return`. This is because the parent of `x + f()` has function literal type, not expression type.

 **Definition** (“Lvalue”): The following expressions, and no others, are called lvalue expressions or lvalues:

 1. `this` inside `struct` and `union` member functions;
2. a variable or the result of the *DotIdentifier* grammatical construct `.` (left side may be missing) when the rightmost side of the dot is a variable, field (direct or `static`), function name, or invocation of a function that returns by reference;
3. the result of the following expressions:
	* built-in unary operators `+` (when applied to an lvalue), `*`, `++` (prefix only), `--` (prefix only);
	* built-in indexing operator `[]` (but not the slicing operator);
	* built-in assignment binary operators, i.e. `=`, `+=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `~=`, `<<=`, `>>=`, `>>>=`, and `^^=`;
	* the ternary operator *e* `?` *e1* `:` *e2* under the following circumstances:
	1. *e1* and *e2* are lvalues of the same type; OR
	2. One of *e1* and *e2* is an lvalue of type `T` and the other has and `alias this` converting it to `ref T`;
4. user-defined operators if and only if the function called as a result of lowering returns by reference;
5. `mixin` expressions if and only if the compilation of the expression resulting from compiling the argument(s) to `mixin` is an lvalue;
6. `cast(U)` expressions applied to lvalues of type `T` when `T*` is implicitly convertible to `U*`;
7. `cast()` and `cast(`*qualifier list*`)` when applied to an lvalue.

 **Definition** (“Rvalue”): Expressions that are not lvalues are rvalues.

 Note: Rvalues include all literals, special value keywords such as `__FILE__` and `__LINE__`, `enum` values, and the result of expressions not defined as lvalues above.

 The built-in address-of operator (unary `&`) may only be applied to lvalues.

 **Definition** (“Smallest short-circuit expression”): Given an expression *expr* that is a subexpression of a full expression *fullexpr*, the smallest short-circuit expression, if any, is the shortest subexpression *scexpr* of *fullexpr* that is an [*AndAndExpression*](#AndAndExpression) (`&&`) or an [*OrOrExpression*](#OrOrExpression) (`||`), such that *expr* is a subexpression of *scexpr*.

 Example: in the expression `((f() * 2 && g()) + 1) || h()`, the smallest short-circuit expression of the subexpression `f() * 2` is `f() * 2 && g()`. In the expression `(f() && g()) + h()`, the subexpression `h()` has no smallest short-circuit expression. Order Of Evaluation
-------------------

 Built-in prefix unary expressions `++` and `--` are evaluated as if lowered (rewritten) to assignments as follows: `++expr` becomes `((expr) += 1)`, and `--expr` becomes `((expr) -= 1)`. Therefore, the result of prefix `++` and `--` is the lvalue after the side effect has been effected.

 Built-in postfix unary expressions `++` and `--` are evaluated as if lowered (rewritten) to [lambda](expression#function_literals) invocations as follows: `expr++` becomes `(ref T x){auto t = x; ++x; return t;}(expr)`, and `expr--` becomes `(ref T x){auto t = x; --x; return t;}(expr)`. Therefore, the result of postfix `++` and `--` is an rvalue just before the side effect has been effected.

 Binary expressions except for [*AssignExpression*](#AssignExpression), [*OrOrExpression*](#OrOrExpression), and [*AndAndExpression*](#AndAndExpression) are evaluated in lexical order (left-to-right). Example:

 
```
int i = 2;
i = ++i * i++ + i;
assert(i == 3 * 3 + 4);

```
 [*OrOrExpression*](#OrOrExpression) and [*AndAndExpression*](#AndAndExpression) evaluate their left-hand side argument first. Then, [*OrOrExpression*](#OrOrExpression) evaluates its right-hand side if and only if its left-hand side does not evaluate to nonzero. [*AndAndExpression*](#AndAndExpression) evaluates its right-hand side if and only if its left-hand side evaluates to nonzero.

 [*ConditionalExpression*](#ConditionalExpression) evaluates its left-hand side argument first. Then, if the result is nonzero, the second operand is evaluated. Otherwise, the third operand is evaluated.

 Calls to functions with `extern(D)` [linkage](attribute#linkage) (which is the default linkage) are evaluated in the following order: first, if necessary, the address of the function to call is evaluated (e.g. in the case of a computed function pointer or delegate). Then, arguments are evaluated left to right. Finally, transfer is passed to the function. Example:

 
```
import std.stdio;
void function(int a, int b, int c) fun()
{
    writeln("fun() called");
    static void r(int a, int b, int c) { writeln("callee called"); }
    return &r;
}
int f1() { writeln("f1() called"); return 1; }
int f2() { writeln("f2() called"); return 2; }
int f3(int x) { writeln("f3() called"); return x + 3; }
int f4() { writeln("f4() called"); return 4; }
// evaluates fun() then f1() then f2() then f3() then f4()
// after which control is transferred to the callee
fun()(f1(), f3(f2()), f4());

```
 **Implementation Defined:** 1. The order of evaluation of the operands of [*AssignExpression*](#AssignExpression).
2. The order of evaluation of function arguments for functions with linkage other than `extern (D)`.

 **Best Practices:** Even though the order of evaluation is well-defined, writing code that depends on it is rarely recommended. Lifetime of Temporaries
-----------------------

 Expressions and statements may create and/or consume rvalues. Such values are called *temporaries* and do not have a name or a visible scope. Their lifetime is managed automatically as defined in this section.

 For each evaluation that yields a temporary value, the lifetime of that temporary begins at the evaluation point, similarly to creation of a usual named value initialized with an expression.

 Termination of lifetime of temporaries does not obey the customary scoping rules and is defined as follows:

 * If:
	1. the full expression has a smallest short-circuit expression *expr*; and
	2. the temporary is created on the right-hand side of the `&&` or `||` operator; and
	3. the right-hand side is evaluated, then temporary destructors are evaluated right after the right-hand side expression has been evaluated and converted to `bool`. Evaluation of destructors proceeds in reverse order of construction.
* For all other cases, the temporaries generated for the purpose of invoking functions are deferred to the end of the full expression. The order of destruction is inverse to the order of construction.

 If a subexpression of an expression throws an exception, all temporaries created up to the evaluation of that subexpression will be destroyed per the rules above. No destructor calls will be issued for temporaries not yet constructed.

 Note: An intuition behind these rules is that destructors of temporaries are deferred to the end of full expression and in reverse order of construction, with the exception that the right-hand side of `&&` and `||` are considered their own full expressions even when part of larger expressions.

 Note: The ternary expression *e1 ? e2 : e3* is not a special case although it evaluates expressions conditionally: *e1* and one of *e2* and *e3* may create temporaries. Their destructors are inserted to the end of the full expression in the reverse order of creation.

 Example:

 
```
import std.stdio;
struct S
{
    int x;
    this(int n) { x = n; writefln("S(%s)", x); }
    ~this() { writefln("~S(%s)", x); }
}
bool b = (S(1) == S(2) || S(3) != S(4)) && S(5) == S(6);

```
 The output of the code above is: 
```
S(1)
S(2)
S(3)
S(4)
~S(4)
~S(3)
S(5)
S(6)
~S(6)
~S(5)
~S(2)
~S(1)

```
 First, `S(1)` and `S(2)` are evaluated in lexical order. Per the rules, they will be destroyed at the end of the full expression and in reverse order. The comparison `S(1) == S(2)` yields `false`, so the right-hand side of the `||` is evaluated causing `S(3)` and `S(4)` to be evaluated, also in lexical order. However, their destruction is not deferred to the end of the full expression. Instead, `S(4)` and then `S(3)` are destroyed at the end of the `||` expression. Following their destruction, `S(5)` and `S(6)` are constructed in lexical order. Again they are not destroyed at the end of the full expression, but right at the end of the `&&` expression. Consequently, the destruction of `S(6)` and `S(5)` is carried before that of `S(2)` and `S(1)`. Expressions
-----------

 
```
Expression:
    CommaExpression

CommaExpression:
    AssignExpression
    AssignExpression , CommaExpression

```
 The left operand of the `,` is evaluated, then the right operand is evaluated. The type of the expression is the type of the right operand, and the result is the result of the right operand. Using the result of comma expressions isn't allowed. 

 Assign Expressions
------------------

 
```
AssignExpression:
    ConditionalExpression
    ConditionalExpression = AssignExpression
    ConditionalExpression += AssignExpression
    ConditionalExpression -= AssignExpression
    ConditionalExpression *= AssignExpression
    ConditionalExpression /= AssignExpression
    ConditionalExpression %= AssignExpression
    ConditionalExpression &= AssignExpression
    ConditionalExpression |= AssignExpression
    ConditionalExpression ^= AssignExpression
    ConditionalExpression ~= AssignExpression
    ConditionalExpression <<= AssignExpression
    ConditionalExpression >>= AssignExpression
    ConditionalExpression >>>= AssignExpression
    ConditionalExpression ^^= AssignExpression

```
 For all assign expressions, the left operand must be a modifiable lvalue. The type of the assign expression is the type of the left operand, and the value is the value of the left operand after assignment occurs. The resulting expression is a modifiable lvalue. 

 **Undefined Behavior:** If either operand is a reference type and one of the following: 1. the operands have partially overlapping storage
2. the operands' storage overlaps exactly but the types are different

 **Implementation Defined:** If neither operand is a reference type and one of the following: 1. the operands have partially overlapping storage
2. the operands' storage overlaps exactly but the types are different

 ### Simple Assignment Expression

 If the operator is `=` then it is simple assignment. The right operand is implicitly converted to the type of the left operand, and assigned to it.

 If the left and right operands are of the same struct type, and the struct type has a [*Postblit*](struct#Postblit), then the copy operation is as described in [Struct Postblit](struct#struct-postblit). 

 If the lvalue is the `.length` property of a dynamic array, the behavior is as described in [Setting Dynamic Array Length](array#resize). 

 If the lvalue is a static array or a slice, the behavior is as described in [Array Copying](array#array-copying) and [Array Setting](array#array-setting). 

 If the lvalue is a user-defined property, the behavior is as described in [Property Functions](function#property-functions). 

 ### Assignment Operator Expressions

 For arguments of built-in types, assignment operator expressions such as

 
```
a op= b

```
 are semantically equivalent to: 
```
a = cast(typeof(a))(a op b)

```
 except that * operand `a` is only evaluated once,
* overloading *op* uses a different function than overloading *op*= does, and
* the left operand of `>>>=` does not undergo [Integer Promotions](type#integer-promotions) before shifting.

 For user-defined types, assignment operator expressions are overloaded separately from the binary operator. Still the left operand must be an lvalue. 

 Conditional Expressions
-----------------------

 
```
ConditionalExpression:
    OrOrExpression
    OrOrExpression ? Expression : ConditionalExpression

```
 The first expression is converted to `bool`, and is evaluated. 

 If it is `true`, then the second expression is evaluated, and its result is the result of the conditional expression. 

 If it is `false`, then the third expression is evaluated, and its result is the result of the conditional expression. 

 If either the second or third expressions are of type `void`, then the resulting type is `void`. Otherwise, the second and third expressions are implicitly converted to a common type which becomes the result type of the conditional expression. 

 **Note:** When a conditional expression is the left operand of an [assign expression](#assign_expressions), parentheses are required for disambiguation: 

 
```
bool test;
int a, b, c;
...
test ? a = b : c = 2;   // Deprecated
(test ? a = b : c) = 2; // Equivalent

```
 This makes the intent clearer, because the first statement can easily be misread as the following code: 

 
```
test ? a = b : (c = 2);

```
 OrOr Expressions
----------------

 
```
OrOrExpression:
    AndAndExpression
    OrOrExpression || AndAndExpression

```
 The result type of an *OrOrExpression* is `bool`, unless the right operand has type `void`, when the result is type `void`. 

 The *OrOrExpression* evaluates its left operand. 

 If the left operand, converted to type `bool`, evaluates to `true`, then the right operand is not evaluated. If the result type of the *OrOrExpression* is `bool` then the result of the expression is `true`. 

 If the left operand is `false`, then the right operand is evaluated. If the result type of the *OrOrExpression* is `bool` then the result of the expression is the right operand converted to type `bool`. 

 AndAnd Expressions
------------------

 
```
AndAndExpression:
    OrExpression
    AndAndExpression && OrExpression

```
 The result type of an *AndAndExpression* is `bool`, unless the right operand has type `void`, when the result is type `void`. 

 The *AndAndExpression* evaluates its left operand. 

 If the left operand, converted to type `bool`, evaluates to `false`, then the right operand is not evaluated. If the result type of the *AndAndExpression* is `bool` then the result of the expression is `false`. 

 If the left operand is `true`, then the right operand is evaluated. If the result type of the *AndAndExpression* is `bool` then the result of the expression is the right operand converted to type `bool`. 

 Bitwise Expressions
-------------------

 Bit wise expressions perform a bitwise operation on their operands. Their operands must be integral types. First, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are done. Then, the bitwise operation is done. 

 ### Or Expressions

 
```
OrExpression:
    XorExpression
    OrExpression | XorExpression

```
 The operands are OR'd together.

 ### Xor Expressions

 
```
XorExpression:
    AndExpression
    XorExpression ^ AndExpression

```
 The operands are XOR'd together.

 ### And Expressions

 
```
AndExpression:
    CmpExpression
    AndExpression & CmpExpression

```
 The operands are AND'd together.

 Compare Expressions
-------------------

 
```
CmpExpression:
    ShiftExpression
    EqualExpression
    IdentityExpression
    RelExpression
    InExpression

```
 Equality Expressions
--------------------

 
```
EqualExpression:
    ShiftExpression == ShiftExpression
    ShiftExpression != ShiftExpression

```
 Equality expressions compare the two operands for equality (`==`) or inequality (`!=`). The type of the result is `bool`. 

 Inequality is defined as the logical negation of equality.

 If the operands are integral values, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are applied to bring them to a common type before comparison. Equality is defined as the bit patterns of the common type match exactly. 

 If the operands are pointers, equality is defined as the bit patterns of the operands match exactly. 

 For float, double, and real values, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are applied to bring them to a common type before comparison. The values `-0` and `+0` are considered equal. If either or both operands are NAN, then `==` returns false and `!=` returns `true`. Otherwise, the bit patterns of the common type are compared for equality. 

 For complex numbers, equality is defined as equivalent to: 

 
```
x.re == y.re && x.im == y.im

```
 For struct objects, equality means the result of the [`opEquals()` member function](operatoroverloading#equals). If an `opEquals()` is not provided, equality is defined as the logical product of all equality results of the corresponding object fields. 

 **Implementation Defined:** The contents of any alignment gaps in the struct object. **Best Practices:** If there are overlapping fields, which happens with unions, the default equality will compare each of the overlapping fields. An `opEquals()` can account for which of the overlapping fields contains valid data. An `opEquals()` can override the default behavior of floating point NaN values always comparing as unequal. Be careful using `memcmp()` to implement `opEquals()` if: * there are any alignment gaps
* if any fields have an `opEquals()`
* there are any floating point fields that may contain NaN or `-0` values

 For class and struct objects, the expression `(a == b)` is rewritten as `a.opEquals(b)`, and `(a != b)` is rewritten as `!a.opEquals(b)`. 

 For class objects, the `==` and `!=` operators are intended to compare the contents of the objects, however an appropriate `opEquals` override must be defined for this to work. The default `opEquals` provided by the root `Object` class is equivalent to the `is` operator. Comparing against `null` is invalid, as `null` has no contents. Use the `is` and `!is` operators instead.

 
```
class C;
C c;
if (c == null)  // error
    ...
if (c is null)  // ok
    ...

```
 For static and dynamic arrays, equality is defined as the lengths of the arrays matching, and all the elements are equal. 

 ### Identity Expressions

 
```
IdentityExpression:
    ShiftExpression is ShiftExpression
    ShiftExpression !is ShiftExpression

```
 The `is` compares for identity. To compare for nonidentity, use `e1 !is e2`. The type of the result is `bool`. The operands undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) to bring them to a common type before comparison. 

 For class objects, identity is defined as the object references are for the same object. Null class objects can be compared with `is`. 

 For struct objects and floating point values, identity is defined as the bits in the operands being identical. 

 For static and dynamic arrays, identity is defined as referring to the same array elements and the same number of elements. 

 For other operand types, identity is defined as being the same as equality. 

 The identity operator `is` cannot be overloaded. 

 Relational Expressions
----------------------

 
```
RelExpression:
    ShiftExpression < ShiftExpression
    ShiftExpression <= ShiftExpression
    ShiftExpression > ShiftExpression
    ShiftExpression >= ShiftExpression

```
 First, the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions) are done on the operands. The result type of a relational expression is `bool`. 

 For class objects, the result of Object.opCmp() forms the left operand, and 0 forms the right operand. The result of the relational expression (o1 op o2) is:

 
```
(o1.opCmp(o2) op 0)

```
 It is an error to compare objects if one is `null`.

 For static and dynamic arrays, the result of the relational op is the result of the operator applied to the first non-equal element of the array. If two arrays compare equal, but are of different lengths, the shorter array compares as "less" than the longer array. 

 ### Integer comparisons

 Integer comparisons happen when both operands are integral types. 

 

Integer comparison operators| **Operator** | **Relation** |
| `<` | less |
| `>` | greater |
| `<``=` | less or equal |
| `>=` | greater or equal |
| `==` | equal |
| `!=` | not equal |

 It is an error to have one operand be signed and the other unsigned for a `<`, `<``=`, `>` or `>``=` expression. Use casts to make both operands signed or both operands unsigned. 

 ### Floating point comparisons

 If one or both operands are floating point, then a floating point comparison is performed. 

 A relational operator can have `NaN` operands. If either or both operands is `NaN`, the floating point comparison operation returns as follows:

 

Floating point comparison operators| **Operator** | **Relation** | **Returns** |
| `<` | less | `false` |
| `>` | greater | `false` |
| `<``=` | less or equal | `false` |
| `>=` | greater or equal | `false` |
| `==` | equal | `false` |
| `!=` | unordered, less, or greater | `true` |

 ### Class comparisons

 For class objects, the relational operators compare the contents of the objects. Therefore, comparing against `null` is invalid, as `null` has no contents.

 
```
class C;
C c;
if (c < null)  // error
    ...

```
 In Expressions
--------------

 
```
InExpression:
    ShiftExpression in ShiftExpression
    ShiftExpression !in ShiftExpression

```
 An associative array can be tested to see if an element is in the array:

 
```
int foo[string];
...
if ("hello" in foo)
    ...

```
 The `in` expression has the same precedence as the relational expressions `<`, `<``=`, etc. The return value of the *InExpression* is `null` if the element is not in the array; if it is in the array it is a pointer to the element. 

 The `!in` expression is the logical negation of the `in` operation. 

 Shift Expressions
-----------------

 
```
ShiftExpression:
    AddExpression
    ShiftExpression << AddExpression
    ShiftExpression >> AddExpression
    ShiftExpression >>> AddExpression

```
 The operands must be integral types, and undergo the [Integer Promotions](type#integer-promotions). The result type is the type of the left operand after the promotions. The result value is the result of shifting the bits by the right operand's value. 

 `<``<` is a left shift. `>``>` is a signed right shift. `>``>``>` is an unsigned right shift. 

 It's illegal to shift by the same or more bits than the size of the quantity being shifted:

 
```
int c;
auto x = c << 33;        // error

```
 Add Expressions
---------------

 
```
AddExpression:
    MulExpression
    AddExpression + MulExpression
    AddExpression - MulExpression
    CatExpression

```
 If the operands are of integral types, they undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions), and then are brought to a common type using the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). 

 If either operand is a floating point type, the other is implicitly converted to floating point and they are brought to a common type via the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). 

 If the operator is `+` or `-`, and the first operand is a pointer, and the second is an integral type, the resulting type is the type of the first operand, and the resulting value is the pointer plus (or minus) the second operand multiplied by the size of the type pointed to by the first operand. 

 If the second operand is a pointer, and the first is an integral type, and the operator is `+`, the operands are reversed and the pointer arithmetic just described is applied. 

 If both operands are pointers, and the operator is `+`, then it is illegal. 

 If both operands are pointers, and the operator is `-`, the pointers are subtracted and the result is divided by the size of the type pointed to by the operands. In this calculation the assumed size of `void` is one byte. It is an error if the pointers point to different types. The type of the result is `ptrdiff_t`. 

 If both operands are of integral types and an overflow or underflow occurs in the computation, wrapping will happen. For example, `uint.max + 1 == uint.min`, `uint.min - 1 == uint.max`, `int.max + 1 == int.min`, and `int.min - 1 == int.max`. 

 Add expressions for floating point operands are not associative. 

 Cat Expressions
---------------

 
```
CatExpression:
    AddExpression ~ MulExpression

```
 A *CatExpression* concatenates arrays, producing a dynamic array with the result. The arrays must be arrays of the same element type. If one operand is an array and the other is of that array's element type, that element is converted to an array of length 1 of that element, and then the concatenation is performed. 

 Mul Expressions
---------------

 
```
MulExpression:
    UnaryExpression
    MulExpression * UnaryExpression
    MulExpression / UnaryExpression
    MulExpression % UnaryExpression

```
 The operands must be arithmetic types. They undergo the [Usual Arithmetic Conversions](type#usual-arithmetic-conversions). 

 For integral operands, the `*`, `/`, and `%` correspond to multiply, divide, and modulus operations. For multiply, overflows are ignored and simply chopped to fit into the integral type. 

 For integral operands of the `/` and `%` operators, the quotient rounds towards zero and the remainder has the same sign as the dividend. 

 The following divide or modulus integral operands:

 * denominator is 0
* signed `int.min` is the numerator and `-1` is the denominator
* signed `long.min` is the numerator and `-1L` is the denominator

 are illegal if encountered during Compile Time Execution.

 **Undefined Behavior:** is exhibited if they are encountered during run time. [`core.checkedint`](https://dlang.org/phobos/core_checkedint.html) can be used to check for them and select a defined behavior. For floating point operands, the \* and / operations correspond to the IEEE 754 floating point equivalents. % is not the same as the IEEE 754 remainder. For example, 15.0 % 10.0 == 5.0, whereas for IEEE 754, remainder(15.0,10.0) == -5.0. 

 Mul expressions for floating point operands are not associative. 

 Unary Expressions
-----------------

 
```
UnaryExpression:
    & UnaryExpression
    ++ UnaryExpression
    -- UnaryExpression
    * UnaryExpression
    - UnaryExpression
    + UnaryExpression
    ! UnaryExpression
    ComplementExpression
    ( Type ) . Identifier
    ( Type ) . TemplateInstance
    DeleteExpression
    CastExpression
    PowExpression

```
 ### Complement Expressions

 
```
ComplementExpression:
    ~ UnaryExpression

```
 *ComplementExpression*s work on integral types (except `bool`). All the bits in the value are complemented. 

 **Note:** the usual [Integer Promotions](type#integer-promotions) are not performed prior to the complement operation. 

 ### New Expressions

 
```
NewExpression:
    new AllocatorArgumentsopt Type
    NewExpressionWithArgs

NewExpressionWithArgs:
    new AllocatorArgumentsopt Type [ AssignExpression ]
    new AllocatorArgumentsopt Type ( ArgumentListopt )
    NewAnonClassExpression

AllocatorArguments:
    ( ArgumentListopt )

ArgumentList:
    AssignExpression
    AssignExpression ,
    AssignExpression , ArgumentList

```
 *NewExpression*s are used to allocate memory on the garbage collected heap (default) or using a class or struct specific allocator. 

 To allocate multidimensional arrays, the declaration reads in the same order as the prefix array declaration order.

 
```
char[][] foo;   // dynamic array of strings
...
foo = new char[][30]; // allocate array of 30 strings

```
 The above allocation can also be written as:

 
```
foo = new char[][](30); // allocate array of 30 strings

```
 To allocate the nested arrays, multiple arguments can be used:

 
```
int[][][] bar;
...
bar = new int[][][](5, 20, 30);

```
 The code above is equivalent to: 
```
bar = new int[][][5];
foreach (ref a; bar)
{
    a = new int[][20];
    foreach (ref b; a)
    {
        b = new int[30];
    }
}

```
 If there is a `new (` [*ArgumentList*](#ArgumentList) `)`, then those arguments are passed to the class or struct specific [allocator function](class#allocators) after the size argument. 

 If a *NewExpression* is used as an initializer for a function local variable with `scope` storage class, and the [*ArgumentList*](#ArgumentList) to `new` is empty, then the instance is allocated on the stack rather than the heap or using the class specific allocator. 

 ### Delete Expressions

 
```
DeleteExpression:
    delete UnaryExpression

```
 NOTE: `delete` has been deprecated. Instead, please use [`destroy`](https://dlang.org/phobos/object.html#destroy) if feasible, or [`core.memory.__delete`](https://dlang.org/phobos/core_memory.html#__delete) as a last resort.

 If the *UnaryExpression* is a class object reference, and there is a destructor for that class, the destructor is called for that object instance. 

 Next, if the *UnaryExpression* is a class object reference, or a pointer to a struct instance, and the class or struct has overloaded operator delete, then that operator delete is called for that class object instance or struct instance. 

 Otherwise, the garbage collector is called to immediately free the memory allocated for the class instance or struct instance. 

 If the *UnaryExpression* is a pointer or a dynamic array, the garbage collector is called to immediately release the memory. 

 The pointer, dynamic array, or reference is set to `null` after the delete is performed. Any attempt to reference the data after the deletion via another reference to it will result in undefined behavior. 

 If *UnaryExpression* is a variable allocated on the stack, the class destructor (if any) is called for that instance. Neither the garbage collector nor any class deallocator is called. 

 **Undefined Behavior:** 1. Using `delete` to free memory not allocated by the garbage collector.
2. Referring to data that has been the operand of `delete`.

 ### Cast Expressions

 
```
CastExpression:
    cast ( Type ) UnaryExpression
    cast ( TypeCtorsopt ) UnaryExpression

```
 A *CastExpression* converts the *UnaryExpression* to [*Type*](type#Type).

 
```
cast(foo) -p; // cast (-p) to type foo
(foo) - p;      // subtract p from foo

```
 Any casting of a class reference to a derived class reference is done with a runtime check to make sure it really is a downcast. `null` is the result if it isn't. 

 
```
class A { ... }
class B : A { ... }

void test(A a, B b)
{
    B bx = a;         // error, need cast
    B bx = cast(B) a; // bx is null if a is not a B
    A ax = b;         // no cast needed
    A ax = cast(A) b; // no runtime check needed for upcast
}

```
 In order to determine if an object `o` is an instance of a class `B` use a cast:

 
```
if (cast(B) o)
{
    // o is an instance of B
}
else
{
    // o is not an instance of B
}

```
 Casting a pointer type to and from a class type is done as a type paint (i.e. a reinterpret cast). 

 Casting a dynamic array to another dynamic array is done only if the array lengths multiplied by the element sizes match. The cast is done as a type paint, with the array length adjusted to match any change in element size. If there's not a match, a runtime error is generated.

 
```
import std.stdio;

int main()
{
    byte[] a = [1,2,3];
    auto b = cast(int[])a; // runtime array cast misalignment

    int[] c = [1, 2, 3];
    auto d = cast(byte[])c; // ok
    // prints:
    // [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
    writeln(d);
    return 0;
}

```
 Casting a static array to another static array is done only if the array lengths multiplied by the element sizes match; a mismatch is illegal. The cast is done as a type paint (aka a reinterpret cast). The contents of the array are not changed.

 
```
import core.stdc.stdio;

void main()
{
    byte[16] b = 3;
    int[4] ia = cast(int[4]) b;
    foreach (i; ia)
        printf("%x\n", i);
    /* prints:
       3030303
       3030303
       3030303
       3030303
     */
}

```
 Casting a floating point literal from one type to another changes its type, but internally it is retained at full precision for the purposes of constant folding.

 
```
void test()
{
    real a = 3.40483L;
    real b;
    b = 3.40483;     // literal is not truncated to double precision
    assert(a == b);
    assert(a == 3.40483);
    assert(a == 3.40483L);
    assert(a == 3.40483F);
    double d = 3.40483; // truncate literal when assigned to variable
    assert(d != a);     // so it is no longer the same
    const double x = 3.40483; // assignment to const is not
    assert(x == a);     // truncated if the initializer is visible
}

```
 Casting a floating point value to an integral type is the equivalent of converting to an integer using truncation.

 
```
void main()
{
    int a = cast(int) 0.8f;
    assert(a == 0);
    long b = cast(long) 1.5;
    assert(b == 1L);
    long c = cast(long) -1.5;
    assert(c == -1);
}

```
 Casting a value *v* to a struct *S*, when value is not a struct of the same type, is equivalent to:

 
```
S(v)

```
 Casting to a [*CastQual*](#CastQual) replaces the qualifiers to the type of the [*UnaryExpression*](#UnaryExpression).

 
```
shared int x;
assert(is(typeof(cast(const)x) == const int));

```
 Casting with no [*Type*](#Type) or [*CastQual*](#CastQual) removes any top level `const`, `immutable`, `shared` or `inout` type modifiers from the type of the [*UnaryExpression*](#UnaryExpression).

 
```
shared int x;
assert(is(typeof(cast()x) == int));

```
 Casting an expression to `void` type is allowed to mark that the result is unused. On [*ExpressionStatement*](statement#ExpressionStatement), it could be used properly to avoid "has no effect" error.

 
```
void foo(lazy void exp) {}
void main()
{
    foo(10);            // NG - has no effect in expression '10'
    foo(cast(void)10);  // OK
}

```
 Pow Expressions
---------------

 
```
PowExpression:
    PostfixExpression
    PostfixExpression ^^ UnaryExpression

```
 *PowExpression* raises its left operand to the power of its right operand. 

 Postfix Expressions
-------------------

 
```
PostfixExpression:
    PrimaryExpression
    PostfixExpression . Identifier
    PostfixExpression . TemplateInstance
    PostfixExpression . NewExpression
    PostfixExpression ++
    PostfixExpression --
    PostfixExpression ( ArgumentListopt )
    TypeCtorsopt BasicType ( ArgumentListopt )
    IndexExpression
    SliceExpression

```
 Index Expressions
-----------------

 
```
IndexExpression:
    PostfixExpression [ ArgumentList ]

```
 *PostfixExpression* is evaluated. If *PostfixExpression* is an expression of type static array or dynamic array, the symbol &dollar; is set to be the number of elements in the array. If *PostfixExpression* is a *ValueSeq*, the symbol &dollar; is set to be the number of elements in the sequence. A new declaration scope is created for the evaluation of the [*ArgumentList*](#ArgumentList) and &dollar; appears in that scope only.

 If *PostfixExpression* is a *ValueSeq*, then the [*ArgumentList*](#ArgumentList) must consist of only one argument, and that must be statically evaluatable to an integral constant. That integral constant *n* then selects the *n*th expression in the *ValueSeq*, which is the result of the *IndexExpression*. It is an error if *n* is out of bounds of the *ValueSeq*. 

 Slice Expressions
-----------------

 
```
SliceExpression:
    PostfixExpression [ ]
    PostfixExpression [ Slice ,opt ]
Slice:
    AssignExpression
    AssignExpression , Slice
    AssignExpression .. AssignExpression
    AssignExpression .. AssignExpression , Slice

```
 *PostfixExpression* is evaluated. if *PostfixExpression* is an expression of type static array or dynamic array, the special variable &dollar; is declared and set to be the length of the array. A new declaration scope is created for the evaluation of the [*AssignExpression*](#AssignExpression)..[*AssignExpression*](#AssignExpression) and &dollar; appears in that scope only. 

 The first *AssignExpression* is taken to be the inclusive lower bound of the slice, and the second *AssignExpression* is the exclusive upper bound. The result of the expression is a slice of the *PostfixExpression* array. 

 If the `[ ]` form is used, the slice is of the entire array. 

 The type of the slice is a dynamic array of the element type of the *PostfixExpression*. 

 A *SliceExpression* is not a modifiable lvalue.

 If the slice bounds can be known at compile time, the slice expression is implicitly convertible to an lvalue of static array. For example:

 
```
arr[a .. b]     // typed T[]

```
 If both `a` and `b` are integers (may be constant-folded), the slice expression can be converted to a static array type `T[b - a]`. 
```
void foo(int[2] a)
{
    assert(a == [2, 3]);
}
void bar(ref int[2] a)
{
    assert(a == [2, 3]);
    a[0] = 4;
    a[1] = 5;
    assert(a == [4, 5]);
}
void baz(int[3] a) {}

void main()
{
    int[] arr = [1, 2, 3];

    foo(arr[1 .. 3]);
    assert(arr == [1, 2, 3]);

    bar(arr[1 .. 3]);
    assert(arr == [1, 4, 5]);

  //baz(arr[1 .. 3]); // cannot match length
}

```
 The following forms of slice expression can be convertible to a static array type:

  `e` An expression that contains no side effects. 
`a`, `b`
 Integers (that may be constant-folded).  

Computing array lengths during compilation| **Form** | **The length calculated at compile time** |
| `arr[]` | The compile time length of `arr` if it's known. |
| `arr[a .. b]` | `b - a` |
| `arr[e-a .. e]` | `a` |
| `arr[e .. e+b]` | `b` |
| `arr[e-a .. e+b]` | `a + b` |
| `arr[e+a .. e+b]` | `b - a` *if* `a <= b` |
| `arr[e-a .. e-b]` | `a - b` *if* `a >= b` |

 If *PostfixExpression* is a *ValueSeq*, then the result of the slice is a new *ValueSeq* formed from the upper and lower bounds, which must statically evaluate to integral constants. It is an error if those bounds are out of range. 

 Primary Expressions
-------------------

 
```
PrimaryExpression:
    Identifier
    . Identifier
    TemplateInstance
    . TemplateInstance
    this
    super
    null
    true
    false
    $
    IntegerLiteral
    FloatLiteral
    CharacterLiteral
    StringLiterals
    ArrayLiteral
    AssocArrayLiteral
    FunctionLiteral
    AssertExpression
    MixinExpression
    ImportExpression
    NewExpressionWithArgs
    FundamentalType . Identifier
    FundamentalType ( ArgumentListopt )
    TypeCtor ( Type ) . Identifier
    TypeCtor ( Type ) ( ArgumentListopt )
    Typeof
    TypeidExpression
    IsExpression
    ( Expression )
    SpecialKeyword
    TraitsExpression

```
 ### .Identifier

 [*Identifier*](lex#Identifier) is looked up at module scope, rather than the current lexically nested scope. 

 ### this

 Within a non-static member function, `this` resolves to a reference to the object for which the function was called. If the object is an instance of a struct, `this` will be a pointer to that instance. If a member function is called with an explicit reference to `typeof(this)`, a non-virtual call is made:

 
```
class A
{
    char get() { return 'A'; }

    char foo() { return typeof(this).get(); }
    char bar() { return this.get(); }
}

class B : A
{
    override char get() { return 'B'; }
}

void main()
{
    B b = new B();

    assert(b.foo() == 'A');
    assert(b.bar() == 'B');
}

```
 Assignment to `this` is not allowed.

 ### super

 `super` is identical to `this`, except that it is cast to `this`'s base class. It is an error if there is no base class. It is an error to use `super` within a struct member function. (Only class `Object` has no base class.) If a member function is called with an explicit reference to `super`, a non-virtual call is made. 

 Assignment to `super` is not allowed.

 ### null

 `null` represents the null value for pointers, pointers to functions, delegates, dynamic arrays, associative arrays, and class objects. If it has not already been cast to a type, it is given the singular type `typeof(null)` and it is an exact conversion to convert it to the null value for pointers, pointers to functions, delegates, etc. After it is cast to a type, such conversions are implicit, but no longer exact. 

 ### true, false

 These are of type `bool` and when cast to another integral type become the values 1 and 0, respectively. 

 ### Character Literals

 Character literals are single characters and resolve to one of type `char`, `wchar`, or `dchar`. If the literal is a `\u` escape sequence, it resolves to type `wchar`. If the literal is a `\U` escape sequence, it resolves to type `dchar`. Otherwise, it resolves to the type with the smallest size it will fit into. 

 ### String Literals

 
```
StringLiterals:
    StringLiteral
    StringLiterals StringLiteral

```
 String literals can implicitly convert to any of the following types, they have equal weight: 

 

|  |
| --- |
| `immutable(char)*` |
| `immutable(wchar)*` |
| `immutable(dchar)*` |
| `immutable(char)[]` |
| `immutable(wchar)[]` |
| `immutable(dchar)[]` |

 By default, a string literal is typed as a dynamic array, but the element count is known at compile time. So all string literals can be implicitly converted to static array types.

 
```
void foo(char[2] a)
{
    assert(a == "bc");
}
void bar(ref const char[2] a)
{
    assert(a == "bc");
}
void baz(const char[3] a) {}

void main()
{
    string str = "abc";
    foo(str[1 .. 3]);
    bar(str[1 .. 3]);
  //baz(str[1 .. 3]); // cannot match length
}

```
 String literals have a 0 appended to them, which makes them easy to pass to C or C++ functions expecting a `const char*` string. The 0 is not included in the `.length` property of the string literal. 

 ### Array Literals

 
```
ArrayLiteral:
    [ ArgumentListopt ]

```
 Array literals are a comma-separated list of [*AssignExpression*](#AssignExpression)s between square brackets `[` and `]`. The *AssignExpression*s form the elements of a dynamic array, the length of the array is the number of elements. The common type of the all elements is taken to be the type of the array element, and all elements are implicitly converted to that type.

 
```
auto a1 = [1,2,3];  // type is int[], with elements 1, 2 and 3
auto a2 = [1u,2,3]; // type is uint[], with elements 1u, 2u, and 3u

```
 By default, an array literal is typed as a dynamic array, but the element count is known at compile time. So all array literals can be implicitly converted to static array types.

 
```
void foo(long[2] a)
{
    assert(a == [2, 3]);
}
void bar(ref long[2] a)
{
    assert(a == [2, 3]);
    a[0] = 4;
    a[1] = 5;
    assert(a == [4, 5]);
}
void baz(const char[3] a) {}

void main()
{
    long[] arr = [1, 2, 3];

    foo(arr[1 .. 3]);
    assert(arr == [1, 2, 3]);

    bar(arr[1 .. 3]);
    assert(arr == [1, 4, 5]);

  //baz(arr[1 .. 3]); // cannot match length
}

```
 If any of the arguments in the [*ArgumentList*](#ArgumentList) are a *ValueSeq*, then the elements of the *ValueSeq* are inserted as arguments in place of the sequence. 

 Array literals are allocated on the memory managed heap. Thus, they can be returned safely from functions:

 
```
int[] foo()
{
    return [1, 2, 3];
}

```
 When array literals are cast to another array type, each element of the array is cast to the new element type. When arrays that are not literals are cast, the array is reinterpreted as the new type, and the length is recomputed:

 
```
import std.stdio;

void main()
{
    // cast array literal
    const short[] ct = cast(short[]) [cast(byte)1, 1];
    // this is equivalent with:
    // const short[] ct = [cast(short)1, cast(short)1];
    writeln(ct);  // writes [1, 1]

    // cast other array expression
    // --> normal behavior of CastExpression
    byte[] arr = [cast(byte)1, cast(byte)1];
    short[] rt = cast(short[]) arr;
    writeln(rt);  // writes [257]
}

```
 In other words, casting literal expression will change the literal type. ### Associative Array Literals

 
```
AssocArrayLiteral:
    [ KeyValuePairs ]

KeyValuePairs:
    KeyValuePair
    KeyValuePair , KeyValuePairs

KeyValuePair:
    KeyExpression : ValueExpression

KeyExpression:
    AssignExpression

ValueExpression:
    AssignExpression

```
 Associative array literals are a comma-separated list of *key*`:`*value* pairs between square brackets `[` and `]`. The list cannot be empty. The common type of the all keys is taken to be the key type of the associative array, and all keys are implicitly converted to that type. The common type of the all values is taken to be the value type of the associative array, and all values are implicitly converted to that type. An *AssocArrayLiteral* cannot be used to statically initialize anything.

 
```
[21u:"he", 38:"ho", 2:"hi"];  // type is string[uint],
                              // with keys 21u, 38u and 2u
                              // and values "he", "ho", and "hi"

```
 If any of the keys or values in the *KeyValuePairs* are a *ValueSeq*, then the elements of the *ValueSeq* are inserted as arguments in place of the sequence. 

 ### Function Literals

 
```
FunctionLiteral:
    function refopt Typeopt ParameterWithAttributes opt FunctionLiteralBody2
    delegate refopt Typeopt ParameterWithMemberAttributes opt FunctionLiteralBody2
    refopt ParameterWithMemberAttributes FunctionLiteralBody2
    FunctionLiteralBody
    Identifier => AssignExpression

ParameterWithAttributes:
    Parameters FunctionAttributesopt

ParameterWithMemberAttributes:
    Parameters MemberFunctionAttributesopt

FunctionLiteralBody2:
    => AssignExpression
    FunctionLiteralBody

FunctionLiteralBody:
    BlockStatement
    FunctionContractsopt BodyStatement

```
 *FunctionLiteral*s (also known as *Lambdas*) enable embedding anonymous functions and anonymous delegates directly into expressions. *Type* is the return type of the function or delegate, if omitted it is inferred from any *ReturnStatement*s in the *FunctionLiteralBody*. [*ParameterWithAttributes*](#ParameterWithAttributes) or [*ParameterWithMemberAttributes*](#ParameterWithMemberAttributes) can be used to specify the parameters for the function. If these are omitted, the function defaults to the empty parameter list `( )`. The type of a function literal is pointer to function or pointer to delegate. If the keywords `function` or `delegate` are omitted, it is inferred from whether *FunctionLiteralBody* is actually accessing to the outer context. 

 For example:

 
```
int function(char c) fp; // declare pointer to a function

void test()
{
    static int foo(char c) { return 6; }

    fp = &foo;
}

```
 is exactly equivalent to: 
```
int function(char c) fp;

void test()
{
    fp = function int(char c) { return 6;} ;
}

```
 Also:

 
```
int abc(int delegate(int i));

void test()
{
    int b = 3;
    int foo(int c) { return 6 + b; }

    abc(&foo);
}

```
 is exactly equivalent to: 
```
int abc(int delegate(int i));

void test()
{
    int b = 3;

    abc( delegate int(int c) { return 6 + b; } );
}

```
 and the following where the return type `int` and `function`/`delegate` are inferred:

 
```
int abc(int delegate(int i));
int def(int function(int s));

void test()
{
    int b = 3;

    abc( (int c) { return 6 + b; } );  // inferred to delegate
    def( (int c) { return c * 2; } );  // inferred to function
  //def( (int c) { return c * b; } );  // error!
    // Because the FunctionLiteralBody accesses b, then the function literal type
    // is inferred to delegate. But def cannot receive delegate.
}

```
 If the type of a function literal can be uniquely determined from its context, the parameter type inference is possible.

 
```
void foo(int function(int) fp);

void test()
{
    int function(int) fp = (n) { return n * 2; };
    // The type of parameter n is inferred to int.

    foo((n) { return n * 2; });
    // The type of parameter n is inferred to int.
}

```
 Anonymous delegates can behave like arbitrary statement literals. For example, here an arbitrary statement is executed by a loop:

 
```
double test()
{
    double d = 7.6;
    float f = 2.3;

    void loop(int k, int j, void delegate() statement)
    {
        for (int i = k; i < j; i++)
        {
            statement();
        }
    }

    loop(5, 100, { d += 1; });
    loop(3, 10,  { f += 3; });

    return d + f;
}

```
 The syntax `=> AssignExpression` is equivalent to `{ return AssignExpression; }`.

 The syntax `Identifier => AssignExpression` is equivalent to `(Identifier) { return AssignExpression; }`.

 Example usage:

 
```
import std.stdio;

void main()
{
    auto i = 3;
    auto twice  = function (int x) => x * 2;
    auto square = delegate (int x) => x * x;

    auto n = 5;
    auto mul_n = (int x) => x * n;

    writeln(twice(i));   // prints 6
    writeln(square(i));  // prints 9
    writeln(mul_n(i));   // prints 15
}

```
 When comparing with [nested functions](function#nested), the `function` form is analogous to static or non-nested functions, and the `delegate` form is analogous to non-static nested functions. In other words, a delegate literal can access stack variables in its enclosing function, a function literal cannot. 

 ### Uniform construction syntax for built-in scalar types

 The implicit conversions of built-in scalar types can be explicitly represented by using function call syntax. For example:

 
```
auto a = short(1);  // implicitly convert an integer literal '1' to short
auto b = double(a); // implicitly convert a short variable 'a' to double
auto c = byte(128); // error, 128 cannot be represented in a byte

```
 If the argument is omitted, it means default construction of the scalar type:

 
```
auto a = ushort();  // same as: ushort.init
auto b = wchar();   // same as: wchar.init
auto c = creal();   // same as: creal.init

```
 ### Assert Expressions

 
```
AssertExpression:
    assert ( AssertArguments )

AssertArguments:
    AssignExpression ,opt
    AssignExpression , AssignExpression ,opt

```
 The first *AssignExpression* must evaluate to true. If it does not, an *Assert Failure* has occurred and the program enters an *Invalid State*. 

 If the first *AssignExpression* consists entirely of compile time constants, and evaluates to false, it is a special case; it signifies that it is unreachable code. Compile Time Function Execution (CTFE) is not attempted. 

 *AssertExpression* has different semantics if it is in a [`unittest`](unittest) or [`in` contract](contracts). 

 The second *AssignExpression*, if present, must be implicitly convertible to type `const(char)[]`. 

 If the first *AssignExpression* is a reference to a class instance for which a [Class Invariant](class#invariants) exists, the *Class Invariant* must hold. 

 If the first *AssignExpression* is a pointer to a struct instance for which a *Struct Invariant* exists, the *Struct Invariant* must hold. 

 The type of an *AssertExpression* is `void`. 

 **Undefined Behavior:** Once in an *Invalid State* the behavior of the continuing execution of the program is undefined. **Implementation Defined:** Whether the first *AssertExpression* is evaluated or not at runtime is typically set with a compiler switch. If it is not evaluated, any side effects specified by the *AssertExpression* may not occur. The behavior if the first *AssertExpression* is evaluated and is false is also typically set with a compiler switch and may include these options: 1. continuing execution
2. immediately halting via execution of a special CPU instruction
3. aborting the program
4. calling the assert failure function in the corresponding C runtime library
5. throwing the `AssertError` exception in the D runtime library

 If the optional second *AssignExpression* is provided, the implementation may evaluate it and print the resulting message upon assert failure: 
```
void main()
{
    assert(0, "an" ~ " error message");
}

```
 When compiled and run, it will produce the message:

 
```
core.exception.AssertError@test.d(3) an error message
```
 The implementation may handle the case of the first *AssignExpression* evaluating at compile time to false differently in that in release mode it may simply generate a `HLT` instruction or equivalent. 

 **Best Practices:** 1. Do not have side effects in either *AssignExpression* that subsequent code depends on.
2. *AssertExpressions* are intended to detect bugs in the program, do not use for detecting input or environmental errors.
3. Do not attempt to resume normal execution after an *Assert Failure*.

 ### Mixin Expressions

 
```
MixinExpression:
    mixin ( ArgumentList )

```
 Each [*AssignExpression*](#AssignExpression) in the *ArgumentList* is evaluated at compile time, and the result must be representable as a string. The resulting strings are concatenated to form a string. The text contents of the string must be compilable as a valid [*Expression*](#Expression), and is compiled as such.

 
```
int foo(int x)
{
    return mixin("x +", 1) * 7;  // same as ((x + 1) * 7)
}

```
 ### Import Expressions

 
```
ImportExpression:
    import ( AssignExpression )

```
 The *AssignExpression* must evaluate at compile time to a constant string. The text contents of the string are interpreted as a file name. The file is read, and the exact contents of the file become a string literal. 

 Implementations may restrict the file name in order to avoid directory traversal security vulnerabilities. A possible restriction might be to disallow any path components in the file name. 

 Note that by default an import expression will not compile unless one or more paths are passed via the **-J** switch. This tells the compiler where it should look for the files to import. This is a security feature.

 
```
void foo()
{
    // Prints contents of file foo.txt
    writeln(import("foo.txt"));
}

```
 ### Typeid Expressions

 
```
TypeidExpression:
    typeid ( Type )
    typeid ( Expression )

```
 If *Type*, returns an instance of class [`TypeInfo`](https://dlang.org/phobos/object.html) corresponding to *Type*. 

 If *Expression*, returns an instance of class [`TypeInfo`](https://dlang.org/phobos/object.html) corresponding to the type of the *Expression*. If the type is a class, it returns the `TypeInfo` of the dynamic type (i.e. the most derived type). The *Expression* is always executed.

 
```
class A { }
class B : A { }

void main()
{
    writeln(typeid(int));        // int
    uint i;
    writeln(typeid(i++));        // uint
    writeln(i);                  // 1
    A a = new B();
    writeln(typeid(a));          // B
    writeln(typeid(typeof(a)));  // A
}

```
 ### IsExpression

 
```
IsExpression:
    is ( Type )
    is ( Type : TypeSpecialization )
    is ( Type == TypeSpecialization )
    is ( Type : TypeSpecialization , TemplateParameterList )
    is ( Type == TypeSpecialization , TemplateParameterList )
    is ( Type Identifier )
    is ( Type Identifier : TypeSpecialization )
    is ( Type Identifier == TypeSpecialization )
    is ( Type Identifier : TypeSpecialization , TemplateParameterList )
    is ( Type Identifier == TypeSpecialization , TemplateParameterList )


TypeSpecialization:
    Type
    struct
    union
    class
    interface
    enum
    __vector
    function
    delegate
    super
    const
    immutable
    inout
    shared
    return
    __parameters
    module
    package

```
 *IsExpression*s are evaluated at compile time and are used for checking for valid types, comparing types for equivalence, determining if one type can be implicitly converted to another, and deducing the subtypes of a type. The result of an *IsExpression* is a boolean of value `true` if the condition is satisfied. If the condition is not satisfied, the result is a boolean of value `false`. 

 *Type* is the type being tested. It must be syntactically correct, but it need not be semantically correct. If it is not semantically correct, the condition is not satisfied. 

 [*Identifier*](lex#Identifier) is declared to be an alias of the resulting type if the condition is satisfied. The [*Identifier*](lex#Identifier) forms can only be used if the *IsExpression* appears in a [*StaticIfCondition*](version#StaticIfCondition). 

 *TypeSpecialization* is the type that *Type* is being compared against. 

 The forms of the *IsExpression* are: 

 1. `is (` *Type* `)`  
 The condition is satisfied if `Type` is semantically correct (it must be syntactically correct regardless). 
```
alias int func(int);    // func is a alias to a function type
void foo()
{
    if (is(func[]))     // not satisfied because arrays of
                        // functions are not allowed
        writeln("satisfied");
    else
        writeln("not satisfied");

    if (is([][]))       // error, [][] is not a syntactically valid type
        ...
}

```
2. `is (` *Type* `:` *TypeSpecialization* `)`  
 The condition is satisfied if *Type* is semantically correct and it is the same as or can be implicitly converted to *TypeSpecialization*. *TypeSpecialization* is only allowed to be a *Type*. 
```
alias Bar = short;
void foo()
{
    if (is(Bar : int))   // satisfied because short can be
                         // implicitly converted to int
        writeln("satisfied");
    else
        writeln("not satisfied");
}

```
3. `is (` *Type* `==` *TypeSpecialization* `)`  
 The condition is satisfied if *Type* is semantically correct and is the same type as *TypeSpecialization*. If *TypeSpecialization* is one of `struct` `union` `class` `interface` `enum` `function` `delegate` `const` `immutable` `shared` `module` `package` then the condition is satisfied if *Type* is one of those. [Package modules](https://dlang.org/%20%20%20%20%20%20%20%20spec/module.html#package-module) are considered to be both packages and modules. 
```
alias Bar = short;
void foo()
{
    if (is(Bar == int))   // not satisfied because short is not
                          // the same type as int
        writeln("satisfied");
    else
        writeln("not satisfied");
}

```
4. `is (` *Type* *Identifier* `)`  
 The condition is satisfied if *Type* is semantically correct. If so, *Identifier* is declared to be an alias of *Type*. 
```
alias Bar = short;
void foo()
{
    static if (is(Bar T))
        alias S = T;
    else
        alias S = long;

    writeln(typeid(S)); // prints "short"
    if (is(Bar T))      // error, Identifier T form can
                        // only be in StaticIfConditions
        ...
}

```
5. `is (` *Type* *Identifier* `:` *TypeSpecialization* `)`  
 The condition is satisfied if *Type* is the same as *TypeSpecialization*, or if *Type* is a class and *TypeSpecialization* is a base class or base interface of it. The *Identifier* is declared to be either an alias of the *TypeSpecialization* or, if *TypeSpecialization* is dependent on *Identifier*, the deduced type. 
```
alias Bar = int;
alias Abc = long*;
void foo()
{
    static if (is(Bar T : int))
        alias S = T;
    else
        alias S = long;

    writeln(typeid(S));  // prints "int"

    static if (is(Abc U : U*))
    {
        U u;
        writeln(typeid(typeof(u)));  // prints "long"
    }
}

```
 The way the type of *Identifier* is determined is analogous to the way template parameter types are determined by [*TemplateTypeParameterSpecialization*](template#TemplateTypeParameterSpecialization).
6. `is (` *Type* *Identifier* `==` *TypeSpecialization* `)`  
 The condition is satisfied if *Type* is semantically correct and is the same as *TypeSpecialization*. The *Identifier* is declared to be either an alias of the *TypeSpecialization* or, if *TypeSpecialization* is dependent on *Identifier*, the deduced type. If *TypeSpecialization* is one of `struct` `union` `class` `interface` `enum` `function` `delegate` `const` `immutable` `shared` then the condition is satisfied if *Type* is one of those. Furthermore, *Identifier* is set to be an alias of the type: 

| **keyword** | **alias type for *Identifier*** |
| --- | --- |
| `struct` | *Type* |
| `union` | *Type* |
| `class` | *Type* |
| `interface` | *Type* |
| `super` | *TypeSeq* of base classes and interfaces |
| `enum` | the base type of the enum |
| `function` | *TypeSeq* of the function parameter types. For C- and D-style variadic functions, only the non-variadic parameters are included. For typesafe variadic functions, the `...` is ignored. |
| `delegate` | the function type of the delegate |
| `return` | the return type of the function, delegate, or function pointer |
| `__parameters` | the parameter sequence of a function, delegate, or function pointer. This includes the parameter types, names, and default values. |
| `const` | *Type* |
| `immutable` | *Type* |
| `shared` | *Type* |


```
alias Bar = short;
enum E : byte { Emember }
void foo()
{
    static if (is(Bar T == int))   // not satisfied, short is not int
        alias S = T;
    alias U = T;                   // error, T is not defined

    static if (is(E V == enum))    // satisfied, E is an enum
        V v;                       // v is declared to be a byte
}

```
7. `is (` *Type* `:` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)`  
 `is (` *Type* `==` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)`  
 `is (` *Type* *Identifier* `:` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)`  
 `is (` *Type* *Identifier* `==` *TypeSpecialization* `,` [*TemplateParameterList*](template#TemplateParameterList) `)` More complex types can be pattern matched; the [*TemplateParameterList*](template#TemplateParameterList) declares symbols based on the parts of the pattern that are matched, analogously to the way implied template parameters are matched. 
```
import std.stdio, std.typecons;

void main()
{
    alias Tup = Tuple!(int, string);
    alias AA = long[string];

    static if (is(Tup : Template!Args, alias Template, Args...))
    {
        writeln(__traits(isSame, Template, Tuple)); // true
        writeln(is(Template!(int, string) == Tup));  // true
        writeln(typeid(Args[0]));  // int
        writeln(typeid(Args[1]));  // immutable(char)[]
    }

    static if (is(AA T : T[U], U : string))
    {
        writeln(typeid(T));  // long
        writeln(typeid(U));  // string
    }

    static if (is(AA A : A[B], B : int))
    {
        assert(0);  // should not match, as B is not an int
    }

    static if (is(int[10] W : W[len], int len))
    {
        writeln(typeid(W));  // int
        writeln(len);        // 10
    }

    static if (is(int[10] X : X[len], int len : 5))
    {
        assert(0);  // should not match, len should be 10
    }
}

```

 Special Keywords
----------------

 
```
SpecialKeyword:
    __FILE__
    __FILE_FULL_PATH__
    __MODULE__
    __LINE__
    __FUNCTION__
    __PRETTY_FUNCTION__

```
 `__FILE__` and `__LINE__` expand to the source file name and line number at the point of instantiation. The path of the source file is left up to the compiler. 

 `__FILE_FULL_PATH__` expands to the absolute source file name at the point of instantiation.

 `__MODULE__` expands to the module name at the point of instantiation.

 `__FUNCTION__` expands to the fully qualified name of the function at the point of instantiation.

 `__PRETTY_FUNCTION__` is similar to `__FUNCTION__`, but also expands the function return type, its parameter types, and its attributes.

 Example:

 
```
module test;
import std.stdio;

void test(string file = __FILE__, size_t line = __LINE__,
        string mod = __MODULE__, string func = __FUNCTION__,
        string pretty = __PRETTY_FUNCTION__,
        string fileFullPath = __FILE_FULL_PATH__)
{
    writefln("file: '%s', line: '%s', module: '%s',\nfunction: '%s', " ~
        "pretty function: '%s',\nfile full path: '%s'",
        file, line, mod, func, pretty, fileFullPath);
}

int main(string[] args)
{
    test();
    return 0;
}

```
 Assuming the file was at /example/test.d, this will output:

 
```
file: 'test.d', line: '13', module: 'test',
function: 'test.main', pretty function: 'int test.main(string[] args)',
file full path: '/example/test.d'

```
 Associativity and Commutativity
-------------------------------

 An implementation may rearrange the evaluation of expressions according to arithmetic associativity and commutativity rules as long as, within that thread of execution, no observable difference is possible. 

 This rule precludes any associative or commutative reordering of floating point expressions. 

 

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/expression.html>

Functions
=========

 **Contents** 1. [Grammar](#grammar)
2. [Function Contracts](#contracts)
	1. [In, Out and Inheritance](#in_out_inheritance)
3. [Function Return Values](#function-return-values)
4. [Functions Without Bodies](#function-declarations)
5. [Pure Functions](#pure-functions)
6. [Nothrow Functions](#nothrow-functions)
7. [Ref Functions](#ref-functions)
8. [Auto Functions](#auto-functions)
9. [Auto Ref Functions](#auto-ref-functions)
10. [Inout Functions](#inout-functions)
	1. [Matching an `inout` Parameter](#matching-an-inout-parameter)
11. [Optional Parentheses](#optional-parenthesis)
12. [Property Functions](#property-functions)
13. [Virtual Functions](#virtual-functions)
	1. [Function Inheritance and Overriding](#function-inheritance)
14. [Inline Functions](#inline-functions)
15. [Function Overloading](#function-overloading)
	1. [Overload Sets](#overload-sets)
16. [Function Parameters](#parameters)
	1. [Parameter Storage Classes](#param-storage)
	2. [In Parameters](#in-params)
	3. [Ref and Out Parameters](#ref-params)
	4. [Lazy Parameters](#lazy-params)
	5. [Function Default Arguments](#function-default-args)
	6. [Return Ref Parameters](#return-ref-parameters)
	7. [Scope Parameters](#scope-parameters)
	8. [Return Scope Parameters](#return-scope-parameters)
	9. [Ref Return Scope Parameters](#ref-return-scope-parameters)
	10. [User-Defined Attributes for Parameters](#udas-parameters)
	11. [Variadic Functions](#variadic)
17. [Local Variables](#local-variables)
	1. [Local Static Variables](#local-static-variables)
18. [Nested Functions](#nested)
19. [Delegates, Function Pointers, and Closures](#closures)
	1. [Anonymous Functions and Anonymous Delegates](#anonymous)
20. [`main()` Function](#main)
	1. [BetterC `main()` Function](#betterc-main)
21. [Function Templates](#function-templates)
22. [Compile Time Function Execution (CTFE)](#interpretation)
	1. [String Mixins and Compile Time Function Execution](#string-mixins)
23. [No-GC Functions](#nogc-functions)
24. [Function Safety](#function-safety)
	1. [Safe Functions](#safe-functions)
	2. [Trusted Functions](#trusted-functions)
	3. [System Functions](#system-functions)
	4. [Safe Interfaces](#safe-interfaces)
	5. [Safe Values](#safe-values)
	6. [Safe Aliasing](#safe-aliasing)
25. [Function Attribute Inference](#function-attribute-inference)
26. [Uniform Function Call Syntax (UFCS)](#pseudo-member)

 Grammar
-------

 ### Function declaration

 
```
FuncDeclaration:
    StorageClassesopt BasicType FuncDeclarator FunctionBody
    AutoFuncDeclaration

AutoFuncDeclaration:
    StorageClasses Identifier FuncDeclaratorSuffix FunctionBody

FuncDeclarator:
    TypeSuffixesopt Identifier FuncDeclaratorSuffix

FuncDeclaratorSuffix:
    Parameters MemberFunctionAttributesopt
    TemplateParameters Parameters MemberFunctionAttributesopt Constraintopt

```
 ### Parameters

 
```
Parameters:
    ( ParameterListopt )

ParameterList:
    Parameter
    Parameter , ParameterList
    VariadicArgumentsAttributes ...

Parameter:
    ParameterAttributesopt BasicType Declarator
    ParameterAttributesopt BasicType Declarator ...
    ParameterAttributesopt BasicType Declarator = AssignExpression
    ParameterAttributesopt Type
    ParameterAttributesopt Type ...

ParameterAttributes:
    InOut
    UserDefinedAttribute
    ParameterAttributes InOut
    ParameterAttributes UserDefinedAttribute
    ParameterAttributes

InOut:
    auto
    TypeCtor
    final
    in
    lazy
    out
    ref
    return ref
    scope

VariadicArgumentsAttributes:
    VariadicArgumentsAttribute
    VariadicArgumentsAttribute VariadicArgumentsAttributes

VariadicArgumentsAttribute:
    const
    immutable
    return
    scope
    shared

```
 ### Function attributes

 
```
FunctionAttributes:
    FunctionAttribute
    FunctionAttribute FunctionAttributes

FunctionAttribute:
    FunctionAttributeKwd
    Property

MemberFunctionAttributes:
    MemberFunctionAttribute
    MemberFunctionAttribute MemberFunctionAttributes

MemberFunctionAttribute:
    const
    immutable
    inout
    return
    shared
    FunctionAttribute

```
 ### Function body

 
```
FunctionBody:
    SpecifiedFunctionBody
    MissingFunctionBody
    ShortenedFunctionBody

FunctionLiteralBody:
    SpecifiedFunctionBody

SpecifiedFunctionBody:
    doopt BlockStatement
    FunctionContractsopt InOutContractExpression doopt BlockStatement
    FunctionContractsopt InOutStatement do BlockStatement

MissingFunctionBody:
    ;
    FunctionContractsopt InOutContractExpression ;
    FunctionContractsopt InOutStatement

ShortenedFunctionBody:
    => AssignExpression ;

```
 Examples:

 
```
int hasSpecifiedBody() { return 1; }
int hasMissingBody();
int hasShortenedBody() => 1;

```
 **Note:** The `ShortenedFunctionBody` form requires the `-preview=shortenedMethods` command-line switch, which is available starting in v2.096.0.

 Function Contracts
------------------

 
```
FunctionContracts:
    FunctionContract
    FunctionContract FunctionContracts

FunctionContract:
    InOutContractExpression
    InOutStatement

InOutContractExpression:
    InContractExpression
    OutContractExpression

InOutStatement:
    InStatement
    OutStatement

InContractExpression:
    in ( AssertArguments )

OutContractExpression:
    out ( ; AssertArguments )
    out ( Identifier ; AssertArguments )

InStatement:
    in BlockStatement

OutStatement:
    out BlockStatement
    out ( Identifier ) BlockStatement

```
 Function Contracts specify the preconditions and postconditions of a function. They are used in [Contract Programming](contracts). 

 Preconditions and postconditions do not affect the type of the function.

 ### Preconditions

 An [*InContractExpression*](#InContractExpression) is a precondition.

 The first [*AssignExpression*](expression#AssignExpression) of the [*AssertArguments*](expression#AssertArguments) must evaluate to true. If it does not, the precondition has failed.

 The second *AssignExpression*, if present, must be implicitly convertible to type `const(char)[]`. 

 An [*InStatement*](#InStatement) is also a precondition. Any [*AssertExpression*](expression#AssertExpression) appearing in an *InStatement* will be an *InContractExpression*. 

 Preconditions must semantically be satisfied before the function starts executing. If it is not, the program enters an *Invalid State*. 

 **Implementation Defined:** Whether the preconditions are actually run or not is implementation defined. This is usually selectable with a compiler switch. Its behavior upon precondition failure is also usually selectable with a compiler switch. One option is to throw an `AssertError` with a message consisting of the optional second *AssignExpression*. **Best Practices:** Use preconditions to validate that input arguments have values that are expected by the function. **Best Practices:** Since preconditions may or may not be actually checked at runtime, avoid using preconditions that have side effects. The expression form is:

 
```
in (expression)
in (expression, "failure string")
{
    ...function body...
}

```
 The block statement form is:

 
```
in
{
    ...contract preconditions...
}
do
{
    ...function body...
}

```
 ### Postconditions

 An [*OutContractExpression*](#OutContractExpression) is a postcondition.

 The first [*AssignExpression*](expression#AssignExpression) of the [*AssertArguments*](expression#AssertArguments) must evaluate to true. If it does not, the postcondition has failed.

 The second *AssignExpression*, if present, must be implicitly convertible to type `const(char)[]`. 

 An [*OutStatement*](#OutStatement) is also a postcondition. Any [*AssertExpression*](expression#AssertExpression) appearing in an *OutStatement* will be an *OutContractExpression*. 

 Postconditions must semantically be satisfied after the function finishes executing. If it is not, the program enters an *Invalid State*. 

 **Implementation Defined:** Whether the postconditions are actually run or not is implementation defined. This is usually selectable with a compiler switch. Its behavior upon postcondition failure is also usually selectable with a compiler switch. One option is to throw an `AssertError` with a message consisting of the optional second *AssignExpression*. **Best Practices:** Use postconditions to validate that the input arguments and return value have values that are expected by the function. **Best Practices:** Since postconditions may or may not be actually checked at runtime, avoid using postconditions that have side effects. The expression form is:

 
```
out (identifier; expression)
out (identifier; expression, "failure string")
out (; expression)
out (; expression, "failure string")
{
    ...function body...
}

```
 The block statement form is:

 
```
out
{
    ...contract postconditions...
}
out (identifier)
{
    ...contract postconditions...
}
do
{
    ...function body...
}

```
 The optional identifier in either type of postcondition is set to the return value of the function, and can be accessed from within the postcondition.

 ### Example

 
```
int fun(ref int a, int b)
in (a > 0)
in (b >= 0, "b cannot be negative!")
out (r; r > 0, "return must be positive")
out (; a != 0)
{
    // function body
}

```
 
```
int fun(ref int a, int b)
in
{
    assert(a > 0);
    assert(b >= 0, "b cannot be negative!");
}
out (r)
{
    assert(r > 0, "return must be positive");
    assert(a != 0);
}
do
{
    // function body
}

```
 The two functions are identical semantically.

 ### In, Out and Inheritance

 If a function in a derived class overrides a function from its super class, then only the preconditions of one of the function and its overridden functions must be satisfied. Overriding functions then becomes a process of *loosening* the preconditions. 

 A function without preconditions means its precondition is always satisfied. Therefore if any function in an inheritance hierarchy has no preconditions, then any preconditions on functions overriding it have no meaningful effect. 

 Conversely, all of the postconditions of the function and its overridden functions must to be satisfied. Adding overriding functions then becomes a processes of *tightening* the postconditions. 

 Function Return Values
----------------------

 Function return values not marked as `ref` are considered to be rvalues. This means they cannot be passed by reference to other functions. 

 Functions Without Bodies
------------------------

 Functions without bodies:

 
```
int foo();

```
 that are not declared as `abstract` are expected to have their implementations elsewhere, and that implementation will be provided at the link step. This enables an implementation of a function to be completely hidden from the user of it, and the implementation may be in another language such as C, assembler, etc. 

 Pure Functions
--------------

 Pure functions are annotated with the `pure` attribute. 

 Pure functions cannot directly access global or static mutable state. 

 Pure functions can only call pure functions.

 A pure function can override an impure function, but cannot be overridden by an impure function. I.e. it is covariant with an impure function. 

 A *weakly pure function* has parameters with mutable indirections. Program state can be modified transitively through the matching argument. 

 
```
pure int foo(int[] arr) { arr[] += 1; return arr.length; }
int[] a = [1, 2, 3];
foo(a);
assert(a == [2, 3, 4]);

```
 A *strongly pure function* has no parameters with mutable indirections and cannot modify any program state external to the function. 

 
```
struct S { double x; }
pure int foo(immutable(int)[] arr, int num, S val)
{
    //arr[num] = 1; // compile error
    num = 2;        // has no side effect to the caller side
    val.x = 3.14;   // ditto
    return arr.length;
}

```
 A strongly pure function can call a weakly pure function.

 Pure functions can modify the local state of the function.

 A pure function can:

 * read and write the floating point exception flags
* read and write the floating point mode flags, as long as those flags are restored to their initial state upon function entry

 **Undefined Behavior:** occurs if these flags are not restored to their initial state upon function exit. It is the programmer's responsibility to ensure this. A pure function can perform impure operations in statements that are in a [*ConditionalStatement*](version#ConditionalStatement) controlled by a [*DebugCondition*](version#DebugCondition). 

 **Best Practices:** this relaxation of purity checks in DebugConditions is intended solely to make debugging programs easier. A pure function can throw exceptions.

 
```
import std.stdio;
int x;
immutable int y;
const int* pz;

pure int foo(int i,
             char* p,
             const char* q,
             immutable int* s)
{
    debug writeln("in foo()"); // ok, impure code allowed in debug statement
    x = i;   // error, modifying global state
    i = x;   // error, reading mutable global state
    i = y;   // ok, reading immutable global state
    i = *pz; // error, reading const global state
    return i;
}

```
 [Nested functions](#variadicnested) inside a pure function are implicitly marked as pure.

 
```
pure int foo(int x, immutable int y)
{
    int bar()
    // implicitly marked as pure, to be "weakly pure"
    // since hidden context pointer to foo stack context is mutable
    {
        x = 10;     // can access states in enclosing scope
                    // through the mutable context pointer
        return x;
    }
    pragma(msg, typeof(&bar));  // int delegate() pure

    int baz() immutable
    // qualifies hidden context pointer with immutable,
    // and has no other parameters, therefore "strongly pure"
    {
        //return x; // error, cannot access mutable data
                    // through the immutable context pointer
        return y;   // ok
    }

    // can call pure nested functions
    return bar() + baz();
}

```
 A *pure factory function* is a strongly pure function that returns a result that has mutable indirections. All mutable memory returned by the call may not be referenced by any other part of the program, i.e. it is newly allocated by the function. Nor may the mutable references of the result refer to any object that existed before the function call. For example:

 
```
struct List { int payload; List* next; }
pure List* make(int a, int b)
{
    auto result = new List(a, null);
    result.next = new List(b, result);
    return result;
}

```
 All references in `make`'s result refer to other `List` objects created by `make`, and no other part of the program refers to any of these objects. This restriction does not apply to any Exception or Error thrown from the function. 

 Pure destructors do not benefit of special elision.

 **Implementation Defined:** An implementation may assume that a strongly pure function that returns a result without mutable indirections will have the same effect for all invocations with equivalent arguments. It is allowed to memoize the result of the function under the assumption that equivalent parameters always produce equivalent results. A strongly pure function may still have behavior inconsistent with memoization by e.g. using `cast`s or by changing behavior depending on the address of its parameters. An implementation is currently not required to enforce validity of memoization in all cases. If a strongly pure function throws an Exception or an Error, the assumptions related to memoization do not carry to the thrown exception. Nothrow Functions
-----------------

 Nothrow functions can only throw exceptions derived from [`class Error`](https://dlang.org/phobos/object.html#Error). 

 Nothrow functions are covariant with throwing ones.

 Ref Functions
-------------

 Ref functions allow functions to return by reference, meaning that the return value must be an lvalue, and the lvalue is returned, not the rvalue. 

 
```
ref int foo()
{
    auto p = new int(2);
    return *p;
}
...
int i = foo(); // i is set to 2
foo() = 3;     // reference returns can be lvalues

```
 Returning a reference to an expired function context is not allowed. This includes local variables, temporaries and parameters that are part of an expired function context. 

 
```
ref int sun()
{
    int i;
    return i;  // error, escaping a reference to local variable i
}

```
 A `ref` parameter may not be returned by `ref`.

 
```
ref int moon(ref int i)
{
    return i; // error
}

```
 Auto Functions
--------------

 Auto functions have their return type inferred from any [*ReturnStatement*](statement#ReturnStatement)s in the function body. 

 An auto function is declared without a return type. If it does not already have a storage class, use the auto storage class. 

 If there are multiple *ReturnStatement*s, the types of them must be implicitly convertible to a common type. If there are no *ReturnStatement*s, the return type is inferred to be void.

 
```
auto foo(int x) { return x + 3; }          // inferred to be int
auto bar(int x) { return x; return 2.5; }  // inferred to be double

```
 Auto Ref Functions
------------------

 Auto ref functions infer their return type just as [auto functions](#auto-functions) do. In addition, they become [ref functions](#ref-functions) if all return expressions are lvalues, and it would not be a reference to a local or a parameter.

 
```
auto ref f1(int x)     { return x; }  // value return
auto ref f2()          { return 3; }  // value return
auto ref f3(ref int x) { return x; }  // ref return
auto ref f4(out int x) { return x; }  // ref return
auto ref f5() { static int x; return x; }  // ref return

```
 The ref-ness of a function is determined from all [*ReturnStatement*](statement#ReturnStatement)s in the function body:

 
```
auto ref f1(ref int x) { return 3; return x; }  // ok, value return
auto ref f2(ref int x) { return x; return 3; }  // ok, value return
auto ref f3(ref int x, ref double y)
{
    return x; return y;
    // The return type is deduced to double, but cast(double)x is not an lvalue,
    // then become a value return.
}

```
 Auto ref function can have explicit return type.

 
```
auto ref int (ref int x) { return x; }  // ok, ref return
auto ref int foo(double x) { return x; }   // error, cannot convert double to int

```
 Inout Functions
---------------

 Functions that differ only in whether the parameters are mutable, `const` or `immutable`, and have corresponding mutable, `const` or `immutable` return types, can be combined into one function using the `inout` type constructor. Consider the following overload set: 

 
```
int[] slice(int[] a, int x, int y) { return a[x .. y]; }

const(int)[] slice(const(int)[] a, int x, int y) { return a[x .. y]; }

immutable(int)[] slice(immutable(int)[] a, int x, int y) { return a[x .. y]; }

```
 The code generated by each of these functions is identical. The inout type constructor can combine them into one function:

 
```
inout(int)[] slice(inout(int)[] a, int x, int y) { return a[x .. y]; }

```
 The inout keyword forms a wildcard that stands in for mutable, `const`, `immutable`, `inout`, or `inout const`. When calling the function, the `inout` state of the return type is changed to match that of the argument type passed to the `inout` parameter. 

 `inout` can also be used as a type constructor inside a function that has a parameter declared with `inout`. The `inout` state of a type declared with `inout` is changed to match that of the argument type passed to the `inout` parameter: 

 
```
inout(int)[] asymmetric(inout(int)[] input_data)
{
    inout(int)[] r = input_data;
    while (r.length > 1 && r[0] == r[$-1])
        r = r[1..$-1];
    return r;
}

```
 Inout types can be implicitly converted to `const` or `inout const`, but to nothing else. Other types cannot be implicitly converted to `inout`. Casting to or from `inout` is not allowed in `@safe` functions. 

 
```
void f(inout int* ptr)
{
    const int* p = ptr;
    int* q = ptr; // error
    immutable int* r = ptr; // error
}

```
 ### Matching an `inout` Parameter

 A set of arguments to a function with `inout` parameters is considered a match if any `inout` argument types match exactly, or:

 1. No argument types are composed of `inout` types.
2. A mutable, `const` or `immutable` argument type can be matched against each corresponding parameter `inout` type.

 If such a match occurs, `inout` is considered the common qualifier of the matched qualifiers. If more than two parameters exist, the common qualifier calculation is recursively applied. 

 

Common qualifier of the two type qualifiers|  | *mutable* | `const` | `immutable` | `inout` | `inout const` |
| *mutable* (= m) | m | c | c | c | c |
| `const` (= c) | c | c | c | c | c |
| `immutable` (= i) | c | c | i | wc | wc |
| `inout` (= w) | c | c | wc | w | wc |
| `inout const` (= wc) | c | c | wc | wc | wc |

 The `inout` in the return type is then rewritten to match the `inout` qualifiers:

 
```
int[] ma;
const(int)[] ca;
immutable(int)[] ia;

inout(int)[] foo(inout(int)[] a) { return a; }
void test1()
{
    // inout matches to mutable, so inout(int)[] is
    // rewritten to int[]
    int[] x = foo(ma);

    // inout matches to const, so inout(int)[] is
    // rewritten to const(int)[]
    const(int)[] y = foo(ca);

    // inout matches to immutable, so inout(int)[] is
    // rewritten to immutable(int)[]
    immutable(int)[] z = foo(ia);
}

inout(const(int))[] bar(inout(int)[] a) { return a; }
void test2()
{
    // inout matches to mutable, so inout(const(int))[] is
    // rewritten to const(int)[]
    const(int)[] x = bar(ma);

    // inout matches to const, so inout(const(int))[] is
    // rewritten to const(int)[]
    const(int)[] y = bar(ca);

    // inout matches to immutable, so inout(int)[] is
    // rewritten to immutable(int)[]
    immutable(int)[] z = bar(ia);
}

```
 **Note:** Shared types cannot be matched with `inout`. 

 Optional Parentheses
--------------------

 If a function call passes no explicit argument, i.e. it would syntactically use `()`, then these parentheses may be omitted, similar to a getter invocation of a [property function](#property-functions). 

 
```
void foo() {}   // no arguments
void fun(int x = 10) { }
void bar(int[] arr) {}  // for UFCS

void main()
{
    foo();      // OK
    foo;        // also OK
    fun;        // OK

    int[] arr;
    arr.bar();  // OK
    arr.bar;    // also OK
}

```
 Optional parentheses are not applied to delegates or function pointers.

 
```
void main()
{
    int function() fp;

    assert(fp == 6);    // Error, incompatible types int function() and int
    assert(*fp == 6);   // Error, incompatible types int() and int

    int delegate() dg;
    assert(dg == 6);    // Error, incompatible types int delegate() and int
}

```
 If a function returns a delegate or function pointer, the parentheses are required if the returned value is to be called. 

 
```
struct S {
    int function() callfp() { return &numfp; }
    int delegate() calldg() return { return &numdg; }
    int numdg() { return 6; }
}

int numfp() { return 6; }

void main()
{
    S s;
    int function() fp;

    fp = s.callfp;
    assert(fp() == 6);

    fp = s.callfp();
    assert(fp() == 6);

    int x = s.callfp()();
    assert(x == 6);

    int delegate() dg;

    dg = s.calldg;
    assert(dg() == 6);

    dg = s.calldg();
    assert(dg() == 6);

    int y = s.calldg()();
    assert(y == 6);
}

```
 Property Functions
------------------

 WARNING: The definition and usefulness of property functions is being reviewed, and the implementation is currently incomplete. Using property functions is not recommended until the definition is more certain and implementation more mature.

 Properties are functions that can be syntactically treated as if they were fields or variables. Properties can be read from or written to. A property is read by calling a method or function with no arguments; a property is written by calling a method or function with its argument being the value it is set to. 

 Simple getter and setter properties can be written using [UFCS](#pseudo-member). These can be enhanced with the additon of the `@property` attribute to the function, which adds the following behaviors: 

 * `@property` functions cannot be overloaded with non-`@property` functions with the same name.
* `@property` functions can only have zero, one or two parameters.
* `@property` functions cannot have variadic parameters.
* For the expression `typeof(exp)` where `exp` is an `@property` function, the type is the return type of the function, rather than the type of the function.
* For the expression `__traits(compiles, exp)` where `exp` is an `@property` function, a further check is made to see if the function can be called.
* `@property` are mangled differently, meaning that `@property` must be consistently used across different compilation units.
* The ObjectiveC interface recognizes `@property` setter functions as special and modifies them accordingly.

 A simple property would be:

 
```
struct Foo
{
    @property int data() { return m_data; } // read property

    @property int data(int value) { return m_data = value; } // write property

  private:
    int m_data;
}

```
 To use it:

 
```
int test()
{
    Foo f;

    f.data = 3;        // same as f.data(3);
    return f.data + 3; // same as return f.data() + 3;
}

```
 The absence of a read method means that the property is write-only. The absence of a write method means that the property is read-only. Multiple write methods can exist; the correct one is selected using the usual function overloading rules. 

 In all the other respects, these methods are like any other methods. They can be static, have different linkages, have their address taken, etc. 

 The built in properties `.sizeof`, `.alignof`, and `.mangleof` may not be declared as fields or methods in structs, unions, classes or enums. 

 If a property function has no parameters, it works as a getter. If has exactly one parameter, it works as a setter. 

 Virtual Functions
-----------------

 Virtual functions are class member functions that are called indirectly through a function pointer table, called a `vtbl[]`, rather than directly. 

 Member functions that are virtual can be overridden, unless they are `final`. 

 Struct and union member functions are not virtual. 

 Static member functions are not virtual. 

 Member functions which are `private` or `package` are not virtual. 

 Member template functions are not virtual. 

 Member functions with `Objective-C` linkage are virtual even if marked with `final` or `static`. 

 
```
class A
{
    int def() { ... }
    final int foo() { ... }
    final private int bar() { ... }
    private int abc() { ... }
}

class B : A
{
    override int def() { ... }  // ok, overrides A.def
    override int foo() { ... }  // error, A.foo is final
    int bar() { ... }  // ok, A.bar is final private, but not virtual
    int abc() { ... }  // ok, A.abc is not virtual, B.abc is virtual
}

void test(A a)
{
    a.def();    // calls B.def
    a.foo();    // calls A.foo
    a.bar();    // calls A.bar
    a.abc();    // calls A.abc
}

void func()
{
    B b = new B();
    test(b);
}

```
 The overriding function may be covariant with the overridden function. A covariant function has a type that is implicitly convertible to the type of the overridden function. 

 
```
class A { }
class B : A { }

class Foo
{
    A test() { return null; }
}

class Bar : Foo
{
    // overrides and is covariant with Foo.test()
    override B test() { return null; }
}

```
 Virtual functions all have a hidden parameter called the *this* reference, which refers to the class object instance for which the function is called. 

  Functions with `Objective-C` linkage have an additional hidden, unnamed, parameter which is the selector it was called with. 

 To directly call a base member function, insert base class name before the member function name. For example: 

 
```
class B
{
    int foo() { return 1; }
}
class C : B
{
    override int foo() { return 2; }

    void test()
    {
        assert(B.foo() == 1);  // translated to this.B.foo(), and
                               // calls B.foo statically.
        assert(C.foo() == 2);  // calls C.foo statically, even if
                               // the actual instance of 'this' is D.
    }
}
class D : C
{
    override int foo() { return 3; }
}
void main()
{
    auto d = new D();
    assert(d.foo() == 3);    // calls D.foo
    assert(d.B.foo() == 1);  // calls B.foo
    assert(d.C.foo() == 2);  // calls C.foo
    d.test();
}

```
 **Implementation Defined:** Normally calling a virtual function implies getting the address of the function at runtime by indexing into the class's `vtbl[]`. If the implementation can determine that the called virtual function will be statically known, such as if it is `final`, it can use a direct call instead. ### Function Inheritance and Overriding

 A function in a derived class with the same name and covariant with a function in a base class overrides that function:

 
```
class A
{
    int foo(int x) { ... }
}

class B : A
{
    override int foo(int x) { ... }
}

void test()
{
    B b = new B();
    bar(b);
}

void bar(A a)
{
    a.foo(1);   // calls B.foo(int)
}

```
 When doing overload resolution, the functions in the base class are not considered, as they are not in the same [Overload Set](#overload-sets): 

 
```
class A
{
    int foo(int x) { ... }
    int foo(long y) { ... }
}

class B : A
{
    override int foo(long x) { ... }
}

void test()
{
    B b = new B();
    b.foo(1);  // calls B.foo(long), since A.foo(int) not considered
    A a = b;

    a.foo(1);  // issues runtime error (instead of calling A.foo(int))
}

```
 To include the base class's functions in the overload resolution process, use an [*AliasDeclaration*](declaration#AliasDeclaration): 

 
```
class A
{
    int foo(int x) { ... }
    int foo(long y) { ... }
}

class B : A
{
    alias foo = A.foo;
    override int foo(long x) { ... }
}

void test()
{
    B b = new B();
    bar(b);
}

void bar(A a)
{
    a.foo(1);      // calls A.foo(int)
    B b = new B();
    b.foo(1);      // calls A.foo(int)
}

```
 If such an *AliasDeclaration* is not used, the derived class's functions completely override all the functions of the same name in the base class, even if the types of the parameters in the base class functions are different. It is illegal if, through implicit conversions to the base class, those other functions do get called: 

 
```
class A
{
    void set(long i) { }
    void set(int i)  { }
}
class B : A
{
    void set(long i) { }
}

void foo(A a)
{
    int i;
    a.set(3);   // error, use of A.set(int) is hidden by B
                // use 'alias set = A.set;' to introduce base class overload set
    assert(i == 1);
}

void main()
{
    foo(new B);
}

```
 A function parameter's default value is not inherited:

 
```
class A
{
    void foo(int x = 5) { ... }
}

class B : A
{
    void foo(int x = 7) { ... }
}

class C : B
{
    void foo(int x) { ... }
}

void test()
{
    A a = new A();
    a.foo();       // calls A.foo(5)

    B b = new B();
    b.foo();       // calls B.foo(7)

    C c = new C();
    c.foo();       // error, need an argument for C.foo
}

```
 An overriding function inherits any unspecified [*FunctionAttributes*](#FunctionAttributes) from the attributes of the overridden function.

 
```
class B
{
    void foo() pure nothrow @safe {}
}
class D : B
{
    override void foo() {}
}
void main()
{
    auto d = new D();
    pragma(msg, typeof(&d.foo));
    // prints "void delegate() pure nothrow @safe" in compile time
}

```
 The attributes [`@disable`](attribute#disable) and [`deprecated`](attribute#deprecated) are not allowed on overriding functions. 

 **Rationale:** To stop the compilation or to output the deprecation message, the implementation must be able to determine the target of the call, which can't be guaranteed when it is virtual. 
```
class B
{
    void foo() {}
}

class D : B
{
    @disable override void foo() {}  // error, can't apply @disable to overriding function
}

```
 Static functions with `Objective-C` linkage are overridable.

 Inline Functions
----------------

 The compiler makes the decision whether to inline a function or not. This decision may be controlled by [`pragma(inline)`](pragma#inline).

 **Implementation Defined:** Whether a function is inlined or not is implementation defined, though any [*FunctionLiteral*](expression#FunctionLiteral) should be inlined when used in its declaration scope. Function Overloading
--------------------

 *Function overloading* occurs when two or more functions in the same scope have the same name. The function selected is the one that is the *best match* to the arguments. The matching levels are: 

 1. no match
2. match with implicit conversions
3. match with qualifier conversion (if the argument type is [qualifier-convertible](http://dlang.org/glossary.html#qualifier-convertible) to the parameter type)
4. exact match

 Each argument (including any `this` reference) is compared against the function's corresponding parameter to determine the match level for that argument. The match level for a function is the *worst* match level of each of its arguments.

 Literals do not match `ref` or `out` parameters.

 If two or more functions have the same match level, then *partial ordering* is used to disambiguate to find the best match. Partial ordering finds the most specialized function. If neither function is more specialized than the other, then it is an ambiguity error. Partial ordering is determined for functions *f* and *g* by taking the parameter types of *f*, constructing a list of arguments by taking the default values of those types, and attempting to match them against *g*. If it succeeds, then *g* is at least as specialized as *f*. For example: 

 
```
class A { }
class B : A { }
class C : B { }
void foo(A);
void foo(B);

void test()
{
    C c;
    /* Both foo(A) and foo(B) match with implicit conversions (level 2).
     * Applying partial ordering rules,
     * foo(B) cannot be called with an A, and foo(A) can be called
     * with a B. Therefore, foo(B) is more specialized, and is selected.
     */
    foo(c); // calls foo(B)
}

```
 A function with a variadic argument is considered less specialized than a function without. 

 ### Overload Sets

 Functions declared at the same scope overload against each other, and are called an *Overload Set*. An example of an overload set are functions defined at module level: 

 
```
module A;
void foo() { }
void foo(long i) { }

```
 `A.foo()` and `A.foo(long)` form an overload set. A different module can also define another overload set of functions with the same name: 

 
```
module B;
class C { }
void foo(C) { }
void foo(int i) { }

```
 and A and B can be imported by a third module, C. Both overload sets, the `A.foo` overload set and the `B.foo` overload set, are found when searching for symbol `foo`. An instance of `foo` is selected based on it matching in exactly one overload set: 

 
```
import A;
import B;

void bar(C c , long i)
{
    foo();    // calls A.foo()
    foo(i);  // calls A.foo(long)
    foo(c);   // calls B.foo(C)
    foo(1,2); // error, does not match any foo
    foo(1);   // error, matches A.foo(long) and B.foo(int)
    A.foo(1); // calls A.foo(long)
}

```
 Even though `B.foo(int)` is a better match than  `A.foo(long)` for `foo(1)`, it is an error because the two matches are in different overload sets. 

 Overload sets can be merged with an alias declaration:

 
```
import A;
import B;

alias foo = A.foo;
alias foo = B.foo;

void bar(C c)
{
    foo();    // calls A.foo()
    foo(1L);  // calls A.foo(long)
    foo(c);   // calls B.foo(C)
    foo(1,2); // error, does not match any foo
    foo(1);   // calls B.foo(int)
    A.foo(1); // calls A.foo(long)
}

```
 Function Parameters
-------------------

 ### Parameter Storage Classes

 Parameter storage classes are `in`, `out`, `ref`, `lazy`, `return` and `scope`. Parameters can also take the type constructors `const`, `immutable`, `shared` and `inout`. 

 `in`, `out`, `ref` and `lazy` are mutually exclusive. The first three are used to denote input, input/output, and output parameters, respectively. For example: 

 
```
int read(in char[] input, ref size_t count, out int errno);

void main()
{
    size_t a = 42;
    int b;
    int r = read("Hello World", a, b);
}

```
 `read` has three parameters. `input` will only be read and no reference to it will be retained. `count` may be read and written to, and `errno` will be set to a value from within the function.

 The argument `"Hello World"` gets bound to parameter `input`, `a` gets bound to `count` and `b` to `errno`. 

 

Parameter Storage Class and Type Constructor Overview| **Storage Class** | **Description** |
| *none* | The parameter will be a mutable copy of its argument. |
| `in` | The parameter is an input to the function. |
| `out` | The argument must be an lvalue, which will be passed by reference and initialized upon function entry with the default value (`T.init`) of its type.  |
| `ref` | The parameter is an *input/output* parameter, passed by reference.  |
| `scope` |  The parameter must not escape the function call (e.g. by being assigned to a global variable). Ignored for any parameter that is not a reference type.  |
| `return` | Parameter may be returned or copied to the first parameter, but otherwise does not escape from the function. Such copies are required not to outlive the argument(s) they were derived from. Ignored for parameters with no references. See [Scope Parameters](memory-safe-d#scope-return-params). |
| `lazy` | argument is evaluated by the called function and not by the caller |
| **Type Constructor** | **Description** |
| `const` | argument is implicitly converted to a const type |
| `immutable` | argument is implicitly converted to an immutable type |
| `shared` | argument is implicitly converted to a shared type |
| `inout` | argument is implicitly converted to an inout type |

 ### In Parameters

 **Note: The following requires the `-preview=in` switch, available in [v2.094.0](https://dlang.org/changelog/2.094.0.html#preview-in) or higher. When not in use, `in` is equivalent to `const`.** The parameter is an input to the function. Input parameters behave as if they have the `const scope` storage classes. Input parameters may also be passed by reference by the compiler.

 Unlike `ref` parameters, `in` parameters can bind to both lvalues and rvalues (such as literals).

 Types that would trigger a side effect if passed by value (such as types with copy constructor, postblit, or destructor), and types which cannot be copied (e.g. if their copy constructor is marked as `@disable`) will always be passed by reference. Dynamic arrays, classes, associative arrays, function pointers, and delegates will always be passed by value.

 **Implementation Defined:** If the type of the parameter does not fall in one of those categories, whether or not it is passed by reference is implementation defined, and the backend is free to choose the method that will best fit the ABI of the platform. ### Ref and Out Parameters

 By default, parameters take rvalue arguments. A `ref` parameter takes an lvalue argument, so changes to its value will operate on the caller's argument.

 
```
void inc(ref int x)
{
    x += 1;
}

void seattle()
{
    int z = 3;
    inc(z);
    assert(z == 4);
}

```
 A `ref` parameter can also be returned by reference, see [Return Ref Parameters.](#return-ref-parameters)

 An `out` parameter is similar to a `ref` parameter, except it is initialized with `x.init` upon function invocation.

 
```
void zero(out int x)
{
    assert(x == 0);
}

void two(out int x)
{
    x = 2;
}

void tacoma()
{
    int a = 3;
    zero(a);
    assert(a == 0);

    int y = 3;
    two(y);
    assert(y == 2);
}

```
 For dynamic array and class object parameters, which are always passed by reference, `out` and `ref` apply only to the reference and not the contents. 

 ### Lazy Parameters

 An argument to a `lazy` parameter is not evaluated before the function is called. The argument is only evaluated if/when the parameter is evaluated within the function. Hence, a `lazy` argument can be executed 0 or more times. 

 
```
import std.stdio : writeln;

void main()
{
    int x;
    3.times(writeln(x++));
    writeln("-");
    writeln(x);
}

void times(int n, lazy void exp)
{
    while (n--)
        exp();
}

```
 prints to the console:

 
```
0
1
2
−
3

```
 A `lazy` parameter cannot be an lvalue.

 The underlying delegate of the `lazy` parameter may be extracted by using the `&` operator:

 
```
void test(lazy int dg)
{
    int delegate() dg_ = &dg;
    assert(dg_() == 7);
    assert(dg == dg_());
}

void main()
{
    int a = 7;
    test(a);
}

```
 A `lazy` parameter of type `void` can accept an argument of any type.

 See Also: [Lazy Variadic Functions](#lazy_variadic_functions)

 ### Function Default Arguments

 Function parameter declarations can have default values:

 
```
void foo(int x, int y = 3)
{
    ...
}
...
foo(4);   // same as foo(4, 3);

```
 Default parameters are resolved and semantically checked in the context of the function declaration.

 
```
module m;
private immutable int b;
pure void g(int a=b){}

```
 
```
import m;
int b;
pure void f()
{
  g();  // ok, uses m.b
}

```
 The attributes of the [*AssignExpression*](expression#AssignExpression) are applied where the default expression is used.

 
```
module m;
int b;
pure void g(int a=b){}

```
 
```
import m;
enum int b = 3;
pure void f()
{
  g();  // error, cannot access mutable global `m.b` in pure function
}

```
 If the default value for a parameter is given, all following parameters must also have default values. 

 ### Return Ref Parameters

 Return ref parameters are used with [ref functions](#ref-functions) to ensure that the returned reference will not outlive the matching argument's lifetime. 

 
```
ref int identity(return ref int x) {
  return x; // pass-through function that does nothing
}

ref int fun() {
  int x;
  return identity(x); // Error: escaping reference to local variable x
}

ref int gun(return ref int x) {
  return identity(x); // OK
}

```
 Struct non-static methods marked with the `return` attribute ensure the returned reference will not outlive the struct instance. 

 
```
struct S
{
    private int x;
    ref int get() return { return x; }
}

ref int escape()
{
    S s;
    return s.get(); // Error: escaping reference to local variable s
}

```
 Returning the address of a `ref` variable is also checked.

 
```
int* pluto(ref int i)
{
    return &i; // error: returning &i escapes a reference to parameter i
}

int* mars(return ref int i)
{
    return &i;  // ok
}

```
 If the function returns `void`, and the first parameter is `ref` or `out`, then all subsequent `return ref` parameters are considered as being assigned to the first parameter for lifetime checking. The `this` reference parameter to a struct non-static member function is considered the first parameter.

 If there are multiple `return ref` parameters, the lifetime of the return value is the smallest lifetime of the corresponding arguments.

 Neither the type of the `return ref` parameter(s) nor the type of the return value is considered when determining the lifetime of the return value.

 It is not an error if the return type does not contain any indirections.

 
```
int mercury(return ref int i)
{
    return i; // ok
}

```
 Template functions, auto functions, nested functions and [lambdas](expression#function_literals) can deduce the `return` attribute.

 
```
ref int templateFunction()(ref int i)
{
    return i; // ok
}

ref auto autoFunction(ref int i)
{
    return i; // ok
}

void uranus()
{
    ref int nestedFunction(ref int i)
    {
        return i; // ok
    }
}

void venus()
{
    auto lambdaFunction =
        (ref int i)
        {
            return &i; // ok
        };
}

```
 `inout ref` parameters imply the `return` attribute.

 
```
inout(int)* neptune(inout ref int i)
{
    return &i;  // ok
}

```
 ### Scope Parameters

 A `scope` parameter of reference type must not escape the function call (e.g. by being assigned to a global variable). It has no effect for non-reference types. `scope` escape analysis is only done for `@safe` functions. For other functions `scope` semantics must be manually enforced.

 **Note:** `scope` escape analysis is currently only done by the `dmd` compiler when the `-dip1000` switch is passed. 
```
@safe:

int* gp;
void thorin(scope int*);
void gloin(int*);
int* balin(scope int* q, int* r)
{
     gp = q; // error, q escapes to global gp
     gp = r; // ok

     thorin(q); // ok, q does not escape thorin()
     thorin(r); // ok

     gloin(q); // error, gloin() escapes q
     gloin(r); // ok that gloin() escapes r

     return q; // error, cannot return 'scope' q
     return r; // ok
}

```
 As a `scope` parameter must not escape, the compiler can potentially avoid heap-allocating a unique argument to a `scope` parameter. Due to this, passing an array literal, delegate literal or a [*NewExpression*](expression#NewExpression) to a scope parameter may be allowed in a `@nogc` context, depending on the compiler implementation.

 ### Return Scope Parameters

 Parameters marked as `return scope` that contain indirections can only escape those indirections via the function's return value.

 
```
@safe:

int* gp;
void thorin(scope int*);
void gloin(int*);
int* balin(return scope int* p)
{
     gp = p; // error, p escapes to global gp
     thorin(p); // ok, p does not escape thorin()
     gloin(p); // error, gloin() escapes p
     return p; // ok
}

```
 Class references are considered pointers that are subject to `scope`.

 
```
@safe:

class C { }
C gp;
void thorin(scope C);
void gloin(C);
C balin(return scope C p, scope C q, C r)
{
     gp = p; // error, p escapes to global gp
     gp = q; // error, q escapes to global gp
     gp = r; // ok

     thorin(p); // ok, p does not escape thorin()
     thorin(q); // ok
     thorin(r); // ok

     gloin(p); // error, gloin() escapes p
     gloin(q); // error, gloin() escapes q
     gloin(r); // ok that gloin() escapes r

     return p; // ok
     return q; // error, cannot return 'scope' q
     return r; // ok
}

```
 `return scope` can be applied to the `this` of class and interface member functions.

 
```
class C
{
    C bofur() return scope { return this; }
}

```
 Template functions, auto functions, nested functions and [lambdas](expression#function_literals) can deduce the `return scope` attribute.

 ### Ref Return Scope Parameters

 Parameters marked as `ref return scope` come in two forms:

 
```
U xerxes(ref return scope V v);      // (1) ref and return scope
ref U sargon(ref return scope V v);  // (2) return ref and scope

```
 The first form attaches the `return` to the `scope`, and has [return scope parameter](#return-scope-parameters) semantics for the value of the `ref` parameter.

 The second form attaches the `return` to the `ref`, and has [return ref parameter](#return-ref-parameters) semantics with additional [scope parameter](memory-safe-d#scope-return-params) semantics.

 Although a struct constructor returns a reference to the instance being constructed, it is treated as form (1).

 The lexical order of the attributes `ref`, `return`, and `scope` is not significant.

 It is not possible to have both `return ref` and `return scope` semantics for the same parameter.

 
```
@safe:

struct S
{
    this(return scope ref int* p) { ptr = p; }

    int  val;
    int* ptr;
}

int* foo1(ref return scope S s);
int  foo2(ref return scope S s);

ref int* foo3(ref return scope S s);
ref int  foo4(ref return scope S s);

int* test1(scope S s)
{
    return foo1(s);  // Error: scope variable `s` may not be returned
    return foo3(s);  // Error: scope variable `s` may not be returned
}

int test2(S s)
{
    return foo2(s);
    return foo4(s);
}

ref int* test3(S s)
{
    return foo3(s);  // Error: returning `foo3(s)` escapes a reference to parameter `s`
}

ref int test4(S s)
{
    return foo4(s);  // Error: returning `foo4(s)` escapes a reference to parameter `s`
}

S test5(ref scope int* p)
{
    return S(p); // Error: scope variable `p` may not be returned
}

S test6(ref return scope int* p)
{
    return S(p);
}

```
 ### User-Defined Attributes for Parameters

 See also: [*User-Defined Attributes*](attribute#UserDefinedAttribute) ### Variadic Functions

 *Variadic Functions* take a variable number of arguments. There are three forms:

 1. [C-style variadic functions](#c_style_variadic_functions)
2. [Variadic functions with type info](#d_style_variadic_functions)
3. [Typesafe variadic functions](#typesafe-variadic_functions)

 #### C-style Variadic Functions

 A C-style variadic function is declared with a parameter `...` as the last function parameter. It has non-D linkage, such as `extern (C)`.

 To access the variadic arguments, import the standard library module [`core.stdc.stdarg`](https://dlang.org/phobos/core_stdc_stdarg.html). 

 
```
import core.stdc.stdarg;

extern (C) void dry(int x, int y, ...); // C-style Variadic Function

void spin()
{
    dry(3, 4);      // ok, no variadic arguments
    dry(3, 4, 6.8); // ok, one variadic argument
    dry(2);         // error, no argument for parameter y
}

```
 There must be at least one non-variadic parameter declared.

 
```
extern (C) int def(...); // error, must have at least one parameter

```
  C-style variadic functions match the C calling convention for variadic functions, and can call C Standard library functions like `printf`. 

 
```
extern (C) int printf(const(char)*, ...);

void main()
{
    printf("hello world\n");
}

```
 C-style variadic functions cannot be marked as `@safe`.

 
```
void wash()
{
    rinse(3, 4, 5);   // first variadic argument is 5
}

import core.stdc.stdarg;
extern (C) void rinse(int x, int y, ...)
{
    va_list args;
    va_start(args, y); // y is the last named parameter
    int z;
    va_arg(args, z);   // z is set to 5
    va_end(args);
}

```
 #### D-style Variadic Functions

 D-style variadic functions have D linkage and `...` as the last parameter.

 `...` can be the only parameter.

 If there are parameters preceding the `...` parameter, there must be a comma separating them from the `...`.

 **Note:** If the comma is ommitted, it is a [TypeSafe Variadic Function](#variadic). 
```
int abc(char c, ...);   // one required parameter: c
int def(...);           // no required parameters
int ghi(int i ...);     // a typesafe variadic function
//int boo(, ...);       // error

```
 Two hidden arguments are passed to the function:

 * `void* _argptr`
* `TypeInfo[] _arguments`

 `_argptr` is a reference to the first of the variadic arguments. To access the variadic arguments, import [`core.vararg`](https://dlang.org/phobos/core_vararg.html). Use `_argptr` in conjunction with `core.va_arg`:

 
```
import core.vararg;

void test()
{
    foo(3, 4, 5);   // first variadic argument is 5
}

@system void foo(int x, int y, ...)
{
    int z = va_arg!int(_argptr); // z is set to 5 and _argptr is advanced
                                 // to the next argument
}

```
 `_arguments` gives the number of arguments and the `typeid` of each, enabling type safety to be checked at run time. 
```
import std.stdio;

void main()
{
    Foo f = new Foo();
    Bar b = new Bar();

    writefln("%s", f);
    printargs(1, 2, 3L, 4.5, f, b);
}

class Foo { int x = 3; }
class Bar { long y = 4; }

import core.vararg;

@system void printargs(int x, ...)
{
    writefln("%d arguments", _arguments.length);
    for (int i = 0; i < _arguments.length; i++)
    {
        writeln(_arguments[i]);

        if (_arguments[i] == typeid(int))
        {
            int j = va_arg!(int)(_argptr);
            writefln("\t%d", j);
        }
        else if (_arguments[i] == typeid(long))
        {
            long j = va_arg!(long)(_argptr);
            writefln("\t%d", j);
        }
        else if (_arguments[i] == typeid(double))
        {
            double d = va_arg!(double)(_argptr);
            writefln("\t%g", d);
        }
        else if (_arguments[i] == typeid(Foo))
        {
            Foo f = va_arg!(Foo)(_argptr);
            writefln("\t%s", f);
        }
        else if (_arguments[i] == typeid(Bar))
        {
            Bar b = va_arg!(Bar)(_argptr);
            writefln("\t%s", b);
        }
        else
            assert(0);
    }
}

```
 which prints: 
```
0x00870FE0
5 arguments
int
        2
long
        3
double
        4.5
Foo
        0x00870FE0
Bar
        0x00870FD0

```
 D-style variadic functions cannot be marked as `@safe`.

 #### Typesafe Variadic Functions

 A typesafe variadic function has D linkage and a variadic parameter declared as either an array or a class. The array or class is constructed from the arguments, and is passed as an array or class object. 

 For dynamic arrays:

 
```
int sum(int[] ar ...) // typesafe variadic function
{
    int s;
    foreach (int x; ar)
        s += x;
    return s;
}

import std.stdio;

void main()
{
    writeln(stan());  // 6
    writeln(ollie()); // 15
}

int stan()
{
    return sum(1, 2, 3) + sum(); // returns 6+0
}

int ollie()
{
    int[3] ii = [4, 5, 6];
    return sum(ii);             // returns 15
}

```
 For static arrays, the number of arguments must match the array dimension.

 
```
int sum(int[3] ar ...) // typesafe variadic function
{
    int s;
    foreach (int x; ar)
        s += x;
    return s;
}

int frank()
{
    return sum(2, 3);    // error, need 3 values for array
    return sum(1, 2, 3); // returns 6
}

int dave()
{
    int[3] ii = [4, 5, 6];
    int[] jj = ii;
    return sum(ii); // returns 15
    return sum(jj); // error, type mismatch
}

```
 For class objects:

 
```
int tesla(int x, C c ...)
{
    return x + c.x;
}

class C
{
    int x;
    string s;

    this(int x, string s)
    {
        this.x = x;
        this.s = s;
    }
}

void edison()
{
    C g = new C(3, "abc");
    tesla(1, c);         // ok, since c is an instance of C
    tesla(1, 4, "def");  // ok
    tesla(1, 5);         // error, no matching constructor for C
}

```
 The lifetime of the variadic class object or array instance ends at the end of the function. 

 
```
C orville(C c ...)
{
    return c;   // error, c instance contents invalid after return
}

int[] wilbur(int[] a ...)
{
    return a;       // error, array contents invalid after return
    return a[0..1]; // error, array contents invalid after return
    return a.dup;   // ok, since copy is made
}

```
 **Implementation Defined:** the variadic object or array instance may be constructed on the stack. For other types, the argument is passed by value.

 
```
int neil(int i ...)
{
    return i;
}

void buzz()
{
    neil(3);    // returns 3
    neil(3, 4); // error, too many arguments
    int[] x;
    neil(x);    // error, type mismatch
}

```
 #### Lazy Variadic Functions

 If the variadic parameter of a function is an array of delegates with no parameters, then each of the arguments whose type does not match that of the delegate is converted to a delegate of that type. 

 
```
void hal(scope int delegate()[] dgs ...);

void dave()
{
    int delegate() dg;
    hal(1, 3+x, dg, cast(int delegate())null);   // (1)
    hal( { return 1; }, { return 3+x; }, dg, null ); // same as (1)
}

```
 The variadic delegate array differs from using a lazy variadic array. With the former each array element access would evaluate every array element. With the latter, only the element being accessed would be evaluated.

 
```
import std.stdio;

void main()
{
    int x;
    ming(++x, ++x);

    int y;
    flash(++y, ++y);
}

// lazy variadic array
void ming(lazy int[] arr...)
{
    writeln(arr[0]); // 1
    writeln(arr[1]); // 4
}

// variadic delegate array
void flash(scope int delegate()[] arr ...)
{
    writeln(arr[0]); // 1
    writeln(arr[1]); // 2
}

```
 **Best Practices:** Use `scope` when declaring the array of delegates parameter. This will prevent a closure being generated for the delegate, as `scope` means the delegate will not escape the function. Local Variables
---------------

 Local variables are declared within the scope of a function. Function parameters are included.

 A local variable cannot be read without first assigning it a value.

 **Implementation Defined:** The implementation may not always be able to detect these cases. The address of or reference to a local non-static variable cannot be returned from the function. 

 A local variable and a label in the same function cannot have the same name. 

 A local variable cannot hide another local variable in the same function. 

 **Rationale:** whenever this is done it often is a bug or at least looks like a bug. 
```
ref double func(int x)
{
    int x;       // error, hides previous definition of x
    double y;
    {
        char y;  // error, hides previous definition of y
        int z;
    }
    {
        wchar z; // Ok, previous z is out of scope
    }
  z:             // error, z is a local variable and a label
    return y;    // error, returning ref to local
}

```
 ### Local Static Variables

 Local variables in functions declared as `static`, `shared static` or `__gshared` are statically allocated rather than being allocated on the stack. The lifetime of `__gshared` and `shared static` variables begins when the function is first executed and ends when the program ends. The lifetime of `static` variables begins when the function is first executed within the thread and ends when that thread terminates. 

 
```
void foo()
{
    static int n;
    if (++n == 100)
        writeln("called 100 times");
}

```
 The initializer for a static variable must be evaluatable at compile time. There are no static constructors or static destructors for static local variables. 

 Although static variable name visibility follows the usual scoping rules, the names of them must be unique within a particular function. 

 
```
void main()
{
    { static int x; }
    { static int x; } // error
    { int i; }
    { int i; } // ok
}

```
 Nested Functions
----------------

 Functions may be nested within other functions:

 
```
int bar(int a)
{
    int foo(int b)
    {
        int abc() { return 1; }

        return b + abc();
    }
    return foo(a);
}

void test()
{
    int i = bar(3); // i is assigned 4
}

```
 Nested functions can be accessed only if the name is in scope.

 
```
void foo()
{
    void A()
    {
        B(); // error, B() is forward referenced
        C(); // error, C undefined
    }
    void B()
    {
        A(); // ok, in scope
        void C()
        {
            void D()
            {
                A();      // ok
                B();      // ok
                C();      // ok
                D();      // ok
            }
        }
    }
    A(); // ok
    B(); // ok
    C(); // error, C undefined
}

```
 and: 
```
int bar(int a)
{
    int foo(int b) { return b + 1; }
    int abc(int b) { return foo(b); }   // ok
    return foo(a);
}

void test()
{
    int i = bar(3);     // ok
    int j = bar.foo(3); // error, bar.foo not visible
}

```
 Nested functions have access to the variables and other symbols defined by the lexically enclosing function. This access includes both the ability to read and write them. 

 
```
int bar(int a)
{
    int c = 3;

    int foo(int b)
    {
        b += c;       // 4 is added to b
        c++;          // bar.c is now 5
        return b + c; // 12 is returned
    }
    c = 4;
    int i = foo(a); // i is set to 12
    return i + c;   // returns 17
}

void test()
{
    int i = bar(3); // i is assigned 17
}

```
 This access can span multiple nesting levels:

 
```
int bar(int a)
{
    int c = 3;

    int foo(int b)
    {
        int abc()
        {
            return c;   // access bar.c
        }
        return b + c + abc();
    }
    return foo(3);
}

```
 Static nested functions cannot access any stack variables of any lexically enclosing function, but can access static variables. This is analogous to how static member functions behave. 

 
```
int bar(int a)
{
    int c;
    static int d;

    static int foo(int b)
    {
        b = d;          // ok
        b = c;          // error, foo() cannot access frame of bar()
        return b + 1;
    }
    return foo(a);
}

```
 Functions can be nested within member functions:

 
```
struct Foo
{
    int a;

    int bar()
    {
        int c;

        int foo()
        {
            return c + a;
        }
        return 0;
    }
}

```
 Nested functions always have the D function linkage type. 

 Unlike module level declarations, declarations within function scope are processed in order. This means that two nested functions cannot mutually call each other: 

 
```
void test()
{
    void foo() { bar(); } // error, bar not defined
    void bar() { foo(); } // ok
}

```
 There are several workarounds for this limitation:

 * Declare the functions to be static members of a nested struct:



```
void test()
{
    static struct S
    {
        static void foo() { bar(); } // ok
        static void bar() { foo(); } // ok
    }

    S.foo();  // compiles (but note the infinite runtime loop)
}

```
 - Declare one or more of the functions to be function templates even if they take no specific template arguments:
 
```
void test()
{
    void foo()() { bar(); } // ok (foo is a function template)
    void bar()   { foo(); } // ok
}

```
 - Declare the functions inside of a mixin template:
 
```
mixin template T()
{
    void foo() { bar(); } // ok
    void bar() { foo(); } // ok
}

void main()
{
    mixin T!();
}

```
 - Use a delegate:
 
```
void test()
{
    void delegate() fp;
    void foo() { fp(); }
    void bar() { foo(); }
    fp = &bar;
}

```
 Nested functions cannot be overloaded.

 Delegates, Function Pointers, and Closures
------------------------------------------

 A function pointer can point to a static nested function:

 
```
int function() fp;  // fp is a pointer to a function returning an int

void test()
{
    static int a = 7;
    static int foo() { return a + 3; }

    fp = &foo;
}

void bar()
{
    test();
    int i = fp();       // i is set to 10
}

```
 **Implementation Defined:** Two functions with identical bodies, or two functions that compile to identical assembly code, are not guaranteed to have distinct function pointer values. The implementation may merge functions bodies into one if they compile to identical code. 
```
int abc(int x)   { return x + 1; }
uint def(uint y) { return y + 1; }

int delegate(int)   fp1 = &abc;
uint delegate(uint) fp2 = &def;
// Do not rely on fp1 and fp2 being different values; the compiler may merge
// them.

```
 A delegate can be set to a non-static nested function:

 
```
int delegate() dg;

void test()
{
    int a = 7;
    int foo() { return a + 3; }

    dg = &foo;
    int i = dg(); // i is set to 10
}

```
 The stack variables referenced by a nested function are still valid even after the function exits (NOTE this is different from D 1.0.) This is called a *closure*. 

 Those referenced stack variables that make up the closure are allocated on the GC heap. Closures are not allowed for `@nogc` functions.

 **Note:** Returning addresses of stack variables, however, is not a closure and is an error. 
```
void bar()
{
    int b;
    test();
    int i = dg(); // ok, test.a is in a closure and still exists
}

```
 Delegates to non-static nested functions contain two pieces of data: the pointer to the stack frame of the lexically enclosing function (called the *context pointer*) and the address of the function. This is analogous to struct/class non-static member function delegates consisting of a *this* pointer and the address of the member function. Both forms of delegates are indistinguishable, and are the same type. 

 
```
struct Foo
{
    int a = 7;
    int bar() { return a; }
}

int foo(int delegate() dg)
{
    return dg() + 1;
}

void test()
{
    int x = 27;
    int abc() { return x; }
    Foo f;
    int i;

    i = foo(&abc);   // i is set to 28
    i = foo(&f.bar); // i is set to 8
}

```
 This combining of the environment and the function is called a *dynamic closure*. 

 The `.ptr` property of a delegate will return the *context pointer* value as a `void*`. 

 The `.funcptr` property of a delegate will return the *function pointer* value as a function type. 

 Function pointers are zero-initialized by default. They can be initialized to the address of any function (including a function literal). Initialization with the address of a function that requires a context pointer is not allowed in @safe functions. 

 
```
struct S
{
    static int sfunc();
    int member();   // has hidden `this` reference parameter
}

@safe void sun()
{
    int function() fp = &S.sfunc;
    fp(); // Ok
    fp = &S.member; // error
}

@system void moon()
{
    int function() fp = &S.member; // Ok because @system
    fp(); // undefined behavior
}

```
 Delegates are zero-initialized by default. They can be initialized by taking the address of a non-static member function, but a context pointer must be supplied. They can be initialized by taking the address of a non-static nested function or function literal, where the context pointer will be set to point to the stack frame, closure, or `null`. 

 Delegates cannot be initialized by taking the address of a global function, a static member function, or a static nested function. 

 
```
struct S
{
    static int sfunc();
    int member() { return 1; }
}

void main()
{
    S s;
    int delegate() dg = &s.member; // Ok, s supplies context pointer
    assert(dg() == 1);

    dg = &S.sfunc;  // error
    dg = &S.member; // error

    int moon() { return 2; }
    dg = &moon;     // Ok
    assert(dg() == 2);

    static int mars() { return 3; }
    dg = &mars;     // error

    dg = () { return 4; }; // Ok
    assert(dg() == 4);
}

```
 **Note:** Function pointers can be passed to functions taking a delegate argument by passing them through the [`std.functional.toDelegate`](https://dlang.org/phobos/std_functional.html#toDelegate) template, which converts any callable to a delegate with a `null` context pointer. ### Anonymous Functions and Anonymous Delegates

 See [*FunctionLiteral*](expression#FunctionLiteral)s. 

 
`main()` Function
------------------

 For console programs, `main()` serves as the entry point. It gets called after all the module initializers are run, and after any unittests are run. After it returns, all the module destructors are run. `main()` must be declared using one of the following forms: 

 * `void main() { ... }`
* `void main(string[] args) { ... }`
* `int main() { ... }`
* `int main(string[] args) { ... }`

 The main function must have D linkage.

 Attributes may be added as needed, e.g. `@safe`, `@nogc`, `nothrow`, etc.

 ### BetterC `main()` Function

 For **BetterC** programs, the main function is declared using one of the following forms:

 * `extern (C) int main() { ... }`
* `extern (C) int main(int argc, char** argv) { ... }`

 This takes the place of the C main function and serves the identical purpose.

 Module constructors, module destructors, and unittests are not run.

 **Implementation Defined:** Other system-specific entry points may exist, such as `WinMain` and `DllMain` on Windows systems. Function Templates
------------------

 Functions can have compile time arguments in the form of a template. See [function templates](template#function-templates).

 Compile Time Function Execution (CTFE)
--------------------------------------

 In contexts where a compile time value is required, functions can be used to compute those values. This is called *Compile Time Function Execution*, or *CTFE*.

 These contexts are:

 * initialization of a static variable or a [manifest constant](enum#manifest_constants)
* static initializers of struct/class members
* dimension of a [static array](arrays#static-arrays)
* argument for a  [template value parameter](template#template_value_parameter)
* [`static if`](version#staticif)
* [`static foreach`](version#staticforeach)
* [`static assert`](version#static-assert)
* [`mixin` statement](statement#mixin-statement)
* [`pragma` argument](pragma)
* [`__traits` argument](traits)

 
```
enum eval(Args...) = Args[0];

int square(int i)
{
    return i * i;
}

void foo()
{
    static j = square(3);      // CTFE
    writeln(j);
    assert(square(4));         // run time
    static assert(square(3) == 9); // CTFE
    writeln(eval!(square(5))); // CTFE
}

```
 The function must have a [*SpecifiedFunctionBody*](#SpecifiedFunctionBody).

 CTFE is subject to the following restrictions:

 1. Expressions may not reference any global or local static variables.
2. [AsmStatements](https://dlang.org/iasm.html#asmstatements) are not permitted
3. Non-portable casts (eg, from `int[]` to `float[]`), including casts which depend on endianness, are not permitted. Casts between signed and unsigned types are permitted.
4. Reinterpretation of overlapped fields in a union is not permitted.

 Pointers are permitted in CTFE, provided they are used safely:

 * Pointer arithmetic is permitted only on pointers which point to static or dynamic array elements. A pointer may also point to the first element past the array, although such pointers cannot be dereferenced. Pointer arithmetic on pointers which are null, or which point to a non-array, is not allowed.
* Ordered comparison (`<`, `<``=`, `>`, `>=`) between two pointers is permitted when both pointers point to the same array, or when at least one pointer is `null`.
* Pointer comparisons between discontiguous memory blocks are illegal, unless two such comparisons are combined using `&&` or `|``|` to yield a result which is independent of the ordering of memory blocks. Each comparison must consist of two pointer expressions compared with `<`, `<``=`, `>`, or `>``=`, and may optionally be negated with `!`. For example, the expression `(p1 > q1 && p2 <= q2)` is permitted when `p1`, `p2` are expressions yielding pointers to memory block *P*, and `q1`, `q2` are expressions yielding pointers to memory block *Q*, even when *P* and *Q* are unrelated memory blocks. It returns true if `[p1..p2]` lies inside `[q1..q2]`, and false otherwise. Similarly, the expression `(p1 < q1 || p2 > q2)` is true if `[p1..p2]` lies outside `[q1..q2]`, and false otherwise.
* Equality comparisons (==, !=, is, !is) are permitted between all pointers, without restriction.
* Any pointer may be cast to `void*` and from `void*` back to its original type. Casting between pointer and non-pointer types is illegal.

 The above restrictions apply only to expressions which are actually executed. For example: 

 
```
static int y = 0;

int countTen(int x)
{
    if (x > 10)
        ++y;    // access static variable
    return x;
}

static assert(countTen(6) == 6);    // OK
static assert(countTen(12) == 12);  // invalid, modifies y.

```
 The `__ctfe` boolean pseudo-variable evaluates to true during CTFE but false otherwise. 

 **Note:** `__ctfe` can be used to provide an alternative execution path to avoid operations which are forbidden in CTFE. Every usage of `__ctfe` is statically evaluated and has no run-time cost. ) Non-recoverable errors (such as assert failures) are illegal. 

 **Implementation Defined:** Executing functions via CTFE can take considerably longer than executing it at run time. If the function goes into an infinite loop, it may cause the compiler to hang. **Implementation Defined:** Functions executed via CTFE can give different results from run time when implementation-defined or undefined-behavior occurs. ### String Mixins and Compile Time Function Execution

 All functions that execute in CTFE must also be executable at run time. The compile time evaluation of a function does the equivalent of running the function at run time. The semantics of a function cannot depend on compile time values of the function. For example:

 
```
int foo(string s)
{
    return mixin(s);
}

const int x = foo("1");

```
 is illegal, because the runtime code for `foo` cannot be generated. **Best Practices:** A function template, where `s` is a template argument, would be the appropriate method to implement this sort of thing. No-GC Functions
---------------

 No-GC functions are functions marked with the `@nogc` attribute. Those functions do not allocate memory on the GC heap. These operations are not allowed in No-GC functions: 

 1. [constructing an array](https://dlang.org/expression.html#ArrayLiteral) on the heap
2. resizing an array by writing to its `.length` property
3. [array concatenation](https://dlang.org/expression.html#CatExpression)
4. [array appending](https://dlang.org/expression.html#simple_assignment_expressions)
5. [constructing an associative array](https://dlang.org/expression.html#AssocArrayLiteral)
6. [indexing](https://dlang.org/expression.html#IndexExpression) an associative array **Note:** because it may throw `RangeError` if the specified key is not present
7. [allocating an object with `new`](https://dlang.org/expression.html#NewExpression) on the heap
8. calling functions that are not `@nogc`, unless the call is in a [*ConditionalStatement*](version#ConditionalStatement) controlled by a [*DebugCondition*](version#DebugCondition)

 
```
@nogc void foo()
{
    auto a = ['a'];    // (1) error, allocates
    a.length = 1;      // (2) error, array resizing allocates
    a = a ~ a;         // (3) error, arrays concatenation allocates
    a ~= 'c';          // (4) error, appending to arrays allocates

    auto aa = ["x":1]; // (5) error, allocates
    aa["abc"];         // (6) error, indexing may allocate and throws

    auto p = new int;  // (7) error, operator new allocates
    bar();             // (8) error, bar() may allocate
    debug bar();       // (8) Ok
}
void bar() { }

```
 No-GC functions cannot be closures. 

 
```
@nogc int delegate() foo()
{
    int n;              // error, variable n cannot be allocated on heap
    return (){ return n; } // since `n` escapes `foo()`, a closure is required
}

```
 `@nogc` affects the type of the function. A `@nogc` function is covariant with a non-`@nogc` function. 

 
```
void function() fp;
void function() @nogc gp;  // pointer to @nogc function

void foo();
@nogc void bar();

void test()
{
    fp = &foo; // ok
    fp = &bar; // ok, it's covariant
    gp = &foo; // error, not contravariant
    gp = &bar; // ok
}

```
 Function Safety
---------------

 ### Safe Functions

 Safe functions are marked with the `@safe` attribute. `@safe` can be inferred, see [Function Attribute Inference](#function-attribute-inference).

 Safe functions have [safe interfaces](#safe-interfaces). An implementation must enforce this by restricting the function's body to operations that are known safe.

 The following operations are not allowed in safe functions:

 * No casting from a pointer type to any type with pointers other than `void*`.
* No casting from any non-pointer type to a pointer type.
* No pointer arithmetic (including pointer indexing).
* Cannot access unions that have pointers or references overlapping with other types.
* Calling any [System Functions](#system-functions).
* No catching of exceptions that are not derived from [`class Exception`](https://dlang.org/phobos/object.html#Exception).
* No inline assembler.
* No explicit casting of mutable objects to immutable.
* No explicit casting of immutable objects to mutable.
* No explicit casting of thread local objects to shared.
* No explicit casting of shared objects to thread local.
* Cannot access `__gshared` variables.
* Cannot use `void` initializers for pointers.
* Cannot use `void` initializers for class or interface references.

 When indexing or slicing an array, an out of bounds access will cause a runtime error.

 ) Functions nested inside safe functions default to being safe functions. 

 Safe functions are covariant with trusted or system functions.

 **Best Practices:** Mark as many functions `@safe` as practical. #### Safe External Functions

 External functions don't have a function body visible to the compiler: 

 
```
@safe extern (C) void play();

```
 and so safety cannot be verified automatically. **Best Practices:** Explicitly set an attribute for external functions rather than relying on default settings. ### Trusted Functions

 Trusted functions are marked with the `@trusted` attribute.

 Like [safe functions](#safe-functions), trusted functions have [safe interfaces](#safe-interfaces). Unlike safe functions, this is not enforced by restrictions on the function body. Instead, it is the responsibility of the programmer to ensure that the interface of a trusted function is safe.

 Example:

 
```
immutable(int)* f(int* p) @trusted
{
    version (none) p[2] = 13;
    // Invalid. p[2] is out of bounds. This line would exhibit undefined
    // behavior.

    version (none) p[1] = 13;
    // Invalid. In this program, p[1] happens to be in-bounds, so the
    // line would not exhibit undefined behavior, but a trusted function
    // is not allowed to rely on this.

    version (none) return cast(immutable) p;
    // Invalid. @safe code still has mutable access and could trigger
    // undefined behavior by overwriting the value later on.

    int* p2 = new int;
    *p2 = 42;
    return cast(immutable) p2;
    // Valid. After f returns, no mutable aliases of p2 can exist.
}

void main() @safe
{
    int[2] a = [10, 20];
    int* mp = &a[0];
    immutable(int)* ip = f(mp);
    assert(a[1] == 20); // Guaranteed. f cannot access a[1].
    assert(ip !is mp); // Guaranteed. f cannot introduce unsafe aliasing.
}

```
 Trusted functions may call safe, trusted, or system functions. 

 Trusted functions are covariant with safe or system functions.

 **Best Practices:** Trusted functions should be kept small so that they are easier to manually verify. ### System Functions

 System functions are functions not marked with `@safe` or `@trusted` and are not nested inside `@safe` functions. System functions may be marked with the `@system` attribute. A function being system does not mean it actually is unsafe, it just means that its safety must be manually verified. 

 System functions are **not** covariant with trusted or safe functions. 

 System functions can call safe and trusted functions.

 **Best Practices:** When in doubt, mark `extern (C)` and `extern (C++)` functions as `@system` when their implementations are not in D, as the D compiler will be unable to check them. Most of them are `@safe`, but will need to be manually checked. **Best Practices:** The number and size of system functions should be minimized. This minimizes the work necessary to manually check for safety. ### Safe Interfaces

 When it is only called with [safe values](#safe-values) and [safe aliasing](#safe-aliasing), a function has a safe interface when:

 1. it cannot exhibit [undefined behavior](https://dlang.org/glossary.html#undefined_behavior), and
2. it cannot create unsafe values that are accessible from other parts of the program (e.g., via return values, global variables, or `ref` parameters), and
3. it cannot introduce unsafe aliasing that is accessible from other parts of the program.

 Functions that meet these requirements may be [`@safe`](#safe-functions) or [`@trusted`](#trusted-functions). Function that do not meet these requirements can only be [`@system`](#system-functions).

 Examples:

 * C's `free` does not have a safe interface: 
```
extern (C) @system void free(void* ptr);

```
 because `free(p)` invalidates `p`, making its value unsafe. `free` can only be `@system`.
* C's `strlen` and `memcpy` do not have safe interfaces: 
```
extern (C) @system size_t strlen(char* s);
extern (C) @system void* memcpy(void* dst, void* src, size_t nbytes);

```
 because they iterate pointers based on unverified assumptions (`strlen` assumes that `s` is zero-terminated; `memcpy` assumes that the memory objects pointed to by `dst` and `src` are at least `nbytes` big). Any function that traverses a C string passed as an argument can only be `@system`. Any function that trusts a separate parameter for array bounds can only be `@system`.
* C's `malloc` does have a safe interface: 
```
extern (C) @trusted void* malloc(size_t sz);

```
 It does not exhibit undefined behavior for any input. It returns either a valid pointer, which is safe, or `null` which is also safe. It returns a pointer to a fresh allocation, so it cannot introduce any unsafe aliasing. **Note:** The implementation of `malloc` is most likely @system code.
* A D version of `memcpy` can have a safe interface: 
```
@safe void memcpy(E)(E[] src, E[] dst)
{
    import std.math : min;
    foreach (i; 0 .. min(src.length, dst.length))
    {
        dst[i] = src[i];
    }
}

```
 because the rules for [safe values](#safe-values) ensure that the lengths of the arrays are correct.

 ### Safe Values

 For [basic data types](type#basic-data-types), all possible bit patterns are safe.

 A pointer is a safe value when it is one of:

 1. `null`
2. it points to a memory object that is live and the pointed to value in that memory object is safe.

 Examples:

 
```
int* n = null; /* n is safe because dereferencing null is a well-defined
    crash. */
int* x = cast(int*) 0xDEADBEEF; /* x is (most likely) unsafe because it
    is not a valid pointer and cannot be dereferenced. */

import core.stdc.stdlib: malloc, free;
int* p1 = cast(int*) malloc(int.sizeof); /* p1 is safe because the
    pointer is valid and *p1 is safe regardless of its actual value. */
free(p1); /* This makes p1 unsafe. */
int** p2 = &p1; /* While it can be dereferenced, p2 is unsafe because p1
    is unsafe. */
p1 = null; /* This makes p1 and p2 safe. */

```
 A dynamic array is safe when:

 1. its pointer is safe, and
2. its length is in-bounds with the corresponding memory object, and
3. all its elements are safe.

 Examples:

 
```
int[] f() @system
{
    int[3] a;
    int[] d1 = a[0 .. 2]; /* d1 is safe. */
    int[] d2 = a.ptr[0 .. 3]; /* d2 is unsafe because it goes beyond a's
        bounds. */
    int*[] d3 = [cast(int*) 0xDEADBEEF]; /* d3 is unsafe because the
        element is unsafe. */
    return d1; /* Up to here, d1 was safe, but its pointer becomes
        invalid when the function returns, so the returned dynamic array
        is unsafe. */
}

```
 A static array is safe when all its elements are safe. Regardless of the element type, a static array with length zero is always safe.

 An associative array is safe when all its keys and elements are safe.

 A struct/union instance is safe when:

 1. the values of its accessible fields are safe, and
2. it does not introduce [unsafe aliasing](#safe-aliasing) with unions.

 Examples:

 
```
struct S { int* p; }
S s1 = S(new int); /* s1 is safe. */
S s2 = S(cast(int*) 0xDEADBEEF); /* s2 is unsafe, because s2.p is
    unsafe. */

union U { int* p; size_t x; }
U u = U(new int); /* Even though both u.p and u.x are safe, u is unsafe
    because of unsafe aliasing. */

```
 A class reference is safe when it is `null` or:

 1. it refers to a valid class instance of the class type or a type derived from the class type, and
2. the values of the instance's accessible fields are safe, and
3. it does not introduce unsafe aliasing with unions.

 A function pointer is safe when it is `null` or it refers to a valid function that has the same or a covariant signature.

 A `delegate` is safe when:

 1. its `.funcptr` property is `null` or refers to a function that matches or is covariant with the delegate type, and
2. its `.ptr` property is `null` or refers to a memory object that is in a form expected by the function.

 ### Safe Aliasing

 When one memory location is accessible with two different types, that aliasing is considered safe if:

 1. both types are `const` or `immutable`; or
2. one of the types is mutable while the other is a `const`-qualified [basic data type](type#basic-data-types); or
3. both types are mutable basic data types; or
4. one of the types is a static array type with length zero; or
5. one of the types is a static array type with non-zero length, and aliasing of the array's element type and the other type is safe; or
6. both types are pointer types, and aliasing of the target types is safe, and the target types have the same size.

 All other cases of aliasing are considered unsafe.

 **Note:** Safe aliasing may be exposed to functions with [safe interfaces](#safe-interfaces) without affecting their guaranteed safety. Unsafe aliasing does not guarantee safety. **Note:** Safe aliasing does not imply that all aliased views of the data have [safe values](#safe-values). Those must examined separately for safety. Examples:

 
```
void f1(ref ubyte x, ref float y) @safe { x = 0; y = float.init; }
union U1 { ubyte x; float y; } // safe aliasing
U1 u1;
f1(u1.x, u1.y); // Ok

void f2(ref int* x, ref int y) @trusted { x = new int; y = 0xDEADBEEF; }
union U2 { int* x; int y; } // unsafe aliasing
U2 u2;
version (none) f1(u2.x, u2.y); // not safe

```
 Function Attribute Inference
----------------------------

 [*FunctionLiteral*](expression#FunctionLiteral)s, [Auto Functions](#auto-functions), [Auto Ref Functions](#auto-ref-functions), [nested functions](#nested) and [function templates](template#function-templates), since their function bodies are always present, infer the [`pure`](#pure-functions), [`nothrow`](#nothrow-functions), [`@safe`](#safe-functions), [`@nogc`](#nogc-functions), [return ref parameters](#return-ref-parameters), [scope parameters](#scope-parameters), [return scope parameters](#return-scope-parameters) and [ref return scope parameters](#ref-return-scope-parameters) attributes unless specifically overridden. 

 Attribute inference is not done for other functions, even if the function body is present. 

 The inference is done by determining if the function body follows the rules of the particular attribute. 

 Cyclic functions (i.e. functions that wind up directly or indirectly calling themselves) are inferred as being impure, throwing, and @system. 

 If a function attempts to test itself for those attributes, then the function is inferred as not having those attributes. 

 **Rationale:** Function attribute inference greatly reduces the need for the user to add attributes to functions, especially for templates. Uniform Function Call Syntax (UFCS)
-----------------------------------

 A free function can be called with a syntax equivalent to that of a member function of its first parameter type. The free function is called a *UFCS function*. 

 
```
void sun(T, int);

void moon(T t)
{
    t.sun(1);
    // If `T` does not have member function `sun`,
    // `t.sun(1)` is interpreted as if it were written `sun(t, 1)`
}

```
 **Rationale:** This provides a way to add external functions to a class as if they were public final member functions. This enables minimizing the number of functions in a class to only the essentials that are needed to take care of the object's private state, without the temptation to add a kitchen-sink's worth of member functions. It also enables  [function chaining and component programming](http://www.drdobbs.com/architecture-and-design/component-programming-in-d/240008321). A more complex example:

 
```
stdin.byLine(KeepTerminator.yes)
    .map!(a => a.idup)
    .array
    .sort
    .copy(stdout.lockingTextWriter());

```
 is the equivalent of:

 
```
copy(sort(array(map!(a => a.idup)(byLine(stdin, KeepTerminator.yes))), lockingTextWriter(stdout));

```
 UFCS works with `@property` functions:

 
```
@property prop(X thisObj);
@property prop(X thisObj, int value);

X obj;
obj.prop;      // if X does not have member prop, reinterpret as prop(obj);
obj.prop = 1;  // similarly, reinterpret as prop(obj, 1);

```
 Functions declared in a local scope are not found when searching for a matching UFCS function.

 Member functions are not found when searching for a matching UFCS function.

 Otherwise, UFCS function lookup proceeds normally.

 
```
module a;
void foo(X);
alias boo = foo;
void main()
{
    void bar(X);     // bar declared in local scope
    import b : baz;  // void baz(X);

    X obj;
    obj.foo();    // OK, calls a.foo;
    //obj.bar();  // NG, UFCS does not see nested functions
    obj.baz();    // OK, calls b.baz, because it is declared at the
                  // top level scope of module b

    import b : boo = baz;
    obj.boo();    // OK, calls aliased b.baz instead of a.boo (== a.foo),
                  // because the declared alias name 'boo' in local scope
                  // overrides module scope name
}
class C
{
    void mfoo(X);           // member function
    static void sbar(X);    // static member function
    import b : ibaz = baz;  // void baz(X);
    void test()
    {
        X obj;
        //obj.mfoo();  // NG, UFCS does not see member functions
        //obj.sbar();  // NG, UFCS does not see static member functions
        obj.ibaz();    // OK, ibaz is an alias of baz which declared at
                       //     the top level scope of module b
    }
}

```
 **Rationale:** Local function symbols are not considered by UFCS to avoid unexpected name conflicts. See below problematic examples. 
```
int front(int[] arr) { return arr[0]; }

void main()
{
    int[] a = [1,2,3];
    auto x = a.front();   // call .front by UFCS

    auto front = x;       // front is now a variable
    auto y = a.front();   // Error, front is not a function
}

class C
{
    int[] arr;
    int front()
    {
        return arr.front(); // Error, C.front is not callable
                            // using argument types (int[])
    }
}

```
 )

 © 1999–2021 The D Language Foundation  
Licensed under the Boost License 1.0.  

<https://dlang.org/spec/function>

d