recovery-cadence.dhover×251all
#!/usr/bin/env dub
/+ dub.sdl:
    name "editor-recovery-cadence"
    targetPath "../../../build"
    dependency "sparkles:base" path="../../.."
    dependency "sparkles:wired" path="../../.."
    dependency "sparkles:event-horizon" path="../../.."
    dependency "sparkles:recovery" path="../../.."
    dependency "sparkles:ui" path="../../.."
    dependency "sparkles:text-buffer" path="../../.."
    dflags "-preview=in" "-preview=dip1000" "-I$PACKAGE_DIR/../src"
    dflags "-i=editor_document" "-i=document_files"
    dflags "-i=session_record" "-i=session_archive"
    dflags "-i=session_snapshot" "-i=session_checkpoint" "-i=session_discovery" "-i=session_runtime"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
/// Measure recovery under sustained edits, independently of shaping and drawing.
module 
(module) editor_recovery_cadence

Measure recovery under sustained edits, independently of shaping and drawing.

editor_recovery_cadence
;
import
(package) core
core
.
(module) core.thread

The thread module provides support for thread creation and management.

Source

core/thread/package.d

@copyrightCopyright Sean Kelly 2005 - 2012.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
thread
:
(class) core.thread.osthread.Thread

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.

Thread
;
import
(package) core
core
.
(module) core.time

Module containing core time functionality, such as Duration (which represents a duration of time) or 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.

Symbol Description
Types
Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).
TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides.
MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides.
Functions
convert Generic way of converting between two time units.
dur Allows constructing a Duration from the given time units with the given length.
weeks days hours

minutes seconds msecs

usecs hnsecs nsecs | Convenience aliases for dur. | | abs | Returns the absolute value of a duration. |

From Duration
From TickDuration
From units
To Duration
tickDuration.to, std,conv!Duration()
dur!"msecs"(5) or 5.msecs()

| To TickDuration | duration.to, std,conv!TickDuration() |

  • | TickDuration.from!"msecs"(msecs) |

| To units | duration.total!"days" | tickDuration.msecs | convert!("days", "msecs")(msecs) |

Source

core/time.d

@copyrightCopyright 2010 - 2012@licenseBoost License 1.0.@authorsJonathan M Davis and Kato Shoichi
time
:
(struct) core.time.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 Thread.sleep.

In std.datetime, it is also used as the result of various arithmetic operations on time points.

Use the dur function or one of its non-generic aliases to create Durations.

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 Durations when dealing with months or years. Rather, functions specific to months and years are defined. For instance, 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 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);
Duration
,
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
, msecs, seconds;
import
(package) core
core
.
(package) core.sys
sys
.
(package) core.sys.posix
posix
.
(package) core.sys.posix.sys
sys
.
(module) core.sys.posix.sys.resource

D header file for POSIX.

@copyrightCopyright (c) 2013 Lars Tandle Kyllingstad.@licenseBoost License 1.0.@authorsLars Tandle Kyllingstad@standardsThe Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008
resource
:
(alias) editor_recovery_cadence.getrusage = int core.sys.posix.sys.resource.getrusage(int, core.sys.posix.sys.resource.rusage*) nothrow @nogc
getrusage
,
(alias enum value) editor_recovery_cadence.RUSAGE_SELF = core.sys.posix.sys.resource.RUSAGE_SELF = 0
RUSAGE_SELF
,
(struct) core.sys.posix.sys.resource.rusage
rusage
;
import
(module) editor_document

Editor document state, independent of its application and rendering host.

editor_document
:
(class) editor_document.Document

A tab owns its reference-counted field; arrays contain tab references, never Text values.

Document
;
import
(module) session_runtime

Application-facing recovery service over sparkles:recovery; maintenance runs on a CPU worker.

session_runtime
:
(class) session_runtime.RecoverySession

