rust_widgets 2.1.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! BLUE13 Phase 3: Alloc bridge — unified imports for std and no_std.
//!
//! All crate files should import common types from here instead of `std`
//! when those types are not available in `core`/`alloc`. This keeps the
//! codebase ready for `#![cfg_attr(feature = "mini", no_std)]` without
//! `#[cfg]` in 200+ files. Note: that attribute is not yet enabled — the
//! `mini` profile currently compiles on std.
//!
//! # The rule
//!
//! Inside this crate, a name that exists in `core` or `alloc` must be imported
//! as `crate::compat::Name`, never as `std::Name`. The re-exports below resolve
//! to the same types today (this build links std regardless), so the rule buys
//! nothing at present except that it is already true at every one of the ~120
//! call sites when `no_std` is switched on. A direct `use std::...` is the one
//! thing that would have to be undone everywhere, which is why the ban is on the
//! import rather than on the capability.
//!
//! # What this module is *not*
//!
//! Switching `mini` to `no_std` is **not** simply a matter of enabling the
//! attribute: the `#[cfg(alloc_frugal)]` arms below are written for a single
//! threaded, allocation-frugal target, but several are still backed by `std`
//! types (`RwLock`, `Mutex`, `Instant`, `RwLock`-guarded `Condvar` paths, and the
//! `std::sync::mpsc` re-export). Do not read the presence of a `no_std`-shaped
//! alias here as evidence that its `alloc_frugal` arm is `no_std`-clean.

// ── core re-exports (exported unconditionally, always available) ──
pub use core::any::Any;
pub use core::cell::{Cell, RefCell};
pub use core::fmt;
pub use core::hash::{Hash, Hasher};
pub use core::sync::atomic;
pub use core::time::Duration;

// ── RwLock (thread-safe in both profiles) ──
// Under mini (which compiles on std), re-uses the battle-tested std RwLock
// instead of a RefCell wrapper. A RefCell-backed "RwLock" would panic on
// concurrent access (e.g. tests sharing a global), which is not a real lock.
pub use std::sync::RwLock;

// ── alloc re-exports (available in both std and no_std) ──
pub use alloc::boxed::Box;
pub use alloc::collections::BTreeMap;
pub use alloc::collections::VecDeque;
pub use alloc::format;
pub use alloc::rc::Rc;
pub use alloc::string::{String, ToString};
pub use alloc::sync::Arc;
pub use alloc::vec;
pub use alloc::vec::Vec;

// ── heapless/MiniVec for compile-time fixed-size collections (BLUE13 R5.3-R5.4) ──
// Under mini, Vec and String are replaced with fixed-capacity alternatives.
// Under desktop/full, they remain dynamic (alloc::vec::Vec, alloc::string::String).

/// Fixed-capacity vector for mini builds. Falls back to `Vec<T>` on desktop.
///
/// Under `alloc_frugal` this is `heapless::Vec<T, 64>`: **pushing beyond 64
/// elements fails** rather than reallocating. Under desktop builds it is an
/// ordinary growable `alloc::vec::Vec<T>`, so code must not rely on the
/// capacity limit being enforced.
#[cfg(alloc_frugal)]
pub type MiniVec<T> = heapless::Vec<T, 64>;
/// Growable vector alias used on desktop builds; see the `alloc_frugal`
/// definition for the capacity-limited variant.
#[cfg(not(alloc_frugal))]
pub type MiniVec<T> = alloc::vec::Vec<T>;

/// Fixed-capacity string for mini builds. Falls back to `String` on desktop.
///
/// Under `alloc_frugal` this is `heapless::String<256>`, so at most 256 bytes
/// of UTF-8 are retained; see [`into_mini`], which silently truncates on
/// overflow. Under desktop builds it is an unbounded `alloc::string::String`.
#[cfg(alloc_frugal)]
pub type MiniString = heapless::String<256>;
/// Growable string alias used on desktop builds; see the `alloc_frugal`
/// definition for the capacity-limited variant.
#[cfg(not(alloc_frugal))]
pub type MiniString = alloc::string::String;

/// Convert a `&str` to `MiniString`. Under mini, copies into fixed buffer.
/// Under desktop, creates an owned `String`.
///
/// Truncation is **silent** under `alloc_frugal`: the `heapless` push fails on
/// the byte that would cross 256, so the result is the longest whole-prefix of
/// `s` that fits, cut at a UTF-8 boundary, with no error reported. A caller that
/// must know the text survived intact has to compare lengths.
pub fn into_mini(s: &str) -> MiniString {
    #[cfg(alloc_frugal)]
    {
        let mut ms = MiniString::new();
        let _ = ms.push_str(s);
        ms
    }
    #[cfg(not(alloc_frugal))]
    {
        MiniString::from(s)
    }
}

