probe.dhover×369 errorall
#!/usr/bin/env dub
/+ dub.sdl:
    name "sparkles_large_view_probe"
    dependency "sparkles:ui" path="../../../../../.."
    dflags "-preview=in" "-preview=dip1000"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
// Per-frame CPU cost of a large tree in sparkles:ui: flatten, build (treeView),
// layout, display list — all rows versus the explorer's window of rows.
// Probe for docs/research/ui-virtualization/immediate-mode-large-views.md.
// Usage: dub run --single probe.d -b checked --compiler=ldc2 -- <scenario> <N> [frames]
import 
(package) core
core
.
(module) core.time

Module containing core time functionality, such as Duration (which represents a duration of time) or MonoTime (which represents a timestamp of the system's monotonic clock).

Various functions take a string (or strings) to represent a unit of time (e.g. convert!("days", "hours")(numDays)). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There are a few functions that also allow "nsecs", but very little actually has precision greater than hnsecs.

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

minutes&nbsp;seconds&nbsp;msecs

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

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

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

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

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

Source

core/time.d

@copyrightCopyright 2010 - 2012@licenseBoost License 1.0.@authorsJonathan M Davis and Kato Shoichi
time
:
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
;
import
(package) std
std
.
(module) std.algorithm

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

Algorithms are categorized into the following submodules:

Submodule Functions

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

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

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

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

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

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

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

Example

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

Source

std/algorithm/package.d

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

Iterates the passed arguments and returns the minimum value.

@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
,
(alias template) probe.max = std.algorithm.comparison.max(T...)(T args) if (T.length >= 2 && !is(CommonType!T == void))

Iterates the passed arguments and returns the maximum value.

@paramargs The values to select the maximum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe maximum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the largest value. If at least one of the arguments is NaN, the result is an unspecified value. See maxElement for examples on how to cope with NaNs.@seemaxElement
max
,
(alias template) probe.sort = std.algorithm.sorting.sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)

Sorts a random-access range according to the predicate less.

Performs O(r.length * log(r.length)) evaluations of less. If less involves expensive computations on the sort key, it may be worthwhile to use schwartzSort instead.

Stable sorting requires hasAssignableElements!Range to be true.

sort returns a SortedRange over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The SortedRange is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they can know that SortedRange has been sorted.

Preconditions

The predicate is expected to satisfy certain rules in order for sort to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory assumeSorted check. Specifically, sort expects less(a,b) && less(b,c) to imply less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to imply !less(a,c). Note that the default predicate ("a < b") does not always satisfy these conditions for floating point types, because the expression will always be false when either a or b is NaN. Use cmp instead.

Algorithms

Introsort is used for unstable sorting and Timsort is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have O(n log n) worst-case time complexity.

@paramless The predicate to sort by.@paramss The swapping strategy to use.@paramr The range to sort.@returnsThe initial range wrapped as a SortedRange with the predicate binaryFun!less.@see

assumeSorted

SortedRange

SwapStrategy

binaryFun

sort
;
import
(package) std
std
.
(module) std.conv

A one-stop shop for converting values from one type to another.

Category Functions
Generic asOriginalType castFrom parse to toChars bitCast
Strings text wtext dtext writeText writeWText writeDText hexString
Numeric octal roundTo signed unsigned
Exceptions ConvException ConvOverflowException

Source

std/conv.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) probe.to = std.conv.to(T)

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

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

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

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

to
,
(alias template) probe.text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into text (the three character widths).

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

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

There are three layers of I/O:

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

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

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

Source

std/stdio.d

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

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

writefln
, stderr;
import
(package) sparkles
sparkles
.
(package) sparkles.base
base
.
(module) sparkles.base.term_color

Terminal color foundation: the Color type, capability tiers, depth folding, and SGR color-parameter emission.

This is the single home for how sparkles models a terminal color and turns it into SGR bytes.

Color is a four-case value (unset, default_, palette, rgb) covering everything a theme or style expresses; unset (Color.init) is "not specified", default_ is "the terminal's own default". It is the shared type consumed by sparkles.base.styled_template, sparkles.syntax (re-exported as sparkles.syntax.color.Color), and any future cell-grid backend.

ColorDepth + classifyColorDepth name the capability tiers and their pure, CTFE-able classifier; detectColorDepth is the thin environment-reading edge for standalone use. ansi256FromRgb, ansi16FromRgb, and xterm256ToRgb are the depth fold — themes author in 24-bit RGB and terminals that speak only 256 or 16 colors get the nearest approximation.

writeSgrColor emits the SGR parameters selecting a color on a ColorChannel (foreground/background/underline), depth-folded. The escape ESC[/m wrapper and the transition diff live in sparkles.base.term_style.writeStyleTransition.

#RRGGBBAA hex parsing (parseHexColor) understands bat's alpha convention (alpha 0 ⇒ palette index, alpha 1 ⇒ terminal default) at the boundary, turning the encoding trick into structure.

term_color
:
(struct) sparkles.base.term_color.RgbColor

A 24-bit RGB color value.

RgbColor
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.cmd_buffer

The command buffer: a frame's DrawOp stream plus the storage those operations point into.

An operation is 64 bytes because its two bulky parts — the text of a run, the chrome of a decorated box — live somewhere else. This is that somewhere, paired with the operations so the two cannot be separated by accident:

An operation is valid while the buffer that built it is alive and unreset.

That is the ownership policy UI-O4 asks for, and stating it as a type is the point. A retained consumer keeps the buffer, not a slice of one; a frame loop calls CmdBufferT.reset and reuses both halves, allocating nothing in the steady state.

Two arenas, one emitter. The buffer is generic over isArena, so the same emitting code serves both paths:

  • CmdBuffer — FrameArena-backed. @nogc, reset per frame.

  • GcCmdBuffer — collector-backed. Its operations outlive it, so buildDisplayList can keep handing back a plain DrawOp[] that needs no lifetime rule at all.

cmd_buffer
:
(struct) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU)
CmdBuffer
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(package) sparkles.ui.components
components
.
(module) sparkles.ui.components.tree_widget

The tree component (WGT12, VMD1–VMD6) — the exemplar of the view-model/view split, built to the tree-view case study's three-layer design:

data (TreeData) — a flat node arena with parent/child/sibling index links. No interaction state, no decoration: an independent structural snapshot needs one explicit arena duplication. The current D slice aliases under default copy (UI-O1), and T supplies its own copy contract. interaction — an opened set (DisclosureState), a selection, a scroll offset — lives beside the data, keyed by identity, so one tree can back several independent views. view (treeView) — a pure function from both to a widget subtree; owns glyphs and slots only.

flatten — hierarchy to the visible rows — is a pure free function with no lazy loading and no filtering mixed in (the case study names mixing them as the failure mode), and it precomputes the four-state guide model (space / continue / fork / end) per depth level, so no renderer re-derives rails per frame.

tree_widget
:
(alias template) probe.flatten = sparkles.ui.components.tree_widget.flatten(T)(in TreeData!T data, scope bool delegate(uint) @safe isOpen)

