Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::{sync::atomic::Ordering, task::Poll};

use crate::{
	Closed, Counts, State,
	consumer::Consumer,
	lock::*,
	producer::{Producer, Ref},
	sync::Arc,
	waiter::*,
};

/// A handle that owns nothing at all ([`Producer::downgrade`](crate::Producer::downgrade)).
///
/// Unlike [`ProducerWeak`], which keeps the state allocated so it stays readable after
/// the channel closes, this drops with the last real handle. That makes it the one
/// handle you can store *inside* the state it points at (a child holding a link back to
/// its parent, say) without the two keeping each other alive forever.
///
/// [`upgrade`](Self::upgrade) it back to a [`Producer`] while the channel is still live.
pub struct Weak<T> {
	pub(crate) state: WeakLock<State<T>>,
	pub(crate) counts: Arc<Counts>,
}

impl<T> Weak<T> {
	/// A handle that never upgrades, mirroring [`std::sync::Weak::new`].
	///
	/// Useful as a placeholder for a link that isn't wired up yet, or that a
	/// standalone (channel-less) value doesn't have.
	pub fn new() -> Self {
		Self {
			state: WeakLock::new(),
			counts: Arc::new(Counts::default()),
		}
	}

	/// Recover a [`Producer`], or `None` once the state has been dropped or the
	/// channel closed.
	///
	/// This counts: while the returned producer lives the channel stays open, and
	/// dropping it can be what finally closes it.
	pub fn upgrade(&self) -> Option<Producer<T>> {
		// Reuse `produce`'s increment-then-check ordering, which is what keeps the
		// last `Producer::drop` from closing the channel out from under us.
		ProducerWeak {
			state: self.state.upgrade()?,
			counts: self.counts.clone(),
		}
		.produce()
	}
}

impl<T> Default for Weak<T> {
	fn default() -> Self {
		Self::new()
	}
}

impl<T> Clone for Weak<T> {
	fn clone(&self) -> Self {
		Self {
			state: self.state.clone(),
			counts: self.counts.clone(),
		}
	}
}

impl<T> std::fmt::Debug for Weak<T> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Weak")
			.field("alive", &self.state.upgrade().is_some())
			.finish()
	}
}

/// A weak handle from the producing side ([`Producer::weak`](crate::Producer::weak)).
///
/// Holds no ref count, so it never keeps the channel open. Upgrade it back to a [`Producer`]
/// (write access) or a [`Consumer`] (read access) while the channel is still live.
///
/// It does keep the state *allocated*, which is what lets it read a closed channel's final
/// value. Reach for [`Weak`] instead when the handle is stored inside that same state.
#[derive(Debug)]
pub struct ProducerWeak<T> {
	pub(crate) state: Lock<State<T>>,
	pub(crate) counts: Arc<Counts>,
}

impl<T> ProducerWeak<T> {
	/// Upgrade to a [`Producer`], returning `None` if the channel is already closed.
	pub fn produce(&self) -> Option<Producer<T>> {
		{
			// Registering under the same lock that guards `closed` is what makes the
			// returned producer keep the channel open: a concurrent last-producer drop
			// either closes first (and we bail) or sees our count and doesn't close.
			let state = self.state.lock();
			if state.closed {
				return None;
			}
			self.counts.producers.fetch_add(1, Ordering::Relaxed);
		}

		Some(Producer {
			state: self.state.clone(),
			counts: self.counts.clone(),
		})
	}

	/// Create a new [`Consumer`] that shares this state.
	pub fn consume(&self) -> Consumer<T> {
		let prev = self.counts.consumers.fetch_add(1, Ordering::AcqRel);

		// Wake `used()` waiters when the first consumer appears.
		if prev == 0 {
			let mut waiters = self.state.lock().waiters_consumer.take();
			waiters.wake();
		}

		Consumer {
			state: self.state.clone(),
			counts: self.counts.clone(),
		}
	}