/// Convert a `String` to `MiniString` (consumes the String).
/// Under mini, copies into fixed buffer. Under desktop, zero-cost.
///
/// Under `alloc_frugal` the original heap `String` is dropped after being copied
/// into the fixed buffer, so this is not a move — the allocation is released and
/// the same silent 256-byte truncation as [`into_mini`] applies. Under desktop
/// it is a genuine no-op move.
pub fn mini_string_from(s: String) -> MiniString {
    #[cfg(alloc_frugal)]
    {
        into_mini(&s)
    }
    #[cfg(not(alloc_frugal))]
    {
        s
    }
}

// ── std→alloc bridge (conditional: BTreeMap stands in for HashMap under mini) ──
/// Map type used across the crate, so call sites do not name a concrete map.
///
/// Resolves to `std::collections::HashMap` on desktop builds and to
/// `alloc::collections::BTreeMap` under `alloc_frugal`. The two are only
/// interchangeable through this alias: they do not share an implementation, and
/// the difference is observable in iteration order (hashed vs sorted by key) and
/// in the key requirements — `BTreeMap` needs `Ord` where `HashMap` needs `Hash`.
/// Code that relies on either property through this alias will not compile, or
/// will silently change behaviour, on the other profile; treat it as an
/// unordered map.
#[cfg(alloc_frugal)]
pub use alloc::collections::BTreeMap as HashMap;
#[cfg(not(alloc_frugal))]
pub use std::collections::HashMap;

// ── Mutex (thread-safe in both profiles) ──
// Under mini (which compiles on std), re-uses the battle-tested std Mutex
// instead of a RefCell wrapper. A RefCell-backed "Mutex" panics on
// re-entrant/concurrent access — not a real mutual-exclusion primitive.
/// Mutual-exclusion lock used across the crate; `std::sync::Mutex` under both
/// profiles, because `mini` still links std.
///
/// Poisoning is a real possibility here (unlike the `no_std` plan, where the
/// lock would have no poison state), so call sites handle the `Err` arm by
/// recovering the guard.
pub use std::sync::Mutex;
/// Guard returned by [`Mutex::lock`]. Its lifetime ties the guard to the lock, so
/// it cannot outlive the mutex it came from.
pub use std::sync::MutexGuard;

// ── Bump arena allocator (BLUE13 R5.5) ──
// Under mini, a pre-allocated bump arena replaces the global heap allocator.
// This eliminates the need for a full `alloc` runtime while keeping Box-like
// allocation via `arena_box()`. The arena is reset on each frame cycle.

/// Bump arena allocator. On mini, backed by a single-threaded `bumpalo::Bump`.
/// On desktop, this is a no-op wrapper (allocation goes through the global allocator).
///
/// # Invariants
///
/// * **Single-threaded.** The safety of the aliasing rules below rests on `mini`
///   never running the arena from two threads; there is no synchronisation
///   inside it.
/// * **Nothing is freed until [`MiniArena::reset`].** A dropped arena value, a
///   dropped allocation, a dropped box — none of them release the backing block.
///   `reset` frees *everything* at once, so it invalidates every reference the
///   arena has handed out.
/// * **The returned references are not tied to a borrow.** See
///   [`MiniArena::alloc`].
///
/// Under `not(alloc_frugal)` this is a zero-sized type; see the desktop
/// definition below.
#[cfg(alloc_frugal)]
pub struct MiniArena {
    // Use UnsafeCell instead of RefCell because bumpalo::Bump::alloc() returns
    // references tied to &self, which is incompatible with temporary RefMut guards.
    // Under mini (single-threaded), this is safe.
    bump: core::cell::UnsafeCell<bumpalo::Bump>,
}

#[cfg(alloc_frugal)]
impl MiniArena {
    /// Create a new arena with default capacity (~16KB).
    ///
    /// The ~16 KiB is `bumpalo::Bump::new()`'s first chunk; the arena grows in
    /// further chunks on demand, so this is a starting size and not a cap.
    pub fn new() -> Self {
        Self { bump: core::cell::UnsafeCell::new(bumpalo::Bump::new()) }
    }