The flatten step (VMD3): hierarchy → the visible rows, honoring isOpen (closed nodes keep their subtree out). Pure and free — no lazy loading, no filtering — and the guides are computed here, once, from a per-depth "has later siblings" accumulator (broot's precomputed rails).

flatten
,
(struct) sparkles.ui.components.tree_widget.FlatTreeRow

One visible row of a flattened tree: the node, its depth, and the guide column per depth level (guides.length == depth + 1; the last entry is the row's own fork/end).

FlatTreeRow
,
(alias struct) probe.TreeData = sparkles.ui.components.tree_widget.TreeData(T)

The data layer (VMD1): a flat arena of T values with index links. add appends under a parent (or as a root), maintaining sibling chains; there is no remove — rebuild instead (flat storage is what makes per-keystroke rebuilding viable, per the case study's tree-as-search-result mode).

TreeData
,
(struct) sparkles.ui.components.tree_widget.TreeGlyphs

The tree's charset: the guides are the theme's data (GLY1, from GlyphSet.guides), the disclosure markers the caller's. All guide cells are three columns wide, with one space between the connector and the row's content. An adapter whose icons already express disclosure (the explorer's open/closed folder) passes empty marker strings.

TreeGlyphs
,
(alias template) probe.treeView = sparkles.ui.components.tree_widget.treeView(T)(ref Builder b, in TreeData!T data, in FlatTreeRow[] rows, scope bool delegate(uint) @safe isOpen, uint selected = (uint).max, TreeGlyphs glyphs = TreeGlyphs.init, RgbColor selectionBg = RgbColor.init, bool hasSelectionBg = false, HitBlock hits = HitBlock.init)
treeView
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(package) sparkles.ui.components
components
.
(module) sparkles.ui.components.tree_view

The interactive tree view (TRV1–TRV7) — the interaction half of the tree component, completing the three-layer split whose data and view halves live in sparkles.ui.components.tree_widget:

data — TreeData, the flat arena. Owned by the adapter, rebuilt at will. interaction (TreeViewState) — the opened set, the cursor, the viewport and both scrollbars, and the live filter's editor: every piece of state a tree pane keeps between frames, as one value. view — treeView over the viewSlice window this state selects.

Before this module the interaction layer existed three times — hue's explorer pane, hue's GUI re-implementation of the same pane, and the gallery's tree page each carried their own copy of "move through the visible rows", "left closes, then climbs", and the scrollbar-grab-owns-the-pointer pointer arms. The behaviors here are those, stated once:

The cursor moves by visible row, never by arena index — pressing down inside a closed folder cannot land on a node nobody can see. TreeViewState.clamp couples the cursor and the viewport: the cursor stays in view, and the view never shows dead space below the last row. collapseOrUp is the universal two-step Left: close an open node, else climb to its parent's row. A press on a scrollbar is a grab, never a row click, and the grab owns the pointer until release wherever the drag strays (STM9's inverse mapping, same as the viewer's). The live filter is an editor field (EditorField, editor EDU4); every edit asks the adapter to rebuild, because in broot's tree-as-search-result mode the tree is a function of the query.

What is deliberately not here: the node model and its rebuild policy (lazy children, filtering predicates, git decoration — the adapter's), and painting (a host slices with viewSlice and paints through its own canvas). Mutations that invalidate the visible rows return TreeStep`.rebuild` rather than calling anything: the adapter owns rebuilding, the state only reports that it is needed.

tree_view
:
(alias template) probe.measureContent = sparkles.ui.components.tree_view.measureContent(Key, T)(ref TreeViewState!Key s, in TreeData!T data)

Recomputes the widest visible row in cells (contentCols) from the same node capabilities the renderer reads: per-depth guide cells (3), the marker column (3), the label, and a badge's two cells when one is present.

measureContent
,
(alias struct) probe.TreeViewState = sparkles.ui.components.tree_view.TreeViewState(Key)

The tree pane's interaction state (VMD2 + the viewport): one value a host embeds, keyed by the adapter's node identity Key (a path for a filesystem tree, a node index for an in-memory one) so the opened set survives rebuilds.

sel/top index the visible rows, not the arena. rows is the cached result of the adapter's last flatten — derived data stored here so every motion and clamp can see how many rows exist without a callback.

TreeViewState
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.display_list

The display-list stage of sparkles.ui: buildDisplayList walks a laid-out WidgetTree and emits a flat DrawOp stream, resolving each node's Slot to a concrete Visual against the palette and page colors. This is the last backend-neutral, GL-free stage — the boundary a painter (sparkles.ui.interp.immediate) or an SSG/ANSI backend consumes without ever touching a widget or a palette again.

display_list
:
(alias template) probe.buildDisplayListInto = sparkles.ui.display_list.buildDisplayListInto(Sink, TM = CellMeasure)(in WidgetTree tree, in Frame[] frames, in Palette pal, in RgbColor pageFg, in RgbColor pageBg, ref Sink ops, TM tm = TM.init) if (__traits(compiles, (ref Sink s) { s.fillRect(Rect.init); s.textRun(Rect.init, "x"); s.pushClip(Rect.init); s.popClip(); } ))

Builds the display list into a caller-supplied sink — the @nogc path (NFR2).

Sink is anything that accepts ~= DrawOp, so a SharedBuffer the caller reuses across frames works, and a plain DrawOp[] still works. Attributes are inferred from the sink: with a SharedBuffer this whole path is @nogc, which a function returning an array can never be.

The operations live in ops. The sink owns them; each textRun copies its UTF-8 into the op, so the widget tree need not outlive the list for text content. A caller that stores a display list past the scope that built it therefore stores the sink, not a slice of it. This is the ownership question UI-O4 records.

buildDisplayListInto
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.geometry

Abstract geometry for sparkles.ui: points, sizes, rectangles, and insets measured in abstract cells — the monospace column/row grid every backend shares. An interpreter scales cells to pixels (GUI), keeps them 1:1 (TUI cell grid), or maps them to ch/em (HTML). Nothing here knows about a specific backend.

Also the sizing vocabulary (SizeSpec: fit / grow / fixed / percent with min/max) the layout pass (sparkles.ui.layout) resolves. Text cell widths and whole-grapheme fitting belong to sparkles.base.text.grapheme's visibleWidth and fitCells, using the shared terminalKitty profile.

The 2-D types specialize sparkles.math.vector's numeric Vector, the same way TermSize/TermPosition do for the terminal — one vector implementation and one field vocabulary across the stack.

geometry
:
(struct) sparkles.ui.geometry.Constraints

The available space a layout pass fills — the extent (in cells) a widget may grow into. int.max on an axis means unbounded (shrink-to-fit).

Constraints
,
(struct) sparkles.ui.geometry.SizeSpec

How a widget claims space along one axis (the sizing vocabulary the layout pass resolves). fit = shrink to content; grow = take remaining space (weight n); fixed = exactly n cells; percent = n% of the parent.

SizeSpec
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.layout

The layout level (LAY) of sparkles.ui: layout turns a WidgetTree into a Frame per node — an absolute Rect on the cell grid — in four O(n) passes, all @safe pure:

natural width, bottom-up — each node's intrinsic extent with no bound, width allocation, top-down — the parent's content width resolves grow/percent, distributes leftover space and reclaims overflow, height for width, bottom-up — heights measured against the width each node was actually allocated (where wrapping text reports its line count), and height allocation + place, top-down — column distributes heights the way row distributed widths, and every node gets its absolute origin.

Splitting each axis into a measure and an allocation is GTK's measure(orientation, for_size) protocol: the width↔height cycle ("wrapping needs a width; the width comes from layout") is broken by ordering, not iteration. Every extent is an integer cell; leftover space is distributed with divmod plus explicit remainder assignment so the parts always sum exactly to the whole (see docs/specs/ui/layout.md, LAY4/LAY6).

Text uses the owned terminalKitty cell profile and retained rich cell plans. Styled interface faces supply target widths and line heights without changing the owned Unicode segmentation, source ledgers or terminal cell advances.

layout
:
(alias template) probe.layout = sparkles.ui.layout.layout(TM = CellMeasure)(in WidgetTree tree, in Constraints c = Constraints.init, TM tm = TM.init) if (isTextMeasure!TM)

Lays tree out within c, returning a Frame per node. An unbounded axis (int.max, the default) sizes the root to its content; a bounded one is the viewport the root resolves against (fit clamps, grow fills, percent takes its share). tm supplies backend styled text and image metrics.

layout
,
(struct) sparkles.ui.layout.LayoutStore

Storage layout reuses from one call to the next: its per-node scratch and the frames it returns. A model that lays its tree out on every relayout keeps one, so the frames are allocated once, not once per width.

The frames a call returns are overwritten by the next call on the same store.

LayoutStore
,
(struct) sparkles.ui.layout.CellMeasure

Default cell-profile measurement. Backend cell-to-pixel metrics do not override the owned terminalKitty text advance.

CellMeasure
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.style

The style layer for sparkles.ui — the single source of truth the three twoslash backends (CSS, raylib GUI, ANSI) had triplicated.

A widget names a semantic Slot (error, warn, surface, …), never a concrete color. A Palette maps every slot to a foreground/background Color plus per-channel alpha and a handful of scalar chrome knobs (popup radius/padding, detach gap, chrome glyphs). defaultTwoslashPalette authors the canonical twoslash hexes once.

Three generators consume a palette:

resolveSlot → a concrete Visual (RGB + alpha) for the GUI and the display list, deferring "inherit" to the page fg/bg; writeTwoslashVars → the CSS :root { --twoslash-* } block, kept in lockstep with views/twoslash.css by a unittest; writeSlotSgr → the SGR parameters for the terminal renderer.

style
:
(alias) probe.defaultTwoslashPalette = sparkles.ui.style.Palette sparkles.ui.style.defaultTwoslashPalette(sparkles.ui.style.ColorScheme scheme = ColorScheme.light) pure nothrow @nogc @safe

The canonical twoslash palette — the one place the twoslash hexes are authored. Mirrors libs/twoslash/src/sparkles/twoslash/views/twoslash.css (:root + its dark @media overrides), which a unittest checks byte-for-value via writeTwoslashVars. scheme selects the surface/docs pair.

defaultTwoslashPalette
,
(enum) sparkles.ui.style.Slot

A semantic style role. Widgets and display-list ops carry a Slot, and a Palette turns it into a concrete Visual. Roles are intentionally generic (an app palette can reuse them) even though the seed values come from twoslash.

Every member carries its design-system token path as @WireName data (TOK2): the one spelling wired resolves for JSON and the DTCG theme file, and from which sparkles.ui.tokens.writeCssName derives the CSS custom property. The semantic groups (text, status, surface, border, accent, link, selection, focus, shadow) and the component namespaces (chrome, gutter, scrollbar, completion, input, twoslash, diff, coverage) are the spec's tiers; inherit is the one single-segment path.

The semantic roles are TOK3's minimum set. A theme may leave any of them unset: defaultTwoslashPalette supplies the scheme default and a theme that pins its page colors derives them (Theme.effectivePalette), so every role is total for every theme.

Slot
;
import
(package) sparkles
sparkles
.
(package) sparkles.ui
ui
.
(module) sparkles.ui.widget

The widget level (WGT) of sparkles.ui: a Widget is currently a tagged record in a flat arena, each container referencing its children by an explicit index list — not a class hierarchy. WGT3 / UI-O2 replace the record with the required closed sum. The whole tree is one relocatable buffer (WidgetTree), cheap to diff and (later) SharedBuffer-back for @nogc.

A widget names a semantic Slot, never a concrete color, keeping presentation out of the tree (the palette resolves slots during sparkles.ui.display_list construction). Build a tree with Builder — add each child (getting its index back), then a container over the child-index list. An explicit list (rather than a contiguous [first, count) range) lets a container's siblings be containers in their own right, whose descendants interleave in the arena.

widget
:
(struct) sparkles.ui.widget.Builder

Accumulates Widgets into an arena. Add each child (keeping its index), then a container over the child-index list:

auto b = Builder();
const sig  = b.add(Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code));
const docs = b.add(Widget(kind: WidgetKind.text, text: "The title.",     slot: Slot.docs));
const panel = b.container(WidgetKind.popup, [sig, docs],
    slot: Slot.surface, padding: Insets.all(1));
auto tree = b.finish(panel);

Uses a GC array in U1 (matching gui_preview.d's PreviewLine[]); the node type is chosen so a later SharedBuffer!Widget swap is non-breaking.

Builder
,
(struct) sparkles.ui.widget.Widget

One node in the widget arena. All fields default, so DIP1030 named-argument construction reads declaratively:

Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code)

Containers (row/column/stack/panel/popup) address their children through the children index list; leaves leave it empty.

Widget
,
(enum) sparkles.ui.widget.WidgetKind

The kind of a Widget node.

WidgetKind
;
enum
(constant) int probe.FANOUT = 16
FANOUT
= 16;
enum
(constant) int probe.bodyRows = 48
bodyRows
= 48;
struct
(struct) probe.Item
Item
{
(alias) object.string = string
string
(field) string probe.Item.label
label
;
(alias) object.string = string
string
(field) string probe.Item.icon
icon
;
(alias) object.string = string
string
(field) string probe.Item.badge
badge
;
enum
(constant) bool probe.Item.badgeRight = true
badgeRight
= true;
} void
void D main(string[] args)
main
(
(alias) object.string = string
string
[]
(parameter) string[] args
args
)
{ const
(local variable) const(string) sc
sc
=
(parameter) string[] args
args
[1];
const
(local variable) const(uint) n
n
=
(parameter) string[] args
args
[2].
uint std.conv.to!uint.to!string(string __param_0) pure @safe

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

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

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

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

Examples

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

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

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

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

import std.exception : assertThrown;

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

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

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

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

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

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

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

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

import std.exception : assertThrown;

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

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

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

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

import std.string : split;

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

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

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

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

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

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

Stringize conversion from all types is supported.

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

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

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

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

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

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

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

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

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

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

  • All floating point types to all string types.

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

See formatValue on how toString should be defined.

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

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

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

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

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

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

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

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!uint;
const
(local variable) const(bool) isAll
isAll
=
(local variable) const(string) sc
sc
== "all" ||
(local variable) const(string) sc
sc
== "labels_all";
const
(local variable) const(int) frames
frames
=
(parameter) string[] args
args
.
(field) ulong string[].length
length
> 3 ?
(parameter) string[] args
args
[3].
int std.conv.to!int.to!string(string __param_0) pure @safe

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

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

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

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

Examples

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

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

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

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

import std.exception : assertThrown;

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

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

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

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

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

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

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

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

import std.exception : assertThrown;

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

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

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

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

import std.string : split;

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

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

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

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

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

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

Stringize conversion from all types is supported.

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

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

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

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

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

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

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

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

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

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

  • All floating point types to all string types.

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

See formatValue on how toString should be defined.

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

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

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

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

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

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

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

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!int :
(local variable) const(bool) isAll
isAll
?
int std.algorithm.comparison.max!(int, int)(int a, int b) pure nothrow @nogc @safe

Iterates the passed arguments and returns the maximum value.

Examples

int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
assert(d == 6);
auto e = min(a, b, c);
assert(is(typeof(e) == double));
assert(e == 2);
@paramargs The values to select the maximum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe maximum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the largest value. If at least one of the arguments is NaN, the result is an unspecified value. See maxElement for examples on how to cope with NaNs.@seemaxElement
max
(3,
int std.algorithm.comparison.min!(int, uint)(int __param_0, uint __param_1) pure nothrow @nogc @safe

Iterates the passed arguments and returns the minimum value.

@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
(100, 200_000 /
(local variable) const(uint) n
n
)) : 200;
(struct) sparkles.ui.components.tree_widget.TreeData!(probe.Item)

The data layer (VMD1): a flat arena of T values with index links. add appends under a parent (or as a root), maintaining sibling chains; there is no remove — rebuild instead (flat storage is what makes per-keystroke rebuilding viable, per the case study's tree-as-search-result mode).

TreeData
!
(struct) probe.Item
Item
(local variable) sparkles.ui.components.tree_widget.TreeData!(Item) data
data
;
foreach (
(local variable) uint i
i
; 0 ..
(local variable) const(uint) n
n
)
{ const
(local variable) const(bool) dir
dir
= cast(ulong)
(local variable) uint i
i
*
(constant) int probe.FANOUT = 16
FANOUT
+ 1 <
(local variable) const(uint) n
n
;
const
(local variable) const(uint) parent
parent
=
(local variable) uint i
i
== 0 ? uint.
(constant) uint uint.max = 4294967295u
max
: (
(local variable) uint i
i
- 1) /
(constant) int probe.FANOUT = 16
FANOUT
;
(local variable) sparkles.ui.components.tree_widget.TreeData!(Item) data
data
.
uint sparkles.ui.components.tree_widget.TreeData!(probe.Item).add(probe.Item value, uint parent = 4294967295u) pure nothrow @safe

Appends value under parent (uint.max = a new root); returns its index.

Constant time. Walking firstChild's chain to find the tail made filling one parent quadratic in its children — invisible on a source directory, and 45 ms of stall on a flat directory of 2662 entries, which is one whole frame budget spent on relinking a list the arena could have remembered the end of.

add
(
(struct) probe.Item
Item
(
(local variable) const(bool) dir
dir
?
string std.conv.text!(string, uint)(string __param_0, uint __param_1) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("dir_",
(local variable) uint i
i
) :
string std.conv.text!(string, uint, string)(string __param_0, uint __param_1, string __param_2) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("file_",
(local variable) uint i
i
, ".rs"),
(local variable) const(bool) dir
dir
? " " : " ",
(local variable) const(bool) dir
dir
? "(16 members, 4.0 KiB)" : "(regular, 1.2 KiB)"),
(local variable) const(uint) parent
parent
);
}
(alias) object.string = string
string
[]
(local variable) string[] labels
labels
= new
(alias) object.string = string
string
[
(local variable) const(uint) n
n
];
foreach (
(local variable) uint i
i
; 0 ..
(local variable) const(uint) n
n
)
(local variable) string[] labels
labels
[
(local variable) uint i
i
] =
string std.conv.text!(string, uint, string, const(uint), string)(string __param_0, uint __param_1, string __param_2, const(uint) __param_3, string __param_4) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("Row ",
(local variable) uint i
i
, " of ",
(local variable) const(uint) n
n
, ": some_file_name.rs");
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) t0
t0
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
auto
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
=
sparkles.ui.components.tree_widget.FlatTreeRow[] sparkles.ui.components.tree_widget.flatten!(probe.Item)(in sparkles.ui.components.tree_widget.TreeData!(Item) data, scope bool delegate(uint) @safe isOpen) @safe

The flatten step (VMD3): hierarchy → the visible rows, honoring isOpen (closed nodes keep their subtree out). Pure and free — no lazy loading, no filtering — and the guides are computed here, once, from a per-depth "has later siblings" accumulator (broot's precomputed rails).

flatten
(
(local variable) sparkles.ui.components.tree_widget.TreeData!(Item) data
data
, (uint) => true);
const
(local variable) const(long) flattenUs
flattenUs
= (
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"usecs";
if (
(local variable) const(string) sc
sc
== "reflatten")
{ // The explorer's `reflatten` minus `syncFolders`: flatten + measureContent, per disclosure change. double[]
(local variable) double[] tf
tf
,
(local variable) double[] tm
tm
;
TreeViewState!
(alias) object.string = string
string
(local variable) _error_ st
st
;
template instance `sparkles.ui.components.tree_view.TreeViewState!string` error instantiating
foreach (
(local variable) int f
f
; 0 ..
(local variable) const(int) frames
frames
)
{ auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) a
a
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
st.
st.rows
rows
= flatten(data, (uint) => true);
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) m
m
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
(template function) sparkles.ui.components.tree_view.measureContent(Key, T)(ref TreeViewState!Key s, in TreeData!T data)
measureContent
(st,
(local variable) sparkles.ui.components.tree_widget.TreeData!(Item) data
data
);
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) e
e
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
(local variable) double[] tf
tf
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) m
m
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
(local variable) double[] tm
tm
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) e
e
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
}
(local variable) double[] tf
tf
.
std.range.SortedRange!(double[], "a < b", SortedRangeOptions.assumeSorted) std.algorithm.sorting.sort!("a < b", SwapStrategy.unstable, double[])(double[] r) pure nothrow @nogc @safe

Sorts a random-access range according to the predicate less.

Performs O(r.length * log(r.length)) evaluations of less. If less involves expensive computations on the sort key, it may be worthwhile to use schwartzSort instead.

Stable sorting requires hasAssignableElements!Range to be true.

sort returns a SortedRange over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The SortedRange is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they can know that SortedRange has been sorted.

Preconditions

The predicate is expected to satisfy certain rules in order for sort to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory assumeSorted check. Specifically, sort expects less(a,b) && less(b,c) to imply less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to imply !less(a,c). Note that the default predicate ("a < b") does not always satisfy these conditions for floating point types, because the expression will always be false when either a or b is NaN. Use cmp instead.

Algorithms

Introsort is used for unstable sorting and Timsort is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have O(n log n) worst-case time complexity.

Examples

int[] array = [ 1, 2, 3, 4 ];

// sort in descending order
array.sort!("a > b");
assert(array == [ 4, 3, 2, 1 ]);

// sort in ascending order
array.sort();
assert(array == [ 1, 2, 3, 4 ]);

// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
assert(array.sort!(myComp).release == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];

import std.algorithm.comparison : equal;
import std.math.operations : cmp;
import std.math.traits : isIdentical;

sort!((a, b) => cmp(a, b) < 0)(numbers);

double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));
@paramless The predicate to sort by.@paramss The swapping strategy to use.@paramr The range to sort.@returnsThe initial range wrapped as a SortedRange with the predicate binaryFun!less.@see

assumeSorted

SortedRange

SwapStrategy

binaryFun

sort
();
(local variable) double[] tm
tm
.
std.range.SortedRange!(double[], "a < b", SortedRangeOptions.assumeSorted) std.algorithm.sorting.sort!("a < b", SwapStrategy.unstable, double[])(double[] r) pure nothrow @nogc @safe

Sorts a random-access range according to the predicate less.

Performs O(r.length * log(r.length)) evaluations of less. If less involves expensive computations on the sort key, it may be worthwhile to use schwartzSort instead.

Stable sorting requires hasAssignableElements!Range to be true.

sort returns a SortedRange over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The SortedRange is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they can know that SortedRange has been sorted.

Preconditions

The predicate is expected to satisfy certain rules in order for sort to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory assumeSorted check. Specifically, sort expects less(a,b) && less(b,c) to imply less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to imply !less(a,c). Note that the default predicate ("a < b") does not always satisfy these conditions for floating point types, because the expression will always be false when either a or b is NaN. Use cmp instead.

Algorithms

Introsort is used for unstable sorting and Timsort is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have O(n log n) worst-case time complexity.

Examples

int[] array = [ 1, 2, 3, 4 ];

// sort in descending order
array.sort!("a > b");
assert(array == [ 4, 3, 2, 1 ]);

// sort in ascending order
array.sort();
assert(array == [ 1, 2, 3, 4 ]);

// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
assert(array.sort!(myComp).release == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];

import std.algorithm.comparison : equal;
import std.math.operations : cmp;
import std.math.traits : isIdentical;

sort!((a, b) => cmp(a, b) < 0)(numbers);

double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));
@paramless The predicate to sort by.@paramss The swapping strategy to use.@paramr The range to sort.@returnsThe initial range wrapped as a SortedRange with the predicate binaryFun!less.@see

