1
//! Shared datatypes for azul-* crates
2
//!
3
//! `azul-core` provides the platform-independent core types used throughout
4
//! the Azul toolkit.
5
//!
6
//! Key modules include [`dom`] for DOM construction, [`callbacks`] for event
7
//! callback types, [`styled_dom`] for the CSSOM, and [`window`] for OS
8
//! windowing abstractions.
9
//!
10
//! This crate depends on [`azul_css`] for CSS property definitions and is
11
//! consumed by `azul-layout`, `azul-dll`, and the platform shell crates.
12
//! It supports `no_std` environments via `#![cfg_attr(not(feature = "std"), no_std)]`.
13

            
14
#![cfg_attr(not(feature = "std"), no_std)]
15
// Lint policy: deny correctness/safety issues, warn on style
16
#![deny(unused_must_use)]
17
#![warn(clippy::all)]
18
// Extreme-lint lockdown: all clippy groups plus opt-in rustc lints, enforced as
19
// -D warnings on library code by the CI clippy job. Test builds are exempt via
20
// cfg(not(test)) below since the set is high-noise and low-value on unit and
21
// generated tests; clippy::all correctness still applies to test code.
22
// (clippy::restriction wholesale + unused_results + box_pointers deliberately
23
// omitted — contradictory / overwhelmingly noisy by design.)
24
#![cfg_attr(not(test), warn(
25
    clippy::pedantic,
26
    clippy::nursery,
27
    clippy::cargo,
28
    // missing_docs,  // TODO(docs): re-enable as a dedicated final docs pass; disabled
29
    //                // for now so the cleanup focuses on code-quality lints, not doc debt.
30
    missing_debug_implementations,
31
    missing_copy_implementations,
32
    unreachable_pub,
33
    unused_qualifications,
34
    unused_lifetimes,
35
    unused_import_braces,
36
    unused_macro_rules,
37
    unused_crate_dependencies,
38
    meta_variable_misuse,
39
    trivial_casts,
40
    trivial_numeric_casts,
41
    elided_lifetimes_in_paths,
42
    single_use_lifetimes,
43
    variant_size_differences,
44
    non_ascii_idents,
45
    unsafe_op_in_unsafe_fn,
46
    let_underscore_drop,
47
))]
48
// `multiple_crate_versions` (implied by clippy::cargo) flags transitive
49
// dependency-version dups that cannot be resolved in azul's own source:
50
// `syn` 1.0.x ↔ 2.0.x (the proc-macro ecosystem is mid-migration; both are
51
// pulled in transitively). Documented allow — re-audit when the dep tree aligns.
52
#![allow(clippy::multiple_crate_versions)]
53
#![allow(
54
    clippy::non_canonical_partial_ord_impl,
55
    clippy::legacy_numeric_constants,
56
    clippy::should_implement_trait,
57
    clippy::result_unit_err,
58
    clippy::ptr_as_ptr,
59
    clippy::too_many_arguments,
60
    clippy::type_complexity,
61
    unused_imports,
62
    unused_variables,
63
    unused_mut,
64
    unused_parens,
65
    dead_code,
66
    unused_doc_comments,
67
    unused_assignments,                    // compact_cache_builder incremental updates
68
    unexpected_cfgs,
69
    unpredictable_function_pointer_comparisons, // intentional in dom callback comparison
70
    improper_ctypes_definitions,           // xml component fns use Rust fn pointers internally
71
    static_mut_refs,                       // TODO: migrate to OnceLock for Rust 2024