    /// Allocate a value in the arena. Returns a mutable reference.
    /// The value lives until the arena is reset.
    // NOTE: `&self -> &mut T` is the arena contract — the returned reference is
    // exclusive until `reset()` because the arena is single-threaded under mini.
    ///
    /// # Why `&self` yields `&mut T`
    ///
    /// `&self` is taken so a caller can allocate through a `&'static MiniArena`
    /// (see [`frame_arena`]) without a mutable borrow of a global. The exclusivity
    /// of the result is therefore a *convention*, not something the compiler
    /// checks: two live references to the same allocation, or a reference that is
    /// still in use when [`Self::reset`] runs, are undefined behaviour. The value
    /// is moved into the arena and is dropped only when the arena resets, so it
    /// must not own a resource whose release is time-critical.
    #[allow(clippy::mut_from_ref)]
    pub fn alloc<T>(&self, val: T) -> &mut T {
        // SAFETY: Under mini (single-threaded), no concurrent access.
        // The Bump is only borrowed mutably here, and the returned reference
        // is valid until reset() is called.
        unsafe { (*self.bump.get()).alloc(val) }
    }

    /// Allocate a slice by copying from an iterator.
    // NOTE: Same arena contract as `alloc` — see above.
    ///
    /// `T: Copy` rather than `T: Clone` because the source is copied bytewise
    /// into the arena; the returned slice is arena-owned and carries the same
    /// lifetime convention as [`Self::alloc`] — inclusive of the requirement that
    /// it must not outlive a [`Self::reset`].
    #[allow(clippy::mut_from_ref)]
    pub fn alloc_slice<T: Copy>(&self, slice: &[T]) -> &mut [T] {
        // SAFETY: Same reasoning as alloc().
        unsafe { (*self.bump.get()).alloc_slice_copy(slice) }
    }

    /// Reset the arena, freeing all allocations.
    ///
    /// This is the only way memory returns to the allocator, and it is total:
    /// every reference the arena has handed out is dangling afterwards. Callers
    /// must stop using them (and drop anything holding one) before calling this,
    /// which is why the frame cycle that calls it also has to know that no
    /// frame-scoped value outlives the frame.
    ///
    /// The arena stays usable afterwards and keeps its largest chunk, so a reset
    /// between frames does not re-grow from scratch.
    pub fn reset(&self) {
        // SAFETY: Under mini (single-threaded), no concurrent access.
        unsafe {
            (*self.bump.get()).reset();
        }
    }

    /// Remaining capacity hint.
    ///
    /// Returns the number of bytes currently **allocated** from this arena, in
    /// bytes — not the remaining headroom, despite the name. Compare it against
    /// the budget the caller has in mind, or against a previous reading to see
    /// how much a frame accounted for; it falls back to zero after a reset.
    pub fn allocated_bytes(&self) -> usize {
        // SAFETY: allocated_bytes() is a read-only operation safe under single-threaded.
        unsafe { (*self.bump.get()).allocated_bytes() }
    }
}

#[cfg(alloc_frugal)]
crate::impl_default_via_new!(MiniArena);

#[cfg(not(alloc_frugal))]
#[derive(Default)]
/// No-op arena used on desktop builds.
///
/// Allocation is delegated to the global allocator, and [`MiniArena::reset`]
/// does nothing because there is nothing arena-owned to free. It exists so the
/// arena call sites compile unchanged on both profiles.
///
/// It is zero-sized, so this type costs nothing to pass around, and the methods
/// below deliberately differ in signature from the `alloc_frugal` ones — see
/// [`MiniArena::alloc`] — because a global-heap allocation *is* owned by its
/// caller rather than borrowed from a shared arena.
pub struct MiniArena;

#[cfg(not(alloc_frugal))]
impl MiniArena {
    /// Creates the desktop no-op arena; there is exactly one, but constructing
    /// extra values is harmless since it carries no state.
    pub const fn new() -> Self {
        Self
    }
    /// Allocates on the global heap and returns an owning `Box<T>`.
    ///
    /// Unlike the `alloc_frugal` version, the result is a normal owned pointer
    /// that is freed when dropped rather than borrowed from an arena.
    pub fn alloc<T>(&self, val: T) -> alloc::boxed::Box<T> {
        alloc::boxed::Box::new(val)
    }
    /// Copies `slice` into a freshly allocated `Vec<T>` owned by the caller.
    ///
    /// The `Vec` is returned by value and is freed when it is dropped; unlike the
    /// `alloc_frugal` version, the copy is not borrowed from an arena and there is
    /// no `reset` that would invalidate it.
    pub fn alloc_slice<T: Copy>(&self, slice: &[T]) -> alloc::vec::Vec<T> {
        slice.to_vec()
    }
    /// No-op on desktop: nothing is arena-owned, so there is nothing to free.
    ///
    /// In particular it does **not** free the `Box`es and `Vec`s returned by
    /// [`Self::alloc`] / [`Self::alloc_slice`]; those are owned by their callers.
    pub fn reset(&self) {}
    /// Always `0` on desktop, because no bytes are tracked by this no-op arena.
    /// Do not use this as a memory-usage measurement.
    pub fn allocated_bytes(&self) -> usize {
        0
    }
}