assumeSorted

SortedRange

SwapStrategy

binaryFun

sort
();
(template function) std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))
writefln
("reflatten\tN=%s\tframes=%s\tflatten_median_us=%.0f\tmeasureContent_median_us=%.0f\tcontentCols=%s",
(local variable) const(uint) n
n
,
(local variable) const(int) frames
frames
,
(local variable) double[] tf
tf
[$ / 2],
(local variable) double[] tm
tm
[$ / 2], st.contentCols);
return; } const
(local variable) const(sparkles.ui.style.Palette) pal
pal
=
sparkles.ui.style.Palette sparkles.ui.style.defaultTwoslashPalette(sparkles.ui.style.ColorScheme scheme = ColorScheme.light) pure nothrow @nogc @safe

The canonical twoslash palette — the one place the twoslash hexes are authored. Mirrors libs/twoslash/src/sparkles/twoslash/views/twoslash.css (:root + its dark @media overrides), which a unittest checks byte-for-value via writeTwoslashVars. scheme selects the surface/docs pair.

defaultTwoslashPalette
();
const
(local variable) const(sparkles.base.term_color.RgbColor) fg
fg
=
(struct) sparkles.base.term_color.RgbColor

A 24-bit RGB color value.

RgbColor
(255, 255, 255),
(local variable) const(sparkles.base.term_color.RgbColor) bg
bg
=
(struct) sparkles.base.term_color.RgbColor