72
)]
73

            
74
// `extern crate` + `#[macro_use]` required for `no_std` support:
75
// makes `core` and `alloc` macros available without `use` imports.
76
#[macro_use]
77
extern crate core;
78
#[macro_use]
79
extern crate alloc;
80
#[macro_use]
81
extern crate azul_css;
82

            
83
// clippy reports `too_long_first_doc_paragraph` here with a span that starts
84
// in the crate-level `//!` doc far above and ends on this one-line `///`,
85
// measuring the two as a single paragraph. The doc below is one short line;
86
// re-paragraphing the crate doc does not move it, and a crate-level allow does
87
// not apply to it. A genuine instance of this lint — a doc comment cut in half
88
// by `#[derive]` / `#[repr]` attributes — was fixed properly in `callbacks.rs`.
89
#[allow(clippy::too_long_first_doc_paragraph)]
90
/// Internal macros for `Vec`, `Option`, and callback boilerplate.
91
#[macro_use]
92
pub mod macros;
93
/// Debug logging system with category filtering.
94
#[macro_use]
95
pub mod debug;
96
/// SQL database POD types — `DbValue` + `DbRows` (engine-agnostic). The
97
/// `Db` handle + SQLite engine live in `azul_dll` behind `db-sqlite`.
98
pub mod db;
99
/// Unified `AZ_PROFILE` gate for memory and CPU profiling instrumentation.
100
pub mod profile;
101
/// `no_std`-friendly synchronization primitives.
102
///
103
/// In `std` builds these re-export the matching `std::sync` types. In
104
/// `no_std` builds they provide minimal spinlock-backed equivalents
105
/// implementing only the API surface azul-core relies on.
106
pub mod sync {
107
    #[cfg(feature = "std")]
108
    pub use std::sync::OnceLock;
109

            
110
    #[cfg(not(feature = "std"))]
111
    pub use self::nostd::OnceLock;
112

            
113
    #[cfg(not(feature = "std"))]
114
    mod nostd {
115
        use core::{
116
            cell::UnsafeCell,
117
            sync::atomic::{AtomicU8, Ordering},
118
        };
119

            
120
        const UNINIT: u8 = 0;
121
        const BUSY: u8 = 1;
122
        const READY: u8 = 2;
123

            
124
        /// Minimal `no_std` `OnceLock` mirroring the slice of the std API used
125
        /// by azul-core (`new`, `get`, `get_or_init`).
126
        pub struct OnceLock<T> {
127
            state: AtomicU8,
128
            value: UnsafeCell<Option<T>>,
129
        }
130

            
131
        unsafe impl<T: Send + Sync> Sync for OnceLock<T> {}
132
        unsafe impl<T: Send> Send for OnceLock<T> {}
133

            
134
        impl<T> OnceLock<T> {
135
            pub const fn new() -> Self {
136
                OnceLock {
137
                    state: AtomicU8::new(UNINIT),
138
                    value: UnsafeCell::new(None),
139
                }
140
            }
141

            
142
            pub fn get(&self) -> Option<&T> {
143
                if self.state.load(Ordering::Acquire) == READY {
144
                    unsafe { (*self.value.get()).as_ref() }
145
                } else {
146
                    None
147
                }
148
            }
149

            
150
            pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T {
151
                if let Some(v) = self.get() {
152
                    return v;
153
                }
154
                // Contend for the right to initialize.
155
                while self
156
                    .state
157
                    .compare_exchange(UNINIT, BUSY, Ordering::Acquire, Ordering::Acquire)
158
                    .is_err()
159
                {
160
                    if self.state.load(Ordering::Acquire) == READY {
161
                        return self.get().expect("OnceLock ready");
162
                    }
163
                    core::hint::spin_loop();
164
                }
165
                unsafe {
166
                    *self.value.get() = Some(f());
167
                }
168
                self.state.store(READY, Ordering::Release);
169
                self.get().expect("OnceLock initialized")
170
            }
171
        }
172

            
173
        impl<T> Default for OnceLock<T> {
174
            fn default() -> Self {
175
                Self::new()
176
            }
177
        }
178

            
179
        impl<T: core::fmt::Debug> core::fmt::Debug for OnceLock<T> {
180
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
181
                f.debug_tuple("OnceLock").field(&self.get()).finish()
182
            }
183
        }
184

            
185
        impl<T: Clone> Clone for OnceLock<T> {
186
            fn clone(&self) -> Self {
187
                let new = OnceLock::new();
188
                if let Some(v) = self.get() {
189
                    let _ = new.get_or_init(|| v.clone());
190
                }
191
                new
192
            }
193
        }
194

            
195
        impl<T: PartialEq> PartialEq for OnceLock<T> {
196
            fn eq(&self, other: &Self) -> bool {
197
                self.get() == other.get()
198
            }
199
        }
200
    }
