# Overview

> @dirtytalk/ranges tracks changes as exact, disjoint, half-open intervals — byte ranges, row spans, time windows — on top of @dirtytalk/engine.

Source: https://dirtytalk.42.dog/docs/ranges/

`@dirtytalk/ranges` is interval-based dirty tracking built on [`@dirtytalk/engine`](/docs/engine/). A dirty region is an `IntervalSet`, a canonical set of disjoint half-open intervals `[start, end)`. Producers mark the spans they changed; each subscriber watches its own spans and is notified only when they overlap a change.

## When to use it

Use it when "what changed" is a set of positions on one axis and the gaps between changes matter:

- **GPU and buffer uploads.** Re-upload only the changed byte ranges of a vertex, instance or uniform buffer (`writeBuffer`, `bufferSubData`), or the changed rows of a texture.
- **Rows and lines.** Re-render only the rows of a virtualized list, table or log view that changed and are visible.
- **Timelines.** Re-render waveforms, thumbnails or baked animation only for the edited time windows.
- **Storage and sync.** Write back dirty chunks of a large `ArrayBuffer`, WASM memory or file; send only changed ranges; re-hash only touched chunks.

For 2-D damage use [`@dirtytalk/spatial`](/docs/spatial/). For named paths in state use [`@dirtytalk/structural`](/docs/structural/).

## Why exact spans, not a bounding range

Two edits at the ends of a 10 MB buffer, bytes `[0, 4)` and `[9999996, 10000000)`, should mean two small uploads, not one 10 MB upload. A bounding-range region (the "numeric range" example in [Custom spaces](/docs/engine/custom-spaces/#example-numeric-range-space)) turns them into `[0, 10000000)`, uploads everything and wakes every subscriber whose spans lie in the gap. `IntervalSet` keeps them as two spans, so the work scales with what changed, not with the distance between changes.

## Install

```sh
pnpm add @dirtytalk/ranges @dirtytalk/engine
```

`@dirtytalk/engine` is a runtime dependency.

## Minimal example

A buffer marks the byte ranges it wrote; an uploader subscribes to the range it keeps on the GPU.

```ts
import { IntervalSet, IntervalSpace } from '@dirtytalk/ranges';
import { DirtyChannel, MicrotaskScheduler } from '@dirtytalk/engine';

const channel = new DirtyChannel(IntervalSpace, new MicrotaskScheduler());

channel.subscribe(
  () => IntervalSet.from([{ start: 0, end: 1024 }]), // resident on the GPU
  (dirty) => upload(dirty.spans()),
);

channel.mark(IntervalSet.from([{ start: 100, end: 104 }]));
channel.mark(IntervalSet.from([{ start: 900, end: 904 }]));
// flush: upload([{ start: 100, end: 104 }, { start: 900, end: 904 }])
```

Marks in one flush window union exactly: the two edits stay two spans, and an edit that overlaps or touches an earlier span merges into it. A subscriber watching `[200, 800)` would not be called.

The callback receives every changed span, not only the part inside its interest. Clip to your own range if you need to.

## Half-open and canonical

- Spans are half-open `[start, end)`: a span contains `start` and everything up to, but not including, `end`.
- `IntervalSet.from` canonicalizes its input: spans are sorted by `start`, empty spans (`start === end`) are dropped, and overlapping **or touching** spans merge, so `[1, 2)` + `[2, 3)` becomes `[1, 3)`.
- `intersects` uses half-open overlap: `[1, 2)` and `[2, 3)` touch but do **not** intersect.
- The representation is exact: `[0, 4)` and `[90, 94)` stay two spans.
- Coordinates are plain numbers and may be negative or fractional. Units, integer-ness and alignment are the consumer's policy.

## Turning spans into work

`IntervalSet` reports exactly what changed. Deciding how to do the work is up to the consumer. Two common policies:

- **Alignment.** APIs often require aligned offsets and sizes, for example `GPUQueue.writeBuffer` needs multiples of 4 bytes.
- **Gap bridging.** Many tiny spans can cost more in per-call overhead than one slightly larger upload. Merge spans separated by less than a threshold.

```ts
import type { Interval } from '@dirtytalk/ranges';

function uploadRanges(
  spans: readonly Interval[],
  align: number,
  maxGap: number,
): Interval[] {
  const out: { start: number; end: number }[] = [];
  for (const span of spans) {
    const start = Math.floor(span.start / align) * align;
    const end = Math.ceil(span.end / align) * align;
    const last = out[out.length - 1];
    if (last !== undefined && start - last.end <= maxGap) {
      last.end = Math.max(last.end, end);
    } else {
      out.push({ start, end });
    }
  }
  return out;
}
```

Spans from `spans()` are sorted, so one pass is enough. Clamp the last `end` to the buffer size if alignment can round past it. If the work fails, mark the spans again so the next flush retries them; the channel has no acknowledgement step.

## Performance

| Operation                   | Cost                                     |
| --------------------------- | ---------------------------------------- |
| `IntervalSet.from`          | O(n log n); the sort dominates           |
| `union`                     | O(n + m) two-pointer merge               |
| `intersects`                | O(n + m) two-pointer scan, no allocation |
| N marks in one flush window | O(N log N) total                         |

`IntervalSpace` implements `unionInto`. During a burst the channel appends each mark to an accumulator it owns and merges once, when the set is first read. 10,000 single-span marks plus a flush take about 0.25 ms on a developer laptop; without `unionInto` the same burst took 1.85 s.

Microbenchmarks are in `packages/ranges/src/interval-set.bench.ts`; run them with `vp test bench`. Every operation stays well under a millisecond at 10,000 spans. Fragmented sets with many thousands of spans cost proportionally more per subscriber, so bridge gaps on the producer side if a set grows that large.

## What it is not

- **Not an edit history.** Inserts and deletes shift positions; a set has no memory of where its spans came from. A producer that inserts must mark the shifted tail itself or map coordinates on its own.
- **Not a work planner.** It does not align, bridge gaps or cap the number of spans. See [Turning spans into work](#turning-spans-into-work).
- **Not a full interval algebra.** It has union and intersection tests only: no subtraction, clipping or containment.
- **Not a spatial index.** `union` and `intersects` scan sorted spans; there is no interval tree.

## Next steps

- [API reference](/docs/ranges/api/): `Interval`, `IntervalSet` and `IntervalSpace` signatures.
- [Custom spaces](/docs/engine/custom-spaces/#example-disjoint-interval-set): the `Space` contract, with the bounding-range contrast.
- [Concepts](/docs/concepts/): the mark-coalesce-flush model this package instantiates.