A 24-bit RGB color value.

RgbColor
(0, 0, 0);
(struct) sparkles.ui.widget.Builder

Accumulates Widgets into an arena. Add each child (keeping its index), then a container over the child-index list:

auto b = Builder();
const sig  = b.add(Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code));
const docs = b.add(Widget(kind: WidgetKind.text, text: "The title.",     slot: Slot.docs));
const panel = b.container(WidgetKind.popup, [sig, docs],
    slot: Slot.surface, padding: Insets.all(1));
auto tree = b.finish(panel);

Uses a GC array in U1 (matching gui_preview.d's PreviewLine[]); the node type is chosen so a later SharedBuffer!Widget swap is non-breaking.

Builder
(local variable) sparkles.ui.widget.Builder b
b
;
(struct) sparkles.ui.layout.LayoutStore

Storage layout reuses from one call to the next: its per-node scratch and the frames it returns. A model that lays its tree out on every relayout keeps one, so the frames are allocated once, not once per width.

The frames a call returns are overwritten by the next call on the same store.

LayoutStore
(local variable) sparkles.ui.layout.LayoutStore store
store
;
(struct) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU)
CmdBuffer
(local variable) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU) ops
ops
;
double[]
(local variable) double[] tb
tb
,
(local variable) double[] tl
tl
,
(local variable) double[] td
td
,
(local variable) double[] tt
tt
;
(alias) object.size_t = ulong
size_t
(local variable) ulong nodes
nodes
,
(local variable) ulong nops
nops
;
foreach (
(local variable) int f
f
; 0 ..
(local variable) const(int) frames
frames
)
{
(alias) object.size_t = ulong
size_t
(local variable) ulong top
top
= 0;
if (
(local variable) const(string) sc
sc
== "window_scroll")
(local variable) ulong top
top
= (cast(
(alias) object.size_t = ulong
size_t
)
(local variable) int f
f
*
(constant) int probe.bodyRows = 48
bodyRows
) %
ulong std.algorithm.comparison.max!(int, ulong)(int __param_0, ulong __param_1) pure nothrow @nogc @safe

Iterates the passed arguments and returns the maximum value.

@paramargs The values to select the maximum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe maximum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the largest value. If at least one of the arguments is NaN, the result is an unspecified value. See maxElement for examples on how to cope with NaNs.@seemaxElement
max
(1,
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
.
(field) ulong sparkles.ui.components.tree_widget.FlatTreeRow[].length
length
-
(constant) int probe.bodyRows = 48
bodyRows
);
const
(local variable) const(ulong) last
last
=
(local variable) const(bool) isAll
isAll
?
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
.
(field) ulong sparkles.ui.components.tree_widget.FlatTreeRow[].length
length
:
ulong std.algorithm.comparison.min!(ulong, ulong)(ulong a, ulong b) pure nothrow @nogc @safe

Iterates the passed arguments and returns the minimum value.

Examples

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

With arguments of mixed signedness, the return type is the one that can store the lowest values.

int a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
assert(min(a, f) == -10);

User-defined types that support comparison with < are supported.

import std.datetime;
assert(min(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date.min) == Date.min);
assert(min(Date.min, Date(1982, 1, 4)) == Date.min);
assert(min(Date(1982, 1, 4), Date.max) == Date(1982, 1, 4));
assert(min(Date.max, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date.min, Date.max) == Date.min);
assert(min(Date.max, Date.min) == Date.min);
@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
(
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
.
(field) ulong sparkles.ui.components.tree_widget.FlatTreeRow[].length
length
,
(local variable) ulong top
top
+
(constant) int probe.bodyRows = 48
bodyRows
+ 1);
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s
s
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
(local variable) sparkles.ui.widget.Builder b
b
.
void sparkles.ui.widget.Builder.reset() @safe

Empties the arena while keeping its storage, so a builder held across frames asks the GC for nothing in the steady state.

A view that rebuilds every frame otherwise pays for its whole arena every frame: hue's DSV grid builds 3307 nodes for one 48-row window, and a Widget is 256 bytes, so a fresh Builder per frame is ~850 KB of garbage per scroll notch — enough, on its own, to run a collection every few frames and put a multi-millisecond pause inside a 4 ms budget.

The previously finished tree is invalidated. Its nodes alias this arena, and the next add overwrites them, so reset only once the last reader of the outgoing tree is done — a rebuild's first act, never its last.

reset
();
uint
(local variable) uint body_
body_
;
if (
(local variable) const(string) sc
sc
.
(field) ulong const(string).length
length
> 6 &&
(local variable) const(string) sc
sc
[0 .. 6] == "labels")
{ uint[]
(local variable) uint[] ids
ids
= new uint[](
(local variable) const(ulong) last
last
-
(local variable) ulong top
top
);
foreach (
(local variable) ulong i
i
;
(local variable) ulong top
top
..
(local variable) const(ulong) last
last
)
(local variable) uint[] ids
ids
[
(local variable) ulong i
i
-
(local variable) ulong top
top
] =
(local variable) sparkles.ui.widget.Builder b
b
.
uint sparkles.ui.widget.Builder.add(sparkles.ui.widget.Widget w) @safe

Appends w; returns its arena index.

add
(
(struct) sparkles.ui.widget.Widget

One node in the widget arena. All fields default, so DIP1030 named-argument construction reads declaratively:

Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code)

Containers (row/column/stack/panel/popup) address their children through the children index list; leaves leave it empty.

Widget
(kind:
(enum) sparkles.ui.widget.WidgetKind

The kind of a Widget node.

WidgetKind
.
(enum value) sparkles.ui.widget.WidgetKind.text = 1

a text run

text
, text:
(local variable) string[] labels
labels
[
(local variable) ulong i
i
]));
(local variable) uint body_
body_
=
(local variable) sparkles.ui.widget.Builder b
b
.
uint sparkles.ui.widget.Builder.container(sparkles.ui.widget.WidgetKind kind, uint[] children, sparkles.ui.style.Slot slot = Slot.inherit, sparkles.ui.geometry.Insets padding = Insets(Vector([0, 0, 0, 0])), int gap = 0, bool paintBackground = false, sparkles.ui.style.Decoration decoration = Decoration(Insets(Vector([0, 0, 0, 0])), BorderStyle.none, Slot.border, 0, false, false, 0, Side.top, 0, 0, 0, false, false, false, false)) @safe

Appends a container over the child nodes named by children.

container
(
(enum) sparkles.ui.widget.WidgetKind

The kind of a Widget node.

WidgetKind
.
(enum value) sparkles.ui.widget.WidgetKind.column = 9

vertical container (children top→bottom, gap between)

column
,
(local variable) uint[] ids
ids
);
} else
(local variable) uint body_
body_
=
uint sparkles.ui.components.tree_widget.treeView!(probe.Item)(ref sparkles.ui.widget.Builder b, in sparkles.ui.components.tree_widget.TreeData!(Item) data, in sparkles.ui.components.tree_widget.FlatTreeRow[] rows, scope bool delegate(uint) @safe isOpen, uint selected = 4294967295u, sparkles.ui.components.tree_widget.TreeGlyphs glyphs = TreeGlyphs(GuideGlyphs("\xe2\x94\x9c\xe2\x94\x80 ", "\xe2\x94\x94\xe2\x94\x80 ", "\xe2\x94\x82 ", " "), "\xe2\x96\xb8 ", "\xe2\x96\xbe ", ""), sparkles.base.term_color.RgbColor selectionBg = RgbColor(cast(ubyte)0u, cast(ubyte)0u, cast(ubyte)0u), bool hasSelectionBg = false, sparkles.ui.hit_ids.HitBlock hits = HitBlock(0LU, 0LU)) @safe
treeView
(
(local variable) sparkles.ui.widget.Builder b
b
,
(local variable) sparkles.ui.components.tree_widget.TreeData!(Item) data
data
,
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
[
(local variable) ulong top
top
..
(local variable) const(ulong) last
last
], (uint) => true, uint.
(constant) uint uint.max = 4294967295u
max
,
(struct) sparkles.ui.components.tree_widget.TreeGlyphs

The tree's charset: the guides are the theme's data (GLY1, from GlyphSet.guides), the disclosure markers the caller's. All guide cells are three columns wide, with one space between the connector and the row's content. An adapter whose icons already express disclosure (the explorer's open/closed folder) passes empty marker strings.

TreeGlyphs
(closed: "", open: "", leaf: ""));
auto
(local variable) sparkles.ui.widget.Widget vp
vp
=
(struct) sparkles.ui.widget.Widget

One node in the widget arena. All fields default, so DIP1030 named-argument construction reads declaratively:

Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code)