Observe state on the application thread, poll with the host clock, and flush before orderly exit. Archive creation and retention run on a maintenance worker independently of checkpoint serialization. Shutdown releases the lease only after both workers stop; it does not promise to submit unflushed state.

Examples

Initialization retains the newest edits and explicit flush acknowledges them before closure.

version (linux) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("Recovery directory leases currently require Linux.");
}
import core.thread : Thread;
import core.time : MonoTime, seconds;
import editor_document : Document;
import session_archive : readSessionGeneration;
import sparkles.test_utils.tmpfs : TmpFS;
import std.path : buildPath;
auto fixture = TmpFS.create();
auto recovery = new RecoverySession(buildPath(fixture.dir, "sessions"), fixture.dir);
scope (exit) recovery.shutdown();
auto document = new Document(7, "draft");
Document[] documents = [document];
document.field.insert("before");
recovery.observe(documents, 7, "github-dark");
document.field.insert(" after");
recovery.observe(documents, 7, "github-dark");
assert(recovery.currentRevision == 2 && recovery.pending);
recovery.flush();
const deadline = MonoTime.currTime + 3.seconds;
while (recovery.pending && MonoTime.currTime < deadline)
{
    recovery.poll();
    (() @trusted => Thread.yield())();
}
assert(!recovery.pending && recovery.durableRevision == 2 && !recovery.error.length);
const saved = readSessionGeneration(recovery.directoryPath, recovery.durableGeneration);
assert(saved.hasValue && saved.value.tabs[0].content == "before after");
const path = recovery.directoryPath;
recovery.shutdown();
auto reclaimed = LeasedDirectory.claim(path);
assert(reclaimed.hasValue);
reclaimed.value.close();
RecoverySession
;
import
(package) std
std
.
(module) std.file

Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module std.stdio.

Category Functions
General exists isDir isFile isSymlink rename thisExePath
Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir
Files append copy read readText remove slurp write
Symlinks symlink readLink
Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes
Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged
Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace

Source

std/file.d

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

Make a new directory pathname.

@parampathname the path of the directory to make@throwsFileException on POSIX or WindowsException on Windows if an error occured.
mkdir
,
(alias) editor_recovery_cadence.rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

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

@parampathname the path of the directory to completely remove@paramde The DirEntry to remove@throwsFileException if there is an error (including if the given file is not a directory).
rmdirRecurse
,
(alias) editor_recovery_cadence.tempDir = string std.file.tempDir() @trusted

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

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

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

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

@returns

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

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

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

tempDir
;
import
(package) std
std
.
(module) 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.

Credits

This module and its documentation are inspired by Perl's Getopt::Long 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