/// Get the global frame arena. Under mini, allocations live until `reset_frame_arena()`.
/// Under desktop, this is a no-op (uses `Box::new` directly).
///
/// The arena is process-global, so every caller shares one allocation pool and a
/// [`reset_frame_arena`] from any of them invalidates all of them. Under
/// `alloc_frugal` it is initialised on first use through [`OnceLock`], so the
/// first call allocates and later ones do not.
pub fn frame_arena() -> &'static MiniArena {
    #[cfg(alloc_frugal)]
    {
        // Use compat OnceLock which is unconditionally Sync under mini.
        static ARENA: OnceLock<MiniArena> = OnceLock::new();
        ARENA.get_or_init(MiniArena::new)
    }
    #[cfg(not(alloc_frugal))]
    {
        static ARENA: MiniArena = MiniArena::new();
        &ARENA
    }
}

/// Reset the global frame arena. Under mini, frees all arena allocations.
/// Under desktop, this is a no-op.
///
/// The word "frame" is a convention, not a clock: nothing calls this
/// automatically, so a build that never calls it never reclaims arena memory.
/// Under `alloc_frugal` it must be called at a point where no arena reference is
/// still live (see [`MiniArena::reset`]).
pub fn reset_frame_arena() {
    frame_arena().reset();
}

// ── OnceLock compat (thread-safe static init for both std and no_std) ──

/// Thread-safe once-cell for static initialization.
/// Under mini (no_std), backed by a spin-based atomic flag + UnsafeCell.
/// Under desktop, re-exports `std::sync::OnceLock`.
///
/// # Why not `std::sync::OnceLock`
///
/// `std`'s version is the default whenever the symlink below resolves to it; this
/// type exists for the `alloc_frugal` arm, where the cell has to be constructible
/// in a `static` (`const fn new`) and usable without the std runtime.
///
/// # Thread safety
///
/// `Send` and `Sync` are asserted unconditionally below even though the type
/// holds a `UnsafeCell<MaybeUninit<T>>` and never synchronises a *second*
/// initialiser: the initialisation path is a plain load, a write, and a store,
/// with no compare-exchange, so two threads racing [`OnceLock::get_or_init`] on
/// the same cell would both write. That is sound only because `mini` is
/// single-threaded. [`OnceLock::set`] is the exception — it does use a
/// compare-exchange, so it reports the loser rather than overwriting.
#[cfg(alloc_frugal)]
pub struct OnceLock<T> {
    initialized: core::sync::atomic::AtomicBool,
    data: core::cell::UnsafeCell<core::mem::MaybeUninit<T>>,
}

#[cfg(alloc_frugal)]
impl<T> OnceLock<T> {
    /// Creates an empty cell. `const`, so it can initialise a `static` directly.
    pub const fn new() -> Self {
        Self {
            initialized: core::sync::atomic::AtomicBool::new(false),
            data: core::cell::UnsafeCell::new(core::mem::MaybeUninit::uninit()),
        }
    }

    /// Returns the cell's value, initialising it with `f` if this is the first
    /// call.
    ///
    /// `f` runs at most once *when calls are serialised*; see the type-level note
    /// on concurrency. The returned reference is valid for as long as the cell is,
    /// and the value is never dropped — a `OnceLock` in a `static` leaks its
    /// contents at process exit, which is the intended meaning of "lives
    /// forever".
    pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T {
        if !self.initialized.load(core::sync::atomic::Ordering::Acquire) {
            let val = f();
            // SAFETY: Under mini (single-threaded), no concurrent access is possible.
            // The Acquire-Release ordering on `initialized` guarantees that the write
            // in `get_or_init` is visible to any subsequent `get` call.
            unsafe {
                (*self.data.get()).write(val);
            }
            self.initialized.store(true, core::sync::atomic::Ordering::Release);
        }
        // SAFETY: Once `initialized` is true, the data has been written and will not
        // be mutated again. The Acquire ordering ensures we see the write above.
        unsafe { (*self.data.get()).assume_init_ref() }
    }