Containers (row/column/stack/panel/popup) address their children through the children index list; leaves leave it empty.

Widget
(kind:
(enum) sparkles.ui.widget.WidgetKind

The kind of a Widget node.

WidgetKind
.
(enum value) sparkles.ui.widget.WidgetKind.column = 9

vertical container (children top→bottom, gap between)

column
, children: [
(local variable) uint body_
body_
], clipY: true,
width:
(struct) sparkles.ui.geometry.SizeSpec

How a widget claims space along one axis (the sizing vocabulary the layout pass resolves). fit = shrink to content; grow = take remaining space (weight n); fixed = exactly n cells; percent = n% of the parent.

SizeSpec
.
sparkles.ui.geometry.SizeSpec sparkles.ui.geometry.SizeSpec.grow(int weight = 1) pure nothrow @nogc @safe

Fill remaining space with weight weight.

grow
(), height:
(struct) sparkles.ui.geometry.SizeSpec

How a widget claims space along one axis (the sizing vocabulary the layout pass resolves). fit = shrink to content; grow = take remaining space (weight n); fixed = exactly n cells; percent = n% of the parent.

SizeSpec
.
sparkles.ui.geometry.SizeSpec sparkles.ui.geometry.SizeSpec.fixed(int n) pure nothrow @nogc @safe

Exactly n cells.

fixed
(
(constant) int probe.bodyRows = 48
bodyRows
));
auto
(local variable) sparkles.ui.widget.WidgetTree tree
tree
=
(local variable) sparkles.ui.widget.Builder b
b
.
sparkles.ui.widget.WidgetTree sparkles.ui.widget.Builder.finish(uint root) @safe