	/// Get read-only access to the shared state.
	pub fn read(&self) -> Ref<'_, T> {
		Ref {
			state: self.state.lock(),
		}
	}

	/// Returns `true` if the channel has been closed.
	pub fn is_closed(&self) -> bool {
		self.state.lock().closed
	}

	/// Wait until the channel is closed.
	pub async fn closed(&self) {
		crate::wait(move |waiter| self.poll_closed(waiter)).await
	}

	/// Poll for channel closure, registering the waiter if still open.
	pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> {
		let mut state = self.state.lock();
		if state.closed {
			return Poll::Ready(());
		}

		waiter.register(&mut state.waiters_closed);
		Poll::Pending
	}

	/// Wait until all consumers have been dropped.
	///
	/// Returns `Ok(())` when no consumers remain, or [`Closed`] if the channel closes first.
	pub async fn unused(&self) -> Result<(), Closed> {
		match crate::wait(move |waiter| self.poll_unused(waiter)).await {
			Some(()) => Ok(()),
			None => Err(Closed),
		}
	}

	/// Poll-based variant of [`Self::unused`]: `Ready(Some(()))` when no consumers
	/// remain, `Ready(None)` if the channel closed first, else `Pending`.
	pub fn poll_unused(&self, waiter: &Waiter) -> Poll<Option<()>> {
		// Closure is checked first, matching `Producer::poll_unused`: a closed channel
		// with no consumers resolves `None` from either handle.
		let mut state = self.state.lock();
		if state.closed {
			return Poll::Ready(None);
		}

		if self.counts.consumers.load(Ordering::Relaxed) == 0 {
			return Poll::Ready(Some(()));
		}

		waiter.register(&mut state.waiters_consumer);

		// Re-check after registration to avoid TOCTOU race where the last
		// consumer drops between the initial check and waiter registration.
		if self.counts.consumers.load(Ordering::Relaxed) == 0 {
			return Poll::Ready(Some(()));
		}

		Poll::Pending
	}

	/// Whether any consumer handle currently exists.
	///
	/// A point-in-time snapshot with no registration; use [`Self::poll_used`] /
	/// [`Self::poll_unused`] to wait for the edge instead.
	pub fn is_used(&self) -> bool {
		self.counts.consumers.load(Ordering::Relaxed) > 0
	}

	/// Wait until at least one consumer exists.
	///
	/// Returns `Ok(())` when a consumer is created, or [`Closed`] if the channel closes first.
	pub async fn used(&self) -> Result<(), Closed> {
		match crate::wait(move |waiter| self.poll_used(waiter)).await {
			Some(()) => Ok(()),
			None => Err(Closed),
		}
	}

	/// Poll-based variant of [`Self::used`]: `Ready(Some(()))` once a consumer
	/// exists, `Ready(None)` if the channel closed first, else `Pending`.
	pub fn poll_used(&self, waiter: &Waiter) -> Poll<Option<()>> {
		// Closure is checked first, matching `Producer::poll_used`.
		let mut state = self.state.lock();
		if state.closed {
			return Poll::Ready(None);
		}

		if self.counts.consumers.load(Ordering::Relaxed) > 0 {
			return Poll::Ready(Some(()));
		}

		waiter.register(&mut state.waiters_consumer);

		// Re-check after registration to avoid TOCTOU race.
		if self.counts.consumers.load(Ordering::Relaxed) > 0 {
			return Poll::Ready(Some(()));
		}

		Poll::Pending
	}

	/// Returns `true` if both handles share the same underlying state.
	pub fn same_channel(&self, other: &Self) -> bool {
		self.state.is_clone(&other.state)
	}
}

impl<T> Clone for ProducerWeak<T> {
	fn clone(&self) -> Self {
		Self {
			state: self.state.clone(),
			counts: self.counts.clone(),
		}
	}
}

/// A weak handle from the consuming side ([`Consumer::weak`](crate::Consumer::weak)).
///
/// Holds no ref count, so it never keeps the channel open. Unlike [`ProducerWeak`] it can
/// only mint more [`Consumer`]s, so a read-only handle can never grow write access.
#[derive(Debug)]
pub struct ConsumerWeak<T> {
	pub(crate) state: Lock<State<T>>,
	pub(crate) counts: Arc<Counts>,
}

impl<T> ConsumerWeak<T> {
	/// Create a new [`Consumer`] that shares this state.
	pub fn consume(&self) -> Consumer<T> {
		let prev = self.counts.consumers.fetch_add(1, Ordering::AcqRel);

		// Wake `used()` waiters when the first consumer appears.
		if prev == 0 {
			let mut waiters = self.state.lock().waiters_consumer.take();
			waiters.wake();
		}

		Consumer {
			state: self.state.clone(),
			counts: self.counts.clone(),
		}
	}

	/// Get read-only access to the shared state.
	pub fn read(&self) -> Ref<'_, T> {
		Ref {
			state: self.state.lock(),
		}
	}

	/// Returns `true` if the channel has been closed.
	pub fn is_closed(&self) -> bool {
		self.state.lock().closed
	}

	/// Wait until the channel is closed.
	pub async fn closed(&self) {
		crate::wait(move |waiter| self.poll_closed(waiter)).await
	}

	/// Poll for channel closure, registering the waiter if still open.
	pub fn poll_closed(&self, waiter: &Waiter) -> Poll<()> {
		let mut state = self.state.lock();
		if state.closed {
			return Poll::Ready(());
		}

		waiter.register(&mut state.waiters_closed);
		Poll::Pending
	}

	/// Returns `true` if both handles share the same underlying state.
	pub fn same_channel(&self, other: &Self) -> bool {
		self.state.is_clone(&other.state)
	}
}

impl<T> Clone for ConsumerWeak<T> {
	fn clone(&self) -> Self {
		Self {
			state: self.state.clone(),
			counts: self.counts.clone(),
		}
	}
}

#[cfg(all(test, not(loom)))]
mod test {
	use super::*;