    /// Returns the value if it has been set, without initialising it.
    ///
    /// Returns `None` for a never-initialised cell. There is no way to tell a cell
    /// whose `f` has not run from one whose `f` has not been *provided* — this
    /// method never takes one — so it is only useful after some other code has
    /// populated the cell.
    pub fn get(&self) -> Option<&T> {
        if self.initialized.load(core::sync::atomic::Ordering::Acquire) {
            // SAFETY: Same as get_or_init — once initialized, data is immutable.
            Some(unsafe { (*self.data.get()).assume_init_ref() })
        } else {
            None
        }
    }

    /// Stores a value, mirroring `std::sync::OnceLock::set`.
    ///
    /// Returns `Ok(())` on first initialization, or `Err(value)` with the
    /// rejected value if the cell was already set.
    ///
    /// Unlike [`Self::get_or_init`], the already-set case is detected with a
    /// compare-exchange, so this is safe against a racing writer and returns the
    /// value rather than dropping it.
    pub fn set(&self, value: T) -> Result<(), T> {
        if self
            .initialized
            .compare_exchange(
                false,
                true,
                core::sync::atomic::Ordering::AcqRel,
                core::sync::atomic::Ordering::Acquire,
            )
            .is_ok()
        {
            // SAFETY: We won the compare-exchange race, so this is the only
            // writer and no reader can observe the cell until the Release store
            // above flips `initialized`. Under mini (single-threaded) there is
            // no concurrent access; the ordering keeps the API equivalent to std.
            unsafe {
                (*self.data.get()).write(value);
            }
            Ok(())
        } else {
            Err(value)
        }
    }
}

#[cfg(alloc_frugal)]
impl<T> Default for OnceLock<T> {
    /// An empty cell, same as [`OnceLock::new`].
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(alloc_frugal)]
// SAFETY: Under mini (no_std, single-threaded), no concurrent access is possible.
unsafe impl<T> Sync for OnceLock<T> {}
#[cfg(alloc_frugal)]
unsafe impl<T> Send for OnceLock<T> {}

#[cfg(not(alloc_frugal))]
pub use std::sync::OnceLock;

// ── Instant (real clock in both profiles) ──
// Under mini (which compiles on std), re-uses the real std clock. A zero-valued
// stub would silently break every timing-based subsystem (timers, FPS counters,
// animation frames) — not a working implementation.
/// Monotonic clock reading used across the crate.
///
/// Both profiles resolve to `std::time::Instant`, because `mini` still links std.
/// Chosen over a zero-valued stub so timing-based subsystems (timers, FPS
/// counters, animation frames) keep working under `mini`; the cost is that this
/// name is one of the re-exports that is *not* `no_std`-ready, and the ban on
/// importing `std::time::Instant` directly does not change that.
pub use std::time::Instant;

// ── mpsc compat (single-threaded channel for mini builds) ──

/// Single-threaded channel for mini (no_std) builds.
/// Wraps a `VecDeque` behind `RefCell` + `Arc`.
///
/// # Not a real channel
///
/// `std::sync::mpsc` blocks in `Receiver::recv`; this one **cannot**, because
/// there is no second thread to wake it. `recv` is defined as a non-blocking poll
/// that reports `Err(())` — the same shape an empty `try_recv` has — so waiters
/// written for the std API must poll instead. `mini`'s event loop does exactly
/// that: it drains with `dequeue()` rather than `dequeue_blocking()`. A caller
/// that reaches for `recv` expecting it to wait will spin or give up early, not
/// block.
///
/// A side effect of the std-shaped surface is that the exact failure reason is
/// lost: there is no `TryRecvError` here, so "empty" and "disconnected" are both
/// `Err(())`. Sharing the queue through `Arc<RefCell<..>>` also means a re-entrant
/// `send` from inside a `recv` would panic on the borrow, and the pair is `!Send`
/// and `!Sync` — deliberately, since it is single-threaded by construction.
#[cfg(alloc_frugal)]
pub mod mpsc {
    use alloc::collections::VecDeque;
    use alloc::sync::Arc;
    use core::cell::RefCell;

    /// Sending half of the channel; cloning shares the same queue.
    pub struct Sender<T> {
        inner: Arc<RefCell<VecDeque<T>>>,
    }