Freezes the arena into a tree rooted at root.

finish
(
(local variable) sparkles.ui.widget.Builder b
b
.
uint sparkles.ui.widget.Builder.add(sparkles.ui.widget.Widget w) @safe

Appends w; returns its arena index.

add
(
(local variable) sparkles.ui.widget.Widget vp
vp
));
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s1
s1
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
auto
(local variable) sparkles.ui.layout.Frame[] frames_
frames_
=
sparkles.ui.layout.Frame[] sparkles.ui.layout.layout!(sparkles.ui.layout.CellMeasure)(in sparkles.ui.widget.WidgetTree tree, in sparkles.ui.geometry.Constraints c, sparkles.ui.layout.CellMeasure tm, ref sparkles.ui.layout.LayoutStore store) @safe

ditto, into store, reused across calls.

layout
(
(local variable) sparkles.ui.widget.WidgetTree tree
tree
,
(struct) sparkles.ui.geometry.Constraints

The available space a layout pass fills — the extent (in cells) a widget may grow into. int.max on an axis means unbounded (shrink-to-fit).

Constraints
(160,
(constant) int probe.bodyRows = 48
bodyRows
),
(struct) sparkles.ui.layout.CellMeasure

Default cell-profile measurement. Backend cell-to-pixel metrics do not override the owned terminalKitty text advance.

CellMeasure
.
(constant) sparkles.ui.layout.CellMeasure sparkles.ui.layout.CellMeasure.init = CellMeasure()
init
,
(local variable) sparkles.ui.layout.LayoutStore store
store
);
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s2
s2
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
(local variable) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU) ops
ops
.
void sparkles.ui.cmd_buffer.CmdBufferT!(sparkles.ui.arena.FrameArena!4096LU, 64LU).reset() pure nothrow @nogc @safe

