#!/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_cadenceMeasure recovery under sustained edits, independently of shaping and drawing.
editor_recovery_cadence;
import (package) corecore.(module) core.threadThe thread module provides support for thread creation and management.
Source
core/thread/package.d
thread : (class) core.thread.osthread.ThreadThis 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) corecore.(module) core.timeModule 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
time : (struct) core.time.DurationRepresents 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) corecore.(package) core.syssys.(package) core.sys.posixposix.(package) core.sys.posix.syssys.(module) core.sys.posix.sys.resourceD header file for POSIX.
resource : (alias) editor_recovery_cadence.getrusage = int core.sys.posix.sys.resource.getrusage(int, core.sys.posix.sys.resource.rusage*) nothrow @nogcgetrusage, (alias enum value) editor_recovery_cadence.RUSAGE_SELF = core.sys.posix.sys.resource.RUSAGE_SELF = 0RUSAGE_SELF, (struct) core.sys.posix.sys.resource.rusagerusage;
import (module) editor_documentEditor document state, independent of its application and rendering host.
editor_document : (class) editor_document.DocumentA tab owns its reference-counted field; arrays contain tab references, never Text values.
Document;
import (module) session_runtimeApplication-facing recovery service over sparkles:recovery; maintenance runs on a CPU worker.
session_runtime : (class) session_runtime.RecoverySessionObserve 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) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) editor_recovery_cadence.mkdir = std.file.mkdir(R)(R pathname) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Make a new directory pathname.
mkdir, (alias) editor_recovery_cadence.rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse, (alias) editor_recovery_cadence.tempDir = string std.file.tempDir() @trustedReturns 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:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/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.
tempDir;
import (package) stdstd.(module) std.getoptProcessing 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
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:
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`.
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`.
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+", ¶noid);
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.
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`.
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'.
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".
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.
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) stdstd.(module) std.pathThis 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
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.
buildPath;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (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) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (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);
}
}
writeln;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) 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.
strip;
import (package) stdstd.(module) std.uuidA 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>
<a href="#variant">UUID.variant</a>
<a href="#toString">UUID.toString</a>
<a href="#data">UUID.data</a>
<a href="#swap">UUID.swap</a>
<a href="#opEquals">UUID.opEquals</a>
<a href="#opCmp">UUID.opCmp</a>
<a href="#toHash">UUID.toHash</a>
|
| 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);
uuid : (alias) editor_recovery_cadence.randomUUID = std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis 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.
randomUUID;
void void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @systemmeasure((alias) object.string = stringstring (parameter) string labellabel, (alias) object.size_t = ulongsize_t (parameter) ulong bytesbytes, bool (parameter) bool longLinelongLine, uint (parameter) uint editBudgetMicroseditBudgetMicros) @system
{
const (local variable) const(string) rootroot = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines 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`);
}
buildPath(string std.file.tempDir() @trustedReturns 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:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/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");
tempDir, "editor-cadence-" ~ std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis 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.
randomUUID().string std.uuid.UUID.toString() const pure nothrow @trustedReturn 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) @safeMake a new directory pathname.
mkdir((local variable) const(string) rootroot);
scope (exit) void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse((local variable) const(string) rootroot);
auto (local variable) char[] contentscontents = new char[(parameter) ulong bytesbytes];
(local variable) char[] contentscontents[] = 'x';
if (!(parameter) bool longLinelongLine)
for ((alias) object.size_t = ulongsize_t (local variable) ulong indexindex = 79; index < contents.length; index += 80) (local variable) char[] contentscontents[(local variable) ulong indexindex] = '\n';
auto (local variable) editor_document.Document documentdocument = new (class) editor_document.DocumentA tab owns its reference-counted field; arrays contain tab references, never Text values.
Document(7, "cadence", cast((alias) object.string = stringstring) (local variable) char[] contentscontents);
(class) editor_document.DocumentA tab owns its reference-counted field; arrays contain tab references, never Text values.
Document[] (local variable) editor_document.Document[] documentsdocuments = [(local variable) editor_document.Document documentdocument];
auto (local variable) session_runtime.RecoverySession recoveryrecovery = new (class) session_runtime.RecoverySessionObserve 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 @safeCombines 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`);
}
buildPath((local variable) const(string) rootroot, "sessions"), (local variable) const(string) rootroot);
scope (exit) (local variable) session_runtime.RecoverySession recoveryrecovery.void session_runtime.RecoverySession.shutdown() nothrow @safeStop 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)[] observedobserved;
(struct) core.time.DurationRepresents 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 worstObservationworstObservation, (local variable) core.time.Duration worstEditworstEdit, (local variable) core.time.Duration worstBatchworstBatch;
ulong (local variable) ulong previousDurablepreviousDurable;
(alias) object.size_t = ulongsize_t (local variable) ulong acknowledgmentsacknowledgments, (local variable) ulong editsedits, (local variable) ulong overdueSamplesoverdueSamples;
void void editor_recovery_cadence.measure.observe(core.time.MonoTimeImpl!(ClockType.normal) now) nothrow @safeobserve((struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime (parameter) core.time.MonoTimeImpl!(ClockType.normal) nownow)
{
const (local variable) const(ulong) revisionrevision = (local variable) session_runtime.RecoverySession recoveryrecovery.ulong session_runtime.RecoverySession.currentRevision() const pure nothrow @nogc @safecurrentRevision;
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) beforebefore = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 recoveryrecovery.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 @safeCapture only changed state, retaining text roots without flattening bytes on this thread.
observe((local variable) editor_document.Document[] documentsdocuments, 7, "github-dark", (parameter) core.time.MonoTimeImpl!(ClockType.normal) nownow);
const (local variable) const(core.time.Duration) tooktook = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safeSubtracting 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) tooktook > int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safeCompares this Duration with the given Duration.
worstObservation) (local variable) core.time.Duration worstObservationworstObservation = (local variable) const(core.time.Duration) tooktook;
if ((local variable) const(ulong) revisionrevision != (local variable) session_runtime.RecoverySession recoveryrecovery.ulong session_runtime.RecoverySession.currentRevision() const pure nothrow @nogc @safecurrentRevision) (local variable) core.time.MonoTimeImpl!(ClockType.normal)[] observedobserved ~= (parameter) core.time.MonoTimeImpl!(ClockType.normal) nownow;
}
void void editor_recovery_cadence.measure.poll() nothrow @safepoll()
{
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) nownow = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 recoveryrecovery.void session_runtime.RecoverySession.poll(core.time.MonoTimeImpl!(ClockType.normal) now = currTime()) nothrow @safePublish maintenance/checkpoint receipts and schedule bounded background work.
poll((local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) nownow);
assert(!(local variable) session_runtime.RecoverySession recoveryrecovery.string session_runtime.RecoverySession.error() const pure nothrow @nogc @safeerror.(field) ulong string.lengthlength, (local variable) session_runtime.RecoverySession recoveryrecovery.string session_runtime.RecoverySession.error() const pure nothrow @nogc @safeerror);
if ((local variable) session_runtime.RecoverySession recoveryrecovery.bool session_runtime.RecoverySession.overdue(core.time.MonoTimeImpl!(ClockType.normal) now) const pure nothrow @nogc @safeoverdue((local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) nownow)) ++(local variable) ulong overdueSamplesoverdueSamples;
if ((local variable) session_runtime.RecoverySession recoveryrecovery.ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safedurableRevision > (local variable) ulong previousDurablepreviousDurable)
{
const (local variable) const(core.time.Duration) ageage = (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) nownow - core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeSubtracting 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 = ulongsize_t) (local variable) ulong previousDurablepreviousDurable];
if ((local variable) const(core.time.Duration) ageage > int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safeCompares this Duration with the given Duration.
worstBatch) (local variable) core.time.Duration worstBatchworstBatch = (local variable) const(core.time.Duration) ageage;
(local variable) ulong previousDurablepreviousDurable = (local variable) session_runtime.RecoverySession recoveryrecovery.ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safedurableRevision;
++(local variable) ulong acknowledgmentsacknowledgments;
}
}
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) startstart = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safeobserve((local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) startstart);
while ((struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safeSubtracting 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)) beforebefore = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 documentdocument.(field) sparkles.ui.editor.field.EditorFieldOf!(LayoutContext) editor_document.Document.fieldWrapped, 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 @safeInsert 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)) beforebefore);
const (local variable) const(core.time.Duration) tooktook = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safeSubtracting 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) tooktook > int core.time.Duration.opCmp(core.time.Duration rhs) const pure nothrow @nogc @safeCompares this Duration with the given Duration.
worstEdit) (local variable) core.time.Duration worstEditworstEdit = (local variable) const(core.time.Duration) tooktook;
++(local variable) ulong editsedits;
void editor_recovery_cadence.measure.observe(core.time.MonoTimeImpl!(ClockType.normal) now) nothrow @safeobserve((struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safepoll();
(class) core.thread.osthread.ThreadThis 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 @trustedSuspends 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
sleep(8.msecs);
}
(local variable) session_runtime.RecoverySession recoveryrecovery.void session_runtime.RecoverySession.flush(core.time.MonoTimeImpl!(ClockType.normal) now = currTime()) nothrow @safeStay in flush mode through initialization and any later observations until the latest receipt.
flush();
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 recoveryrecovery.bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safepending && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe 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 @safeCompares this MonoTime with the given MonoTime.
deadline)
{
void editor_recovery_cadence.measure.poll() nothrow @safepoll();
if ((local variable) session_runtime.RecoverySession recoveryrecovery.bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safepending) (class) core.thread.osthread.ThreadThis 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 @trustedSuspends 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
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) @safeEquivalent to writef(fmt, args, '\n').
writefln("%s,%s,%s,%s,%s,%s,%s,%s", (parameter) string labellabel, (local variable) ulong editsedits, (local variable) ulong acknowledgmentsacknowledgments,
(local variable) core.time.Duration worstEditworstEdit.long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"usecs", (local variable) core.time.Duration worstObservationworstObservation.long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"usecs", (local variable) core.time.Duration worstBatchworstBatch.long core.time.Duration.total!"msecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"msecs",
(local variable) ulong overdueSamplesoverdueSamples, (local variable) session_runtime.RecoverySession recoveryrecovery.ulong session_runtime.RecoverySession.durableRevision() const pure nothrow @nogc @safedurableRevision);
assert(!(local variable) session_runtime.RecoverySession recoveryrecovery.bool session_runtime.RecoverySession.pending() const pure nothrow @nogc @safepending, "The latest recovery revision was not acknowledged.");
assert(!(local variable) ulong overdueSamplesoverdueSamples && (local variable) core.time.Duration worstBatchworstBatch < 1.seconds,
"The one-second recovery bound was exceeded on this workload/host.");
if ((parameter) uint editBudgetMicroseditBudgetMicros)
assert((local variable) core.time.Duration worstEditworstEdit.long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"usecs" <= (parameter) uint editBudgetMicroseditBudgetMicros,
"The requested per-edit CPU budget was exceeded on this workload/host.");
}
int int D main(string[] args) @systemmain((alias) object.string = stringstring[] (parameter) string[] argsargs) @system
{
bool (local variable) bool singleOnlysingleOnly;
uint (local variable) uint editBudgetMicroseditBudgetMicros;
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) @safeParse 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:
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`.
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`.
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+", ¶noid);
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.
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`.
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'.
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".
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.
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[] argsargs, "single-line", &(local variable) bool singleOnlysingleOnly, "edit-budget-us", &(local variable) uint editBudgetMicroseditBudgetMicros);
assert((parameter) string[] argsargs.(field) ulong string[].lengthlength == 1, "Options: --single-line --edit-budget-us=8000");
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystemfilesystem = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute(["stat", "-f", "-c", "%T", string std.file.tempDir() @trustedReturns 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:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/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");
tempDir]);
assert((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystemfilesystem.status == 0);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("filesystem,", (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) filesystemfilesystem.output.string std.string.strip!string(string str) pure nothrow @nogc @safeStrips 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");
strip);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("workload,edits,acks,max_edit_us,max_observe_us,max_oldest_unacked_ms,overdue_samples,final_revision");
if (!(local variable) bool singleOnlysingleOnly)
{
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @systemmeasure("1MiB-80-columns", 1 * 1024 * 1024, false, (local variable) uint editBudgetMicroseditBudgetMicros);
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @systemmeasure("10MiB-80-columns", 10 * 1024 * 1024, false, (local variable) uint editBudgetMicroseditBudgetMicros);
}
void editor_recovery_cadence.measure(string label, ulong bytes, bool longLine, uint editBudgetMicros) @systemmeasure("1MiB-single-line", 1 * 1024 * 1024, true, (local variable) uint editBudgetMicroseditBudgetMicros);
(struct) core.sys.posix.sys.resource.rusagerusage (local variable) core.sys.posix.sys.resource.rusage usageusage;
assert(int core.sys.posix.sys.resource.getrusage(int, core.sys.posix.sys.resource.rusage*) nothrow @nogcgetrusage((enum value) core.sys.posix.sys.resource.RUSAGE_SELF = 0RUSAGE_SELF, &(local variable) core.sys.posix.sys.resource.rusage usageusage) == 0);
void std.stdio.writeln!(string, long)(string __param_0, long __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("process_peak_rss_kib,", (local variable) core.sys.posix.sys.resource.rusage usageusage.(field) long core.sys.posix.sys.resource.rusage.ru_maxrssru_maxrss);
return 0;
}