@copyrightCopyright Andrei Alexandrescu 2008 - 2015.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
getopt
:
(alias template) editor_recovery_cadence.getopt = std.getopt.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, or if a required argument is missing 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`.

  1. 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`.

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

  1. 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`.

  1. 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'.

  1. 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` 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".

  1. 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` 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.

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

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

This module is used to manipulate path strings.

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

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

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

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

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

Source

std/path.d

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

Combines one or more path segments.

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

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

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

@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
;
import
(package) std
std
.
(module) std.process

Functions for starting and interacting with other processes, and for working with the current process' execution environment.

Process handling

  • `spawnProcess` spawns a new `process`, optionally assigning it an
        

    arbitrary set of standard input, output, and error streams. The function returns immediately, leaving the child process to execute in parallel with its parent. All other functions in this module that spawn processes are built around spawnProcess.

  • `wait` makes the parent `process` wait for a child `process` to
        

    terminate. In general one should always do this, to avoid child processes becoming "zombies" when the parent process exits. Scope guards are perfect for this – see the spawnProcess documentation for examples. tryWait is similar to wait, but does not block if the process has not yet terminated.

  • `pipeProcess` also spawns a child `process` which runs
        

    in parallel with its parent. However, instead of taking arbitrary streams, it automatically creates a set of pipes that allow the parent to communicate with the child through the child's standard input, output, and/or error streams. This function corresponds roughly to C's popen function.

  • `execute` starts a new `process` and waits for it
        

    to complete before returning. Additionally, it captures the process' standard output and error streams and returns the output of these as a string.

  • `spawnShell`, `pipeShell` and `executeShell` work like
        

    spawnProcess, pipeProcess and execute, respectively, except that they take a single command string and run it through the current user's default command interpreter. executeShell corresponds roughly to C's system function.

  • `kill` attempts to terminate a running `process`.
    
    

The following table compactly summarises the different process creation functions and how they relate to each other:

Runs program directly
Runs shell command
Low-level process creation
spawnProcess
spawnShell
Automatic input/output redirection using pipes
pipeProcess
pipeShell
Execute and wait for completion, collect output
execute
executeShell

Other functionality

  • `pipe` is used to create unidirectional pipes.
    
  • `environment` is an interface through which the current `process`'
        

    environment variables can be read and manipulated.

  • `escapeShellCommand` and `escapeShellFileName` are useful
        

    for constructing shell command lines in a portable way.

Source

std/process.d

Note

Most of the functionality in this module is not available on iOS, tvOS and watchOS. The only functions available on those platforms are: environment, thisProcessID and thisThreadID.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(alias) editor_recovery_cadence.execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

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

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

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

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
;
import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

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

There are three layers of I/O:

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

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

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

Source

std/stdio.d

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

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

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

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

Example

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

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
;
import
(package) std
std
.
(module) std.string

String handling functions.

Category Functions
Searching
column
indexOf
indexOfAny
indexOfNeither
lastIndexOf
lastIndexOfAny
lastIndexOfNeither
Comparison
isNumeric
Mutation
capitalize
Pruning and Filling
center
chomp
chompPrefix
chop
detabber
detab
entab
entabber
leftJustify
outdent
rightJustify
strip
stripLeft
stripRight
wrap
Substitution
abbrev
soundex
soundexer
succ
tr
translate
Miscellaneous
assumeUTF
fromStringz
lineSplitter
representation
splitLines
toStringz
Objects of types string, wstring, and dstring are value types
and cannot be mutated element-by-element. For using mutation during building
strings, use char[], wchar[], or dchar[]. The xxxstring
types are preferable because they don't exhibit undesired aliasing, thus
making code more robust.

The following functions are publicly imported:

Module Functions
Publicly imported functions
std.algorithm
cmp, std,algorithm,comparison
count, std,algorithm,searching
endsWith, std,algorithm,searching
startsWith, std,algorithm,searching
std.array
join, std,array
replace, std,array
replaceInPlace, std,array
split, std,array
empty, std,array
std.format
format, std,format
sformat, std,format
std.uni
icmp, std,uni
toLower, std,uni
toLowerInPlace, std,uni
toUpper, std,uni
toUpperInPlace, std,uni
There is a rich set of functions for string handling defined in other modules.
Functions related to Unicode and ASCII are found in std.uni
and std.ascii, respectively. Other functions that have a
wider generality than just strings can be found in std.algorithm
and std.range.

Source

std/string.d

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) editor_recovery_cadence.strip = std.string.strip(Range)(Range str) if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range))

Strips both leading and trailing whitespace (as defined by isWhite) or as specified in the second argument.

@paramstr string or random access range of characters@paramchars string of characters to be stripped@paramleftChars string of leading characters to be stripped@paramrightChars string of trailing characters to be stripped@returnsslice of str stripped of leading and trailing whitespace or characters as specified in the second argument.@seeGeneric stripping on ranges: strip
strip
;
import
(package) std
std
.
(module) std.uuid

A UUID, or 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 UUID UUIDParsingException uuidRegex |

| Generating UUIDs | sha1UUID randomUUID md5UUID timestampRandomUUID |

| Using UUIDs | <a href="#uuidVersion">UUID.uuidVersion</a>&nbsp; <a href="#variant">UUID.variant</a>&nbsp; <a href="#toString">UUID.toString</a>&nbsp; <a href="#data">UUID.data</a>&nbsp; <a href="#swap">UUID.swap</a>&nbsp; <a href="#opEquals">UUID.opEquals</a>&nbsp; <a href="#opCmp">UUID.opCmp</a>&nbsp; <a href="#toHash">UUID.toHash</a>&nbsp; |

| UUID namespaces | dnsNamespace urlNamespace oidNamespace 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 <a href="#empty">UUID.empty</a> 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 from the Boost project with some minor additions and API changes for a more D-like API.

Source

std/uuid.d

Examples

import std.uuid;

UUID[] ids;
ids ~= randomUUID();
ids ~= md5UUID("test.name.123");
ids ~= sha1UUID("test.name.123");

foreach (entry; ids)
{
    assert(entry.variant == UUID.Variant.rfc4122);
}
assert(ids[0].uuidVersion == UUID.Version.randomNumberBased);
assert(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);
@standardsRFC 4122@seehttp://en.wikipedia.org/wiki/Universally_unique_identifier@copyrightCopyright Johannes Pfau 2011 - .@licenseBoost License 1.0.@authorsJohannes Pfau
uuid
:
(alias) editor_recovery_cadence.randomUUID = std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safe

This function generates a random number based UUID from a random number generator.

This function is not supported at compile time.

Warning

This function must not be used for cryptographic purposes. UUIDs generated by this function do not have sufficient randomness for all use cases. This especially applies to the overload that accepts a caller-provided RNG. At the moment, Phobos does not provide a cryptographically-secure pseudo-random number generator (CSPRNG) that could be supplied to this function.

While the function overload with no parameters will attempt to use the system CSPRNG where available and implemented, there are no guarantees. See unpredictableSeed for details.

@bugsIssue #9881 - Randomness in UUID generation is insufficient@paramrandomGen uniform RNG@seeisUniformRNG
randomUUID
;
void
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @system
measure
(
(alias) object.string = string
string
(parameter) string label
label
,
(alias) object.size_t = ulong
size_t
(parameter) ulong bytes
bytes
, bool
(parameter) bool longLine
longLine
, uint
(parameter) uint editBudgetMicros
editBudgetMicros
) @system
{ const
(local variable) const(string) root
root
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

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

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

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

Examples

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

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

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

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

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

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

Examples

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

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

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

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

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

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

tempDir
, "editor-cadence-" ~
std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safe

This function generates a random number based UUID from a random number generator.

This function is not supported at compile time.

Warning

This function must not be used for cryptographic purposes. UUIDs generated by this function do not have sufficient randomness for all use cases. This especially applies to the overload that accepts a caller-provided RNG. At the moment, Phobos does not provide a cryptographically-secure pseudo-random number generator (CSPRNG) that could be supplied to this function.

While the function overload with no parameters will attempt to use the system CSPRNG where available and implemented, there are no guarantees. See unpredictableSeed for details.

@bugsIssue #9881 - Randomness in UUID generation is insufficient@paramrandomGen uniform RNG@seeisUniformRNG
randomUUID
().
string std.uuid.UUID.toString() const pure nothrow @trusted

Return the UUID as a string in the canonical form.

Examples

immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46";
auto id = UUID(str);
assert(id.toString() == str);
toString
());
void std.file.mkdir!string(string pathname) @safe

Make a new directory pathname.

@parampathname the path of the directory to make@throwsFileException on POSIX or WindowsException on Windows if an error occured.
mkdir
(
(local variable) const(string) root
root
);
scope (exit)
void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

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

@parampathname the path of the directory to completely remove@paramde The DirEntry to remove@throwsFileException if there is an error (including if the given file is not a directory).
rmdirRecurse
(
(local variable) const(string) root
root
);
auto
(local variable) char[] contents
contents
= new char[
(parameter) ulong bytes
bytes
];
(local variable) char[] contents
contents
[] = 'x';
if (!
(parameter) bool longLine
longLine
)
for (
(alias) object.size_t = ulong
size_t
(local variable) ulong index
index
= 79; index < contents.length; index += 80)
(local variable) char[] contents
contents
[
(local variable) ulong index
index
] = '\n';
auto
(local variable) editor_document.Document document
document
= new
(class) editor_document.Document

A tab owns its reference-counted field; arrays contain tab references, never Text values.

Document
(7, "cadence", cast(
(alias) object.string = string
string
)
(local variable) char[] contents
contents
);
(class) editor_document.Document

A tab owns its reference-counted field; arrays contain tab references, never Text values.

Document
[]
(local variable) editor_document.Document[] documents
documents
= [
(local variable) editor_document.Document document
document
];
auto
(local variable) session_runtime.RecoverySession recovery
recovery
= new
(class) session_runtime.RecoverySession

Observe state on the application thread, poll with the host clock, and flush before orderly exit. Archive creation and retention run on a maintenance worker independently of checkpoint serialization. Shutdown releases the lease only after both workers stop; it does not promise to submit unflushed state.

Examples

Initialization retains the newest edits and explicit flush acknowledges them before closure.

version (linux) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("Recovery directory leases currently require Linux.");
}
import core.thread : Thread;
import core.time : MonoTime, seconds;
import editor_document : Document;
import session_archive : readSessionGeneration;
import sparkles.test_utils.tmpfs : TmpFS;
import std.path : buildPath;
auto fixture = TmpFS.create();
auto recovery = new RecoverySession(buildPath(fixture.dir, "sessions"), fixture.dir);
scope (exit) recovery.shutdown();
auto document = new Document(7, "draft");
Document[] documents = [document];
document.field.insert("before");
recovery.observe(documents, 7, "github-dark");
document.field.insert(" after");
recovery.observe(documents, 7, "github-dark");
assert(recovery.currentRevision == 2 && recovery.pending);
recovery.flush();
const deadline = MonoTime.currTime + 3.seconds;
while (recovery.pending && MonoTime.currTime < deadline)
{
    recovery.poll();
    (() @trusted => Thread.yield())();
}
assert(!recovery.pending && recovery.durableRevision == 2 && !recovery.error.length);
const saved = readSessionGeneration(recovery.directoryPath, recovery.durableGeneration);
assert(saved.hasValue && saved.value.tabs[0].content == "before after");
const path = recovery.directoryPath;
recovery.shutdown();
auto reclaimed = LeasedDirectory.claim(path);
assert(reclaimed.hasValue);
reclaimed.value.close();
RecoverySession
(
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

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

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

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

Examples

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

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) root
root
, "sessions"),
(local variable) const(string) root
root
);
scope (exit)
(local variable) session_runtime.RecoverySession recovery
recovery
.
void session_runtime.RecoverySession.shutdown() nothrow @safe

Stop maintenance before closing the archive lease owned by the checkpoint writer.

shutdown
();
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
[]
(local variable) core.time.MonoTimeImpl!(ClockType.normal)[] observed
observed
;
(struct) core.time.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 Thread.sleep.

In std.datetime, it is also used as the result of various arithmetic operations on time points.

Use the dur function or one of its non-generic aliases to create Durations.

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 Durations when dealing with months or years. Rather, functions specific to months and years are defined. For instance, 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 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);
Duration
(local variable) core.time.Duration worstObservation
worstObservation
,
(local variable) core.time.Duration worstEdit
worstEdit
,
(local variable) core.time.Duration worstBatch
worstBatch
;
ulong
(local variable) ulong previousDurable
previousDurable
;
(alias) object.size_t = ulong
size_t
(local variable) ulong acknowledgments
acknowledgments
,
(local variable) ulong edits
edits
,
(local variable) ulong overdueSamples
overdueSamples
;
void
void editor_recovery_cadence.measure.observe(core.time.MonoTimeImpl!(ClockType.normal) now) nothrow @safe
observe
(
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
(parameter) core.time.MonoTimeImpl!(ClockType.normal) now
now
)
{ const
(local variable) const(ulong) revision
revision
=
(local variable) session_runtime.RecoverySession recovery
recovery
.
ulong session_runtime.RecoverySession.currentRevision() const pure nothrow @nogc @safe
currentRevision
;
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) before
before
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
;
(local variable) session_runtime.RecoverySession recovery
recovery
.
void session_runtime.RecoverySession.observe(scope editor_document.Document[] documents, ulong active, string acceptedTheme, core.time.MonoTimeImpl!(ClockType.normal) now = currTime(), session_record.SessionSettings settings = SessionSettings(true, true, true, true, true, false, cast(ubyte)4u, true, null, 14.0F, true, 1.2F, 0.0F, 400.0F, 0.0F)) nothrow @safe

Capture only changed state, retaining text roots without flattening bytes on this thread.

observe
(
(local variable) editor_document.Document[] documents
documents
, 7, "github-dark",
(parameter) core.time.MonoTimeImpl!(ClockType.normal) now
now
);
const
(local variable) const(core.time.Duration) took
took
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a 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 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.

before
;
if (
(local variable) const(core.time.Duration) took
took
>
int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safe

Compares this Duration with the given Duration.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
worstObservation
)
(local variable) core.time.Duration worstObservation
worstObservation
=
(local variable) const(core.time.Duration) took
took
;
if (
(local variable) const(ulong) revision
revision
!=
(local variable) session_runtime.RecoverySession recovery
recovery
.
ulong session_runtime.RecoverySession.currentRevision() const pure nothrow @nogc @safe
currentRevision
)
(local variable) core.time.MonoTimeImpl!(ClockType.normal)[] observed
observed
~=
(parameter) core.time.MonoTimeImpl!(ClockType.normal) now
now
;
} void
void editor_recovery_cadence.measure.poll() nothrow @safe
poll
()
{ const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) now
now
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
;
(local variable) session_runtime.RecoverySession recovery
recovery
.
void session_runtime.RecoverySession.poll(core.time.MonoTimeImpl!(ClockType.normal) now = currTime()) nothrow @safe

Publish maintenance/checkpoint receipts and schedule bounded background work.

poll
(
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) now
now
);
assert(!
(local variable) session_runtime.RecoverySession recovery
recovery
.
string session_runtime.RecoverySession.error() const pure nothrow @nogc @safe
error
.
(field) ulong string.length
length
,
(local variable) session_runtime.RecoverySession recovery
recovery
.
string session_runtime.RecoverySession.error() const pure nothrow @nogc @safe
error
);
if (
(local variable) session_runtime.RecoverySession recovery
recovery
.
bool session_runtime.RecoverySession.overdue(core.time.MonoTimeImpl!(ClockType.normal) now) const pure nothrow @nogc @safe
overdue
(
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) now
now
)) ++
(local variable) ulong overdueSamples
overdueSamples
;
if (
(local variable) session_runtime.RecoverySession recovery
recovery
.
ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safe
durableRevision
>
(local variable) ulong previousDurable
previousDurable
)
{ const
(local variable) const(core.time.Duration) age
age
=
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) now
now
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a 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 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.

observed
[cast(
(alias) object.size_t = ulong
size_t
)
(local variable) ulong previousDurable
previousDurable
];
if (
(local variable) const(core.time.Duration) age
age
>
int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safe

Compares this Duration with the given Duration.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
worstBatch
)
(local variable) core.time.Duration worstBatch
worstBatch
=
(local variable) const(core.time.Duration) age
age
;
(local variable) ulong previousDurable
previousDurable
=
(local variable) session_runtime.RecoverySession recovery
recovery
.
ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safe
durableRevision
;
++
(local variable) ulong acknowledgments
acknowledgments
;
} } const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) start
start
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
;
void editor_recovery_cadence.measure.observe(core.time.MonoTimeImpl!(ClockType.normal) now) nothrow @safe
observe
(
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) start
start
);
while (
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a 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 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.

start
< 2.seconds)
{ const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) before
before
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
;
(local variable) editor_document.Document document
document
.
(field) sparkles.ui.editor.field.EditorFieldOf!(LayoutContext) editor_document.Document.field

Wrapped, bidi-aware rows: motion, drawing and hits share one layout (EAP17).

field
.
sparkles.ui.editor.field.FieldResult sparkles.ui.editor.field.EditorFieldOf!(sparkles.ui.editor.layout.LayoutContext).insert(scope const(char)[] text, bool paste = false, core.time.MonoTimeImpl!(ClockType.normal) now = MonoTimeImpl(0L)) pure nothrow @nogc @safe

Insert text, as typed or as a paste (EDI4). Text of any length goes in whole.

insert
("a", now:
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) before
before
);
const
(local variable) const(core.time.Duration) took
took
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a 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 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.

before
;
if (
(local variable) const(core.time.Duration) took
took
>
int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safe

Compares this Duration with the given Duration.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
worstEdit
)
(local variable) core.time.Duration worstEdit
worstEdit
=
(local variable) const(core.time.Duration) took
took
;
++
(local variable) ulong edits
edits
;
void editor_recovery_cadence.measure.observe(core.time.MonoTimeImpl!(ClockType.normal) now) nothrow @safe
observe
(
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
);
void editor_recovery_cadence.measure.poll() nothrow @safe
poll
();
(class) core.thread.osthread.Thread

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.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

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.

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

@paramval The minimum duration the calling thread should be suspended.
sleep
(8.msecs);
}
(local variable) session_runtime.RecoverySession recovery
recovery
.
void session_runtime.RecoverySession.flush(core.time.MonoTimeImpl!(ClockType.normal) now = currTime()) nothrow @safe

Stay in flush mode through initialization and any later observations until the latest receipt.

flush
();
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
+ 5.seconds;
while (
(local variable) session_runtime.RecoverySession recovery
recovery
.
bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safe
pending
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

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.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
deadline
)
{
void editor_recovery_cadence.measure.poll() nothrow @safe
poll
();
if (
(local variable) session_runtime.RecoverySession recovery
recovery
.
bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safe
pending
)
(class) core.thread.osthread.Thread

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.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

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.

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

@paramval The minimum duration the calling thread should be suspended.
sleep
(1.msecs);
}
void std.stdio.writefln!(char, string, ulong, ulong, long, long, long, ulong, ulong)(in char[] fmt, string __param_1, ulong __param_2, ulong __param_3, long __param_4, long __param_5, long __param_6, ulong __param_7, ulong __param_8) @safe

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

writefln
("%s,%s,%s,%s,%s,%s,%s,%s",
(parameter) string label
label
,
(local variable) ulong edits
edits
,
(local variable) ulong acknowledgments
acknowledgments
,
(local variable) core.time.Duration worstEdit
worstEdit
.
long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safe

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);
total
!"usecs",
(local variable) core.time.Duration worstObservation
worstObservation
.
long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safe

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);
total
!"usecs",
(local variable) core.time.Duration worstBatch
worstBatch
.
long core.time.Duration.total!"msecs"() const pure nothrow @nogc @property @safe

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);
total
!"msecs",
(local variable) ulong overdueSamples
overdueSamples
,
(local variable) session_runtime.RecoverySession recovery
recovery
.
ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safe
durableRevision
);
assert(!
(local variable) session_runtime.RecoverySession recovery
recovery
.
bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safe
pending
, "The latest recovery revision was not acknowledged.");
assert(!
(local variable) ulong overdueSamples
overdueSamples
&&
(local variable) core.time.Duration worstBatch
worstBatch
< 1.seconds,
"The one-second recovery bound was exceeded on this workload/host."); if (
(parameter) uint editBudgetMicros
editBudgetMicros
)
assert(
(local variable) core.time.Duration worstEdit
worstEdit
.
long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safe

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);
total
!"usecs" <=
(parameter) uint editBudgetMicros
editBudgetMicros
,
"The requested per-edit CPU budget was exceeded on this workload/host."); } int
int D main(string[] args) @system
main
(
(alias) object.string = string
string
[]
(parameter) string[] args
args
) @system
{ bool
(local variable) bool singleOnly
singleOnly
;
uint
(local variable) uint editBudgetMicros
editBudgetMicros
;
std.getopt.GetoptResult std.getopt.getopt!(string, bool*, string, uint*)(ref string[] args, string __param_1, bool* __param_2, string __param_3, uint* __param_4) @safe

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, or if a required argument is missing 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`.

  1. 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`.

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

  1. 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`.

  1. 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'.

  1. 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` 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".

  1. 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` 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.

  1. 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);
}
getopt
(
(parameter) string[] args
args
, "single-line", &
(local variable) bool singleOnly
singleOnly
, "edit-budget-us", &
(local variable) uint editBudgetMicros
editBudgetMicros
);
assert(
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 1, "Options: --single-line --edit-budget-us=8000");
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystem
filesystem
=
std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

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

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

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

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
(["stat", "-f", "-c", "%T",
string std.file.tempDir() @trusted

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

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

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

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

Examples

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

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

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

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

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

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

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

tempDir
]);
assert(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystem
filesystem
.status == 0);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safe

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

