@zio.dev/zio-blocks 0.0.32 → 0.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/guides/compile-time-resource-safety-with-scope.md +16 -17
- package/guides/getting-started-with-mux.md +1507 -0
- package/guides/query-dsl-extending.md +161 -102
- package/guides/query-dsl-fluent-builder.md +217 -157
- package/guides/query-dsl-reified-optics.md +12 -10
- package/guides/query-dsl-sql.md +246 -165
- package/guides/telemetry-guide.md +1069 -0
- package/guides/zio-schema-migration.md +29 -22
- package/index.md +293 -51
- package/package.json +1 -1
- package/plans/config-follow-up-prs.md +188 -0
- package/plans/config-pr-assessment-roadmap.md +310 -0
- package/reference/MuxDataFlow.jsx +250 -0
- package/reference/async.md +651 -0
- package/reference/chunk.md +3533 -308
- package/reference/codegen/case-class.md +436 -0
- package/reference/codegen/emitter-config.md +383 -0
- package/reference/codegen/examples.md +664 -0
- package/reference/codegen/field.md +316 -0
- package/reference/codegen/index.md +317 -0
- package/reference/codegen/scala-emitter.md +392 -0
- package/reference/codegen/scala-file.md +276 -0
- package/reference/codegen/sealed-trait.md +408 -0
- package/reference/codegen/type-definition.md +340 -0
- package/reference/codegen/type-ref.md +201 -0
- package/reference/combinators.md +347 -117
- package/reference/config.md +158 -0
- package/reference/context.md +4 -4
- package/reference/datastar.md +346 -0
- package/reference/docs.md +1461 -345
- package/reference/endpoint/auth-type.md +146 -0
- package/reference/endpoint/endpoint.md +297 -0
- package/reference/endpoint/http-codec.md +249 -0
- package/reference/endpoint/index.md +825 -0
- package/reference/endpoint/path-codec.md +237 -0
- package/reference/endpoint/route-pattern.md +196 -0
- package/reference/endpoint/route-tree.md +111 -0
- package/reference/endpoint/segment-codec.md +212 -0
- package/reference/html.md +1120 -0
- package/reference/htmx/attribute-values.md +359 -0
- package/reference/htmx/hx-encoding.md +111 -0
- package/reference/htmx/hx-params.md +204 -0
- package/reference/htmx/hx-swap.md +276 -0
- package/reference/htmx/hx-sync.md +251 -0
- package/reference/htmx/hx-target.md +314 -0
- package/reference/htmx/hx-trigger.md +457 -0
- package/reference/htmx/hx-url-update.md +239 -0
- package/reference/htmx/index.md +855 -0
- package/reference/http-model/index.md +47 -0
- package/reference/http-model/model.md +1481 -0
- package/reference/http-model/schema.md +747 -0
- package/reference/maybe.md +826 -0
- package/reference/media-type.md +2 -2
- package/reference/mux.mdx +823 -0
- package/reference/openapi.md +1351 -0
- package/reference/resource-management/defer-handle.md +1 -1
- package/reference/resource-management/resource.md +31 -2
- package/reference/resource-management/scope.md +28 -12
- package/reference/resource-management/wire.md +3 -7
- package/reference/ringbuffer/MpmcDiagram.jsx +717 -0
- package/reference/ringbuffer/MpscDiagram.jsx +618 -0
- package/reference/ringbuffer/SpmcDiagram.jsx +680 -0
- package/reference/ringbuffer/SpscDiagram.jsx +677 -0
- package/reference/ringbuffer/advanced.mdx +109 -0
- package/reference/ringbuffer/index.mdx +145 -0
- package/reference/ringbuffer/mpmc.mdx +151 -0
- package/reference/ringbuffer/mpsc.mdx +132 -0
- package/reference/ringbuffer/spmc.mdx +108 -0
- package/reference/ringbuffer/spsc.mdx +344 -0
- package/reference/{allows.md → schema/allows.md} +4 -4
- package/reference/{binding-resolver.md → schema/binding-resolver.md} +1 -1
- package/reference/{binding.md → schema/binding.md} +2 -3
- package/reference/schema/built-in-codecs/avro.md +451 -0
- package/reference/schema/built-in-codecs/bson.md +480 -0
- package/reference/schema/built-in-codecs/csv.md +564 -0
- package/reference/schema/built-in-codecs/index.md +77 -0
- package/reference/schema/built-in-codecs/json/index.md +295 -0
- package/reference/schema/built-in-codecs/json/json-config.md +217 -0
- package/reference/{json-patch.md → schema/built-in-codecs/json/json-patch.md} +3 -3
- package/reference/{json-schema.md → schema/built-in-codecs/json/json-schema.md} +14 -47
- package/reference/schema/built-in-codecs/json/json-selection.md +322 -0
- package/reference/{json.md → schema/built-in-codecs/json/json.md} +32 -64
- package/reference/schema/built-in-codecs/messagepack.md +508 -0
- package/reference/schema/built-in-codecs/thrift.md +433 -0
- package/reference/schema/built-in-codecs/toon.md +1078 -0
- package/reference/{xml.md → schema/built-in-codecs/xml.md} +34 -192
- package/reference/schema/built-in-codecs/yaml.md +552 -0
- package/reference/{codec.md → schema/codec.md} +10 -10
- package/reference/{dynamic-optic.md → schema/dynamic-optic.md} +151 -5
- package/reference/{dynamic-schema.md → schema/dynamic-schema.md} +8 -8
- package/reference/schema/format.md +92 -0
- package/reference/schema/index.md +50 -0
- package/reference/schema/migration.md +297 -0
- package/reference/{modifier.md → schema/modifier.md} +58 -7
- package/reference/{optics.md → schema/optics.md} +2 -2
- package/reference/{patch.md → schema/patch.md} +1 -1
- package/{path-interpolator.md → reference/schema/path-interpolator.md} +165 -72
- package/reference/{schema-evolution → schema/schema-evolution}/as.md +5 -5
- package/reference/{schema-evolution → schema/schema-evolution}/index.md +2 -2
- package/reference/{schema-evolution → schema/schema-evolution}/into.md +3 -3
- package/reference/{schema-expr.md → schema/schema-expr.md} +110 -175
- package/reference/{schema.md → schema/schema.md} +13 -1
- package/reference/{structural-types.md → schema/structural-types.md} +1 -1
- package/reference/{type-class-derivation.md → schema/type-class-derivation.md} +63 -1
- package/reference/smithy.md +533 -0
- package/reference/sql/db-codec-deriver.md +71 -0
- package/reference/sql/db-codec.md +687 -0
- package/reference/sql/db-con.md +271 -0
- package/reference/sql/db-connection.md +153 -0
- package/reference/sql/db-param-writer.md +77 -0
- package/reference/sql/db-param.md +66 -0
- package/reference/sql/db-result-reader.md +146 -0
- package/reference/sql/db-tx.md +82 -0
- package/reference/sql/db-value.md +41 -0
- package/reference/sql/ddl.md +85 -0
- package/reference/sql/frag.md +254 -0
- package/reference/sql/index.md +341 -0
- package/reference/sql/repo.md +600 -0
- package/reference/sql/sql-dialect.md +73 -0
- package/reference/sql/sql-logger.md +62 -0
- package/reference/sql/sql-name-mapper.md +70 -0
- package/reference/sql/table-metadata.md +134 -0
- package/reference/sql/table.md +448 -0
- package/reference/sql/transactor-zio.md +399 -0
- package/reference/sql/transactor.md +353 -0
- package/reference/sql-zio.md +112 -0
- package/reference/streams/concurrent-operators.md +106 -0
- package/reference/streams/index.md +653 -0
- package/reference/streams/pipeline.md +718 -0
- package/reference/streams/reader.md +1284 -0
- package/reference/streams/scala-2-compatibility.md +55 -0
- package/reference/streams/sink.md +1426 -0
- package/reference/streams/stream.md +2526 -0
- package/reference/streams/writer.md +1045 -0
- package/reference/streams/zero-boxing.md +275 -0
- package/reference/telemetry.md +693 -0
- package/reference/typeid.md +2922 -583
- package/sidebars.js +238 -43
- package/superpowers/plans/2026-03-19-docs-critique-subagent.md +407 -0
- package/superpowers/specs/2026-03-19-docs-critique-subagent-design.md +222 -0
- package/reference/formats.md +0 -694
- package/reference/http-model.md +0 -1716
- package/reference/streams.md +0 -989
- package/ringbuffer.md +0 -249
- /package/reference/{json-differ.md → schema/built-in-codecs/json/json-differ.md} +0 -0
- /package/reference/{dynamic-value.md → schema/dynamic-value.md} +0 -0
- /package/reference/{lazy.md → schema/lazy.md} +0 -0
- /package/reference/{reflect.md → schema/reflect.md} +0 -0
- /package/reference/{registers.md → schema/registers.md} +0 -0
- /package/reference/{schema-error.md → schema/schema-error.md} +0 -0
- /package/reference/{syntax.md → schema/syntax.md} +0 -0
- /package/reference/{validation.md → schema/validation.md} +0 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: spsc
|
|
3
|
+
title: "SPSC RingBuffer"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
import SpscDiagram from './SpscDiagram.jsx';
|
|
7
|
+
|
|
8
|
+
`SpscRingBuffer[A]` is optimized for the simplest and fastest case: exactly one producer thread and one consumer thread. It uses the **FastFlow** algorithm to eliminate all cross-core cache traffic, achieving nanosecond-scale latencies with no volatile reads on the fast path.
|
|
9
|
+
|
|
10
|
+
## Why FastFlow?
|
|
11
|
+
|
|
12
|
+
Understanding the FastFlow algorithm helps explain why `SpscRingBuffer` achieves such high performance.
|
|
13
|
+
|
|
14
|
+
Imagine two threads sharing data with a traditional lock-based queue like `ArrayBlockingQueue`. They use a mutex (lock) to coordinate:
|
|
15
|
+
|
|
16
|
+
1. Producer thread: acquires lock, adds element, releases lock
|
|
17
|
+
2. Consumer thread: acquires lock, removes element, releases lock
|
|
18
|
+
|
|
19
|
+
This works, but locks have a cost: when threads contend for the same lock, one thread **blocks** (goes to sleep) while waiting. Waking a thread is expensive (thousands of CPU cycles). Even lock-free queues using `synchronized` or `volatile` reads can cause **cache-coherency traffic**: when one CPU core writes to a variable another core reads, the entire cache line must be invalidated and transferred — a costly operation that slows down both cores.
|
|
20
|
+
|
|
21
|
+
The fundamental issue: **if the producer has to read what the consumer wrote (or vice versa), their CPU caches constantly fight**. This is called *false sharing* and can reduce throughput by 10x or more on heavily loaded systems.
|
|
22
|
+
|
|
23
|
+
The problem is that *any* read by the producer of the consumer's state (or vice versa) causes cache line bouncing. So FastFlow's radical idea: **neither side should ever read the other's state**.
|
|
24
|
+
|
|
25
|
+
Instead, the producer simply **writes data into slots** and marks them non-null. The consumer independently **reads slots** and takes any non-null values. The array slot's null/non-null status itself is the only coordination needed — a *happens-before* relationship written once by the producer, read once by the consumer. No locks, no atomic operations on the fast path, no reading the other side's counters.
|
|
26
|
+
|
|
27
|
+
The **note-passing analogy**:
|
|
28
|
+
- You (producer) have a row of empty desks between you and your friend (consumer)
|
|
29
|
+
- Empty desk = `null` (available)
|
|
30
|
+
- Note on desk = non-null value (message ready)
|
|
31
|
+
- **You never look at your friend's side** — you just place notes on empty desks
|
|
32
|
+
- **Your friend never looks at your side** — they just pick up notes they see
|
|
33
|
+
- No shouting "are you ready?", no waiting, no lock contention
|
|
34
|
+
|
|
35
|
+
**This is how FastFlow solves the cache-coherency problem**: since producer and consumer never read each other's counters, there's no cache line bouncing between CPU cores. All coordination happens through the slots themselves, which are written once and read once.
|
|
36
|
+
|
|
37
|
+
The **look-ahead cache** is a further optimization: the producer maintains a local cached limit (`producerLimit`) so they don't have to check every slot individually. It's like glancing ahead at the next N desks to see if they're empty, without actually bending over to look. This keeps the fast path extremely fast — just a local counter check and an array write.
|
|
38
|
+
|
|
39
|
+
**Why FastFlow is fast**:
|
|
40
|
+
- **No locks** — no thread ever blocks another
|
|
41
|
+
- **Minimal cache coordination** — producer and consumer touch separate memory locations; the array slot is written once, read once
|
|
42
|
+
- **Write-once, read-once semantics** — the slot's null/non-null status is the handshake
|
|
43
|
+
- **Cache-line padding** — producer and consumer indices padded to separate cache lines, eliminating false sharing
|
|
44
|
+
|
|
45
|
+
The result: **lock-free** communication that scales linearly with CPU count and achieves nanosecond-scale latencies. This is why FastFlow is the algorithm of choice for SPSC ring buffers in high-performance systems like trading platforms, game engines, and network stacks. (The slow path's retry on full buffers means the algorithm is not wait-free, though contention is rare.)
|
|
46
|
+
|
|
47
|
+
## Algorithm
|
|
48
|
+
|
|
49
|
+
`SpscRingBuffer` uses the **FastFlow** pattern, originally developed for the C++ FastFlow framework and popularized in Java by JCTools and the LMAX Disruptor. The core insight: the array element's `null`/non-`null` state **is** the synchronization signal. The producer never reads `consumerIndex`; the consumer never reads `producerIndex`. This eliminates all cross-core cache traffic between the two sides.
|
|
50
|
+
|
|
51
|
+
**How it works:**
|
|
52
|
+
|
|
53
|
+
- The producer walks forward through the array, placing elements into slots that are currently `null`. It marks a slot non-`null` after writing. The producer never reads what the consumer has consumed — it only checks its own cached `producerLimit` to know how many slots are available.
|
|
54
|
+
- The consumer walks forward through the array, reading any slot that contains a non-`null` value. After reading, it writes `null` to clear the slot. The consumer never reads the producer's index.
|
|
55
|
+
- The slot's nullness itself is the coordination: written once by the producer, read once by the consumer. No locks, no atomic operations on the fast path, no reading the other side's counters.
|
|
56
|
+
|
|
57
|
+
**Look-ahead cache:** The producer maintains a local `producerLimit` (derived from `consumerIndex` during slow path). This allows the fast path to check a simple local counter instead of reading the volatile `consumerIndex` on every `offer`. The look-ahead step is `max(1, min(capacity/4, 4096))`, balancing between reducing consumer reads and memory usage.
|
|
58
|
+
|
|
59
|
+
### Diagram
|
|
60
|
+
|
|
61
|
+
To see the single-producer single-consumer FastFlow algorithm in action, use this interactive stepper. Type any label, click **Offer** to enqueue or **Take** to dequeue, and watch how the producer and consumer coordinate using only release/acquire semantics — no CAS on either side.
|
|
62
|
+
|
|
63
|
+
<SpscDiagram />
|
|
64
|
+
|
|
65
|
+
Here is a complete walkthrough of every variable in the trace, in the order the algorithm computes them.
|
|
66
|
+
|
|
67
|
+
### `pIdx` — the monotonic producer counter (plain load/store)
|
|
68
|
+
|
|
69
|
+
The producer reads `pIdx` with a plain load — no atomic operations at all. Since only one thread produces, no synchronization is needed. The producer maintains its own count, never reads `consumerIndex`, and advances `pIdx` after writing with a release store.
|
|
70
|
+
|
|
71
|
+
### `cIdx` — the monotonic consumer counter
|
|
72
|
+
|
|
73
|
+
SPSC avoids reading `consumerIndex` entirely. Instead of checking the occupancy formula (`pIdx - cIdx`), the producer reads the array slot at `producerIndex + lookAheadStep` to determine if a slot is free (on the slow path when the look-ahead cache is exhausted). This slot-based approach eliminates all counter reads between producer and consumer.
|
|
74
|
+
|
|
75
|
+
### `size = pIdx − cIdx` — the occupancy check
|
|
76
|
+
|
|
77
|
+
Both sides use the same occupancy formula, but only during slow paths (rare). On the fast path, neither side reads the other's counter; they rely on slot nullness (FastFlow) for synchronization.
|
|
78
|
+
|
|
79
|
+
### `slot = pIdx & mask` or `slot = cIdx & mask` — the circular array index
|
|
80
|
+
|
|
81
|
+
Identical bitmask arithmetic: `& mask` replaces modulo, giving a slot in `[0, capacity)`.
|
|
82
|
+
|
|
83
|
+
### `element = buf[slot]` — no CAS, plain slot reads
|
|
84
|
+
|
|
85
|
+
Unlike SPMC and MPMC, the consumer reads the slot directly with an acquire load — because there's only one consumer, no read-before-CAS is needed. The consumer is the sole owner of the take path. After reading, the consumer nulls the slot with a release store, which serves two purposes: (1) signals to the producer that the slot is free, and (2) releases any bookkeeping updates to other cores via the release semantics.
|
|
86
|
+
|
|
87
|
+
### Why SPSC doesn't read producer state
|
|
88
|
+
|
|
89
|
+
The consumer never reads `pIdx`. Instead, it reads the slot directly: if the slot is non-null, data is ready. If null, the buffer is empty. The producer wrote a non-null value via a release store, and the consumer reads via an acquire load, forming a happens-before pair. This is the core of FastFlow: **eliminate cross-core reads entirely**.
|
|
90
|
+
|
|
91
|
+
The diagram marks slots as "live" (still owned by the producer-consumer pair) or "stale" (consumed but not yet overwritten). Unlike SPMC where consumers CAS and have ordering concerns, SPSC clears immediately because only one consumer exists — there's no race.
|
|
92
|
+
|
|
93
|
+
## Creating Instances
|
|
94
|
+
|
|
95
|
+
Ring buffers are instantiated via the companion object's `apply` method. `SpscRingBuffer[A]` uses the FastFlow pattern with a look-ahead cache. On the fast path, the producer checks a cached `producerLimit` to avoid reading `consumerIndex`. When the cached limit is exhausted, the slow path reads the array slot at `producerIndex + lookAheadStep` — never `consumerIndex` directly. This keeps the producer and consumer cache lines fully independent. The consumer uses null/non-null slot reads (FastFlow semantics). Together, these avoid repeated volatile reads and minimize cross-core cache traffic.
|
|
96
|
+
|
|
97
|
+
```scala
|
|
98
|
+
object SpscRingBuffer {
|
|
99
|
+
def apply[A <: AnyRef](capacity: Int): SpscRingBuffer[A]
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Creates a new SPSC ring buffer with the given capacity. The capacity must be a positive power of two.
|
|
104
|
+
|
|
105
|
+
We create an SPSC buffer as follows:
|
|
106
|
+
|
|
107
|
+
```scala mdoc:compile-only
|
|
108
|
+
import zio.blocks.ringbuffer.SpscRingBuffer
|
|
109
|
+
|
|
110
|
+
val rb = SpscRingBuffer[String](16) // capacity must be power of 2
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Operations
|
|
114
|
+
|
|
115
|
+
`SpscRingBuffer` provides operations for sending and receiving elements, as well as querying buffer state:
|
|
116
|
+
|
|
117
|
+
### Inserting Elements — `SpscRingBuffer#offer`
|
|
118
|
+
|
|
119
|
+
Use `SpscRingBuffer#offer` to insert an element with this signature:
|
|
120
|
+
|
|
121
|
+
```scala
|
|
122
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
123
|
+
def offer(a: A): Boolean
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Inserts the element without blocking. Returns `true` on successful insertion, `false` when the buffer is full. Raises `NullPointerException` if the element is `null`. Call only from the producer thread.
|
|
128
|
+
|
|
129
|
+
To handle backpressure by checking if insertion succeeds:
|
|
130
|
+
|
|
131
|
+
```scala mdoc:silent:reset
|
|
132
|
+
import zio.blocks.ringbuffer.SpscRingBuffer
|
|
133
|
+
|
|
134
|
+
val rb = SpscRingBuffer[String](4)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
When the buffer becomes full, `offer` returns `false`:
|
|
138
|
+
|
|
139
|
+
```scala mdoc
|
|
140
|
+
val result1 = rb.offer("a")
|
|
141
|
+
val result2 = rb.offer("b")
|
|
142
|
+
val result3 = rb.offer("c")
|
|
143
|
+
val result4 = rb.offer("d")
|
|
144
|
+
val result5 = rb.offer("e")
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Removing Elements — `SpscRingBuffer#take`
|
|
148
|
+
|
|
149
|
+
Use `SpscRingBuffer#take` to remove an element with this signature:
|
|
150
|
+
|
|
151
|
+
```scala
|
|
152
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
153
|
+
def take(): A
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Retrieves and removes an element from the front of the buffer. Returns immediately without blocking, providing the element or `null` if the buffer is empty. Call only from the consumer thread.
|
|
158
|
+
|
|
159
|
+
To retrieve elements in FIFO order:
|
|
160
|
+
|
|
161
|
+
```scala mdoc
|
|
162
|
+
rb.take()
|
|
163
|
+
rb.take()
|
|
164
|
+
rb.take()
|
|
165
|
+
rb.take()
|
|
166
|
+
rb.take()
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Checking State — `size`, `isEmpty`, `isFull`
|
|
170
|
+
|
|
171
|
+
Ring buffers provide three query methods to check their state. Note that under concurrent access, these results are **approximate** — by the time the method returns, other threads may modify the buffer.
|
|
172
|
+
|
|
173
|
+
Use `SpscRingBuffer#size` to get the approximate element count with this signature:
|
|
174
|
+
|
|
175
|
+
```scala
|
|
176
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
177
|
+
def size: Int
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Returns the approximate number of elements currently in the buffer. Under concurrent access, the result may be stale. O(1).
|
|
182
|
+
|
|
183
|
+
Use `SpscRingBuffer#isEmpty` to check if the buffer is empty with this signature:
|
|
184
|
+
|
|
185
|
+
```scala
|
|
186
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
187
|
+
def isEmpty: Boolean
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Returns `true` if the buffer contains no elements (approximate). O(1).
|
|
192
|
+
|
|
193
|
+
Use `SpscRingBuffer#isFull` to check if the buffer is at capacity with this signature:
|
|
194
|
+
|
|
195
|
+
```scala
|
|
196
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
197
|
+
def isFull: Boolean
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Returns `true` if the buffer is at capacity (approximate). O(1).
|
|
202
|
+
|
|
203
|
+
All four implementations provide the same three methods. To check state after operations:
|
|
204
|
+
|
|
205
|
+
```scala mdoc:silent:reset
|
|
206
|
+
import zio.blocks.ringbuffer.SpscRingBuffer
|
|
207
|
+
|
|
208
|
+
val rb2 = SpscRingBuffer[String](8)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
State queries are cheap but approximate under concurrency:
|
|
212
|
+
|
|
213
|
+
```scala mdoc
|
|
214
|
+
rb2.offer("x")
|
|
215
|
+
rb2.offer("y")
|
|
216
|
+
|
|
217
|
+
rb2.size
|
|
218
|
+
rb2.isEmpty
|
|
219
|
+
rb2.isFull
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
### Batch Operations — `SpscRingBuffer#drain` and `SpscRingBuffer#fill`
|
|
223
|
+
|
|
224
|
+
Use `SpscRingBuffer#drain` to consume up to N elements with this signature:
|
|
225
|
+
|
|
226
|
+
```scala
|
|
227
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
228
|
+
def drain(consumer: A => Unit, limit: Int): Int
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Removes up to `limit` elements from the buffer, passing each to the `consumer` callback. Returns the number of elements actually drained. Raises `IllegalArgumentException` if `limit` is negative. Call only from the consumer thread. O(n) where n is the number of elements drained. If the callback raises an exception, all elements passed to it up to that point remain consumed and the buffer stays in a consistent state.
|
|
233
|
+
|
|
234
|
+
Use `SpscRingBuffer#fill` to produce up to N elements with this signature:
|
|
235
|
+
|
|
236
|
+
```scala
|
|
237
|
+
final class SpscRingBuffer[A <: AnyRef](val capacity: Int) {
|
|
238
|
+
def fill(supplier: () => A, limit: Int): Int
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Inserts up to `limit` elements by calling the `supplier` for each new element. Returns the number of elements actually inserted. Raises `IllegalArgumentException` if `limit` is negative. Raises `NullPointerException` if the supplier returns `null`. Call only from the producer thread. O(n) where n is the number of elements inserted.
|
|
243
|
+
|
|
244
|
+
Batch operations amortize synchronization costs. To drain multiple elements at once:
|
|
245
|
+
|
|
246
|
+
```scala mdoc:silent:reset
|
|
247
|
+
import zio.blocks.ringbuffer.SpscRingBuffer
|
|
248
|
+
|
|
249
|
+
val rb3 = SpscRingBuffer[java.lang.Integer](16)
|
|
250
|
+
(1 to 5).foreach(i => rb3.offer(Integer.valueOf(i)))
|
|
251
|
+
|
|
252
|
+
val collected = scala.collection.mutable.Buffer[java.lang.Integer]()
|
|
253
|
+
val drained = rb3.drain(collected += _, 10) // drained = 5
|
|
254
|
+
|
|
255
|
+
println(s"Drained items: ${collected.mkString(", ")}")
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
To avoid repeated `offer` calls when producing elements, use fill:
|
|
259
|
+
|
|
260
|
+
```scala mdoc:silent:reset
|
|
261
|
+
import zio.blocks.ringbuffer.SpscRingBuffer
|
|
262
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
263
|
+
|
|
264
|
+
val rb4 = SpscRingBuffer[String](8)
|
|
265
|
+
val counter = new AtomicInteger(0)
|
|
266
|
+
val filled = rb4.fill(() => { counter.incrementAndGet(); s"item-${counter.get()}" }, 5)
|
|
267
|
+
|
|
268
|
+
println(s"Filled $filled items")
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Primitive variants
|
|
272
|
+
|
|
273
|
+
The generic `SpscRingBuffer[A]` stores `AnyRef` slots, which boxes Java primitives on the producer side. For SPSC workloads handing off `Int`, `Long`, `Float`, or `Double` values between two threads, four zero-boxing companions are provided:
|
|
274
|
+
|
|
275
|
+
| Type | Class | Slot encoding |
|
|
276
|
+
|---|---|---|
|
|
277
|
+
| `Int` | `IntSpscRingBuffer` | one `Long` per slot: high 32 bits hold an occupancy tag (`0` = empty, `1` = data, `2` = DONE sentinel), low 32 bits hold the `Int` payload. The whole 64-bit word is `0L` when empty, so any tagged value is non-zero regardless of the payload bits. |
|
|
278
|
+
| `Long` | `LongSpscRingBuffer` | one `Long` per slot. `Long.MinValue` is reserved as the empty marker and `Long.MinValue + 1L` as the in-band DONE sentinel; offering either value throws `IllegalArgumentException`. All other `Long` values pass through unchanged. |
|
|
279
|
+
| `Float` | `FloatSpscRingBuffer` | one `Long` per slot: high 32 bits tag (`0` = empty, `1` = data, `2` = DONE), low 32 bits hold `floatToRawIntBits(value)`. The whole word is `0L` when empty. Every `Float` (including `0.0f`, `NaN`, `±Inf`) is representable. |
|
|
280
|
+
| `Double` | `DoubleSpscRingBuffer` | one `Long` per slot. `doubleToRawLongBits(value)` is stored directly; two reserved non-canonical `NaN` bit patterns mark empty (`0xFFF8_0000_0000_0001L`) and DONE (`0xFFF8_0000_0000_0002L`). Any `NaN` payload is canonicalized to `Double.NaN` on offer so it can never collide with the reserved markers. |
|
|
281
|
+
|
|
282
|
+
All four use the same FastFlow algorithm as the generic version — single backing `Array[Long]`, padded indices, look-ahead cache — and expose the same core operations (`offer`, `take`, `peek`, `isEmpty`, `isFull`, `size`, `capacity`). The only API difference is that `take` returns a primitive instead of `AnyRef`, so callers should check `peek()` first to know whether the next read will be a real value or just the empty marker. (The generic `drain`/`fill` batch helpers are not provided on the primitive variants; loop `peek`/`take` directly.)
|
|
283
|
+
|
|
284
|
+
In addition, each primitive variant exposes two methods for **in-band end-of-stream signalling**, used by the concurrent stream operators to propagate "no more data" through a primitive queue without needing a separate side channel:
|
|
285
|
+
|
|
286
|
+
- `offerDone(): Boolean` — write the DONE sentinel into the next free slot, returning `true` on success or `false` if the queue is full. Once `offerDone()` succeeds the producer should not offer any further values.
|
|
287
|
+
- `pollPacked(): Long` — atomically poll the next slot and return its packed encoding: `EMPTY_PACKED`/`EMPTY` / `EMPTY_BITS` when empty (consumer index NOT advanced), `DONE_PACKED`/`DONE` / `DONE_BITS` for the DONE sentinel (index advanced), or a non-sentinel encoded value otherwise (index advanced). The exact constant names live on each companion object (`IntSpscRingBuffer.DONE_PACKED`, `LongSpscRingBuffer.DONE`, `FloatSpscRingBuffer.DONE_PACKED`, `DoubleSpscRingBuffer.DONE_BITS`).
|
|
288
|
+
|
|
289
|
+
`pollPacked` is intended for advanced consumers that want a single atomic operation distinguishing empty / data / DONE. Most application code that simply needs primitive throughput is fine using the higher-level concurrent stream operators below.
|
|
290
|
+
|
|
291
|
+
```scala mdoc:silent:reset
|
|
292
|
+
import zio.blocks.ringbuffer.{IntSpscRingBuffer, LongSpscRingBuffer, DoubleSpscRingBuffer}
|
|
293
|
+
|
|
294
|
+
val ints = new IntSpscRingBuffer(16)
|
|
295
|
+
ints.offer(42)
|
|
296
|
+
if (ints.peek()) {
|
|
297
|
+
val v: Int = ints.take() // 42
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
val longs = new LongSpscRingBuffer(16)
|
|
301
|
+
longs.offer(Long.MaxValue)
|
|
302
|
+
if (longs.peek()) {
|
|
303
|
+
val w: Long = longs.take() // Long.MaxValue
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
val doubles = new DoubleSpscRingBuffer(16)
|
|
307
|
+
doubles.offer(Double.NaN) // canonicalized to Double.NaN's bit pattern on offer
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
These variants underpin the primitive-specialized concurrent stream operators (`mapPar`, `mergeAll`, `flatMapPar`) so primitive streams do not box during cross-thread handoff.
|
|
311
|
+
|
|
312
|
+
## Examples
|
|
313
|
+
|
|
314
|
+
### SPSC: Producer-Consumer Ping-Pong
|
|
315
|
+
|
|
316
|
+
In a single-producer, single-consumer setup, use `SpscRingBuffer` for maximum throughput. This example demonstrates how two threads communicate efficiently using FastFlow signaling.
|
|
317
|
+
|
|
318
|
+
```scala mdoc:passthrough
|
|
319
|
+
import docs.SourceFile
|
|
320
|
+
|
|
321
|
+
SourceFile.print("zio-blocks-examples/src/main/scala/ringbuffer/SpscExample.scala")
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
([source](https://github.com/zio/zio-blocks/blob/main/zio-blocks-examples/src/main/scala/ringbuffer/SpscExample.scala))
|
|
325
|
+
|
|
326
|
+
```bash
|
|
327
|
+
sbt "zio-blocks-examples/runMain ringbuffer.SpscExample"
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### Batch Fill and Drain (SPSC)
|
|
331
|
+
|
|
332
|
+
Use `fill` and `drain` for efficient batch operations. This example shows how to amortize synchronization costs by processing multiple elements at once.
|
|
333
|
+
|
|
334
|
+
```scala mdoc:passthrough
|
|
335
|
+
import docs.SourceFile
|
|
336
|
+
|
|
337
|
+
SourceFile.print("zio-blocks-examples/src/main/scala/ringbuffer/BatchExample.scala")
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
([source](https://github.com/zio/zio-blocks/blob/main/zio-blocks-examples/src/main/scala/ringbuffer/BatchExample.scala))
|
|
341
|
+
|
|
342
|
+
```bash
|
|
343
|
+
sbt "zio-blocks-examples/runMain ringbuffer.BatchExample"
|
|
344
|
+
```
|
|
@@ -606,7 +606,7 @@ import zio.blocks.schema._
|
|
|
606
606
|
import zio.blocks.schema.comptime.Allows
|
|
607
607
|
import Allows.{Primitive, Record, `|`}
|
|
608
608
|
import Allows.{Optional => AOptional}
|
|
609
|
-
import
|
|
609
|
+
import zio.sbt.ExprEval.show
|
|
610
610
|
|
|
611
611
|
// ---------------------------------------------------------------------------
|
|
612
612
|
// CSV serializer example using Allows[A, S] compile-time shape constraints
|
|
@@ -730,7 +730,7 @@ import zio.blocks.schema._
|
|
|
730
730
|
import zio.blocks.schema.comptime.Allows
|
|
731
731
|
import Allows.{Primitive, Record, Sequence, `|`}
|
|
732
732
|
import Allows.{Optional => AOptional}
|
|
733
|
-
import
|
|
733
|
+
import zio.sbt.ExprEval.show
|
|
734
734
|
|
|
735
735
|
// ---------------------------------------------------------------------------
|
|
736
736
|
// Event bus / message broker example using Allows[A, S]
|
|
@@ -852,7 +852,7 @@ import zio.blocks.schema._
|
|
|
852
852
|
import zio.blocks.schema.comptime.Allows
|
|
853
853
|
import Allows.{Primitive, Record, Sequence, `|`}
|
|
854
854
|
import Allows.{Optional => AOptional, Self => ASelf}
|
|
855
|
-
import
|
|
855
|
+
import zio.sbt.ExprEval.show
|
|
856
856
|
|
|
857
857
|
// ---------------------------------------------------------------------------
|
|
858
858
|
// GraphQL / tree structure example using Self for recursive grammars
|
|
@@ -991,7 +991,7 @@ package comptime
|
|
|
991
991
|
import zio.blocks.schema._
|
|
992
992
|
import zio.blocks.schema.comptime.Allows
|
|
993
993
|
import Allows.{Primitive, Record}
|
|
994
|
-
import
|
|
994
|
+
import zio.sbt.ExprEval.show
|
|
995
995
|
|
|
996
996
|
// ---------------------------------------------------------------------------
|
|
997
997
|
// Sealed trait auto-unwrap example
|
|
@@ -466,4 +466,4 @@ val rebound: Schema[Address] = Schema[Address].toDynamicSchema.rebind[Address](r
|
|
|
466
466
|
If `DynamicSchema#rebind` cannot find a binding for any type present in the unbound schema tree, it throws at runtime. Make sure the resolver covers every concrete type—records, variants, wrappers, primitives, and collections—that appears in the schema.
|
|
467
467
|
:::
|
|
468
468
|
|
|
469
|
-
See [Binding](
|
|
469
|
+
See [Binding](binding.md) for details on each binding kind, and [Schema](schema.md) for the overall structure of the schema system.
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
id: binding
|
|
3
|
-
title: "
|
|
4
|
-
sidebar_label: Binding
|
|
3
|
+
title: "Binding"
|
|
5
4
|
---
|
|
6
5
|
|
|
7
6
|
`Binding` is a sealed trait in ZIO Blocks that provides the operational machinery for constructing and deconstructing values of schema-described types. While `Reflect` describes the **structure** of data types, `Binding` provides the **behavior** needed to work with those types at runtime.
|
|
@@ -339,7 +338,7 @@ When `F[_, _] = NoBinding` in `Reflect[F[_, _], A]` the `Reflect` structure cont
|
|
|
339
338
|
1. **Schema serialization**: Convert schemas to JSON Schema or other formats, making them portable
|
|
340
339
|
2. **Schema rebinding**: Deserialize a schema and rebind it using a `TypeRegistry`, so it becomes type-safe and operational again
|
|
341
340
|
|
|
342
|
-
We will cover schema serialization and rebinding in more detail in the `Reflect` data type documentation page. For the full API of the binding lookup mechanism used during rebinding, see [BindingResolver](
|
|
341
|
+
We will cover schema serialization and rebinding in more detail in the `Reflect` data type documentation page. For the full API of the binding lookup mechanism used during rebinding, see [BindingResolver](binding-resolver.md).
|
|
343
342
|
|
|
344
343
|
## Summary
|
|
345
344
|
|