201
}
202

            
203
/// `no_std`-friendly default hasher used for change-detection hashing.
204
///
205
/// In `std` builds this re-exports `std::hash::DefaultHasher` so behaviour
206
/// is unchanged. In `no_std` builds it provides a small deterministic
207
/// `FxHasher`-style hasher implementing `core::hash::Hasher`. The values are
208
/// only required to be stable within a single process run (they back diffing /
209
/// change detection), not to match `std`'s `SipHash` output.
210
pub mod hash {
211
    #[cfg(feature = "std")]
212
    pub use std::hash::DefaultHasher;
213

            
214
    #[cfg(not(feature = "std"))]
215
    pub use self::nostd::DefaultHasher;
216

            
217
    #[cfg(not(feature = "std"))]
218
    mod nostd {
219
        use core::hash::Hasher;
220

            
221
        const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
222
        const ROTATE: u32 = 5;
223

            
224
        /// FxHasher-style `no_std` hasher. Not DoS-resistant; used purely for
225
        /// in-process change detection.
226
        #[derive(Default)]
227
        pub struct DefaultHasher {
228
            hash: u64,
229
        }
230

            
231
        impl DefaultHasher {
232
            pub fn new() -> Self {
233
                DefaultHasher { hash: 0 }
234
            }
235

            
236
            #[inline]
237
            fn add(&mut self, word: u64) {
238
                self.hash = (self.hash.rotate_left(ROTATE) ^ word).wrapping_mul(SEED);
239
            }
240
        }
241

            
242
        impl Hasher for DefaultHasher {
243
            #[inline]
244
            fn finish(&self) -> u64 {
245
                self.hash
246
            }
247

            
248
            #[inline]
249
            fn write(&mut self, bytes: &[u8]) {
250
                for chunk in bytes.chunks(8) {
251
                    let mut buf = [0u8; 8];
252
                    buf[..chunk.len()].copy_from_slice(chunk);
253
                    self.add(u64::from_le_bytes(buf));
254
                }
255
            }
256

            
257
            #[inline]
258
            fn write_u8(&mut self, i: u8) {
259
                self.add(i as u64);
260
            }
261
            #[inline]
262
            fn write_u64(&mut self, i: u64) {
263
                self.add(i);
264
            }
265
            #[inline]
266
            fn write_usize(&mut self, i: usize) {
267
                self.add(i as u64);
268
            }
269
        }
270
    }
271
}
272
/// Callback types: layout, event, timer, thread, and focus handling.
273
#[macro_use]
274
pub mod callbacks;
275
/// Host-language callback invoker registry.
276
///
277
/// The C-ABI surface managed-FFI bindings (Lua, Ruby, …) use to register one
278
/// per-kind invoker + a single shared releaser, so callbacks can be created via
279
/// `_createFromHostHandle` without the host having to generate trampolines for
280
/// struct-by-value signatures their FFI library can't handle.
281
#[macro_use]
282
/// The host-invoker ABI: how a foreign-language binding routes a callback back into its runtime.
283
pub mod host_invoker;
284
/// Accessibility tree: roles, states and the actions assistive tech can invoke.
285
pub mod a11y;
286
/// Accessibility types for screen-reader integration (AccessKit).
287
/// DOM-morph animation.
288
///
289
/// Interpolation core (springs + easing), FLIP geometry, and the keyed
290
/// store of in-flight animations..
291
pub mod animation;
292
/// Audio POD types — `AudioConfig` (stream format) + `AudioFrame` (interleaved
293
/// f32 samples).
294
///
295
/// The unit captured from the mic, played back, and (P8) shared
296
/// over UDP. Backend (rodio / cpal / AVAudioEngine / AAudio) lives dll-side.
297
pub mod audio;
298
/// Biometric-auth POD types — `BiometricKind` + `BiometricResult` + `BiometricPrompt`.
299
///
300
/// Stateful manager lives in `azul_layout::managers::biometric`.
301
pub mod biometric;
302
/// Camera-capture POD types — `CaptureStreamId` + `CameraConfig` +
303
/// `CameraFacing` + `StreamState` + … .
304
///
305
/// The stateful `CameraStream` /
306
/// `CameraManager` (which own the shared `ImageRef` texture) live in
307
/// `azul_layout::managers::camera`.
308
pub mod camera;
309
/// Converts `CssPropertyCache` into compact three-tier numeric cache.
310
pub mod compact;
311
/// Linear-time DOM diffing for incremental updates.
312
pub mod diagnostics;
313
/// DOM diffing: what changed between two `StyledDom`s, and how far it has to be re-solved.
314
pub mod diff;
315
/// DOM construction: `Dom`, `NodeData`, `NodeType`, and the CSS-in-Rust API.
316
pub mod dom;
317
/// Drag context for text selection, scrollbar, node, and window drags.
318
pub mod drag;
319
/// Event filtering: mouse, keyboard, window, and synthetic events.
320
pub mod events;
321
/// Form constraint validation - the `ValidityState` an `Invalid` event
322
/// explains itself with. The rules live in `azul_layout::form`.
323
pub mod form;
324
/// Gamepad POD types — `GamepadId` + `GamepadButton` + `GamepadAxis` +
325
/// `GamepadState`.
326
///
327
/// Stateful manager lives in `azul_layout::managers::gamepad`.
328
pub mod gamepad;
329
/// Geolocation POD types — `LocationFix` + `GeolocationProbeConfig`.
330
///
331
/// Stateful manager lives in `azul_layout::managers::geolocation`.
332
pub mod geolocation;
333
/// Logical and physical coordinate types (`LogicalSize`, `PhysicalPosition`, etc.).
334
pub mod geom;
335
// clippy reports `too_long_first_doc_paragraph` here with a span that starts
336
// in the crate-level `//!` doc far above and ends on this one-line `///`,
337
// measuring the two as a single paragraph. The doc below is one short line;
338
// re-paragraphing the crate doc does not move it, and a crate-level allow does
339
// not apply to it. A genuine instance of this lint — a doc comment cut in half
340
// by `#[derive]` / `#[repr]` attributes — was fixed properly in `callbacks.rs`.
341
#[allow(clippy::too_long_first_doc_paragraph)]
342
/// OpenGL context wrappers, shader compilation, and texture cache.
343
pub mod gl;
344
/// FXAA (Fast Approximate Anti-Aliasing) shader.
345
pub mod gl_fxaa;
346
/// OpenGL constants (GL 1.1 through GL 4.x).
347
pub mod glconst;
348
/// GPU value cache for CSS transforms and opacity.
349
pub mod gpu;
350
/// Haptic feedback: vibration and force-feedback actuators.
351
pub mod haptics;
352
/// Raw HID device access (game controllers, tablets, custom peripherals).
353
pub mod hid;
354
// clippy reports `too_long_first_doc_paragraph` here with a span that starts
355
// in the crate-level `//!` doc far above and ends on this one-line `///`,
356
// measuring the two as a single paragraph. The doc below is one short line;
357
// re-paragraphing the crate doc does not move it, and a crate-level allow does
358
// not apply to it. A genuine instance of this lint — a doc comment cut in half
359
// by `#[derive]` / `#[repr]` attributes — was fixed properly in `callbacks.rs`.
360
#[allow(clippy::too_long_first_doc_paragraph)]
361
/// Hit-test results (which DOM nodes are under the cursor) + the type-safe
362
/// hit-test tag system for compositor integration (merged from `hit_test_tag`).
363
pub mod hit_test;
364
/// Icon provider system for loading icons from fonts, images, or zip packs.
365
pub mod icon;
366
/// Arena-based node tree storage and hierarchy management.
367
pub mod id;
368
/// JSON value types for the C API (no serde dependency).
369
pub mod json;
370
/// System-keyring POD types — `KeyringRequest` + `KeyringResult`.
371
///
372
/// Stateful manager lives in `azul_layout::managers::keyring`.
373
pub mod keyring;
374
/// Runtime log filtering: per-level and per-category atomics.
375
///
376
/// Parsed from `AZ_LOG` but changeable while the process runs. Logging is gated HERE and
377
/// never by a cargo feature — see the module docs for the 2026-08-07 incident
378
/// that made a compile-time gate delete the one diagnosis that was needed.
379
pub mod log_filter;
380
/// Media playback POD types — the `PlaybackState` the six media events
381
/// describe (11c).
382
///
383
/// Stateful manager lives in `azul_layout::managers::media_player`.
384
pub mod media_player;
385
/// The system media session — what the desktop's media widget shows.
386
///
387
/// The app-facing half of the media-key transport in
388
/// `dll/desktop/extra/media_keys`.
389
pub mod media_session;
390
/// Menu system: context menus, dropdown menus, and menu bars.
391
pub mod menu;
392
/// Paged-media primitives: the `FragmentationContext` (continuous vs. paged) and
393
/// `PageMargins`. The pagination/slicing logic lives in `azul_layout::solver3`.
394
pub mod paged;
395
/// SVG `d=""` path data parser.
396
pub mod path_parser;
397
/// CSS property cache for efficient per-node style resolution.
398
pub mod physical_key;
399
/// Per-node resolved CSS property cache, the layout engine's read path.
400
pub mod prop_cache;
401
/// Type-erased, ref-counted smart pointer with runtime borrow checking.
402
pub mod refany;
403
/// Resource management: font/image loading, caching, and garbage collection.
404
pub mod resources;
405
/// Screen-capture POD types — `ScreenCaptureSource` + `ScreenCaptureConfig`.
406
///
407
/// Symmetric to the camera surface (a "dumb widget" in
408
/// `azul_layout::widgets::screencap`); reuses `camera`'s capture status types.
409
pub mod screencap;
410
/// Text selection and cursor positioning for inline content.
411
pub mod selection;
412
/// Motion-sensor POD types — `SensorKind` + `SensorReading`.
413
///
414
/// Stateful manager lives in `azul_layout::managers::sensors`.
415
pub mod sensors;
416
/// Pointer coordinate spaces as distinct, zero-cost newtypes.
417
///
418
/// Window space, static layout space, border-box-local, content-box-local and
419
/// scrolled content, plus the explicit ancestor-walk [`spaces::Inclusivity`].
420
pub mod spaces;
421
/// CSS cascade: selector matching, specificity, and property inheritance.
422
pub mod style;
423
/// `StyledDom` — the result of applying CSS to a DOM tree (the CSSOM).
424
pub mod styled_dom;
425
/// SVG rendering, path tessellation, and geometric operations.
426
pub mod svg;
427
/// Timer, thread, and async task management.
428
pub mod task;
429
/// 3D transform matrix computation for CSS transforms.
430
pub mod transform;
431
/// Transient windows: menus, dropdowns and dialogs owned by a parent window.
432
pub mod transient;
433
/// System tray / status icon POD types.
434
///
435
/// Icon bitmaps, category/status and the tray event kinds. The OS plumbing
436
/// lives in `azul-dll` (`desktop/tray`).
437
pub mod tray;
438
/// Built-in user-agent default stylesheet.
439
pub mod ua_css;
440
/// Default font/text constants and small geometry helpers for layout.
441
pub mod ui_solver;
442
/// URL POD type (`Url`/`UrlParseError`); parsing gated behind the `url` feature.
443
pub mod url;
444
/// Video-playback POD types — `VideoConfig` (source URL + autoplay/loop).
445
///
446
/// Same "dumb widget" architecture (`azul_layout::widgets::video`); decoded
447
/// via vk-video into the shared GL texture.
448
pub mod video;
449
/// Window configuration, input state, and platform-specific options.
450
pub mod window;
451
/// XML and XHTML parsing for declarative UI definitions.
452
pub mod xml;
453

            
454
/// Ordered map alias used throughout `azul-core`.
455
///
456
/// This is backed by `BTreeMap` (not a hash map) because the `core` crate
457
/// supports `no_std`, where `HashMap` is unavailable. The webrender crates
458
/// define their own `FastHashMap` using `HashMap` + `FxHasher`.
459
pub type OrderedMap<T, U> = alloc::collections::BTreeMap<T, U>;
460
pub type FastBTreeSet<T> = alloc::collections::BTreeSet<T>;
461

            
462
#[cfg(test)]
463
#[allow(clippy::pedantic, clippy::nursery)]
464
mod autotest_generated {
465
    use alloc::{boxed::Box, string::String, vec::Vec};
466
    use core::{
467
        cell::Cell,
468
        hash::{Hash, Hasher},
469
    };
470

            
471
    use super::{hash::DefaultHasher, sync::OnceLock, FastBTreeSet, OrderedMap};
472

            
473
    // NOTE: `sync::OnceLock` and `hash::DefaultHasher` are *aliases*: with the
474
    // (default) `std` feature they re-export `std::sync::OnceLock` /
475
    // `std::hash::DefaultHasher`; without it they resolve to the hand-written
476
    // `no_std` shims in this file. Tests below are split accordingly:
477
    //   * un-gated  -> the API contract BOTH impls must satisfy,
478
    //   * cfg-gated -> behaviour that is specific to one impl.
479
    // `DefaultHasher::add` is private to the private `hash::nostd` module, so it
480
    // is not nameable from here; `write_u64` forwards to it 1:1 and is used as
481
    // the proxy for the numeric/overflow cases.
482

            
483
    // ---------------------------------------------------------------
484
    // OnceLock — constructor / getter invariants
485
    // ---------------------------------------------------------------
486

            
487
    #[test]
488
    fn oncelock_new_is_empty() {
489
        let cell: OnceLock<u32> = OnceLock::new();
490
        assert!(cell.get().is_none());
491
        // getter must stay pure: repeated reads never initialize
492
        assert!(cell.get().is_none());
493
    }
494

            
495
    #[test]
496
    fn oncelock_new_is_usable_in_const_context() {
497
        static CELL: OnceLock<u64> = OnceLock::new();
498
        assert!(CELL.get().is_none());
499
        assert_eq!(*CELL.get_or_init(|| u64::MAX), u64::MAX);
500
        assert_eq!(CELL.get().copied(), Some(u64::MAX));
501
    }
502

            
503
    #[test]
504
    fn oncelock_default_matches_new() {
505
        let cell: OnceLock<Vec<u8>> = OnceLock::default();
506
        assert!(cell.get().is_none());
507
    }
508

            
509
    #[test]
510
    fn oncelock_get_or_init_runs_closure_exactly_once() {
511
        let calls = Cell::new(0usize);
512
        let cell: OnceLock<u32> = OnceLock::new();
513

            
514
        assert_eq!(
515
            *cell.get_or_init(|| {
516
                calls.set(calls.get() + 1);
517
                7
518
            }),
519
            7
520
        );
521
        // The second/third call must return the FIRST value and never re-run `f`.
522
        assert_eq!(
523
            *cell.get_or_init(|| {
524
                calls.set(calls.get() + 1);
525
                9
526
            }),
527
            7
528
        );
529
        assert_eq!(
530
            *cell.get_or_init(|| {
531
                calls.set(calls.get() + 1);
532
                11
533
            }),
534
            7
535
        );
536
        assert_eq!(calls.get(), 1);
537
        assert_eq!(cell.get().copied(), Some(7));
538
    }
539

            
540
    #[test]
541
    fn oncelock_get_and_get_or_init_alias_the_same_storage() {
542
        let cell: OnceLock<u32> = OnceLock::new();
543
        let a: *const u32 = cell.get_or_init(|| 1);
544
        let b: *const u32 = cell.get().expect("initialized");
545
        let c: *const u32 = cell.get_or_init(|| 2);
546
        // The value must never be moved/duplicated by a second init attempt.
547
        assert_eq!(a, b);
548
        assert_eq!(a, c);
549
    }
550

            
551
    #[test]
552
    fn oncelock_holds_zero_sized_type() {
553
        // ZST: `Option<()>` has no payload bits, so a naive impl can confuse
554
        // "initialized" with "None".
555
        let cell: OnceLock<()> = OnceLock::new();
556
        assert!(cell.get().is_none());
557
        cell.get_or_init(|| ());
558
        assert!(cell.get().is_some());
559
    }
560

            
561
    #[test]
562
    fn oncelock_holds_large_payload() {
563
        let cell: OnceLock<Box<[u8]>> = OnceLock::new();
564
        let v = cell.get_or_init(|| alloc::vec![0xABu8; 1 << 20].into_boxed_slice());
565
        assert_eq!(v.len(), 1 << 20);
566
        assert!(v.iter().all(|b| *b == 0xAB));
567
        assert_eq!(cell.get().map(|b| b.len()), Some(1 << 20));
568
    }
569

            
570
    #[test]
571
    fn oncelock_holds_nan_without_eq_confusion() {
572
        let cell: OnceLock<f64> = OnceLock::new();
573
        // `NaN != NaN`, so initialization must be tracked by state, not by
574
        // comparing the payload against a sentinel.
575
        assert!(cell.get_or_init(|| f64::NAN).is_nan());
576
        assert!(cell.get().is_some_and(|f| f.is_nan()));
577
        // A second init must not overwrite the stored NaN with 1.0.
578
        assert!(cell.get_or_init(|| 1.0).is_nan());
579
    }
580

            
581
    #[test]
582
    fn oncelock_clone_copies_state_not_aliases_it() {
583
        let cell: OnceLock<String> = OnceLock::new();
584

            
585
        let empty = cell.clone();
586
        assert!(empty.get().is_none());
587
        // Initializing the source must not retro-fill an earlier clone.
588
        cell.get_or_init(|| String::from("azul"));
589
        assert!(empty.get().is_none());
590

            
591
        let full = cell.clone();
592
        assert_eq!(full.get().map(String::as_str), Some("azul"));
593
        // Distinct storage: the clone must own its own allocation.
594
        assert_ne!(
595
            cell.get().expect("init") as *const String,
596
            full.get().expect("init") as *const String
597
        );
598
    }
599

            
600
    #[test]
601
    fn oncelock_eq_compares_contents() {
602
        let a: OnceLock<u32> = OnceLock::new();
603
        let b: OnceLock<u32> = OnceLock::new();
604
        assert_eq!(a, b); // both empty
605

            
606
        a.get_or_init(|| 5);
607
        assert_ne!(a, b); // Some(5) vs None
608

            
609
        b.get_or_init(|| 5);
610
        assert_eq!(a, b);
611

            
612
        let c: OnceLock<u32> = OnceLock::new();
613
        c.get_or_init(|| 6);
614
        assert_ne!(a, c);
615
    }
616

            
617
    #[cfg(feature = "std")]
618
    #[test]
619
    fn oncelock_concurrent_get_or_init_initializes_exactly_once() {
620
        use std::sync::{
621
            atomic::{AtomicUsize, Ordering},
622
            Barrier,
623
        };
624

            
625
        const THREADS: usize = 8;
626

            
627
        let cell: OnceLock<usize> = OnceLock::new();
628
        let inits = AtomicUsize::new(0);
629
        let gate = Barrier::new(THREADS);
630

            
631
        std::thread::scope(|s| {
632
            for id in 0..THREADS {
633
                let (cell, inits, gate) = (&cell, &inits, &gate);
634
                let _ = s.spawn(move || {
635
                    gate.wait(); // maximize contention on the CAS
636
                    let v = *cell.get_or_init(|| {
637
                        inits.fetch_add(1, Ordering::SeqCst);
638
                        id
639
                    });
640
                    // Every racer must observe the same winner.
641
                    assert_eq!(v, *cell.get().expect("initialized after get_or_init"));
642
                    v
643
                });
644
            }
645
        });
646

            
647
        assert_eq!(inits.load(Ordering::SeqCst), 1);
648
        let winner = cell.get().copied().expect("initialized");
649
        assert!(winner < THREADS);
650
    }
651

            
652
    // The `std` OnceLock documents that a panicking `f` leaves the cell
653
    // *uninitialized* (and re-initializable) rather than poisoned.
654
    //
655
    // The `no_std` shim in this file does NOT hold this property: it leaves
656
    // `state == BUSY`, so any later `get_or_init` spins forever. This test is
657
    // therefore std-gated on purpose — running it under `no_std` would hang the
658
    // test binary instead of failing it.
659
    #[cfg(feature = "std")]
660
    #[test]
661
    fn oncelock_panicking_initializer_leaves_cell_reusable() {
662
        let cell: OnceLock<u32> = OnceLock::new();
663

            
664
        let prev = std::panic::take_hook();
665
        std::panic::set_hook(Box::new(|_| {})); // keep the expected panic quiet
666
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
667
            cell.get_or_init(|| panic!("initializer blew up"));
668
        }));