	/// A closed, consumer-free channel reports the same thing through either handle.
	/// Both check closure before the consumer count, so neither reports `Ok(())` for a
	/// channel that is merely out of consumers because it's dead.
	#[tokio::test]
	async fn weak_and_producer_agree_once_closed() {
		let producer = Producer::new(0u32);
		let weak = producer.weak();

		// No consumers were ever created, and the channel is now closed.
		producer.close().ok().expect("open");

		assert_eq!(producer.unused().await, Err(Closed));
		assert_eq!(weak.unused().await, Err(Closed));

		assert_eq!(producer.used().await, Err(Closed));
		assert_eq!(weak.used().await, Err(Closed));
	}

	/// While the channel is open the two handles still agree on the consumer count.
	#[tokio::test]
	async fn weak_and_producer_agree_while_open() {
		let producer = Producer::new(0u32);
		let weak = producer.weak();

		assert_eq!(producer.unused().await, Ok(()));
		assert_eq!(weak.unused().await, Ok(()));

		let consumer = producer.consume();
		assert_eq!(producer.used().await, Ok(()));
		assert_eq!(weak.used().await, Ok(()));

		drop(consumer);
		assert_eq!(weak.unused().await, Ok(()));
	}

	/// A state holding a handle back to itself is still deallocated once the last real
	/// handle drops. `ProducerWeak` would keep it (and everything it owns) alive forever.
	#[test]
	fn weak_breaks_a_self_reference() {
		struct Node {
			// Only its refcount matters: it's how the test sees the state deallocate.
			_alive: Arc<()>,
			back: Option<Weak<Node>>,
		}

		let alive = Arc::new(());
		let producer = Producer::new(Node {
			_alive: alive.clone(),
			back: None,
		});
		producer.write().ok().expect("open").back = Some(producer.downgrade());
		assert_eq!(Arc::strong_count(&alive), 2, "the state is alive");

		let weak = producer.downgrade();
		assert!(weak.upgrade().is_some(), "upgradeable while the channel is live");

		drop(producer);
		assert_eq!(Arc::strong_count(&alive), 1, "the state is gone despite the cycle");
		assert!(weak.upgrade().is_none());
	}

	/// A closed channel never upgrades, even while a consumer is still draining it.
	/// Producing into it again would resurrect a channel every reader has been told
	/// is over.
	#[test]
	fn weak_does_not_upgrade_once_closed() {
		let producer = Producer::new(0u32);
		let weak = producer.downgrade();
		let consumer = producer.consume();

		drop(producer);
		assert!(weak.upgrade().is_none(), "closed, despite the state being alive");

		drop(consumer);
		assert!(weak.upgrade().is_none());
	}

	/// An upgrade racing the last producer's drop either loses (no handle) or wins
	/// (a handle that is genuinely open). It must never hand back a producer for a
	/// channel that the drop is about to close.
	///
	/// A smoke test, not a reproducer: the window is a few instructions wide and this
	/// doesn't trip on the unsynchronized ordering even with the barrier. What rules
	/// the interleaving out is doing the count transition under the state lock.
	#[test]
	fn upgrade_never_wins_a_closing_channel() {
		for _ in 0..2_000 {
			let producer = Producer::new(0u32);
			let weak = producer.downgrade();
			// Keeps the state allocated so the upgrade is about the channel, not the
			// allocation.
			let consumer = producer.consume();

			// Line both threads up on the drop/upgrade window.
			let gate = std::sync::Arc::new(std::sync::Barrier::new(2));
			let dropper = {
				let gate = gate.clone();
				std::thread::spawn(move || {
					gate.wait();
					drop(producer);
				})
			};

			gate.wait();
			if let Some(upgraded) = weak.upgrade() {
				assert!(
					upgraded.write().is_ok(),
					"an upgrade must not resolve a closing channel"
				);
			}
			dropper.join().expect("dropper panicked");
			drop(consumer);
		}
	}

	/// An upgrade counts as a producer for as long as it lives, so the channel can't
	/// close underneath it.
	#[test]
	fn upgrade_holds_the_channel_open() {
		let producer = Producer::new(0u32);
		let weak = producer.downgrade();
		let consumer = producer.consume();

		let upgraded = weak.upgrade().expect("open");

		drop(producer);
		assert!(!consumer.is_closed(), "the upgrade keeps it open");

		drop(upgraded);
		assert!(consumer.is_closed(), "dropping the last one closes it");
	}

	#[tokio::test]
	async fn consumer_weak_reads_and_observes_close() {
		let producer = Producer::new(7u32);
		let consumer = producer.consume();
		let weak = consumer.weak();

		assert_eq!(*weak.read(), 7);
		assert!(!weak.is_closed());

		// Dropping the last producer closes the channel, resolving `closed()`.
		drop(producer);
		weak.closed().await;
		assert!(weak.is_closed());
		assert!(weak.read().is_closed());
	}
}