Skip to main content

azul_core/
lib.rs

1//! Shared datatypes for azul-* crates
2//!
3//! `azul-core` provides the platform-independent core types used throughout
4//! the Azul toolkit. Key modules include [`dom`] for DOM construction,
5//! [`callbacks`] for event callback types, [`styled_dom`] for the CSSOM,
6//! and [`window`] for OS windowing abstractions.
7//!
8//! This crate depends on [`azul_css`] for CSS property definitions and is
9//! consumed by `azul-layout`, `azul-dll`, and the platform shell crates.
10//! It supports `no_std` environments via `#![cfg_attr(not(feature = "std"), no_std)]`.
11
12#![cfg_attr(not(feature = "std"), no_std)]
13// Lint policy: deny correctness/safety issues, warn on style
14#![deny(unused_must_use)]
15#![warn(clippy::all)]
16// Extreme-lint lockdown: all clippy groups plus opt-in rustc lints, enforced as
17// -D warnings on library code by the CI clippy job. Test builds are exempt via
18// cfg(not(test)) below since the set is high-noise and low-value on unit and
19// generated tests; clippy::all correctness still applies to test code.
20// (clippy::restriction wholesale + unused_results + box_pointers deliberately
21// omitted — contradictory / overwhelmingly noisy by design.)
22#![cfg_attr(not(test), warn(
23    clippy::pedantic,
24    clippy::nursery,
25    clippy::cargo,
26    // missing_docs,  // TODO(docs): re-enable as a dedicated final docs pass; disabled
27    //                // for now so the cleanup focuses on code-quality lints, not doc debt.
28    missing_debug_implementations,
29    missing_copy_implementations,
30    unreachable_pub,
31    unused_qualifications,
32    unused_lifetimes,
33    unused_import_braces,
34    unused_macro_rules,
35    unused_crate_dependencies,
36    meta_variable_misuse,
37    trivial_casts,
38    trivial_numeric_casts,
39    elided_lifetimes_in_paths,
40    single_use_lifetimes,
41    variant_size_differences,
42    non_ascii_idents,
43    unsafe_op_in_unsafe_fn,
44    let_underscore_drop,
45))]
46// `multiple_crate_versions` (implied by clippy::cargo) flags transitive
47// dependency-version dups that cannot be resolved in azul's own source:
48// `syn` 1.0.x ↔ 2.0.x (the proc-macro ecosystem is mid-migration; both are
49// pulled in transitively). Documented allow — re-audit when the dep tree aligns.
50#![allow(clippy::multiple_crate_versions)]
51#![allow(
52    clippy::non_canonical_partial_ord_impl,
53    clippy::legacy_numeric_constants,
54    clippy::should_implement_trait,
55    clippy::result_unit_err,
56    clippy::ptr_as_ptr,
57    clippy::too_many_arguments,
58    clippy::type_complexity,
59    unused_imports,
60    unused_variables,
61    unused_mut,
62    unused_parens,
63    dead_code,
64    unused_doc_comments,
65    unused_assignments,                    // compact_cache_builder incremental updates
66    unexpected_cfgs,
67    unpredictable_function_pointer_comparisons, // intentional in dom callback comparison
68    improper_ctypes_definitions,           // xml component fns use Rust fn pointers internally
69    static_mut_refs,                       // TODO: migrate to OnceLock for Rust 2024
70)]
71
72// `extern crate` + `#[macro_use]` required for `no_std` support:
73// makes `core` and `alloc` macros available without `use` imports.
74#[macro_use]
75extern crate core;
76#[macro_use]
77extern crate alloc;
78#[macro_use]
79extern crate azul_css;
80
81/// Internal macros for `Vec`, `Option`, and callback boilerplate.
82///
83#[macro_use]
84pub mod macros;
85/// Debug logging system with category filtering.
86#[macro_use]
87pub mod debug;
88/// SQL database POD types — `DbValue` + `DbRows` (engine-agnostic). The
89/// `Db` handle + SQLite engine live in `azul_dll` behind `db-sqlite`.
90pub mod db;
91/// Unified `AZ_PROFILE` gate for memory and CPU profiling instrumentation.
92pub mod profile;
93/// `no_std`-friendly synchronization primitives.
94///
95/// In `std` builds these re-export the matching `std::sync` types. In
96/// `no_std` builds they provide minimal spinlock-backed equivalents
97/// implementing only the API surface azul-core relies on.
98pub mod sync {
99    #[cfg(feature = "std")]
100    pub use std::sync::OnceLock;
101
102    #[cfg(not(feature = "std"))]
103    pub use self::nostd::OnceLock;
104
105    #[cfg(not(feature = "std"))]
106    mod nostd {
107        use core::cell::UnsafeCell;
108        use core::sync::atomic::{AtomicU8, Ordering};
109
110        const UNINIT: u8 = 0;
111        const BUSY: u8 = 1;
112        const READY: u8 = 2;
113
114        /// Minimal `no_std` `OnceLock` mirroring the slice of the std API used
115        /// by azul-core (`new`, `get`, `get_or_init`).
116        pub struct OnceLock<T> {
117            state: AtomicU8,
118            value: UnsafeCell<Option<T>>,
119        }
120
121        unsafe impl<T: Send + Sync> Sync for OnceLock<T> {}
122        unsafe impl<T: Send> Send for OnceLock<T> {}
123
124        impl<T> OnceLock<T> {
125            pub const fn new() -> Self {
126                OnceLock {
127                    state: AtomicU8::new(UNINIT),
128                    value: UnsafeCell::new(None),
129                }
130            }
131
132            pub fn get(&self) -> Option<&T> {
133                if self.state.load(Ordering::Acquire) == READY {
134                    unsafe { (*self.value.get()).as_ref() }
135                } else {
136                    None
137                }
138            }
139
140            pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T {
141                if let Some(v) = self.get() {
142                    return v;
143                }
144                // Contend for the right to initialize.
145                while self
146                    .state
147                    .compare_exchange(UNINIT, BUSY, Ordering::Acquire, Ordering::Acquire)
148                    .is_err()
149                {
150                    if self.state.load(Ordering::Acquire) == READY {
151                        return self.get().expect("OnceLock ready");
152                    }
153                    core::hint::spin_loop();
154                }
155                unsafe {
156                    *self.value.get() = Some(f());
157                }
158                self.state.store(READY, Ordering::Release);
159                self.get().expect("OnceLock initialized")
160            }
161        }
162
163        impl<T> Default for OnceLock<T> {
164            fn default() -> Self {
165                Self::new()
166            }
167        }
168
169        impl<T: core::fmt::Debug> core::fmt::Debug for OnceLock<T> {
170            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
171                f.debug_tuple("OnceLock").field(&self.get()).finish()
172            }
173        }
174
175        impl<T: Clone> Clone for OnceLock<T> {
176            fn clone(&self) -> Self {
177                let new = OnceLock::new();
178                if let Some(v) = self.get() {
179                    let _ = new.get_or_init(|| v.clone());
180                }
181                new
182            }
183        }
184
185        impl<T: PartialEq> PartialEq for OnceLock<T> {
186            fn eq(&self, other: &Self) -> bool {
187                self.get() == other.get()
188            }
189        }
190    }
191}
192
193/// `no_std`-friendly default hasher used for change-detection hashing.
194///
195/// In `std` builds this re-exports `std::hash::DefaultHasher` so behaviour
196/// is unchanged. In `no_std` builds it provides a small deterministic
197/// `FxHasher`-style hasher implementing `core::hash::Hasher`. The values are
198/// only required to be stable within a single process run (they back diffing /
199/// change detection), not to match `std`'s `SipHash` output.
200pub mod hash {
201    #[cfg(feature = "std")]
202    pub use std::hash::DefaultHasher;
203
204    #[cfg(not(feature = "std"))]
205    pub use self::nostd::DefaultHasher;
206
207    #[cfg(not(feature = "std"))]
208    mod nostd {
209        use core::hash::Hasher;
210
211        const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
212        const ROTATE: u32 = 5;
213
214        /// FxHasher-style `no_std` hasher. Not DoS-resistant; used purely for
215        /// in-process change detection.
216        #[derive(Default)]
217        pub struct DefaultHasher {
218            hash: u64,
219        }
220
221        impl DefaultHasher {
222            pub fn new() -> Self {
223                DefaultHasher { hash: 0 }
224            }
225
226            #[inline]
227            fn add(&mut self, word: u64) {
228                self.hash = (self.hash.rotate_left(ROTATE) ^ word).wrapping_mul(SEED);
229            }
230        }
231
232        impl Hasher for DefaultHasher {
233            #[inline]
234            fn finish(&self) -> u64 {
235                self.hash
236            }
237
238            #[inline]
239            fn write(&mut self, bytes: &[u8]) {
240                for chunk in bytes.chunks(8) {
241                    let mut buf = [0u8; 8];
242                    buf[..chunk.len()].copy_from_slice(chunk);
243                    self.add(u64::from_le_bytes(buf));
244                }
245            }
246
247            #[inline]
248            fn write_u8(&mut self, i: u8) {
249                self.add(i as u64);
250            }
251            #[inline]
252            fn write_u64(&mut self, i: u64) {
253                self.add(i);
254            }
255            #[inline]
256            fn write_usize(&mut self, i: usize) {
257                self.add(i as u64);
258            }
259        }
260    }
261}
262/// Callback types: layout, event, timer, thread, and focus handling.
263#[macro_use]
264pub mod callbacks;
265/// Host-language callback invoker registry.
266///
267/// The C-ABI surface managed-FFI bindings (Lua, Ruby, …) use to register one
268/// per-kind invoker + a single shared releaser, so callbacks can be created via
269/// `_createFromHostHandle` without the host having to generate trampolines for
270/// struct-by-value signatures their FFI library can't handle.
271#[macro_use]
272pub mod host_invoker;
273/// Accessibility types for screen-reader integration (AccessKit).
274pub mod a11y;
275/// Audio POD types — `AudioConfig` (stream format) + `AudioFrame` (interleaved
276/// f32 samples).
277///
278/// The unit captured from the mic, played back, and (P8) shared
279/// over UDP. Backend (rodio / cpal / AVAudioEngine / AAudio) lives dll-side.
280pub mod audio;
281/// Biometric-auth POD types — `BiometricKind` + `BiometricResult` + `BiometricPrompt`.
282///
283/// Stateful manager lives in `azul_layout::managers::biometric`.
284pub mod biometric;
285/// Camera-capture POD types — `CaptureStreamId` + `CameraConfig` +
286/// `CameraFacing` + `StreamState` + … .
287///
288/// The stateful `CameraStream` /
289/// `CameraManager` (which own the shared `ImageRef` texture) live in
290/// `azul_layout::managers::camera`.
291pub mod camera;
292/// Converts `CssPropertyCache` into compact three-tier numeric cache.
293pub mod compact;
294/// Linear-time DOM diffing for incremental updates.
295pub mod diff;
296/// DOM construction: `Dom`, `NodeData`, `NodeType`, and the CSS-in-Rust API.
297pub mod dom;
298/// Drag context for text selection, scrollbar, node, and window drags.
299pub mod drag;
300/// Event filtering: mouse, keyboard, window, and synthetic events.
301pub mod events;
302/// Gamepad POD types — `GamepadId` + `GamepadButton` + `GamepadAxis` +
303/// `GamepadState`.
304///
305/// Stateful manager lives in `azul_layout::managers::gamepad`.
306pub mod gamepad;
307/// Geolocation POD types — `LocationFix` + `GeolocationProbeConfig`.
308///
309/// Stateful manager lives in `azul_layout::managers::geolocation`.
310pub mod geolocation;
311/// Logical and physical coordinate types (`LogicalSize`, `PhysicalPosition`, etc.).
312pub mod geom;
313/// OpenGL context wrappers, shader compilation, and texture cache.
314///
315pub mod gl;
316/// FXAA (Fast Approximate Anti-Aliasing) shader.
317pub mod gl_fxaa;
318/// OpenGL constants (GL 1.1 through GL 4.x).
319pub mod glconst;
320/// GPU value cache for CSS transforms and opacity.
321pub mod gpu;
322/// Hit-test results (which DOM nodes are under the cursor) + the type-safe
323/// hit-test tag system for compositor integration (merged from `hit_test_tag`).
324///
325pub mod hit_test;
326/// Icon provider system for loading icons from fonts, images, or zip packs.
327pub mod icon;
328/// Arena-based node tree storage and hierarchy management.
329pub mod id;
330/// JSON value types for the C API (no serde dependency).
331pub mod json;
332/// System-keyring POD types — `KeyringRequest` + `KeyringResult`.
333///
334/// Stateful manager lives in `azul_layout::managers::keyring`.
335pub mod keyring;
336/// Menu system: context menus, dropdown menus, and menu bars.
337pub mod menu;
338/// Paged-media primitives: the `FragmentationContext` (continuous vs. paged) and
339/// `PageMargins`. The pagination/slicing logic lives in `azul_layout::solver3`.
340pub mod paged;
341/// SVG `d=""` path data parser.
342pub mod path_parser;
343/// CSS property cache for efficient per-node style resolution.
344pub mod prop_cache;
345/// Type-erased, ref-counted smart pointer with runtime borrow checking.
346pub mod refany;
347/// Resource management: font/image loading, caching, and garbage collection.
348pub mod resources;
349/// Screen-capture POD types — `ScreenCaptureSource` + `ScreenCaptureConfig`.
350///
351/// Symmetric to the camera surface (a "dumb widget" in
352/// `azul_layout::widgets::screencap`); reuses `camera`'s capture status types.
353pub mod screencap;
354/// Text selection and cursor positioning for inline content.
355pub mod selection;
356/// Motion-sensor POD types — `SensorKind` + `SensorReading`.
357///
358/// Stateful manager lives in `azul_layout::managers::sensors`.
359pub mod sensors;
360/// CSS cascade: selector matching, specificity, and property inheritance.
361pub mod style;
362/// `StyledDom` — the result of applying CSS to a DOM tree (the CSSOM).
363pub mod styled_dom;
364/// SVG rendering, path tessellation, and geometric operations.
365pub mod svg;
366/// Timer, thread, and async task management.
367pub mod task;
368/// 3D transform matrix computation for CSS transforms.
369pub mod transform;
370/// Built-in user-agent default stylesheet.
371pub mod ua_css;
372/// Default font/text constants and small geometry helpers for layout.
373pub mod ui_solver;
374/// URL POD type (`Url`/`UrlParseError`); parsing gated behind the `url` feature.
375pub mod url;
376/// Video-playback POD types — `VideoConfig` (source URL + autoplay/loop).
377///
378/// Same "dumb widget" architecture (`azul_layout::widgets::video`); decoded
379/// via vk-video into the shared GL texture.
380pub mod video;
381/// Window configuration, input state, and platform-specific options.
382pub mod window;
383/// XML and XHTML parsing for declarative UI definitions.
384pub mod xml;
385
386/// Ordered map alias used throughout `azul-core`.
387///
388/// This is backed by `BTreeMap` (not a hash map) because the `core` crate
389/// supports `no_std`, where `HashMap` is unavailable. The webrender crates
390/// define their own `FastHashMap` using `HashMap` + `FxHasher`.
391pub type OrderedMap<T, U> = alloc::collections::BTreeMap<T, U>;
392pub type FastBTreeSet<T> = alloc::collections::BTreeSet<T>;
393
394#[cfg(test)]
395#[allow(clippy::pedantic, clippy::nursery)]
396mod autotest_generated {
397    use alloc::{boxed::Box, string::String, vec::Vec};
398    use core::{
399        cell::Cell,
400        hash::{Hash, Hasher},
401    };
402
403    use super::{hash::DefaultHasher, sync::OnceLock, FastBTreeSet, OrderedMap};
404
405    // NOTE: `sync::OnceLock` and `hash::DefaultHasher` are *aliases*: with the
406    // (default) `std` feature they re-export `std::sync::OnceLock` /
407    // `std::hash::DefaultHasher`; without it they resolve to the hand-written
408    // `no_std` shims in this file. Tests below are split accordingly:
409    //   * un-gated  -> the API contract BOTH impls must satisfy,
410    //   * cfg-gated -> behaviour that is specific to one impl.
411    // `DefaultHasher::add` is private to the private `hash::nostd` module, so it
412    // is not nameable from here; `write_u64` forwards to it 1:1 and is used as
413    // the proxy for the numeric/overflow cases.
414
415    // ---------------------------------------------------------------
416    // OnceLock — constructor / getter invariants
417    // ---------------------------------------------------------------
418
419    #[test]
420    fn oncelock_new_is_empty() {
421        let cell: OnceLock<u32> = OnceLock::new();
422        assert!(cell.get().is_none());
423        // getter must stay pure: repeated reads never initialize
424        assert!(cell.get().is_none());
425    }
426
427    #[test]
428    fn oncelock_new_is_usable_in_const_context() {
429        static CELL: OnceLock<u64> = OnceLock::new();
430        assert!(CELL.get().is_none());
431        assert_eq!(*CELL.get_or_init(|| u64::MAX), u64::MAX);
432        assert_eq!(CELL.get().copied(), Some(u64::MAX));
433    }
434
435    #[test]
436    fn oncelock_default_matches_new() {
437        let cell: OnceLock<Vec<u8>> = OnceLock::default();
438        assert!(cell.get().is_none());
439    }
440
441    #[test]
442    fn oncelock_get_or_init_runs_closure_exactly_once() {
443        let calls = Cell::new(0usize);
444        let cell: OnceLock<u32> = OnceLock::new();
445
446        assert_eq!(*cell.get_or_init(|| { calls.set(calls.get() + 1); 7 }), 7);
447        // The second/third call must return the FIRST value and never re-run `f`.
448        assert_eq!(*cell.get_or_init(|| { calls.set(calls.get() + 1); 9 }), 7);
449        assert_eq!(*cell.get_or_init(|| { calls.set(calls.get() + 1); 11 }), 7);
450        assert_eq!(calls.get(), 1);
451        assert_eq!(cell.get().copied(), Some(7));
452    }
453
454    #[test]
455    fn oncelock_get_and_get_or_init_alias_the_same_storage() {
456        let cell: OnceLock<u32> = OnceLock::new();
457        let a: *const u32 = cell.get_or_init(|| 1);
458        let b: *const u32 = cell.get().expect("initialized");
459        let c: *const u32 = cell.get_or_init(|| 2);
460        // The value must never be moved/duplicated by a second init attempt.
461        assert_eq!(a, b);
462        assert_eq!(a, c);
463    }
464
465    #[test]
466    fn oncelock_holds_zero_sized_type() {
467        // ZST: `Option<()>` has no payload bits, so a naive impl can confuse
468        // "initialized" with "None".
469        let cell: OnceLock<()> = OnceLock::new();
470        assert!(cell.get().is_none());
471        cell.get_or_init(|| ());
472        assert!(cell.get().is_some());
473    }
474
475    #[test]
476    fn oncelock_holds_large_payload() {
477        let cell: OnceLock<Box<[u8]>> = OnceLock::new();
478        let v = cell.get_or_init(|| alloc::vec![0xABu8; 1 << 20].into_boxed_slice());
479        assert_eq!(v.len(), 1 << 20);
480        assert!(v.iter().all(|b| *b == 0xAB));
481        assert_eq!(cell.get().map(|b| b.len()), Some(1 << 20));
482    }
483
484    #[test]
485    fn oncelock_holds_nan_without_eq_confusion() {
486        let cell: OnceLock<f64> = OnceLock::new();
487        // `NaN != NaN`, so initialization must be tracked by state, not by
488        // comparing the payload against a sentinel.
489        assert!(cell.get_or_init(|| f64::NAN).is_nan());
490        assert!(cell.get().is_some_and(|f| f.is_nan()));
491        // A second init must not overwrite the stored NaN with 1.0.
492        assert!(cell.get_or_init(|| 1.0).is_nan());
493    }
494
495    #[test]
496    fn oncelock_clone_copies_state_not_aliases_it() {
497        let cell: OnceLock<String> = OnceLock::new();
498
499        let empty = cell.clone();
500        assert!(empty.get().is_none());
501        // Initializing the source must not retro-fill an earlier clone.
502        cell.get_or_init(|| String::from("azul"));
503        assert!(empty.get().is_none());
504
505        let full = cell.clone();
506        assert_eq!(full.get().map(String::as_str), Some("azul"));
507        // Distinct storage: the clone must own its own allocation.
508        assert_ne!(
509            cell.get().expect("init") as *const String,
510            full.get().expect("init") as *const String
511        );
512    }
513
514    #[test]
515    fn oncelock_eq_compares_contents() {
516        let a: OnceLock<u32> = OnceLock::new();
517        let b: OnceLock<u32> = OnceLock::new();
518        assert_eq!(a, b); // both empty
519
520        a.get_or_init(|| 5);
521        assert_ne!(a, b); // Some(5) vs None
522
523        b.get_or_init(|| 5);
524        assert_eq!(a, b);
525
526        let c: OnceLock<u32> = OnceLock::new();
527        c.get_or_init(|| 6);
528        assert_ne!(a, c);
529    }
530
531    #[cfg(feature = "std")]
532    #[test]
533    fn oncelock_concurrent_get_or_init_initializes_exactly_once() {
534        use std::sync::{
535            atomic::{AtomicUsize, Ordering},
536            Barrier,
537        };
538
539        const THREADS: usize = 8;
540
541        let cell: OnceLock<usize> = OnceLock::new();
542        let inits = AtomicUsize::new(0);
543        let gate = Barrier::new(THREADS);
544
545        std::thread::scope(|s| {
546            for id in 0..THREADS {
547                let (cell, inits, gate) = (&cell, &inits, &gate);
548                let _ = s.spawn(move || {
549                    gate.wait(); // maximize contention on the CAS
550                    let v = *cell.get_or_init(|| {
551                        inits.fetch_add(1, Ordering::SeqCst);
552                        id
553                    });
554                    // Every racer must observe the same winner.
555                    assert_eq!(v, *cell.get().expect("initialized after get_or_init"));
556                    v
557                });
558            }
559        });
560
561        assert_eq!(inits.load(Ordering::SeqCst), 1);
562        let winner = cell.get().copied().expect("initialized");
563        assert!(winner < THREADS);
564    }
565
566    // The `std` OnceLock documents that a panicking `f` leaves the cell
567    // *uninitialized* (and re-initializable) rather than poisoned.
568    //
569    // The `no_std` shim in this file does NOT hold this property: it leaves
570    // `state == BUSY`, so any later `get_or_init` spins forever. This test is
571    // therefore std-gated on purpose — running it under `no_std` would hang the
572    // test binary instead of failing it.
573    #[cfg(feature = "std")]
574    #[test]
575    fn oncelock_panicking_initializer_leaves_cell_reusable() {
576        let cell: OnceLock<u32> = OnceLock::new();
577
578        let prev = std::panic::take_hook();
579        std::panic::set_hook(Box::new(|_| {})); // keep the expected panic quiet
580        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
581            cell.get_or_init(|| panic!("initializer blew up"));
582        }));
583        std::panic::set_hook(prev);
584
585        assert!(caught.is_err(), "the panic must propagate to the caller");
586        assert!(cell.get().is_none(), "cell must remain uninitialized");
587        assert_eq!(*cell.get_or_init(|| 42), 42, "cell must still be usable");
588    }
589
590    // ---------------------------------------------------------------
591    // DefaultHasher — construction / determinism
592    // ---------------------------------------------------------------
593
594    fn hash_bytes(bytes: &[u8]) -> u64 {
595        let mut h = DefaultHasher::new();
596        h.write(bytes);
597        h.finish()
598    }
599
600    fn hash_u64(word: u64) -> u64 {
601        let mut h = DefaultHasher::new();
602        h.write_u64(word);
603        h.finish()
604    }
605
606    #[test]
607    fn hasher_new_and_default_agree_and_are_deterministic() {
608        assert_eq!(DefaultHasher::new().finish(), DefaultHasher::new().finish());
609        assert_eq!(
610            DefaultHasher::new().finish(),
611            DefaultHasher::default().finish()
612        );
613    }
614
615    #[test]
616    fn hasher_is_deterministic_within_a_run() {
617        assert_eq!(hash_bytes(b"azul"), hash_bytes(b"azul"));
618        assert_eq!(hash_u64(0xDEAD_BEEF_CAFE_F00D), hash_u64(0xDEAD_BEEF_CAFE_F00D));
619    }
620
621    #[test]
622    fn hasher_distinguishes_different_inputs() {
623        assert_ne!(hash_bytes(b"a"), hash_bytes(b"b"));
624        assert_ne!(hash_u64(0), hash_u64(1));
625    }
626
627    #[test]
628    fn hasher_is_order_sensitive() {
629        let mut a = DefaultHasher::new();
630        a.write_u64(1);
631        a.write_u64(2);
632
633        let mut b = DefaultHasher::new();
634        b.write_u64(2);
635        b.write_u64(1);
636
637        assert_ne!(a.finish(), b.finish());
638    }
639
640    #[test]
641    fn hasher_finish_does_not_consume_state() {
642        let mut h = DefaultHasher::new();
643        h.write_u64(7);
644        let first = h.finish();
645        // `finish` must be a pure read: calling it twice returns the same value.
646        assert_eq!(first, h.finish());
647        // ...and further writes must keep mutating the same running state.
648        h.write_u64(7);
649        assert_ne!(first, h.finish());
650    }
651
652    // ---------------------------------------------------------------
653    // DefaultHasher — numeric limits / overflow (exercises the private `add`
654    // via its 1:1 forwarders `write_u64` / `write_usize` / `write_u8`)
655    // ---------------------------------------------------------------
656
657    #[test]
658    fn hasher_handles_integer_limits_without_panicking() {
659        // `add` does a `wrapping_mul`; a debug build must not overflow-panic.
660        for word in [
661            0u64,
662            1,
663            u64::MAX,
664            u64::MAX - 1,
665            i64::MIN as u64, // 0x8000_0000_0000_0000 — "negative" bit pattern
666            i64::MAX as u64,
667            -1i64 as u64,
668            1 << 63,
669            usize::MAX as u64,
670        ] {
671            let h = hash_u64(word);
672            // deterministic + no panic; value itself is impl-defined
673            assert_eq!(h, hash_u64(word));
674        }
675
676        let mut h = DefaultHasher::new();
677        h.write_usize(usize::MAX);
678        h.write_usize(0);
679        h.write_u8(u8::MAX);
680        h.write_u8(0);
681        let _ = h.finish();
682    }
683
684    #[test]
685    fn hasher_repeated_max_words_do_not_overflow_panic() {
686        // Hammer the wrapping rotate/xor/multiply chain: every iteration
687        // overflows u64. Must wrap, never panic (even in a debug profile).
688        let mut h = DefaultHasher::new();
689        for _ in 0..10_000 {
690            h.write_u64(u64::MAX);
691        }
692        let a = h.finish();
693
694        let mut h2 = DefaultHasher::new();
695        for _ in 0..10_000 {
696            h2.write_u64(u64::MAX);
697        }
698        assert_eq!(a, h2.finish(), "overflowing chain must stay deterministic");
699    }
700
701    #[test]
702    fn hasher_zero_words_are_deterministic() {
703        let mut h = DefaultHasher::new();
704        for _ in 0..1_000 {
705            h.write_u64(0);
706        }
707        let a = h.finish();
708
709        let mut h2 = DefaultHasher::new();
710        for _ in 0..1_000 {
711            h2.write_u64(0);
712        }
713        assert_eq!(a, h2.finish());
714    }
715
716    // ---------------------------------------------------------------
717    // DefaultHasher — `write` chunking / boundaries / unicode
718    // ---------------------------------------------------------------
719
720    #[test]
721    fn hasher_write_empty_slice_does_not_panic() {
722        let mut h = DefaultHasher::new();
723        h.write(&[]);
724        h.write(&[]);
725        let a = h.finish();
726
727        let mut h2 = DefaultHasher::new();
728        h2.write(&[]);
729        h2.write(&[]);
730        assert_eq!(a, h2.finish());
731    }
732
733    #[test]
734    fn hasher_write_covers_every_chunk_boundary() {
735        // The `no_std` impl walks `chunks(8)` and zero-pads the tail; lengths
736        // 0..=24 cover empty, short, exact-multiple and ragged-tail cases.
737        let data: Vec<u8> = (0u8..=24).collect();
738        for len in 0..=24usize {
739            let slice = &data[..len];
740            assert_eq!(hash_bytes(slice), hash_bytes(slice), "len {len}");
741        }
742        // A short slice must not collide with the same slice explicitly padded
743        // out past the next 8-byte chunk boundary.
744        assert_ne!(hash_bytes(&[1u8]), hash_bytes(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0]));
745    }
746
747    // `write` must not swallow a trailing zero byte: `[1]` and `[1, 0]` are
748    // different inputs and must hash differently.
749    //
750    // The `no_std` shim FAILS this: it zero-pads the final `chunks(8)` chunk
751    // and mixes in no length, so `[1]` and `[1, 0]` both become the word
752    // `0x0000_0000_0000_0001` — a guaranteed collision for every pair of byte
753    // strings differing only in trailing zeros. Kept as a live assertion for
754    // the (default) `std` build and `ignore`d rather than weakened under
755    // `no_std`; see the autotest report.
756    #[cfg_attr(
757        not(feature = "std"),
758        ignore = "no_std DefaultHasher zero-pads without length mixing: hash([1]) == hash([1, 0])"
759    )]
760    #[test]
761    fn hasher_write_does_not_swallow_trailing_zero_bytes() {
762        assert_ne!(hash_bytes(&[1u8]), hash_bytes(&[1u8, 0]));
763        assert_ne!(hash_bytes(b"az"), hash_bytes(b"az\0"));
764        assert_ne!(hash_bytes(&[]), hash_bytes(&[0u8]));
765    }
766
767    #[test]
768    fn hasher_handles_huge_input() {
769        let big: Vec<u8> = (0..(1 << 16)).map(|i| (i % 251) as u8).collect();
770        let a = hash_bytes(&big);
771        assert_eq!(a, hash_bytes(&big));
772
773        // A single flipped byte in the middle must change the digest.
774        let mut flipped = big.clone();
775        flipped[1 << 15] ^= 0xFF;
776        assert_ne!(a, hash_bytes(&flipped));
777    }
778
779    #[test]
780    fn hasher_handles_unicode_and_nul_bytes() {
781        for s in [
782            "",
783            "\u{0}",
784            "ascii",
785            "héllo wörld",
786            "日本語テキスト",
787            "🦀🔥👨‍👩‍👧‍👦",
788            "a\u{0}b",
789            "\u{FEFF}bom",
790            "\u{10FFFF}",
791        ] {
792            let mut h = DefaultHasher::new();
793            s.hash(&mut h);
794            let a = h.finish();
795
796            let mut h2 = DefaultHasher::new();
797            s.hash(&mut h2);
798            assert_eq!(a, h2.finish(), "unstable hash for {s:?}");
799        }
800
801        // Interior NUL must not truncate the input (C-string style bug).
802        let mut a = DefaultHasher::new();
803        "a\u{0}b".hash(&mut a);
804        let mut b = DefaultHasher::new();
805        "a".hash(&mut b);
806        assert_ne!(a.finish(), b.finish());
807    }
808
809    #[test]
810    fn hasher_respects_eq_hash_contract_for_std_types() {
811        fn digest<T: Hash>(t: &T) -> u64 {
812            let mut h = DefaultHasher::new();
813            t.hash(&mut h);
814            h.finish()
815        }
816
817        // Equal values must hash equal.
818        assert_eq!(digest(&String::from("x")), digest(&String::from("x")));
819        assert_eq!(digest(&alloc::vec![1u64, 2, 3]), digest(&alloc::vec![1u64, 2, 3]));
820        assert_eq!(digest(&(1u8, "a")), digest(&(1u8, "a")));
821
822        // Length must be part of the digest: [1,2] vs [1,2,0] must differ...
823        assert_ne!(digest(&alloc::vec![1u8, 2]), digest(&alloc::vec![1u8, 2, 0]));
824        // ...and prefix-concatenation must not collide ("ab" vs "a"+"b" fields).
825        assert_ne!(digest(&("ab", "")), digest(&("a", "b")));
826    }
827
828    // ---------------------------------------------------------------
829    // `no_std` shim internals: exact FxHasher-style formula of the private
830    // `add`, reached through its 1:1 forwarder `write_u64`.
831    // ---------------------------------------------------------------
832
833    #[cfg(not(feature = "std"))]
834    #[test]
835    fn nostd_hasher_add_matches_documented_formula() {
836        const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
837        const ROTATE: u32 = 5;
838
839        fn expect(words: &[u64]) -> u64 {
840            words
841                .iter()
842                .fold(0u64, |h, w| (h.rotate_left(ROTATE) ^ w).wrapping_mul(SEED))
843        }
844
845        assert_eq!(DefaultHasher::new().finish(), 0, "fresh state must be 0");
846
847        for words in [
848            &[0u64][..],
849            &[1][..],
850            &[u64::MAX][..],
851            &[i64::MIN as u64][..],
852            &[u64::MAX, u64::MAX, u64::MAX][..],
853            &[0, u64::MAX, 0, 1 << 63][..],
854        ] {
855            let mut h = DefaultHasher::new();
856            for w in words {
857                h.write_u64(*w);
858            }
859            assert_eq!(h.finish(), expect(words), "formula drift for {words:?}");
860        }
861    }
862
863    #[cfg(not(feature = "std"))]
864    #[test]
865    fn nostd_hasher_zero_is_an_absorbing_state() {
866        // Documented FxHasher weakness, asserted so it stays *intentional*:
867        // from a zero state, hashing zero words keeps the state at zero
868        // ((0.rotate_left(5) ^ 0) * SEED == 0).
869        let mut h = DefaultHasher::new();
870        for _ in 0..64 {
871            h.write_u64(0);
872        }
873        assert_eq!(h.finish(), 0);
874
875        // Leading zero words are therefore invisible: hash([0, x]) == hash([x]).
876        let mut a = DefaultHasher::new();
877        a.write_u64(0);
878        a.write_u64(0xABCD);
879        let mut b = DefaultHasher::new();
880        b.write_u64(0xABCD);
881        assert_eq!(a.finish(), b.finish());
882    }
883
884    #[cfg(not(feature = "std"))]
885    #[test]
886    fn nostd_hasher_write_empty_slice_is_a_noop() {
887        // `chunks(8)` over an empty slice yields nothing, so the state is untouched.
888        let mut h = DefaultHasher::new();
889        h.write(b"seed");
890        let before = h.finish();
891        h.write(&[]);
892        assert_eq!(h.finish(), before);
893    }
894
895    // ---------------------------------------------------------------
896    // Public type aliases — ordering / dedup invariants
897    // ---------------------------------------------------------------
898
899    #[test]
900    fn ordered_map_iterates_in_key_order() {
901        let mut m: OrderedMap<i64, &str> = OrderedMap::new();
902        for (k, v) in [(i64::MAX, "max"), (0, "zero"), (i64::MIN, "min"), (-1, "neg")] {
903            let _ = m.insert(k, v);
904        }
905        let keys: Vec<i64> = m.keys().copied().collect();
906        assert_eq!(keys, alloc::vec![i64::MIN, -1, 0, i64::MAX]);
907
908        // Re-insert must overwrite, not duplicate.
909        assert_eq!(m.insert(0, "zero2"), Some("zero"));
910        assert_eq!(m.len(), 4);
911        assert_eq!(m.get(&0).copied(), Some("zero2"));
912    }
913
914    #[test]
915    fn fast_btree_set_dedups_and_orders() {
916        let mut s: FastBTreeSet<u32> = FastBTreeSet::new();
917        assert!(s.insert(u32::MAX));
918        assert!(s.insert(0));
919        assert!(!s.insert(0), "duplicate insert must report false");
920        assert!(s.insert(1));
921
922        assert_eq!(s.len(), 3);
923        assert_eq!(s.iter().copied().collect::<Vec<u32>>(), alloc::vec![0, 1, u32::MAX]);
924        assert!(s.contains(&u32::MAX));
925        assert!(!s.contains(&2));
926    }
927}