### Usage example with checked and Checked Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.checkedint.md Example showing basic usage of checked and Checked with default Abort hook and escape hatch with get. ```d import std.checkedint; void main() { auto a = checked(1_000_000_000); auto b = 2 * a; // overflow -> Abort default: prints message and aborts // Safer for library code: auto x = Checked!(long, Throw)(42); long y = x.get + 1; // escape hatch with unwrapped value } ``` -------------------------------- ### RedBlackTree usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.container.rbtree.md Usage example covering construction, sorted iteration, membership, removal by key, custom ordering, and bound operations. Demonstrates the primary API of RedBlackTree. ```d import std.container; RedBlackTree!int tree = new RedBlackTree!int(3, 1, 2); assert(tree.front == 1 && tree.back == 3); assert(tree.length == 3); // Sorted iteration assert(tree[].equal([1, 2, 3])); // Membership and removal by key assert(2 in tree); tree.removeKey(2); assert(2 !in tree); // Custom ordering auto desc = new RedBlackTree!(int, "a > b")(1, 2, 3); assert(desc.front == 3); // Bounds tree = new RedBlackTree!int(1, 3, 5, 7); assert(tree.lowerBound(4).front == 5); assert(tree.upperBound(5).empty); assert(tree.equalRange(3).length == 1); ``` -------------------------------- ### String conversion and comparisons example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.checkedint.md Example showing string conversion following std.conv.to rules and comparisons across sign boundaries. ```d import std.checkedint; // String conversion follows std.conv.to rules Checked!long v = "4242"; // Comparisons no longer misfire across sign boundaries: property static assert(checked(-1) < 0U); // true (vs built-in int(-1) > uint(0)) ``` -------------------------------- ### opChecked and pow usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.checkedint.md Example showing how to use opChecked and pow with overflow flag. The opChecked example demonstrates overflow detection with int.max + 1, and pow shows a successful exponentiation. ```d import std.checkedint; bool overflow = false; auto sum = opChecked!"+"(int.max, 1, overflow); assert(overflow); assert(sum == int.min); // wrapped result; check overflow flag overflow = false; auto p = pow(2, 10, overflow); assert(p == 1024 && !overflow); ``` -------------------------------- ### Usage example for CRC32 and CRC64 Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.crc.md Complete usage example covering the template API (one-shot), streaming with put/finish, OOP wrapper, and CRC64. Shows expected hex outputs for the given inputs. ```d import std.digest.crc; import std.digest : toHexString; // Template API ubyte[4] hash = crc32Of("The quick brown fox jumps over the lazy dog"); assert(crcHexString(hash) == "414FA339"); assert(toHexString!(Order.decreasing)(hash) == "414FA339"); // Streaming CRC32 crc; crc.put(cast(ubyte[])"The quick brown fox "); crc.put(cast(ubyte[])"jumps over the lazy dog"); ubyte[4] h = crc.finish(); assert(toHexString(h) == "39A34F41"); // OOP API auto oop = new CRC32Digest(); assert(crcHexString(oop.digest("abc")) == crcHexString(crc32Of("abc"))); // CRC64 assert(crc64ECMAOf("abc").toHexString!(Order.decreasing) == "2CD8094A1A277627"); ``` -------------------------------- ### visit usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.variant.md Shows how to use visit with an Algebraic!(int, string). The first matching handler is called; the example asserts the result for both int and string values. ```d import std.variant; import std.conv; Algebraic!(int, string) variant = 10; assert(variant.visit!((string s) => cast(int) s.length, (int i) => i)() == 10); variant = "string"; assert(variant.visit!((int i) => i, (string s) => cast(int) s.length)() == 6); ``` -------------------------------- ### uncompress usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zlib.md Example of using uncompress to decompress data compressed with compress. The result is asserted to equal the original source. ```d import std.zlib; auto src = "the quick brown fox jumps over the lazy dog\r\n"; ubyte[] dst = compress(src); ubyte[] result = cast(ubyte[]) uncompress(dst); assert(result == src); ``` -------------------------------- ### CRC32 hashing example with hexDigest and streaming Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.md Shows one-shot hashing with hexDigest and streaming usage with makeDigest, put, and finish. The example asserts the expected hash values. ```d import std.digest; import std.digest.crc; char[8] hexHash = hexDigest!CRC32("The quick brown fox jumps over the lazy dog"); assert(hexHash == "39A34F41"); CRC32 context = makeDigest!CRC32(); context.put(cast(ubyte[])"The quick brown fox jumps over the lazy dog"); ubyte[4] hash = context.finish(); assert(toHexString(hash) == "39A34F41"); ``` -------------------------------- ### appender usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Usage example for the appender factory. Creates a string appender, appends a string, a character, and another string, then asserts the accumulated data equals "Hello, world!". ```d import std.array : appender; auto a = appender!string; a.put("Hello, "); a.put('w'); a.put("orld!"); assert(a.data == "Hello, world!"); ``` -------------------------------- ### replicate usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Example usage of replicate with a string and n=3, producing "ababab". ```d import std.array : replicate; assert(replicate("ab", 3) == "ababab"); ``` -------------------------------- ### staticArray usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Usage example of staticArray: target-typed variant and explicit size variant. ```d import std.array : staticArray; import std.range : iota; long[3] s = 2.iota.staticArray!(long[3]); // target-typed variant auto s2 = staticArray!3("abcdef"); // first 3 elements ``` -------------------------------- ### Justification and padding usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.string.md Demonstrates leftJustify, center, and rightJustify with a custom fill character and default space padding. ```d import std.string; assert("x".leftJustify(3, '.') == "x.."); assert("x".center(3, '.') == ".x."); assert("xy".rightJustify(4) == " xy"); ``` -------------------------------- ### text usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.conv.md Example of using text to concatenate a string, an integer, and another string into a single string. ```d import std.conv : text; assert(text("value=", 42, ", ok") == "value=42, ok"); ``` -------------------------------- ### split and join usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Example usage of split and join: split collapses whitespace runs, join inserts a separator. ```d import std.array : split, join; assert("a b c".split == ["a", "b", "c"]); assert(["a","b"].join(",") == "a,b"); ``` -------------------------------- ### BinaryHeap usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.container.binaryheap.md Demonstrates creating a max-heap and min-heap using heapify, inserting and removing elements, and adopting a container store. Shows that heapify returns a range supporting front/popFront/empty/save. ```d import std.container.binaryheap : heapify; import std.algorithm.comparison : equal; // Max-heap over a builtin array (default less = "a < b") int[] a = [3, 1, 4, 5, 2]; auto h = heapify(a); assert(h.front == 5); h.insert(10); assert(h.front == 10); h.removeFront(); assert(h.front == 5); // Min-heap with an explicit ordering int[] b = [3, 1, 4]; auto minh = heapify!"a > b"(b); assert(minh.front == 1); // Iterating the logical heap (it is a range!): // heapify(a) supports the range primitives (front/popFront/empty/save) assert(h.front == 5); // Adopting a container store import std.container : Array; auto arr = make!(Array!int)(9, 4, 7); auto h2 = heapify(arr); assert(h2.front == 9); auto storeBack = h2.release(); ``` -------------------------------- ### SHA usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.sha.md Complete usage example covering one-shot helpers, streaming with the template API, hexDigest one-liner, and the OOP wrapper. The digest values are from the module's own unit tests; always verify in-process with the same assertions. ```d import std.digest; import std.digest.sha; import std.stdio : writeln; // Known-answer tests from the module source (std/digest/sha.d:851-937) assert(sha256Of("abc").toHexString == "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); assert(sha1Of("").toHexString == "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"); // Streaming with the template API SHA256 ctx; ctx.start(); ctx.put(cast(ubyte[])"part one "); ctx.put(cast(ubyte[])"part two"); ubyte[32] digest = ctx.finish(); // hexDigest one-liner assert(hexDigest!SHA256("abc") == "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); // OOP API auto d = new SHA512Digest(); ubyte[] out = d.digest("data"); writeln(out.toHexString!(LetterCase.lower)); ``` -------------------------------- ### insertInPlace usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Example of using insertInPlace to insert a range into an array at a specific position. ```d int[] a = [1, 2, 5]; a.insertInPlace(2, [3, 4]); assert(a == [1, 2, 3, 4, 5]); ``` -------------------------------- ### HMAC usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.hmac.md Demonstrates streaming and one-shot HMAC computation with SHA1, including hex digest output. The example shows how to use the put method for streaming and the hmac!SHA1 function for one-shot, and verifies the result with an assertion. ```d import std.digest; import std.digest.hmac; import std.digest.sha : SHA1; import std.string : representation; // Streaming auto hmac = HMAC!SHA1("My s3cR3T keY".representation); hmac.put("Hello, world".representation); ubyte[20] mac = hmac.finish(); // One-shot (usable via UFCS on byte ranges) auto mac2 = "Hello, world".representation.hmac!SHA1("secret".representation); // hexDigest works because HMAC!SHA1 passes isDigest import std.digest.sha; const sha1HMAC = "A very long phrase".representation .hmac!SHA1("secret".representation) .toHexString!(LetterCase.lower); assert(sha1HMAC == "49f2073c7bf58577e8c9ae59fe8cfd37c9ab94e5"); ``` -------------------------------- ### uninitializedArray usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.array.md Example of using uninitializedArray to create a ubyte array of size 1024. The caller must fill every slot. ```d import std.array : uninitializedArray; auto buf = uninitializedArray!(ubyte[])(1024); // caller must fill every slot ``` -------------------------------- ### Usage examples for encode, decode, encodeComponent, decodeComponent, uriLength, emailLength Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.uri.md Demonstrates round-trip encoding/decoding, query component encoding, '#' round-trip, error handling with URIException, and URL/email prefix scanning. ```d import std.uri; // Round trip string url = "http://www.digitalmars.com/~fred/fred's RX.html#foo"; assert(url.encode == "http://www.digitalmars.com/~fred/fred's%20RX.html#foo"); assert(url.encode.decode == url); // Query components must use encodeComponent assert(encodeComponent("c++") == "c%2B%2B"); assert(decodeComponent("foo%2F%26") == "foo/&"); // '#' round-trips through encode/URL decode pairs assert("%E3%81%82%E3%81%82".decode.encode == "%E3%81%82%E3%81%82"); // Error handling import std.exception; try "%ab".decode; catch (URIException e) assert(e.msg.length) // "Expected two hexadecimal digits after '%'" — see errors.md // Encoded non-ASCII round trips assert("%E3%81%82%E3%81%82".decode.encode == "%E3%81%82%E3%81%82"); // URL / email scanning assert(uriLength("http://www.digitalmars.com/~fred/fredsRX.html#foo end!") == 49); assert(uriLength("no uri here") == -1); assert(emailLength("my.e-mail@www.example-domain.com with garbage") == 32); assert(emailLength("blah@blub") == -1); ``` -------------------------------- ### Array usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.container.array.md Demonstrates construction, reference semantics, duplication, mutation, and capacity control of Array. Shows that assignment shares underlying data, dup creates an independent copy, and length assignment pads with T.init. ```d import std.algorithm.comparison : equal; import std.container; // Construction Array!int a = Array!int(1, 2, 3); auto b = make!(Array!int)(11, 12, 13); // via std.container.util.make // Reference semantics Array!int c = a; assert(c == a); c.front = 42; assert(a.front == 42); // same underlying data // Duplicating c = a.dup; c.front = 0; assert(a.front == 42); // Mutation a.insertBack(4); // [1,2,3,4] a.removeBack(); // [1,2,3] a.insertBefore(a[].find(2), 99); // [1,99,2,3] a.linearRemove(a[1 .. 2]); // remove the 99 assert(a[].equal([1, 2, 3])); // Capacity control a.reserve(1000); assert(a.capacity >= 1000); a.length = 10; // pads with int.init (0) assert(a.length == 10); a.clear(); assert(a.empty); ``` -------------------------------- ### MD5 usage examples Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.md Shows one-shot usage with md5Of and hexDigest, streaming with the MD5 struct, and the OOP API with MD5Digest. Includes known-answer test assertions. ```d import std.digest; import std.digest.md; // One-shot (known-answer tests from md.d) assert(md5Of("abc").toHexString == "900150983CD24FB0D6963F7D28E17F72"); assert(hexDigest!MD5("") == "D41D8CD98F00B980099ECF8427E"); assert(hexDigest!MD5("a") == "0CC175B9C0F1B6A831C399E269772661"); // Streaming template API MD5 ctx; ctx.start(); ctx.put(cast(ubyte[])"Hello, "); ctx.put(cast(ubyte[])"world"); ubyte[16] out = ctx.finish(); // OOP API auto d = new MD5Digest(); ubyte[] res = d.digest("abc"); assert(res.toHexString == "900150983CD24FB0D6963F7D28E17F72"); ``` -------------------------------- ### octal usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.conv.md Shows how to use octal to declare an octal literal and compare it with parse!int. Requires importing std.conv. ```d import std.conv : octal; assert(octal!177 == 127); assert(parse!int("177", 8) == octal!177); ``` -------------------------------- ### Base64 encode/decode usage examples Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.base64.md Shows the allocating convenience overloads of Base64.encode and Base64.decode, the URL-safe unpadded variant Base64URLNoPadding, a custom alphabet via Base64Impl, and buffer reuse with encodeLength. The assertions confirm the expected outputs. ```d import std.base64; // Allocating convenience overloads ubyte[] data = [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e]; const(char)[] encoded = Base64.encode(data); assert(encoded == "FPucA9l+"); ubyte[] decoded = Base64.decode("FPucA9l+"); assert(decoded == data); // URL-safe, unpadded (RFC 7515 / JWT) assert(Base64URLNoPadding.encode([0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f]) == "g9cwegE-"); // Custom alphabet via the template alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding); // embedding in regexes // Buffer reuse auto buf = new char[Base64.encodeLength(data.length)]; char[] enc = Base64.encode(data, buf); assert(enc == "FPucA9l+"); ``` -------------------------------- ### makeDigest function signature Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.md Returns an initialized digest by calling start(), so makeDigest!MD5().put(...).finish() works. ```d Hash makeDigest(Hash)() // line 591 ``` -------------------------------- ### makeDigest(Hash) Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.digest.md Returns an initialized digest (calls `start()`), so `makeDigest!MD5().put(...).finish()` works. ```APIDOC ## makeDigest(Hash)() ### Description Returns an initialized digest (calls `start()`), so `makeDigest!MD5().put(...).finish()` works. ### Method Function ### Signature ```d Hash makeDigest(Hash)() ``` ### Returns - **Hash** - An initialized digest instance. ### Source Line 591. ``` -------------------------------- ### match with SumType, catch-all, and ref handlers Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.sumtype.md Complete example of match with a SumType alias. Shows conversion to Fahrenheit, a catch-all handler using `_`, and in-place modification using `ref` handlers. The `isClose` assertion verifies the conversion result. ```d import std.math.operations : isClose; import std.sumtype; struct Fahrenheit { double value; } struct Celsius { double value; } struct Kelvin { double value; } alias Temperature = SumType!(Fahrenheit, Celsius, Kelvin); Temperature t = Fahrenheit(98.6); double toFahrenheit(Temperature t) { return t.match!( (Fahrenheit f) => f.value, (Celsius c) => c.value * 9.0/5 + 32, (Kelvin k) => k.value * 9.0/5 - 459.4 ); } assert(toFahrenheit(t).isClose(98.6)); // Catch-all with `_`: bool isFahrenheit(Temperature t) { return t.match!( (Fahrenheit f) => true, _ => false ); } // Modifying in place uses ref handlers: void freeze(ref Temperature t) { t.match!( (ref Fahrenheit f) => f.value = 32, (ref Celsius c) => c.value = 0, (ref Kelvin k) => k.value = 273 ); } ``` -------------------------------- ### Usage examples for std.ascii Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.ascii.md Shows usage of std.ascii validation and conversion functions, and combines to!string with LetterCase for radix formatting. All functions are @safe pure nothrow @nogc, so error handling is not applicable. ```d import std.ascii; assert(isAlpha('a') && isAlpha('Z')); assert(!isAlpha('1') && isDigit('7')); assert(isHexDigit('f') && isOctalDigit('7')); assert(toLower('D') == 'd'); assert(toUpper('d') == 'D'); // Combine with std.conv for radix formatting: import std.conv : to; assert(42.to!string(16, LetterCase.upper) == "2A"); assert(42.to!string(16, LetterCase.lower) == "2a"); ``` -------------------------------- ### Basic getopt usage with help printing Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Shows how to define options of different types (numeric, string, boolean, enum) and how to print help when helpWanted is set. Uses config.bundling to enable short-option bundling and reuses the verbose receiver for the short 'v' option. ```d import std.getopt; void main(string[] args) { string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes } Color color; auto helpInformation = getopt( args, "length", &length, // numeric option "file", &data, // string option "verbose", &verbose, // boolean flag "color", "Information about this color", &color, // enum with help text config.bundling, 'v', &verbose); // short-option bundling + reused receiver if (helpInformation.helpWanted) defaultGetoptPrinter("Some information about the program.", helpInformation.options); } ``` -------------------------------- ### Writing an archive Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zip.md Creates two ArchiveMember objects, adds them to a ZipArchive, builds the archive, and writes it to a file. Demonstrates storing without compression and using deflate compression. ```D import std.file : write; import std.string : representation; import std.zip; ArchiveMember file1 = new ArchiveMember(); file1.name = "test1.txt"; file1.expandedData("Test data.\n".dup.representation); file1.compressionMethod = CompressionMethod.none; // store, don't compress ArchiveMember file2 = new ArchiveMember(); file2.name = "test2.txt"; file2.expandedData("More test data.\n".dup.representation); file2.compressionMethod = CompressionMethod.deflate; // compress ZipArchive zip = new ZipArchive(); zip.addMember(file1); zip.addMember(file2); void[] compressed_data = zip.build(); write("test.zip", compressed_data); ``` -------------------------------- ### getopt - Callbacks and Required Options Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Demonstrates using callback receivers for options and handling repeated options. Also shows how to mark options as required using config.required. ```APIDOC ## getopt - Callbacks and Required Options ### Description Demonstrates using callback receivers for options and handling repeated options. Also shows how to mark options as required using config.required. ### Example: Callback Receiver ```d import std.getopt; bool verbose; string[] args = ["prog", "--count", "3", "--tag", "x", "--tag", "y"]; int count; void countFn(string opt) { count++; } // callback receiver string[] tags; getopt(args, "count", &countFn, "tag", &tags); assert(count == 1); assert(tags == ["x", "y"]); ``` ### Example: Required Option ```d import std.getopt; bool b; string[] args = ["prog"]; try getopt(args, config.required, "mandatory", &b); catch (GetOptException e) assert(e.msg == "Required option mandatory was not supplied"); ``` ``` -------------------------------- ### Usage examples for path functions Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.path.md Shows typical usage of std.path functions under Posix, including baseName, dirName, extension, stripExtension, buildPath, chainPath, isAbsolute, globMatch, and absolutePath. Also demonstrates case sensitivity defaults with baseName using CaseSensitive.no and CaseSensitive.yes. ```d import std.path; version (Posix) { assert(baseName("/foo/bar/file.txt") == "file.txt"); assert(dirName("/foo/bar/file.txt") == "/foo/bar"); assert(extension("file.ext1.ext2") == ".ext2"); assert(stripExtension("file.ext") == "file"); assert(baseName(stripExtension("/d/file.ext")) == "file"); assert(buildPath(["a", "b"]) == "a/b"); assert(chainPath("/foo", "bar").array == "/foo/bar"); assert(isAbsolute("/foo") && !isAbsolute("foo")); assert(globMatch("dir/*.d", "dir/a.d")); assert(absolutePath("some/file", "/foo/bar") == "/foo/bar/some/file"); } // Case sensitivity defaults assert(baseName!(CaseSensitive.no)("dir/file.EXT", ".ext") == "file"); assert(baseName!(CaseSensitive.yes)("dir/file.EXT", ".ext") != "file"); ``` -------------------------------- ### std.json usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.json.md Complete example of using std.json: parse JSON, build JSONValue from D values, serialize with pretty-printing, handle parse errors with JSONException, and round-trip NaN using JSONOptions.specialFloatLiterals. ```d import std.json; import std.stdio : stderr; // Parse JSONValue j = parseJSON(`{"language":"D","rating":3.5}`); assert(j["language"].get!string == "D"); // Build from D values JSONValue jj = ["language": "D"]; jj.object["rating"] = JSONValue(3.5); // existing key: use indexing instead jj["list"] = JSONValue(["a", "b", "c"]); // creates the key jj["list"].array ~= JSONValue("D"); string out = toJSON(jj, true); // pretty-printed assert(parseJSON(out)["rating"].floating == 3.5); // Error handling try parseJSON(`{"a": }`); catch (JSONException e) stderr.writeln(e.msg); // "Unexpected character '}' (Line 1:6)" // Round-trip with NaN encoding JSONValue v = 0.0; v.floating = double.nan; auto s = toJSON(v, false, JSONOptions.specialFloatLiterals); assert(s == `"NaN"`); ``` -------------------------------- ### Checksum usage example with assertions Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zlib.md Example usage of adler32 and crc32. It imports std.zlib, defines a static ubyte array, and asserts the expected checksum values for the given data. Note that crc32 requires a cast to void[]. ```d import std.zlib; static ubyte[] data = [1,2,3,4,5,6,7,8,9,10]; assert(adler32(0u, data) == 0xdc0037); assert(crc32(0u, cast(void[])data) == 0x2520577b); ``` -------------------------------- ### getopt function signature Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md The main entry point for parsing command-line arguments. Takes a mutable array of arguments and a variadic list of option descriptors. ```d GetoptResult getopt(T...)(ref string[] args, T opts) ``` -------------------------------- ### getopt - Error Handling Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Shows how to catch GetOptException for unknown options and how to use config.passThrough to leave unrecognized arguments in place. ```APIDOC ## getopt - Error Handling ### Description Shows how to catch GetOptException for unknown options and how to use config.passThrough to leave unrecognized arguments in place. ### Example: Unknown Option ```d import std.exception; import std.getopt; import std.stdio : writeln; bool b; string[] args = ["prog", "--unknown"]; try getopt(args, "known", &b); catch (GetOptException e) writeln("unknown option: ", e.msg); ``` ### Example: passThrough ```d import std.getopt; bool b; string[] args = ["prog", "--unknown"]; auto r = getopt(args, config.passThrough, "known", &b); assert(args == ["prog", "--unknown"]); ``` ``` -------------------------------- ### isRooted Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.path.md Checks if a path starts at a root. ```APIDOC ## isRooted ### Description Checks if a path starts at a root. ### Signature `bool isRooted(R)(R path)` ### Parameters - `path` (R) - Required - The path to test. ### Returns - `true` if the path starts at a root (drive root on Windows). ``` -------------------------------- ### Preview changelog with make Source: https://github.com/dlang/phobos/blob/master/changelog/README.md Command to preview the pending changelog. Requires cloned tools and dlang.org repositories. Run from the changelog directory. ```bash make -C ../dlang.org -f posix.mak pending_changelog ``` -------------------------------- ### parse usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.conv.md Example of using parse to parse an int and a double from a string. The source string is consumed during parsing, so after parsing the double, the string becomes empty. Also shows UFCS usage on ranges. Throws ConvException on malformed input. ```d import std.conv : parse; string s = "42 3.14"; auto a = parse!int(s); // 42 auto b = parse!double(s); // 3.14 — s is now "" // Also exposed via std.string-style UFCS on ranges assert(parse!double("1.5rest") == 1.5); ``` -------------------------------- ### class JSONException : Exception Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.json.md Documentation for the JSONException class, including its constructors and usage example. ```APIDOC ## `class JSONException : Exception` ### Description Exception thrown for JSON parsing and serialization errors. If `line` is non-zero, the message is wrapped as `"msg (Line L:P)"`. ### Constructors - `this(string msg, int line = 0, int pos = 0) pure nothrow @safe` - `this(string msg, string file, size_t line) pure nothrow @safe` ### Parameters - `msg` (string) - Required - The error message. - `line` (int) - Optional - Line number where the error occurred. Defaults to 0. - `pos` (int) - Optional - Position within the line. Defaults to 0. - `file` (string) - Required - Source file name. - `line` (size_t) - Required - Line number. ### Usage Example ```d import std.json; import std.stdio : stderr; try parseJSON(`{"a": }`); catch (JSONException e) stderr.writeln(e.msg); // "Unexpected character '}' (Line 1:6)" ``` ``` -------------------------------- ### Callbacks and repeated options with getopt Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Demonstrates a callback receiver for an option and a repeated option that collects into an array. The callback increments count each time the option is seen; the tag option accumulates its values into tags. ```d import std.getopt; bool verbose; string[] args = ["prog", "--count", "3", "--tag", "x", "--tag", "y"]; int count; void countFn(string opt) { count++; } // callback receiver string[] tags; getopt(args, "count", &countFn, "tag", &tags); assert(count == 1); assert(tags == ["x", "y"]); ``` -------------------------------- ### ZipArchive.comment Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zip.md Gets or sets the archive comment. The comment must be less than 65536 bytes. ```APIDOC ## ZipArchive.comment ### Description Archive comment. Must be less than 65536 bytes. ### Type string ### Access Read/write field ### Constraints Length must be < 65536 bytes. ``` -------------------------------- ### GetoptResult and Option structs Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Return type of getopt and the structure describing each defined option, used for building help text. ```d struct GetoptResult { bool helpWanted; /// true if `--help` or `-h` was seen Option[] options; /// all defined options (for building help text) } struct Option { string optShort; /// e.g. "-f" string optLong; /// e.g. "--foo" string help; /// description bool required; /// required options fail when absent } ``` -------------------------------- ### parseJSON usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.json.md Parses a JSON string literal and asserts the values of the resulting JSONValue fields. ```d string s = `{ "language": "D", "rating": 3.5, "code": "42" }`; JSONValue j = parseJSON(s); assert(j["language"].str == "D"); assert(j["rating"].floating == 3.5); ``` -------------------------------- ### RedBlackTree!T Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.container.rbtree.md Documentation for the RedBlackTree class in std.container.rbtree, including constructors, ranges, members, and usage examples. ```APIDOC ## RedBlackTree!T ### Description A red-black tree (sorted set/map) with reference semantics. Class-based: must be allocated with `new` (or `make`). ### Import `import std.container;` (re-exported) or `import std.container.rbtree;` ### Declaration ```d final class RedBlackTree(T, alias less = "a < b", bool allowDuplicates = false) ``` ### Constructors - `this(Elem[] values...)` - Variadic element constructor. - Range constructor - Constructs from an input range. ### Ranges - `alias Range = RBRange!(RBNode*);` - `alias ConstRange = RBRange!(const(RBNode)*);` - `alias ImmutableRange = RBRange!(immutable(RBNode)*);` ### Members #### `empty()` ```d @property bool empty() const ``` Returns `true` if the tree is empty. #### `length()` ```d @property size_t length() const ``` Returns the number of elements in the tree. #### `dup` ```d @property RedBlackTree dup() ``` Returns a duplicate of the tree. #### `opSlice()` ```d Range opSlice() ``` Returns a range that iterates over the tree in sorted order. #### `front()` / `back()` ```d ref inout(Elem) front() inout ref inout(Elem) back() inout ``` Returns the smallest/largest element. #### `opBinaryRight!("in")` ```d bool opBinaryRight(string op)(Elem e) const if (op == "in") ``` Membership test: `e in tree`. #### `opEquals` ```d override bool opEquals(Object rhs) ``` Compares two trees for equality. #### `toHash` ```d override size_t toHash() nothrow @safe ``` Returns a hash of the tree. #### `clear()` ```d void clear() ``` Removes all elements. #### `stableInsert` / `insert` ```d size_t stableInsert(Stuff)(Stuff stuff) alias insert = stableInsert; ``` Inserts an element or an input range. Returns the number of elements inserted. #### `removeAny()` ```d Elem removeAny() ``` Removes and returns the smallest element. O(log n). #### `removeFront()` / `removeBack()` ```d void removeFront() void removeBack() ``` Removes the smallest/largest element. #### `remove(Range)` ```d Range remove(Range r) Range remove(Take!Range r) ``` Removes the elements in the given range. Returns the range following the removed elements. #### `removeKey` ```d size_t removeKey(U...)(U elems) ``` Removes elements by value. Returns the number of elements removed. Also accepts arrays/ranges. #### `upperBound(Elem e)` ```d Range upperBound(Elem e) ``` Returns a range of elements strictly greater than `e` (according to `less`). #### `lowerBound(Elem e)` ```d Range lowerBound(Elem e) ``` Returns a range of elements greater than or equal to `e`. #### `equalRange(Elem e)` ```d auto equalRange(this This)(Elem e) ``` Returns a range of all elements equal to `e`. #### `trisect(Elem e)` ```d auto trisect(this This)(Elem e) ``` Returns a tuple `(lowerBound, equalRange, upperBound)`. ### Usage Example ```d import std.container; RedBlackTree!int tree = new RedBlackTree!int(3, 1, 2); assert(tree.front == 1 && tree.back == 3); assert(tree.length == 3); // Sorted iteration assert(tree[].equal([1, 2, 3])); // Membership and removal by key assert(2 in tree); tree.removeKey(2); assert(2 !in tree); // Custom ordering auto desc = new RedBlackTree!(int, "a > b")(1, 2, 3); assert(desc.front == 3); // Bounds tree = new RedBlackTree!int(1, 3, 5, 7); assert(tree.lowerBound(4).front == 5); assert(tree.upperBound(5).empty); assert(tree.equalRange(3).length == 1); ``` ### Errors - `removeKey`/`insert`/`dup` use `std.exception.enforce` for precondition violations (e.g. range arguments from another tree). - `removeAny`/`front`/`back` on an empty tree assert. - An uninitialized `RedBlackTree` (not allocated with `new`/`make`) dereferences `null`. ``` -------------------------------- ### StopWatch Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.datetime.md StopWatch measures wall-clock or monotonic time with start, stop, reset, and peek operations. ```APIDOC ## [D] StopWatch ### Description Measures wall-clock (ClockType.normal) or monotonic time. Constructor accepts a clock type and whether to auto-start. ### Method Constructor and member functions ### Endpoint std.datetime.stopwatch.StopWatch ### Parameters #### Constructor Parameters - **clockType** (ClockType) - Optional - Clock type: ClockType.normal or ClockType.monotonic - **autoStart** (AutoStart) - Optional - Whether to start automatically (AutoStart.yes or AutoStart.no) #### Member Functions - **start()** - Starts the stopwatch - **stop()** - Stops the stopwatch - **reset()** - Resets the stopwatch - **peek()** - Returns the elapsed Duration so far - **empty** (property) - Indicates whether the stopwatch is empty - **running** (property) - Indicates whether the stopwatch is running ### Request Example ```d StopWatch sw = StopWatch(ClockType.normal, AutoStart.yes); ``` ### Response #### Success Response - **peek()** returns a Duration representing elapsed time #### Response Example ```d Duration elapsed = sw.peek(); ``` ``` -------------------------------- ### tr usage example Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.string.md Demonstrates transliteration using tr, mapping each character in the from string to the corresponding character in the to string. ```d import std.string : tr; assert("abc".tr("abc", "ABC") == "ABC"); ``` -------------------------------- ### config Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Configuration flags for `getopt`. ```APIDOC ## `enum config` ### Description Configuration flags that control `getopt` behavior. Mutually exclusive flags (e.g., `caseSensitive`/`caseInsensitive`) - the last one given wins. ### Values - **caseSensitive** - Case-sensitive matching (default: case-insensitive). - **caseInsensitive** - Case-insensitive matching. - **bundling** - `-abc` = `-a -b -c` (default: off). - **noBundling** - Disable bundling. - **passThrough** - Leave unrecognized args in `args`. - **noPassThrough** - Error on unrecognized args (default). - **stopOnFirstNonOption** - Stop at the first argument that doesn't look like an option. - **keepEndOfOptions** - Don't erase the `--` separator from args. - **required** - The following option is required. ``` -------------------------------- ### Catching UUIDParsingException Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.uuid.md Example of catching UUIDParsingException around the UUID constructor. The exception has reason and position fields that can be asserted. ```d import std.uuid; try auto id = UUID("this-is-invalid"); catch (UUIDParsingException e) { assert(e.reason == UUIDParsingException.Reason.tooLittle); assert(e.position == 0); } ``` -------------------------------- ### emailLength function signature Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.uri.md Scans an RFC 2822-ish email address at the start of s and returns its length, or -1 if not found. ```d ptrdiff_t emailLength(Char)(scope const(Char)[] s) if (isSomeChar!Char) ``` -------------------------------- ### defaultGetoptPrinter Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.getopt.md Writes aligned help information to stdout. It takes a program description and an array of Option structs, formatting them in a readable column layout. ```APIDOC ## defaultGetoptPrinter ### Description Writes aligned help information to stdout. It takes a program description and an array of Option structs, formatting them in a readable column layout. ### Function Signature ```d void defaultGetoptPrinter(string text, Option[] opt) @safe ``` ### Parameters - **text** (string) - Required - The program description or help text to display. - **opt** (Option[]) - Required - An array of Option structs representing the command-line options to display. ### Behavior Prints the help text and option details to stdout in an aligned format. ``` -------------------------------- ### ZipArchive.isZip64() Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zip.md Gets or sets whether the archive uses ZIP64 records. ZIP64 is used for large archives. ```APIDOC ## ZipArchive.isZip64() ### Description Reads or writes whether the archive uses ZIP64 records. ZIP64 is required for archives exceeding certain size limits. ### Method Property ### Signature `bool isZip64()` ### Parameters None. ### Returns - **bool** - True if ZIP64 is enabled, false otherwise. ``` -------------------------------- ### Inflate lookup table example: code, first table, sub-tables X and Y Source: https://github.com/dlang/phobos/blob/master/etc/c/zlib/doc/algorithm.txt Illustrates the inflate lookup table construction with a scaled-down example: a 10-symbol code (1 to 6 bits) is decoded using a three-bit first table, plus two sub-tables (X and Y) for longer symbols. The tables show entries as 'bits: symbol, bits-to-gobble' or a pointer to another table. ```text A: 0 B: 10 C: 1100 D: 11010 E: 11011 F: 11100 G: 11101 H: 11110 I: 111110 J: 111111 ``` ```text 000: A,1 001: A,1 010: A,1 011: A,1 100: B,2 101: B,2 110: -> table X (gobble 3 bits) 111: -> table Y (gobble 3 bits) ``` ```text 00: C,1 01: C,1 10: D,2 11: E,2 ``` ```text 000: F,2 001: F,2 010: G,2 011: G,2 100: H,2 101: H,2 110: I,3 111: J,3 ``` -------------------------------- ### UnCompress constructor (destbufsize) Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.zlib.md Creates an UnCompress instance with an initial output buffer size hint. ```APIDOC ## UnCompress constructor (destbufsize) ### Description Creates an UnCompress instance with an initial output buffer size hint. ### Signature `this(uint destbufsize)` ### Parameters - **destbufsize** (uint) - Required - Initial output buffer size hint. ### Usage ```d UnCompress decmp = new UnCompress(4096); ``` ``` -------------------------------- ### DList and SList basic usage Source: https://github.com/dlang/phobos/blob/master/_autodocs/api-reference/std.container.dlist-and-slist.md Shows construction, insertion, removal, and property assertion for both DList and SList. DList provides O(1) push/pop at both ends; SList allows cheap front insertion and O(1) removeAny. The example uses `std.algorithm.comparison.equal` and `import std.container`. ```d import std.algorithm.comparison : equal; import std.container; // DList: O(1) push/pop at both ends DList!int dl = DList!int(1, 2, 3); dl.insertFront(0); dl.insertBack(4); assert(dl[].equal([0, 1, 2, 3, 4])); dl.removeFront(); dl.removeBack(); assert(dl.front == 1 && dl.back == 3); // Remove a specific value dl.insertBack(2); assert(dl.linearRemoveElement(2)); assert(dl[].equal([1, 3])); // SList: front insertion is cheap, removeAny is O(1) SList!string sl = SList!string("b", "c"); sl.insertFront("a"); assert(sl[].equal(["a", "b", "c"])); sl.reverse(); assert(sl.front == "c"); auto x = sl.removeAny(); ```