# UUIDv7 generation

MoonUUID implements RFC 9562 UUID version 7 with deterministic construction,
injectable providers and an optional monotonic generator.

## Layout

UUIDv7 stores a Unix Epoch timestamp in milliseconds in the most significant
48 bits. The remaining layout is:

```text
48 bits  unix_ts_ms
4 bits   version = 0111
12 bits  rand_a
2 bits   variant = 10
62 bits  rand_b
```

RFC 9562 Appendix A uses:

```text
unix_ts_ms = 0x017F22E279B0
rand_a     = 0xCC3
rand_b     = 0x18C4DC0C0C07398F

017f22e2-79b0-7cc3-98c4-dc0c0c07398f
```

MoonUUID keeps that vector as a conformance test.

## API layers

### Deterministic fields

```moonbit
let id = @moonuuid.v7_from_parts(
  1645557742000UL,
  0xCC3UL,
  0x18C4DC0C0C07398FUL,
)
```

This is the most explicit API and validates the 48/12/62-bit field widths.

### Timestamp plus entropy

`v7_from_entropy(unix_ms, entropy)` consumes exactly 10 bytes and maps them
into rand_a/rand_b while masking reserved version and variant positions.

### Injected providers

```moonbit
let id = @moonuuid.v7_with(clock, entropy)
```

The clock has type `() -> UInt64` and returns Unix milliseconds. The entropy
provider has type `(Int) -> Bytes?` and is requested for exactly 10 bytes.

### Platform convenience API

`v7()` uses `@env.now` and `@env.rand`. It never substitutes weak randomness
when secure platform entropy is unavailable.

## Monotonic generation

```moonbit
let generator = @moonuuid.V7Generator::new()
match generator.next() {
  Ok(id) => println(@moonuuid.to_string(id))
  Err(_) => println("UUIDv7 unavailable")
}
```

The stateful generator follows RFC 9562 section 6.2 guidance:

1. when the clock advances, seed new rand_a/rand_b values;
2. within the same millisecond, increment the random payload;
3. if the clock moves backwards, reuse the last timestamp and increment the
   previous payload so the next UUID still sorts after the previous UUID;
4. if all 74 random/counter bits are exhausted before time advances, return
   `MonotonicOverflow` rather than knowingly emitting a duplicate or
   non-monotonic identifier.

The implementation increments rand_b first and carries into rand_a only on
rand_b rollover.

## Ordering

Because the 48-bit timestamp occupies the most significant portion of the UUID,
UUIDv7 values are naturally time sortable. `V7Generator` additionally provides
strict generation-order monotonicity for repeated calls on one generator
instance.