669
        std::panic::set_hook(prev);
670

            
671
        assert!(caught.is_err(), "the panic must propagate to the caller");
672
        assert!(cell.get().is_none(), "cell must remain uninitialized");
673
        assert_eq!(*cell.get_or_init(|| 42), 42, "cell must still be usable");
674
    }
675

            
676
    // ---------------------------------------------------------------
677
    // DefaultHasher — construction / determinism
678
    // ---------------------------------------------------------------
679

            
680
    fn hash_bytes(bytes: &[u8]) -> u64 {
681
        let mut h = DefaultHasher::new();
682
        h.write(bytes);
683
        h.finish()
684
    }
685

            
686
    fn hash_u64(word: u64) -> u64 {
687
        let mut h = DefaultHasher::new();
688
        h.write_u64(word);
689
        h.finish()
690
    }
691

            
692
    #[test]
693
    fn hasher_new_and_default_agree_and_are_deterministic() {
694
        assert_eq!(DefaultHasher::new().finish(), DefaultHasher::new().finish());
695
        assert_eq!(
696
            DefaultHasher::new().finish(),
697
            DefaultHasher::default().finish()
698
        );
699
    }
700

            
701
    #[test]
702
    fn hasher_is_deterministic_within_a_run() {
703
        assert_eq!(hash_bytes(b"azul"), hash_bytes(b"azul"));
704
        assert_eq!(
705
            hash_u64(0xDEAD_BEEF_CAFE_F00D),
706
            hash_u64(0xDEAD_BEEF_CAFE_F00D)
707
        );
708
    }