    impl<T> Clone for Sender<T> {
        /// Shares the queue rather than duplicating it, so every clone delivers to
        /// the same receiver.
        fn clone(&self) -> Self {
            Self { inner: self.inner.clone() }
        }
    }

    impl<T> Sender<T> {
        /// Appends `value` to the queue.
        ///
        /// Always succeeds, even with no receiver left — the queue is unbounded and
        /// does not track whether the receiving half is still alive, so a `Sender`
        /// held after the `Receiver` is dropped just grows a queue nobody reads.
        ///
        /// The `Result<(), ()>` return mirrors `std::sync::mpsc`; this arm never
        /// takes the `Err`.
        // `Result<(), ()>` mirrors the `std::sync::mpsc` API shape.
        #[allow(clippy::result_unit_err)]
        pub fn send(&self, value: T) -> Result<(), ()> {
            self.inner.borrow_mut().push_back(value);
            Ok(())
        }
    }

    /// Receiving half of the channel.
    pub struct Receiver<T> {
        inner: Arc<RefCell<VecDeque<T>>>,
    }

    impl<T> Receiver<T> {
        /// Removes and returns the oldest queued value, or `Err(())` when empty.
        ///
        /// The `Err` carries no reason: see [`Sender`] for why "empty" and
        /// "disconnected" are indistinguishable here.
        #[allow(clippy::result_unit_err)]
        pub fn try_recv(&self) -> Result<T, ()> {
            self.inner.borrow_mut().pop_front().ok_or(())
        }
        /// Removes and returns the oldest queued value, or `Err(())` when empty.
        ///
        /// **Does not block**, unlike `std::sync::mpsc::Receiver::recv` whose name it
        /// takes. There is no thread to wait for under `mini`, so an empty queue is
        /// reported immediately; a caller that must wait has to poll.
        ///
        /// This is kept only so that the profile-independent call sites compile
        /// unchanged; it is an alias for [`Self::try_recv`]. Callers that could block
        /// are gated `not(alloc_frugal)` instead of relying on this method's name —
        /// see [`crate::event::queue`].
        #[allow(clippy::result_unit_err)]
        pub fn recv(&self) -> Result<T, ()> {
            // No threads under mini, so there is nothing to wait on —
            // return the first available value or an error.
            self.inner.borrow_mut().pop_front().ok_or(())
        }
    }

    /// Creates a connected sender/receiver pair over one shared queue.
    ///
    /// The queue starts empty and grows without bound; its capacity is bounded
    /// only by the values the caller posts. The pair is `!Send`, so it cannot be
    /// moved to another thread — see the module-level note.
    pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
        let inner = Arc::new(RefCell::new(VecDeque::new()));
        (Sender { inner: inner.clone() }, Receiver { inner })
    }
}

#[cfg(not(alloc_frugal))]
pub use std::sync::mpsc;

// ── Condvar compat (no_std stub for mini builds) ──

/// A condition variable for thread synchronization.
/// Under mini, all operations are no-ops (single-threaded).
/// Under desktop, re-exports `std::sync::Condvar`.
///
/// # This one is a genuine stub
///
/// The `alloc_frugal` version below is **not** a usable condition variable: it has
/// no `wait` and no `wait_timeout`, so it cannot park a caller, and both notify
/// methods do nothing. Code that needs to wait cannot be written against this
/// type at all — which is why the crate's waiting queues are gated the other way
/// around (see [`crate::event::queue`], whose blocking paths are
/// `not(alloc_frugal)`). The desktop alias is the real thing.
#[cfg(alloc_frugal)]
pub struct Condvar;

#[cfg(alloc_frugal)]
impl Condvar {
    /// Creates the stub. `const`-compatible, and carries no state.
    pub fn new() -> Self {
        Self
    }
    /// Does nothing: there is no waiter to wake.
    pub fn notify_all(&self) {}
    /// Does nothing: there is no waiter to wake.
    pub fn notify_one(&self) {}
}

#[cfg(alloc_frugal)]
crate::impl_default_via_new!(Condvar);

#[cfg(not(alloc_frugal))]
/// A condition variable for thread synchronization.
///
/// The real `std::sync::Condvar`, re-exported so call sites need no profile
/// branch. Unlike the `alloc_frugal` stub it has `wait` / `wait_timeout`, which is
/// what makes the blocking paths of `crate::event::queue` possible on this
/// profile.
pub use std::sync::Condvar;