Drops every operation and every byte they pointed at, keeping the capacity both halves have already paid for.

reset
();
void sparkles.ui.display_list.buildDisplayListInto!(sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU), sparkles.ui.layout.CellMeasure)(in sparkles.ui.widget.WidgetTree tree, in sparkles.ui.layout.Frame[] frames, in sparkles.ui.style.Palette pal, in sparkles.base.term_color.RgbColor pageFg, in sparkles.base.term_color.RgbColor pageBg, ref sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU) ops, sparkles.ui.layout.CellMeasure tm = CellMeasure()) pure nothrow @nogc @safe

Builds the display list into a caller-supplied sink — the @nogc path (NFR2).

Sink is anything that accepts ~= DrawOp, so a SharedBuffer the caller reuses across frames works, and a plain DrawOp[] still works. Attributes are inferred from the sink: with a SharedBuffer this whole path is @nogc, which a function returning an array can never be.

The operations live in ops. The sink owns them; each textRun copies its UTF-8 into the op, so the widget tree need not outlive the list for text content. A caller that stores a display list past the scope that built it therefore stores the sink, not a slice of it. This is the ownership question UI-O4 records.

buildDisplayListInto
(
(local variable) sparkles.ui.widget.WidgetTree tree
tree
,
(local variable) sparkles.ui.layout.Frame[] frames_
frames_
,
(local variable) const(sparkles.ui.style.Palette) pal
pal
,
(local variable) const(sparkles.base.term_color.RgbColor) fg
fg
,
(local variable) const(sparkles.base.term_color.RgbColor) bg
bg
,
(local variable) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU) ops
ops
);
auto
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s3
s3
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
;
(local variable) double[] tb
tb
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s1
s1
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
(local variable) double[] tl
tl
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s2
s2
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
(local variable) double[] td
td
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s3
s3
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
(local variable) double[] tt
tt
~= (
(local variable) core.time.MonoTimeImpl!(ClockType.normal) s3
s3
-
core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

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

Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.

The primary way that programs should time how long something takes is to do

MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;

or to use a wrapper (such as a stop watch type) which does that.

Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail

auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);

This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.

total
!"nsecs" / 1e3;
(local variable) ulong nodes
nodes
=
(local variable) sparkles.ui.widget.WidgetTree tree
tree
.
(field) sparkles.ui.widget.Widget[] sparkles.ui.widget.WidgetTree.nodes
nodes
.
(field) ulong sparkles.ui.widget.Widget[].length
length
;
(local variable) ulong nops
nops
=
(local variable) sparkles.ui.cmd_buffer.CmdBufferT!(FrameArena!4096LU, 64LU) ops
ops
.
ulong sparkles.ui.cmd_buffer.CmdBufferT!(sparkles.ui.arena.FrameArena!4096LU, 64LU).length() const pure nothrow @nogc @safe

How many operations the frame has emitted.

length
;
} double
double probe.main.pct(double[] v, double q) pure nothrow @safe
pct
(double[]
(parameter) double[] v
v
, double
(parameter) double q
q
) { auto
(local variable) double[] w
w
=
(parameter) double[] v
v
[
int std.algorithm.comparison.min!(int, ulong)(int __param_0, ulong __param_1) pure nothrow @nogc @safe

Iterates the passed arguments and returns the minimum value.

@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
(1, $ - 1) .. $].
double[] object.dup!double(const(double)[] a) pure nothrow @property @safe
dup
;
(local variable) double[] w
w
.
std.range.SortedRange!(double[], "a < b", SortedRangeOptions.assumeSorted) std.algorithm.sorting.sort!("a < b", SwapStrategy.unstable, double[])(double[] r) pure nothrow @nogc @safe

Sorts a random-access range according to the predicate less.

Performs O(r.length * log(r.length)) evaluations of less. If less involves expensive computations on the sort key, it may be worthwhile to use schwartzSort instead.

Stable sorting requires hasAssignableElements!Range to be true.

sort returns a SortedRange over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The SortedRange is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they can know that SortedRange has been sorted.

Preconditions

The predicate is expected to satisfy certain rules in order for sort to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory assumeSorted check. Specifically, sort expects less(a,b) && less(b,c) to imply less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to imply !less(a,c). Note that the default predicate ("a < b") does not always satisfy these conditions for floating point types, because the expression will always be false when either a or b is NaN. Use cmp instead.

Algorithms

Introsort is used for unstable sorting and Timsort is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have O(n log n) worst-case time complexity.

Examples

int[] array = [ 1, 2, 3, 4 ];

// sort in descending order
array.sort!("a > b");
assert(array == [ 4, 3, 2, 1 ]);

// sort in ascending order
array.sort();
assert(array == [ 1, 2, 3, 4 ]);

// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
assert(array.sort!(myComp).release == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];

import std.algorithm.comparison : equal;
import std.math.operations : cmp;
import std.math.traits : isIdentical;

sort!((a, b) => cmp(a, b) < 0)(numbers);

double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));
@paramless The predicate to sort by.@paramss The swapping strategy to use.@paramr The range to sort.@returnsThe initial range wrapped as a SortedRange with the predicate binaryFun!less.@see