709

            
710
    #[test]
711
    fn hasher_distinguishes_different_inputs() {
712
        assert_ne!(hash_bytes(b"a"), hash_bytes(b"b"));
713
        assert_ne!(hash_u64(0), hash_u64(1));
714
    }
715

            
716
    #[test]
717
    fn hasher_is_order_sensitive() {
718
        let mut a = DefaultHasher::new();
719
        a.write_u64(1);
720
        a.write_u64(2);
721

            
722
        let mut b = DefaultHasher::new();
723
        b.write_u64(2);
724
        b.write_u64(1);
725

            
726
        assert_ne!(a.finish(), b.finish());
727
    }
728

            
729
    #[test]
730
    fn hasher_finish_does_not_consume_state() {
731
        let mut h = DefaultHasher::new();
732
        h.write_u64(7);
733
        let first = h.finish();
734
        // `finish` must be a pure read: calling it twice returns the same value.
735
        assert_eq!(first, h.finish());
736
        // ...and further writes must keep mutating the same running state.
737
        h.write_u64(7);
738
        assert_ne!(first, h.finish());
739
    }
740

            
741
    // ---------------------------------------------------------------
742
    // DefaultHasher — numeric limits / overflow (exercises the private `add`
743
    // via its 1:1 forwarders `write_u64` / `write_usize` / `write_u8`)