Example

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

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("filesystem,",
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystem
filesystem
.output.
string std.string.strip!string(string str) pure nothrow @nogc @safe

Strips both leading and trailing whitespace (as defined by isWhite) or as specified in the second argument.

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");
@paramstr string or random access range of characters@paramchars string of characters to be stripped@paramleftChars string of leading characters to be stripped@paramrightChars string of trailing characters to be stripped@returnsslice of str stripped of leading and trailing whitespace or characters as specified in the second argument.@seeGeneric stripping on ranges: strip
strip
);
void std.stdio.writeln!string(string __param_0) @safe

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

Example

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

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("workload,edits,acks,max_edit_us,max_observe_us,max_oldest_unacked_ms,overdue_samples,final_revision");
if (!
(local variable) bool singleOnly
singleOnly
)
{
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @system
measure
("1MiB-80-columns", 1 * 1024 * 1024, false,
(local variable) uint editBudgetMicros
editBudgetMicros
);
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @system
measure
("10MiB-80-columns", 10 * 1024 * 1024, false,
(local variable) uint editBudgetMicros
editBudgetMicros
);
}
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @system
measure
("1MiB-single-line", 1 * 1024 * 1024, true,
(local variable) uint editBudgetMicros
editBudgetMicros
);
(struct) core.sys.posix.sys.resource.rusage
rusage
(local variable) core.sys.posix.sys.resource.rusage usage
usage
;
assert(
int core.sys.posix.sys.resource.getrusage(int, core.sys.posix.sys.resource.rusage*) nothrow @nogc
getrusage
(
(enum value) core.sys.posix.sys.resource.RUSAGE_SELF = 0
RUSAGE_SELF
, &
(local variable) core.sys.posix.sys.resource.rusage usage
usage
) == 0);
void std.stdio.writeln!(string, long)(string __param_0, long __param_1) @safe

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

Example

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

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("process_peak_rss_kib,",
(local variable) core.sys.posix.sys.resource.rusage usage
usage
.
(field) long core.sys.posix.sys.resource.rusage.ru_maxrss
ru_maxrss
);
return 0; }