assumeSorted

SortedRange

SwapStrategy

binaryFun

sort
(); return
(local variable) double[] w
w
[
ulong std.algorithm.comparison.min!(ulong, ulong)(ulong a, ulong b) pure nothrow @nogc @safe

Iterates the passed arguments and returns the minimum value.

Examples

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

With arguments of mixed signedness, the return type is the one that can store the lowest values.

int a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
assert(min(a, f) == -10);

User-defined types that support comparison with < are supported.

import std.datetime;
assert(min(Date(2012, 12, 21), Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(min(Date(1982, 1, 4), Date.min) == Date.min);
assert(min(Date.min, Date(1982, 1, 4)) == Date.min);
assert(min(Date(1982, 1, 4), Date.max) == Date(1982, 1, 4));
assert(min(Date.max, Date(1982, 1, 4)) == Date(1982, 1, 4));
assert(min(Date.min, Date.max) == Date.min);
assert(min(Date.max, Date.min) == Date.min);
@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
($ - 1, cast(
(alias) object.size_t = ulong
size_t
)(
(parameter) double q
q
* ($ - 1)))]; }
double
double probe.main.med(double[] v) pure nothrow @safe
med
(double[]
(parameter) double[] v
v
) { auto
(local variable) double[] w
w
=
(parameter) double[] v
v
[
int std.algorithm.comparison.min!(int, ulong)(int __param_0, ulong __param_1) pure nothrow @nogc @safe

Iterates the passed arguments and returns the minimum value.

@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
(1, $ - 1) .. $].
double[] object.dup!double(const(double)[] a) pure nothrow @property @safe
dup
;
(local variable) double[] w
w
.
std.range.SortedRange!(double[], "a < b", SortedRangeOptions.assumeSorted) std.algorithm.sorting.sort!("a < b", SwapStrategy.unstable, double[])(double[] r) pure nothrow @nogc @safe

Sorts a random-access range according to the predicate less.

Performs O(r.length * log(r.length)) evaluations of less. If less involves expensive computations on the sort key, it may be worthwhile to use schwartzSort instead.

Stable sorting requires hasAssignableElements!Range to be true.

sort returns a SortedRange over the original range, allowing functions that can take advantage of sorted data to know that the range is sorted and adjust accordingly. The SortedRange is a wrapper around the original range, so both it and the original range are sorted. Other functions can't know that the original range has been sorted, but they can know that SortedRange has been sorted.

Preconditions

The predicate is expected to satisfy certain rules in order for sort to behave as expected - otherwise, the program may fail on certain inputs (but not others) when not compiled in release mode, due to the cursory assumeSorted check. Specifically, sort expects less(a,b) && less(b,c) to imply less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to imply !less(a,c). Note that the default predicate ("a < b") does not always satisfy these conditions for floating point types, because the expression will always be false when either a or b is NaN. Use cmp instead.

Algorithms

Introsort is used for unstable sorting and Timsort is used for stable sorting. Each algorithm has benefits beyond stability. Introsort is generally faster but Timsort may achieve greater speeds on data with low entropy or if predicate calls are expensive. Introsort performs no allocations whereas Timsort will perform one or more allocations per call. Both algorithms have O(n log n) worst-case time complexity.

Examples

int[] array = [ 1, 2, 3, 4 ];

// sort in descending order
array.sort!("a > b");
assert(array == [ 4, 3, 2, 1 ]);

// sort in ascending order
array.sort();
assert(array == [ 1, 2, 3, 4 ]);

// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
assert(array.sort!(myComp).release == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];

import std.algorithm.comparison : equal;
import std.math.operations : cmp;
import std.math.traits : isIdentical;

sort!((a, b) => cmp(a, b) < 0)(numbers);

double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));
@paramless The predicate to sort by.@paramss The swapping strategy to use.@paramr The range to sort.@returnsThe initial range wrapped as a SortedRange with the predicate binaryFun!less.@see

assumeSorted

SortedRange

SwapStrategy

binaryFun

sort
(); return
(local variable) double[] w
w
[$ / 2]; }
void std.stdio.writefln!(char, string, const(uint), const(int), ulong, ulong, ulong, double, double, double, double, double, const(long), ulong, double, double)(in char[] fmt, string __param_1, const(uint) __param_2, const(int) __param_3, ulong __param_4, ulong __param_5, ulong __param_6, double __param_7, double __param_8, double __param_9, double __param_10, double __param_11, const(long) __param_12, ulong __param_13, double __param_14, double __param_15) @safe

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

writefln
("%s\tN=%s\tframes=%s\tflat_rows=%s\tnodes=%s\tops=%s\tfirst_us=%.0f\tmedian_us=%.1f\tbuild_us=%.1f\tlayout_us=%.1f\tdl_us=%.1f\tflatten_us=%s\twidget_bytes=%s\tp99_us=%.0f\tmax_us=%.0f",
(local variable) const(string) sc
sc
,
(local variable) const(uint) n
n
,
(local variable) const(int) frames
frames
,
(local variable) sparkles.ui.components.tree_widget.FlatTreeRow[] rows
rows
.
(field) ulong sparkles.ui.components.tree_widget.FlatTreeRow[].length
length
,
(local variable) ulong nodes
nodes
,
(local variable) ulong nops
nops
,
(local variable) double[] tt
tt
[0],
double probe.main.med(double[] v) pure nothrow @safe
med
(
(local variable) double[] tt
tt
),
double probe.main.med(double[] v) pure nothrow @safe
med
(
(local variable) double[] tb
tb
),
double probe.main.med(double[] v) pure nothrow @safe
med
(
(local variable) double[] tl
tl
),
double probe.main.med(double[] v) pure nothrow @safe
med
(
(local variable) double[] td
td
),
(local variable) const(long) flattenUs
flattenUs
,
(struct) sparkles.ui.widget.Widget

One node in the widget arena. All fields default, so DIP1030 named-argument construction reads declaratively:

Widget(kind: WidgetKind.text, text: "title: string", slot: Slot.code)

Containers (row/column/stack/panel/popup) address their children through the children index list; leaves leave it empty.

Widget
.
(constant) ulong sparkles.ui.widget.Widget.sizeof = 384LU
sizeof
,
double probe.main.pct(double[] v, double q) pure nothrow @safe
pct
(
(local variable) double[] tt
tt
, 0.99),
double probe.main.pct(double[] v, double q) pure nothrow @safe
pct
(
(local variable) double[] tt
tt
, 1.0));
}