744
    // ---------------------------------------------------------------
745

            
746
    #[test]
747
    fn hasher_handles_integer_limits_without_panicking() {
748
        // `add` does a `wrapping_mul`; a debug build must not overflow-panic.
749
        for word in [
750
            0u64,
751
            1,
752
            u64::MAX,
753
            u64::MAX - 1,
754
            i64::MIN as u64, // 0x8000_0000_0000_0000 — "negative" bit pattern
755
            i64::MAX as u64,
756
            -1i64 as u64,
757
            1 << 63,
758
            usize::MAX as u64,
759
        ] {
760
            let h = hash_u64(word);
761
            // deterministic + no panic; value itself is impl-defined
762
            assert_eq!(h, hash_u64(word));
763
        }
764

            
765
        let mut h = DefaultHasher::new();
766
        h.write_usize(usize::MAX);
767
        h.write_usize(0);
768
        h.write_u8(u8::MAX);
769
        h.write_u8(0);
770
        let _ = h.finish();
771
    }
772

            
773
    #[test]
774
    fn hasher_repeated_max_words_do_not_overflow_panic() {
775
        // Hammer the wrapping rotate/xor/multiply chain: every iteration
776
        // overflows u64. Must wrap, never panic (even in a debug profile).
777
        let mut h = DefaultHasher::new();
778
        for _ in 0..10_000 {
779
            h.write_u64(u64::MAX);
780
        }
781
        let a = h.finish();
782

            
783
        let mut h2 = DefaultHasher::new();
784
        for _ in 0..10_000 {
785
            h2.write_u64(u64::MAX);
786
        }
787
        assert_eq!(a, h2.finish(), "overflowing chain must stay deterministic");
788
    }
789

            
790
    #[test]
791
    fn hasher_zero_words_are_deterministic() {
792
        let mut h = DefaultHasher::new();
793
        for _ in 0..1_000 {
794
            h.write_u64(0);
795
        }
796
        let a = h.finish();
797

            
798
        let mut h2 = DefaultHasher::new();
799
        for _ in 0..1_000 {
800
            h2.write_u64(0);
801
        }
802
        assert_eq!(a, h2.finish());
803
    }
804

            
805
    // ---------------------------------------------------------------
806
    // DefaultHasher — `write` chunking / boundaries / unicode
807
    // ---------------------------------------------------------------
808

            
809
    #[test]
810
    fn hasher_write_empty_slice_does_not_panic() {
811
        let mut h = DefaultHasher::new();
812
        h.write(&[]);
813
        h.write(&[]);
814
        let a = h.finish();
815

            
816
        let mut h2 = DefaultHasher::new();
817
        h2.write(&[]);
818
        h2.write(&[]);
819
        assert_eq!(a, h2.finish());
820
    }
821

            
822
    #[test]
823
    fn hasher_write_covers_every_chunk_boundary() {
824
        // The `no_std` impl walks `chunks(8)` and zero-pads the tail; lengths
825
        // 0..=24 cover empty, short, exact-multiple and ragged-tail cases.
826
        let data: Vec<u8> = (0u8..=24).collect();
827
        for len in 0..=24usize {
828
            let slice = &data[..len];
829
            assert_eq!(hash_bytes(slice), hash_bytes(slice), "len {len}");
830
        }
831
        // A short slice must not collide with the same slice explicitly padded
832
        // out past the next 8-byte chunk boundary.
833
        assert_ne!(
834
            hash_bytes(&[1u8]),
835
            hash_bytes(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0])
836
        );
837
    }
838

            
839
    // `write` must not swallow a trailing zero byte: `[1]` and `[1, 0]` are
840
    // different inputs and must hash differently.
841
    //
842
    // The `no_std` shim FAILS this: it zero-pads the final `chunks(8)` chunk
843
    // and mixes in no length, so `[1]` and `[1, 0]` both become the word
844
    // `0x0000_0000_0000_0001` — a guaranteed collision for every pair of byte
845
    // strings differing only in trailing zeros. Kept as a live assertion for
846
    // the (default) `std` build and `ignore`d rather than weakened under
847
    // `no_std`; see the autotest report.
848
    #[cfg_attr(
849
        not(feature = "std"),
850
        ignore = "no_std DefaultHasher zero-pads without length mixing: hash([1]) == hash([1, 0])"
851
    )]
852
    #[test]
853
    fn hasher_write_does_not_swallow_trailing_zero_bytes() {
854
        assert_ne!(hash_bytes(&[1u8]), hash_bytes(&[1u8, 0]));
855
        assert_ne!(hash_bytes(b"az"), hash_bytes(b"az\0"));
856
        assert_ne!(hash_bytes(&[]), hash_bytes(&[0u8]));
857
    }
858

            
859
    #[test]
860
    fn hasher_handles_huge_input() {
861
        let big: Vec<u8> = (0..(1 << 16)).map(|i| (i % 251) as u8).collect();
862
        let a = hash_bytes(&big);
863
        assert_eq!(a, hash_bytes(&big));
864

            
865
        // A single flipped byte in the middle must change the digest.
866
        let mut flipped = big.clone();
867
        flipped[1 << 15] ^= 0xFF;
868
        assert_ne!(a, hash_bytes(&flipped));
869
    }
870

            
871
    #[test]
872
    fn hasher_handles_unicode_and_nul_bytes() {
873
        for s in [
874
            "",
875
            "\u{0}",
876
            "ascii",
877
            "héllo wörld",
878
            "日本語テキスト",
879
            "🦀🔥👨‍👩‍👧‍👦",
880
            "a\u{0}b",
881
            "\u{FEFF}bom",
882
            "\u{10FFFF}",
883
        ] {
884
            let mut h = DefaultHasher::new();
885
            s.hash(&mut h);
886
            let a = h.finish();
887

            
888
            let mut h2 = DefaultHasher::new();
889
            s.hash(&mut h2);
890
            assert_eq!(a, h2.finish(), "unstable hash for {s:?}");
891
        }
892

            
893
        // Interior NUL must not truncate the input (C-string style bug).
894
        let mut a = DefaultHasher::new();
895
        "a\u{0}b".hash(&mut a);
896
        let mut b = DefaultHasher::new();
897
        "a".hash(&mut b);
898
        assert_ne!(a.finish(), b.finish());
899
    }
900

            
901
    #[test]
902
    fn hasher_respects_eq_hash_contract_for_std_types() {
903
        fn digest<T: Hash>(t: &T) -> u64 {
904
            let mut h = DefaultHasher::new();
905
            t.hash(&mut h);
906
            h.finish()
907
        }
908

            
909
        // Equal values must hash equal.
910
        assert_eq!(digest(&String::from("x")), digest(&String::from("x")));
911
        assert_eq!(
912
            digest(&alloc::vec![1u64, 2, 3]),
913
            digest(&alloc::vec![1u64, 2, 3])
914
        );
915
        assert_eq!(digest(&(1u8, "a")), digest(&(1u8, "a")));
916

            
917
        // Length must be part of the digest: [1,2] vs [1,2,0] must differ...
918
        assert_ne!(
919
            digest(&alloc::vec![1u8, 2]),
920
            digest(&alloc::vec![1u8, 2, 0])
921
        );
922
        // ...and prefix-concatenation must not collide ("ab" vs "a"+"b" fields).
923
        assert_ne!(digest(&("ab", "")), digest(&("a", "b")));
924
    }
925

            
926
    // ---------------------------------------------------------------
927
    // `no_std` shim internals: exact FxHasher-style formula of the private
928
    // `add`, reached through its 1:1 forwarder `write_u64`.
929
    // ---------------------------------------------------------------
930

            
931
    #[cfg(not(feature = "std"))]
932
    #[test]
933
    fn nostd_hasher_add_matches_documented_formula() {
934
        const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
935
        const ROTATE: u32 = 5;
936

            
937
        fn expect(words: &[u64]) -> u64 {
938
            words
939
                .iter()
940
                .fold(0u64, |h, w| (h.rotate_left(ROTATE) ^ w).wrapping_mul(SEED))
941
        }
942

            
943
        assert_eq!(DefaultHasher::new().finish(), 0, "fresh state must be 0");
944

            
945
        for words in [
946
            &[0u64][..],
947
            &[1][..],
948
            &[u64::MAX][..],
949
            &[i64::MIN as u64][..],
950
            &[u64::MAX, u64::MAX, u64::MAX][..],
951
            &[0, u64::MAX, 0, 1 << 63][..],
952
        ] {
953
            let mut h = DefaultHasher::new();
954
            for w in words {
955
                h.write_u64(*w);
956
            }
957
            assert_eq!(h.finish(), expect(words), "formula drift for {words:?}");
958
        }
959
    }
960

            
961
    #[cfg(not(feature = "std"))]
962
    #[test]
963
    fn nostd_hasher_zero_is_an_absorbing_state() {
964
        // Documented FxHasher weakness, asserted so it stays *intentional*:
965
        // from a zero state, hashing zero words keeps the state at zero
966
        // ((0.rotate_left(5) ^ 0) * SEED == 0).
967
        let mut h = DefaultHasher::new();
968
        for _ in 0..64 {
969
            h.write_u64(0);
970
        }
971
        assert_eq!(h.finish(), 0);
972

            
973
        // Leading zero words are therefore invisible: hash([0, x]) == hash([x]).
974
        let mut a = DefaultHasher::new();
975
        a.write_u64(0);
976
        a.write_u64(0xABCD);
977
        let mut b = DefaultHasher::new();
978
        b.write_u64(0xABCD);
979
        assert_eq!(a.finish(), b.finish());
980
    }
981

            
982
    #[cfg(not(feature = "std"))]
983
    #[test]
984
    fn nostd_hasher_write_empty_slice_is_a_noop() {
985
        // `chunks(8)` over an empty slice yields nothing, so the state is untouched.
986
        let mut h = DefaultHasher::new();
987
        h.write(b"seed");
988
        let before = h.finish();
989
        h.write(&[]);
990
        assert_eq!(h.finish(), before);
991
    }
992

            
993
    // ---------------------------------------------------------------
994
    // Public type aliases — ordering / dedup invariants
995
    // ---------------------------------------------------------------
996

            
997
    #[test]
998
    fn ordered_map_iterates_in_key_order() {
999
        let mut m: OrderedMap<i64, &str> = OrderedMap::new();
        for (k, v) in [
            (i64::MAX, "max"),
            (0, "zero"),
            (i64::MIN, "min"),
            (-1, "neg"),
        ] {
            let _ = m.insert(k, v);
        }
        let keys: Vec<i64> = m.keys().copied().collect();
        assert_eq!(keys, alloc::vec![i64::MIN, -1, 0, i64::MAX]);
        // Re-insert must overwrite, not duplicate.
        assert_eq!(m.insert(0, "zero2"), Some("zero"));
        assert_eq!(m.len(), 4);
        assert_eq!(m.get(&0).copied(), Some("zero2"));
    }
    #[test]
    fn fast_btree_set_dedups_and_orders() {
        let mut s: FastBTreeSet<u32> = FastBTreeSet::new();
        assert!(s.insert(u32::MAX));
        assert!(s.insert(0));
        assert!(!s.insert(0), "duplicate insert must report false");
        assert!(s.insert(1));
        assert_eq!(s.len(), 3);
        assert_eq!(
            s.iter().copied().collect::<Vec<u32>>(),
            alloc::vec![0, 1, u32::MAX]
        );
        assert!(s.contains(&u32::MAX));
        assert!(!s.contains(&2));
    }
}