1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use super::*;
6

            
7
    // AUDIT: FFI slice/str accessors must return an empty slice (not form a
8
    // slice over a null/dangling ptr, which is UB) when handed a null or
9
    // zero-length descriptor from C.
10
    #[test]
11
1
    fn refstr_null_and_empty_is_empty_str() {
12
1
        let null = Refstr {
13
1
            ptr: core::ptr::null(),
14
1
            len: 0,
15
1
        };
16
1
        assert_eq!(null.as_str(), "");
17

            
18
        // null ptr but nonzero len (garbage from FFI) must also not deref.
19
1
        let null_lenful = Refstr {
20
1
            ptr: core::ptr::null(),
21
1
            len: 5,
22
1
        };
23
1
        assert_eq!(null_lenful.as_str(), "");
24

            
25
1
        let s = "hello";
26
1
        let good: Refstr = s.into();
27
1
        assert_eq!(good.as_str(), "hello");
28
1
    }
29

            
30
    #[test]
31
1
    fn refstr_vec_ref_null_is_empty_slice() {
32
1
        let null = RefstrVecRef {
33
1
            ptr: core::ptr::null(),
34
1
            len: 3,
35
1
        };
36
1
        assert!(null.as_slice().is_empty());
37
1
    }
38

            
39
    #[test]
40
1
    fn u8_vec_ref_null_is_empty_slice() {
41
1
        let null = U8VecRef {
42
1
            ptr: core::ptr::null(),
43
1
            len: 8,
44
1
        };
45
1
        assert!(null.as_slice().is_empty());
46

            
47
1
        let data = [1u8, 2, 3];
48
1
        let good: U8VecRef = (&data[..]).into();
49
1
        assert_eq!(good.as_slice(), &[1, 2, 3]);
50
1
    }
51
}
52

            
53
#[cfg(test)]
54
#[allow(clippy::float_cmp)] // exact f32 compares are the point: these assert bit-exact round-trips
55
                            // / lossy-cast values
56
mod autotest_generated {
57
    use super::*;
58

            
59
    // ---------------------------------------------------------------------
60
    // Test scaffolding: a "null" GL context.
61
    //
62
    // Every field of `GenericGlContext` is a `*mut c_void` function pointer
63
    // (780 of them, no other field types), and every gl-context-loader method
64
    // null-checks its pointer and returns a default (0 / empty Vec / "") rather
65
    // than calling through. So an all-zero context is a SAFE no-op GL driver:
66
    // it lets us drive azul's whole wrapper surface off-GPU and assert how the
67
    // wrappers behave when the driver hands back degenerate values -- which is
68
    // exactly the "broken driver" path `is_gl_usable()` exists for.
69
    // ---------------------------------------------------------------------
70
    fn null_gl() -> Rc<GenericGlContext> {
71
        // SAFETY: `GenericGlContext` is `repr(C)` and every field is a raw
72
        // pointer, for which the all-zero bit pattern (null) is valid.
73
        Rc::new(unsafe { core::mem::zeroed::<GenericGlContext>() })
74
    }
75

            
76
    fn null_ctx() -> GlContextPtr {
77
        GlContextPtr::new(RendererType::Software, null_gl())
78
    }
79

            
80
    fn test_texture(texture_id: GLuint, width: u32, height: u32) -> Texture {
81
        Texture::create(
82
            texture_id,
83
            TextureFlags {
84
                is_opaque: false,
85
                is_video_texture: false,
86
            },
87
            PhysicalSizeU32 { width, height },
88
            ColorU {
89
                r: 1,
90
                g: 2,
91
                b: 3,
92
                a: 4,
93
            },
94
            null_ctx(),
95
            RawImageFormat::RGBA8,
96
        )
97
    }
98

            
99
    const ALL_ATTRIB_TYPES: [VertexAttributeType; 5] = [
100
        VertexAttributeType::Float,
101
        VertexAttributeType::Double,
102
        VertexAttributeType::UnsignedByte,
103
        VertexAttributeType::UnsignedShort,
104
        VertexAttributeType::UnsignedInt,
105
    ];
106

            
107
    const ALL_INDEX_FORMATS: [IndexBufferFormat; 6] = [
108
        IndexBufferFormat::Points,
109
        IndexBufferFormat::Lines,
110
        IndexBufferFormat::LineStrip,
111
        IndexBufferFormat::Triangles,
112
        IndexBufferFormat::TriangleStrip,
113
        IndexBufferFormat::TriangleFan,
114
    ];
115

            
116
    // =====================================================================
117
    // Refstr / *VecRef / *VecRefMut -- FFI slice+str accessors
118
    // (parsers: malformed / huge / boundary / unicode)
119
    // =====================================================================
120

            
121
    #[test]
122
    fn refstr_roundtrips_unicode_multibyte_and_combining_marks() {
123
        // Non-ASCII, emoji, and combining marks must survive byte-exactly:
124
        // `as_str` rebuilds the str via `from_utf8_unchecked` over the raw bytes.
125
        for s in [
126
            "\u{1F600}",
127
            "日本語のテキスト",
128
            "e\u{0301}\u{0328}combining",
129
            "\u{0}nul\u{0}embedded\u{0}",
130
            "\u{FFFD}\u{200B}zero-width",
131
        ] {
132
            let r: Refstr = s.into();
133
            assert_eq!(r.as_str(), s);
134
            assert_eq!(r.as_str().len(), s.len());
135
        }
136
    }
137

            
138
    #[test]
139
    fn refstr_len_zero_over_nonempty_buffer_is_empty_not_dangling() {
140
        // len == 0 must short-circuit even when ptr is a perfectly valid buffer.
141
        let backing = "not empty";
142
        let r = Refstr {
143
            ptr: backing.as_ptr(),
144
            len: 0,
145
        };
146
        assert_eq!(r.as_str(), "");
147
    }
148

            
149
    #[test]
150
    fn refstr_huge_input_does_not_hang() {
151
        // 1 MB single-token string: as_str is O(1) (no scan), so this must be instant.
152
        let huge = "x".repeat(1_000_000);
153
        let r: Refstr = huge.as_str().into();
154
        assert_eq!(r.as_str().len(), 1_000_000);
155
        assert_eq!(r.as_str(), huge.as_str());
156
    }
157

            
158
    #[test]
159
    fn refstr_debug_on_null_does_not_panic() {
160
        let null = Refstr {
161
            ptr: core::ptr::null(),
162
            len: usize::MAX,
163
        };
164
        // Debug goes through as_str(); a null guard failure here would be UB, not a panic.
165
        assert_eq!(alloc::format!("{null:?}"), "\"\"");
166
    }
167

            
168
    #[test]
169
    fn refstr_clone_preserves_ptr_and_len() {
170
        let s = "clone me";
171
        let r: Refstr = s.into();
172
        let c = r.clone();
173
        assert_eq!(c.as_str(), s);
174
        assert!(core::ptr::eq(c.ptr, r.ptr));
175
        assert_eq!(c.len, r.len);
176
    }
177

            
178
    #[test]
179
    fn every_vec_ref_with_null_ptr_and_nonzero_len_is_empty() {
180
        // The FFI boundary can hand us a null ptr with a garbage (nonzero) len.
181
        // Forming a slice over null is UB, so every accessor must return empty.
182
        const GARBAGE_LEN: usize = usize::MAX;
183

            
184
        assert!(RefstrVecRef {
185
            ptr: core::ptr::null(),
186
            len: GARBAGE_LEN
187
        }
188
        .as_slice()
189
        .is_empty());
190
        assert!(GLuintVecRef {
191
            ptr: core::ptr::null(),
192
            len: GARBAGE_LEN
193
        }
194
        .as_slice()
195
        .is_empty());
196
        assert!(GLenumVecRef {
197
            ptr: core::ptr::null(),
198
            len: GARBAGE_LEN
199
        }
200
        .as_slice()
201
        .is_empty());
202
        assert!(U8VecRef {
203
            ptr: core::ptr::null(),
204
            len: GARBAGE_LEN
205
        }
206
        .as_slice()
207
        .is_empty());
208
        assert!(F32VecRef {
209
            ptr: core::ptr::null(),
210
            len: GARBAGE_LEN
211
        }
212
        .as_slice()
213
        .is_empty());
214
        assert!(I32VecRef {
215
            ptr: core::ptr::null(),
216
            len: GARBAGE_LEN
217
        }
218
        .as_slice()
219
        .is_empty());
220

            
221
        // ...and the same for the mutable variants, through BOTH accessors.
222
        let mut m64 = GLint64VecRefMut {
223
            ptr: core::ptr::null_mut(),
224
            len: GARBAGE_LEN,
225
        };
226
        assert!(m64.as_slice().is_empty());
227
        assert!(m64.as_mut_slice().is_empty());
228

            
229
        let mut mf = GLfloatVecRefMut {
230
            ptr: core::ptr::null_mut(),
231
            len: GARBAGE_LEN,
232
        };
233
        assert!(mf.as_slice().is_empty());
234
        assert!(mf.as_mut_slice().is_empty());
235

            
236
        let mut mi = GLintVecRefMut {
237
            ptr: core::ptr::null_mut(),
238
            len: GARBAGE_LEN,
239
        };
240
        assert!(mi.as_slice().is_empty());
241
        assert!(mi.as_mut_slice().is_empty());
242

            
243
        let mut mb = GLbooleanVecRefMut {
244
            ptr: core::ptr::null_mut(),
245
            len: GARBAGE_LEN,
246
        };
247
        assert!(mb.as_slice().is_empty());
248
        assert!(mb.as_mut_slice().is_empty());
249

            
250
        let mut mu8 = U8VecRefMut {
251
            ptr: core::ptr::null_mut(),
252
            len: GARBAGE_LEN,
253
        };
254
        assert!(mu8.as_slice().is_empty());
255
        assert!(mu8.as_mut_slice().is_empty());
256
    }
257

            
258
    #[test]
259
    fn vec_refs_roundtrip_from_slice() {
260
        let u: [GLuint; 3] = [0, 1, u32::MAX];
261
        assert_eq!(GLuintVecRef::from(&u[..]).as_slice(), &u[..]);
262

            
263
        let e: [GLenum; 2] = [gl::TRIANGLES, u32::MAX];
264
        assert_eq!(GLenumVecRef::from(&e[..]).as_slice(), &e[..]);
265

            
266
        let b: [u8; 4] = [0, 127, 128, 255];
267
        assert_eq!(U8VecRef::from(&b[..]).as_slice(), &b[..]);
268

            
269
        let i: [i32; 3] = [i32::MIN, 0, i32::MAX];
270
        assert_eq!(I32VecRef::from(&i[..]).as_slice(), &i[..]);
271

            
272
        // Empty (but non-null) slices must also come back empty.
273
        let empty: [u8; 0] = [];
274
        assert!(U8VecRef::from(&empty[..]).as_slice().is_empty());
275
    }
276

            
277
    #[test]
278
    fn f32_vec_ref_preserves_nan_inf_and_subnormals_bit_exactly() {
279
        // These are pointer casts, not conversions: NaN payloads and -0.0 must
280
        // survive bit-for-bit (a NaN-normalizing copy would be a real bug).
281
        let vals: [f32; 6] = [
282
            f32::NAN,
283
            f32::INFINITY,
284
            f32::NEG_INFINITY,
285
            -0.0,
286
            f32::MIN_POSITIVE / 2.0, // subnormal
287
            f32::MAX,
288
        ];
289
        let r = F32VecRef::from(&vals[..]);
290
        let got = r.as_slice();
291
        assert_eq!(got.len(), vals.len());
292
        for (g, v) in got.iter().zip(vals.iter()) {
293
            assert_eq!(g.to_bits(), v.to_bits());
294
        }
295
        assert!(got[0].is_nan());
296
        assert!(got[3].is_sign_negative());
297
    }
298

            
299
    #[test]
300
    fn glint64_vec_ref_mut_handles_boundary_values() {
301
        let mut vals: [GLint64; 4] = [i64::MIN, -1, 0, i64::MAX];
302
        let mut r = GLint64VecRefMut::from(&mut vals[..]);
303
        assert_eq!(r.as_slice(), &[i64::MIN, -1, 0, i64::MAX]);
304

            
305
        // Writes through as_mut_slice must land in the caller's buffer.
306
        r.as_mut_slice()[0] = i64::MAX;
307
        r.as_mut_slice()[3] = i64::MIN;
308
        assert_eq!(vals, [i64::MAX, -1, 0, i64::MIN]);
309
    }
310

            
311
    #[test]
312
    fn mut_vec_refs_write_through_to_the_caller_buffer() {
313
        let mut floats: [GLfloat; 2] = [0.0, 0.0];
314
        GLfloatVecRefMut::from(&mut floats[..]).as_mut_slice()[1] = f32::NAN;
315
        assert!(floats[1].is_nan());
316

            
317
        let mut ints: [GLint; 2] = [0, 0];
318
        GLintVecRefMut::from(&mut ints[..]).as_mut_slice()[0] = i32::MIN;
319
        assert_eq!(ints[0], i32::MIN);
320

            
321
        let mut bools: [GLboolean; 2] = [0, 0];
322
        GLbooleanVecRefMut::from(&mut bools[..]).as_mut_slice()[1] = 255;
323
        assert_eq!(bools[1], 255);
324

            
325
        let mut bytes: [u8; 3] = [1, 2, 3];
326
        U8VecRefMut::from(&mut bytes[..]).as_mut_slice()[2] = 0;
327
        assert_eq!(bytes, [1, 2, 0]);
328
    }
329

            
330
    #[test]
331
    fn u8_vec_ref_ord_eq_hash_agree_with_the_underlying_slice() {
332
        use alloc::collections::BTreeSet;
333
        use core::hash::{BuildHasher, Hasher};
334

            
335
        let a = [1u8, 2, 3];
336
        let b = [1u8, 2, 4];
337
        let ra = U8VecRef::from(&a[..]);
338
        let rb = U8VecRef::from(&b[..]);
339

            
340
        assert_eq!(ra, U8VecRef::from(&a[..]));
341
        assert!(ra < rb);
342
        assert_eq!(ra.cmp(&rb), a[..].cmp(&b[..]));
343

            
344
        // A null ref must compare equal to an empty one (both are the empty slice).
345
        let null = U8VecRef {
346
            ptr: core::ptr::null(),
347
            len: 99,
348
        };
349
        let empty: [u8; 0] = [];
350
        assert_eq!(null, U8VecRef::from(&empty[..]));
351

            
352
        // Hash must be consistent with Eq (equal values -> equal hashes).
353
        fn hash_of(v: &U8VecRef) -> u64 {
354
            core::hash::BuildHasherDefault::<TestHasher>::default().hash_one(v)
355
        }
356
        #[derive(Default)]
357
        struct TestHasher(u64);
358
        impl Hasher for TestHasher {
359
            fn finish(&self) -> u64 {
360
                self.0
361
            }
362
            fn write(&mut self, bytes: &[u8]) {
363
                for b in bytes {
364
                    self.0 = self.0.wrapping_mul(31).wrapping_add(u64::from(*b));
365
                }
366
            }
367
        }
368
        assert_eq!(hash_of(&ra), hash_of(&U8VecRef::from(&a[..])));
369
        assert_eq!(hash_of(&null), hash_of(&U8VecRef::from(&empty[..])));
370

            
371
        // Ord must be a total order good enough for a BTreeSet.
372
        let mut set = BTreeSet::new();
373
        set.insert(ra.clone());
374
        set.insert(U8VecRef::from(&a[..]));
375
        set.insert(rb);
376
        assert_eq!(set.len(), 2);
377
    }
378

            
379
    #[test]
380
    fn refstr_vec_ref_roundtrips_and_maps_back_to_strs() {
381
        let strs = ["", "a", "\u{1F600}"];
382
        let refstrs: Vec<Refstr> = strs.iter().map(|s| Refstr::from(*s)).collect();
383
        let vec_ref = RefstrVecRef::from(&refstrs[..]);
384
        let got: Vec<&str> = vec_ref.as_slice().iter().map(Refstr::as_str).collect();
385
        assert_eq!(got, strs);
386
    }
387

            
388
    // =====================================================================
389
    // GLsyncPtr (constructor + round-trip)
390
    // =====================================================================
391

            
392
    #[test]
393
    fn glsync_ptr_roundtrips_null_and_nonnull() {
394
        let null = GLsyncPtr::new(core::ptr::null());
395
        assert!(null.clone().get().is_null());
396
        assert_eq!(alloc::format!("{null:?}"), "0x0");
397

            
398
        // A non-null (never dereferenced) sentinel must round-trip identically.
399
        let sentinel = usize::MAX as *const c_void;
400
        let p = GLsyncPtr::new(sentinel);
401
        assert_eq!(p.clone().get() as usize, usize::MAX);
402
        assert!(p.run_destructor);
403
    }
404

            
405
    // =====================================================================
406
    // shader_with_glsl_version (parser: the `#version` line swap)
407
    // =====================================================================
408

            
409
    #[cfg(feature = "std")]
410
    #[test]
411
    fn shader_with_glsl_version_replaces_only_the_first_line() {
412
        let src = b"#version 150\nbody line 1\nbody line 2";
413
        let out = shader_with_glsl_version(src, b"#version 300 es\n");
414
        assert_eq!(out, b"#version 300 es\nbody line 1\nbody line 2".to_vec());
415
    }
416

            
417
    #[cfg(feature = "std")]
418
    #[test]
419
    fn shader_with_glsl_version_empty_src_yields_just_the_version_line() {
420
        // No newline in src -> body_start = 0 (the map_or default), so the whole
421
        // (empty) src is kept and only the version line is prepended.
422
        assert_eq!(
423
            shader_with_glsl_version(b"", b"#version 150\n"),
424
            b"#version 150\n".to_vec()
425
        );
426
    }
427

            
428
    #[cfg(feature = "std")]
429
    #[test]
430
    fn shader_with_glsl_version_src_without_newline_is_kept_whole() {
431
        // A src with NO newline has no first line to strip: body_start stays 0,
432
        // so the version line is prepended and nothing is lost.
433
        let out = shader_with_glsl_version(b"void main(){}", b"#version 150\n");
434
        assert_eq!(out, b"#version 150\nvoid main(){}".to_vec());
435
    }
436

            
437
    #[cfg(feature = "std")]
438
    #[test]
439
    fn shader_with_glsl_version_leading_newline_drops_only_that_newline() {
440
        let out = shader_with_glsl_version(b"\nrest", b"V\n");
441
        assert_eq!(out, b"V\nrest".to_vec());
442
    }
443

            
444
    #[cfg(feature = "std")]
445
    #[test]
446
    fn shader_with_glsl_version_empty_version_line_still_strips_first_line() {
447
        let out = shader_with_glsl_version(b"#version 150\nbody", b"");
448
        assert_eq!(out, b"body".to_vec());
449

            
450
        // Both empty -> empty, no panic.
451
        assert!(shader_with_glsl_version(b"", b"").is_empty());
452
    }
453

            
454
    #[cfg(feature = "std")]
455
    #[test]
456
    fn shader_with_glsl_version_is_byte_exact_on_invalid_utf8_and_nul_bytes() {
457
        // Shader sources are bytes, not str: invalid UTF-8 / NULs must pass
458
        // through untouched (this is fed straight to glShaderSource).
459
        let src = b"#version 150\n\xFF\xFE\x00\x80body";
460
        let out = shader_with_glsl_version(src, b"#version 100\n");
461
        assert_eq!(out, b"#version 100\n\xFF\xFE\x00\x80body".to_vec());
462

            
463
        // A src that is ONLY invalid bytes with no newline is kept whole.
464
        let out2 = shader_with_glsl_version(&[0xFF, 0xFE, 0x00], b"V\n");
465
        assert_eq!(out2, vec![b'V', b'\n', 0xFF, 0xFE, 0x00]);
466
    }
467

            
468
    #[cfg(feature = "std")]
469
    #[test]
470
    fn shader_with_glsl_version_handles_a_1mb_source_without_hanging() {
471
        let mut src = b"#version 150\n".to_vec();
472
        src.resize(src.len() + 1_000_000, b'x');
473
        let out = shader_with_glsl_version(&src, b"#version 300 es\n");
474
        assert_eq!(out.len(), b"#version 300 es\n".len() + 1_000_000);
475
        assert!(out.starts_with(b"#version 300 es\n"));
476
        assert!(out.ends_with(b"xxxx"));
477
    }
478

            
479
    // =====================================================================
480
    // glsl_version_candidates (invariants the version probe relies on)
481
    // =====================================================================
482

            
483
    #[test]
484
    fn glsl_version_candidates_are_wellformed_and_distinct() {
485
        for gl_type in [GlType::Gl, GlType::Gles] {
486
            let candidates = glsl_version_candidates(gl_type);
487
            assert!(
488
                !candidates.is_empty(),
489
                "{gl_type:?} must have at least one candidate or the probe can never succeed"
490
            );
491
            for c in candidates {
492
                // GlContextPtr::new parses these back out with
493
                // `trim().trim_start_matches("#version ")`, which requires
494
                // valid UTF-8, the exact prefix, and a trailing newline.
495
                let s = core::str::from_utf8(c).expect("candidate must be valid UTF-8");
496
                assert!(s.starts_with("#version "), "{s:?}");
497
                assert!(s.ends_with('\n'), "{s:?}");
498
                let parsed = s.trim().trim_start_matches("#version ");
499
                assert!(!parsed.is_empty(), "{s:?} must parse to a nonempty version");
500
            }
501
            // No duplicates: a repeated candidate would just re-probe a known failure.
502
            for (i, a) in candidates.iter().enumerate() {
503
                for b in candidates.iter().skip(i + 1) {
504
                    assert_ne!(a, b, "duplicate candidate in {gl_type:?}");
505
                }
506
            }
507
        }
508

            
509
        // The GL and GLES lists must be disjoint (a GLES driver rejects `#version 150`).
510
        for g in glsl_version_candidates(GlType::Gl) {
511
            assert!(!glsl_version_candidates(GlType::Gles).contains(g));
512
        }
513

            
514
        // Documented examples from the API docs: "150" (GL) and "300 es" (GLES).
515
        let first_gl = core::str::from_utf8(glsl_version_candidates(GlType::Gl)[0]).unwrap();
516
        assert_eq!(first_gl.trim().trim_start_matches("#version "), "150");
517
        let first_es = core::str::from_utf8(glsl_version_candidates(GlType::Gles)[0]).unwrap();
518
        assert_eq!(first_es.trim().trim_start_matches("#version "), "300 es");
519
    }
520

            
521
    #[test]
522
    fn gl_type_from_context_gl_type_is_total() {
523
        assert_eq!(GlType::from(GlContextGlType::Gl), GlType::Gl);
524
        assert_eq!(GlType::from(GlContextGlType::GlEs), GlType::Gles);
525
    }
526

            
527
    // =====================================================================
528
    // GlContextPtr -- construction + the documented "unusable driver" fallback
529
    // =====================================================================
530

            
531
    #[test]
532
    fn gl_context_ptr_software_is_never_usable_and_has_no_shaders() {
533
        // Documented: "Always `false` for a Software context (which never
534
        // compiles these shaders)".
535
        let ctx = GlContextPtr::new(RendererType::Software, null_gl());
536
        assert!(!ctx.is_gl_usable());
537
        assert_eq!(ctx.get_svg_shader(), 0);
538
        assert_eq!(ctx.get_brush_shader(), 0);
539
        assert_eq!(ctx.get_fxaa_shader(), 0);
540
        assert_eq!(ctx.get_usable_glsl_version().as_str(), "");
541
        assert_eq!(ctx.renderer_type, RendererType::Software);
542
    }
543

            
544
    #[test]
545
    fn gl_context_ptr_hardware_with_broken_driver_falls_back_instead_of_panicking() {
546
        // THE contract `is_gl_usable()` exists for: context creation "succeeds"
547
        // but the driver compiles nothing. The probe must try every candidate
548
        // version, fail them all, and leave every program id at 0 -- so the
549
        // caller can fall back to CPU rendering -- rather than panicking or
550
        // handing out a garbage program id.
551
        let ctx = GlContextPtr::new(RendererType::Hardware, null_gl());
552
        assert!(
553
            !ctx.is_gl_usable(),
554
            "a driver that compiles nothing must report is_gl_usable() == false"
555
        );
556
        assert_eq!(ctx.get_svg_shader(), 0);
557
        assert_eq!(ctx.get_brush_shader(), 0);
558
        assert_eq!(ctx.get_fxaa_shader(), 0);
559
        assert_eq!(
560
            ctx.get_usable_glsl_version().as_str(),
561
            "",
562
            "glsl_version must be empty when the context is unusable"
563
        );
564
    }
565

            
566
    #[test]
567
    fn gl_context_ptr_get_type_defaults_to_desktop_gl_on_an_empty_version_string() {
568
        // get_type() sniffs the GL_VERSION string for "OpenGL ES"; a driver that
569
        // returns nothing must deterministically fall out as desktop Gl.
570
        assert_eq!(null_ctx().get_type(), GlType::Gl);
571
    }
572

            
573
    #[test]
574
    fn gl_context_ptr_clone_is_eq_but_distinct_contexts_are_not() {
575
        // Eq/Ord are identity-based (`as_usize` = the inner Rc address), so a
576
        // clone must compare equal and two independently created contexts must not.
577
        let a = null_ctx();
578
        let clone = a.clone();
579
        assert_eq!(a, clone);
580
        assert_eq!(a.cmp(&clone), core::cmp::Ordering::Equal);
581
        assert_eq!(a.partial_cmp(&clone), Some(core::cmp::Ordering::Equal));
582

            
583
        let b = null_ctx();
584
        assert_ne!(a, b);
585
        // Ord must be antisymmetric and consistent with PartialOrd.
586
        assert_eq!(a.cmp(&b), a.partial_cmp(&b).unwrap());
587
        assert_eq!(a.cmp(&b).reverse(), b.cmp(&a));
588

            
589
        // The clone must point at the same underlying GL context.
590
        assert!(Rc::ptr_eq(a.get(), clone.get()));
591
        assert!(!Rc::ptr_eq(a.get(), b.get()));
592
    }
593

            
594
    #[test]
595
    fn gl_context_ptr_gen_family_returns_empty_for_every_n_including_negatives() {
596
        // A driver that generates nothing returns an EMPTY list. Callers index
597
        // into this ([0] / .get(0).unwrap()), so the wrappers must at least not
598
        // panic on the way out -- and must not choke on a negative/extreme n.
599
        let ctx = null_ctx();
600
        for n in [0, 1, -1, i32::MIN, i32::MAX] {
601
            assert!(ctx.gen_buffers(n).as_slice().is_empty(), "gen_buffers({n})");
602
            assert!(
603
                ctx.gen_textures(n).as_slice().is_empty(),
604
                "gen_textures({n})"
605
            );
606
            assert!(
607
                ctx.gen_framebuffers(n).as_slice().is_empty(),
608
                "gen_framebuffers({n})"
609
            );
610
            assert!(
611
                ctx.gen_renderbuffers(n).as_slice().is_empty(),
612
                "gen_renderbuffers({n})"
613
            );
614
            assert!(
615
                ctx.gen_vertex_arrays(n).as_slice().is_empty(),
616
                "gen_vertex_arrays({n})"
617
            );
618
            assert!(ctx.gen_queries(n).as_slice().is_empty(), "gen_queries({n})");
619
        }
620
    }
621

            
622
    #[test]
623
    fn gl_context_ptr_integer_extremes_do_not_panic() {
624
        // Offsets/sizes/limits at the boundary of their integer types. These are
625
        // passed straight through to GL, so the wrapper must not do arithmetic
626
        // that overflows on the way.
627
        let ctx = null_ctx();
628
        let data = [0u8; 4];
629
        let void_ptr = || GlVoidPtrConst {
630
            ptr: data.as_ptr().cast(),
631
            run_destructor: false,
632
        };
633

            
634
        for offset in [0isize, -1, isize::MIN, isize::MAX] {
635
            for size in [0isize, -1, isize::MIN, isize::MAX] {
636
                ctx.buffer_sub_data_untyped(gl::ARRAY_BUFFER, offset, size, void_ptr());
637
                let _ = ctx.map_buffer_range(gl::ARRAY_BUFFER, offset, size, 0);
638
            }
639
        }
640
        ctx.buffer_data_untyped(gl::ARRAY_BUFFER, isize::MIN, void_ptr(), gl::STATIC_DRAW);
641

            
642
        // usize offset at the extreme (reinterpreted as a byte offset pointer).
643
        for offset in [0usize, 1, usize::MAX] {
644
            ctx.tex_sub_image_2d_pbo(
645
                gl::TEXTURE_2D,
646
                0,
647
                0,
648
                0,
649
                1,
650
                1,
651
                gl::RGBA,
652
                gl::UNSIGNED_BYTE,
653
                offset,
654
            );
655
        }
656

            
657
        ctx.pixel_store_i(gl::PACK_ALIGNMENT, i32::MIN);
658
        ctx.pixel_store_i(gl::PACK_ALIGNMENT, i32::MAX);
659
        let _ = ctx.unmap_buffer(gl::ARRAY_BUFFER);
660
    }
661

            
662
    #[test]
663
    fn gl_context_ptr_float_extremes_do_not_panic() {
664
        // NaN / inf / subnormal floats must pass through the f32 wrappers untouched.
665
        let ctx = null_ctx();
666
        for v in [
667
            0.0,
668
            1.0,
669
            -1.0,
670
            f32::NAN,
671
            f32::INFINITY,
672
            f32::NEG_INFINITY,
673
            f32::MIN,
674
            f32::MAX,
675
        ] {
676
            ctx.sample_coverage(v, false);
677
            ctx.sample_coverage(v, true);
678
            ctx.polygon_offset(v, v);
679
        }
680
    }
681

            
682
    #[test]
683
    fn gl_context_ptr_shader_source_handles_empty_unicode_and_embedded_nuls() {
684
        // shader_source NUL-terminates each string itself; an already-embedded
685
        // NUL or multibyte UTF-8 must not panic on the way through.
686
        let ctx = null_ctx();
687
        let strings: StringVec = vec![
688
            AzString::from(String::new()),
689
            AzString::from("\u{1F600} emoji".to_string()),
690
            AzString::from("has\u{0}nul".to_string()),
691
            AzString::from("x".repeat(100_000)),
692
        ]
693
        .into();
694
        ctx.shader_source(0, strings);
695

            
696
        // An empty list of sources must also be fine.
697
        ctx.shader_source(u32::MAX, Vec::<AzString>::new().into());
698
    }
699

            
700
    #[test]
701
    fn gl_context_ptr_read_pixels_sizes_the_buffer_from_the_dimensions() {
702
        // NOTE: only SAFE (small, positive) dimensions are exercised here.
703
        // Negative dimensions are a live hazard in this path -- see the report:
704
        // gl-context-loader's read_pixels does
705
        //   `vec![0; width as usize * height as usize * bit_depth]`
706
        // BEFORE its null-pointer check, so a negative width sign-extends to
707
        // ~usize::MAX and the multiply overflows (debug) / requests an
708
        // exabyte-scale allocation (release). Deliberately not provoked.
709
        let ctx = null_ctx();
710
        let px = ctx.read_pixels(0, 0, 2, 3, gl::RGBA, gl::UNSIGNED_BYTE);
711
        assert_eq!(
712
            px.len(),
713
            2 * 3 * 4,
714
            "RGBA/UNSIGNED_BYTE = 4 bytes per pixel"
715
        );
716

            
717
        // A zero-size read is the degenerate-but-safe case.
718
        assert_eq!(
719
            ctx.read_pixels(0, 0, 0, 0, gl::RGBA, gl::UNSIGNED_BYTE)
720
                .len(),
721
            0
722
        );
723
    }
724

            
725
    #[test]
726
    fn gl_context_ptr_read_pixels_into_buffer_accepts_null_and_undersized_targets() {
727
        // The destination is caller-owned here (no allocation from the dims), so
728
        // a null / empty / undersized target must simply no-op.
729
        let ctx = null_ctx();
730
        ctx.read_pixels_into_buffer(
731
            0,
732
            0,
733
            4,
734
            4,
735
            gl::RGBA,
736
            gl::UNSIGNED_BYTE,
737
            U8VecRefMut {
738
                ptr: core::ptr::null_mut(),
739
                len: 64,
740
            },
741
        );
742

            
743
        let mut small = [0u8; 1];
744
        ctx.read_pixels_into_buffer(
745
            0,
746
            0,
747
            4,
748
            4,
749
            gl::RGBA,
750
            gl::UNSIGNED_BYTE,
751
            (&mut small[..]).into(),
752
        );
753
        assert_eq!(small, [0u8; 1]);
754
    }
755

            
756
    #[test]
757
    fn gl_context_ptr_uniform_getters_accept_null_result_buffers() {
758
        let ctx = null_ctx();
759
        ctx.get_uniform_iv(
760
            0,
761
            -1,
762
            GLintVecRefMut {
763
                ptr: core::ptr::null_mut(),
764
                len: 16,
765
            },
766
        );
767
        ctx.get_uniform_fv(
768
            0,
769
            i32::MIN,
770
            GLfloatVecRefMut {
771
                ptr: core::ptr::null_mut(),
772
                len: 16,
773
            },
774
        );
775

            
776
        // ...and real buffers, at extreme locations.
777
        let mut ints = [0i32; 2];
778
        ctx.get_uniform_iv(u32::MAX, i32::MAX, (&mut ints[..]).into());
779
        let mut floats = [0f32; 2];
780
        ctx.get_uniform_fv(u32::MAX, i32::MAX, (&mut floats[..]).into());
781
    }
782

            
783
    #[test]
784
    fn gl_context_ptr_get_uniform_indices_handles_empty_and_null_name_lists() {
785
        let ctx = null_ctx();
786
        let empty: &[Refstr] = &[];
787
        assert!(ctx
788
            .get_uniform_indices(0, empty.into())
789
            .as_slice()
790
            .is_empty());
791
        assert!(ctx
792
            .get_uniform_indices(
793
                0,
794
                RefstrVecRef {
795
                    ptr: core::ptr::null(),
796
                    len: 4,
797
                },
798
            )
799
            .as_slice()
800
            .is_empty());
801
    }
802

            
803
    #[test]
804
    fn gl_context_ptr_delete_family_accepts_empty_and_null_id_lists() {
805
        // Deleting nothing must be a no-op, not an out-of-bounds read.
806
        let ctx = null_ctx();
807
        let empty: &[GLuint] = &[];
808
        ctx.delete_buffers(empty.into());
809
        ctx.delete_textures(empty.into());
810
        ctx.delete_framebuffers(empty.into());
811
        ctx.delete_renderbuffers(empty.into());
812
        ctx.delete_vertex_arrays(empty.into());
813
        ctx.delete_queries(empty.into());
814

            
815
        let null = || GLuintVecRef {
816
            ptr: core::ptr::null(),
817
            len: 7,
818
        };
819
        ctx.delete_buffers(null());
820
        ctx.delete_textures(null());
821
        ctx.delete_framebuffers(null());
822
        ctx.delete_renderbuffers(null());
823
        ctx.delete_vertex_arrays(null());
824
        ctx.delete_queries(null());
825

            
826
        // A real (bogus) id list, incl. 0 and u32::MAX, must also be fine.
827
        let ids: &[GLuint] = &[0, 1, u32::MAX];
828
        ctx.delete_buffers(ids.into());
829
        ctx.delete_textures(ids.into());
830
    }
831

            
832
    #[test]
833
    fn gl_context_ptr_draw_buffers_accepts_an_empty_list() {
834
        let ctx = null_ctx();
835
        let empty: &[GLenum] = &[];
836
        ctx.draw_buffers(empty.into());
837
        ctx.draw_buffers(GLenumVecRef {
838
            ptr: core::ptr::null(),
839
            len: 3,
840
        });
841
    }
842

            
843
    // =====================================================================
844
    // VertexAttributeType / VertexAttribute / VertexLayout (numeric + invariants)
845
    // =====================================================================
846

            
847
    #[test]
848
    fn vertex_attribute_type_mem_size_matches_the_rust_type_it_names() {
849
        assert_eq!(
850
            VertexAttributeType::Float.get_mem_size(),
851
            core::mem::size_of::<f32>()
852
        );
853
        assert_eq!(
854
            VertexAttributeType::Double.get_mem_size(),
855
            core::mem::size_of::<f64>()
856
        );
857
        assert_eq!(
858
            VertexAttributeType::UnsignedByte.get_mem_size(),
859
            core::mem::size_of::<u8>()
860
        );
861
        assert_eq!(
862
            VertexAttributeType::UnsignedShort.get_mem_size(),
863
            core::mem::size_of::<u16>()
864
        );
865
        assert_eq!(
866
            VertexAttributeType::UnsignedInt.get_mem_size(),
867
            core::mem::size_of::<u32>()
868
        );
869

            
870
        // Every size must be nonzero -- a 0 would make get_stride() collapse to 0
871
        // and silently produce a degenerate vertex layout.
872
        for t in ALL_ATTRIB_TYPES {
873
            assert!(t.get_mem_size() > 0, "{t:?}");
874
        }
875
    }
876

            
877
    #[test]
878
    fn vertex_attribute_type_gl_ids_are_distinct_and_nonzero() {
879
        for (i, a) in ALL_ATTRIB_TYPES.iter().enumerate() {
880
            assert_ne!(a.get_gl_id(), 0, "{a:?} maps to the GL 'no type' id 0");
881
            for b in ALL_ATTRIB_TYPES.iter().skip(i + 1) {
882
                assert_ne!(
883
                    a.get_gl_id(),
884
                    b.get_gl_id(),
885
                    "{a:?} and {b:?} share a GL id -- one of them would upload as the wrong type"
886
                );
887
            }
888
        }
889
        assert_eq!(VertexAttributeType::Float.get_gl_id(), gl::FLOAT);
890
        assert_eq!(
891
            VertexAttributeType::UnsignedByte.get_gl_id(),
892
            gl::UNSIGNED_BYTE
893
        );
894
    }
895

            
896
    #[test]
897
    fn vertex_attribute_get_stride_at_zero_and_at_the_overflow_boundary() {
898
        let attr = |ty, item_count| VertexAttribute {
899
            va_name: AzString::from_const_str("vAttrXY"),
900
            layout_location: OptionUsize::None,
901
            attribute_type: ty,
902
            item_count,
903
        };
904

            
905
        // Zero items -> zero stride.
906
        for t in ALL_ATTRIB_TYPES {
907
            assert_eq!(attr(t, 0).get_stride(), 0, "{t:?}");
908
        }
909

            
910
        // Exact multiplication for representative counts.
911
        assert_eq!(attr(VertexAttributeType::Float, 2).get_stride(), 8);
912
        assert_eq!(attr(VertexAttributeType::Double, 4).get_stride(), 32);
913
        assert_eq!(attr(VertexAttributeType::UnsignedByte, 3).get_stride(), 3);
914

            
915
        // The LARGEST item_count that does not overflow `mem_size * item_count`.
916
        // (NOTE: get_stride() is a plain `*`, so an item_count above this bound
917
        // overflow-panics in debug / wraps in release -- see the report.)
918
        for t in ALL_ATTRIB_TYPES {
919
            let max_items = usize::MAX / t.get_mem_size();
920
            assert_eq!(
921
                attr(t, max_items).get_stride(),
922
                max_items * t.get_mem_size(),
923
                "{t:?} at the overflow boundary"
924
            );
925
        }
926
    }
927

            
928
    #[test]
929
    fn vertex_layout_stride_is_the_sum_of_its_fields() {
930
        let attr = |name: &str, ty, item_count| VertexAttribute {
931
            va_name: AzString::from(name.to_string()),
932
            layout_location: OptionUsize::None,
933
            attribute_type: ty,
934
            item_count,
935
        };
936

            
937
        // Empty layout: zero fields, zero total stride.
938
        let empty = VertexLayout {
939
            fields: VertexAttributeVec::from_const_slice(&[]),
940
        };
941
        assert_eq!(
942
            empty
943
                .fields
944
                .iter()
945
                .map(VertexAttribute::get_stride)
946
                .sum::<usize>(),
947
            0
948
        );
949

            
950
        // vec2<f32> + vec4<u8> = 8 + 4 = 12 bytes per vertex.
951
        let layout = VertexLayout {
952
            fields: vec![
953
                attr("vAttrXY", VertexAttributeType::Float, 2),
954
                attr("vColor", VertexAttributeType::UnsignedByte, 4),
955
            ]
956
            .into(),
957
        };
958
        let total: usize = layout.fields.iter().map(VertexAttribute::get_stride).sum();
959
        assert_eq!(total, 12);
960

            
961
        // Equality/Hash are structural, so an identical layout compares equal.
962
        assert_eq!(layout, layout.clone());
963
    }
964

            
965
    #[test]
966
    fn index_buffer_format_gl_ids_are_distinct() {
967
        // A collision here would silently draw the wrong primitive.
968
        for (i, a) in ALL_INDEX_FORMATS.iter().enumerate() {
969
            for b in ALL_INDEX_FORMATS.iter().skip(i + 1) {
970
                assert_ne!(a.get_gl_id(), b.get_gl_id(), "{a:?} vs {b:?}");
971
            }
972
        }
973
        assert_eq!(IndexBufferFormat::Points.get_gl_id(), gl::POINTS);
974
        assert_eq!(
975
            IndexBufferFormat::TriangleStrip.get_gl_id(),
976
            gl::TRIANGLE_STRIP
977
        );
978
    }
979

            
980
    // =====================================================================
981
    // Uniform / UniformType (NaN semantics feed GlShader::draw's dedupe)
982
    // =====================================================================
983

            
984
    #[test]
985
    fn uniform_type_nan_never_equals_itself_so_draw_always_reuploads_it() {
986
        // GlShader::draw skips re-setting a uniform when
987
        // `current_uniforms[i] != Some(uniform.uniform_type)`. With a NaN payload
988
        // that comparison is ALWAYS unequal, so a NaN uniform is re-uploaded on
989
        // every buffer -- correct (never stale), just not deduped. Pin it.
990
        let nan = UniformType::Float(f32::NAN);
991
        assert_ne!(nan, UniformType::Float(f32::NAN));
992
        assert_ne!(Some(nan), Some(nan));
993

            
994
        let nan_vec = UniformType::FloatVec4([f32::NAN, 0.0, 0.0, 0.0]);
995
        assert_ne!(nan_vec, nan_vec);
996

            
997
        // The flip side: +0.0 and -0.0 compare EQUAL, so a -0.0 -> +0.0 change is
998
        // deduped away and never re-uploaded. Harmless for a uniform, but pinned
999
        // so a change in semantics is visible.
        assert_eq!(UniformType::Float(0.0), UniformType::Float(-0.0));
        // Integer uniforms have no such wrinkle: they dedupe exactly.
        assert_eq!(UniformType::Int(i32::MIN), UniformType::Int(i32::MIN));
        assert_ne!(UniformType::Int(0), UniformType::UnsignedInt(0));
    }
    #[test]
    fn uniform_type_matrix_transpose_flag_is_part_of_its_identity() {
        let m = [0.0f32; 4];
        assert_ne!(
            UniformType::Matrix2 {
                transpose: false,
                matrix: m
            },
            UniformType::Matrix2 {
                transpose: true,
                matrix: m
            },
        );
        // Same payload, different arity -> different uniforms.
        assert_ne!(
            UniformType::FloatVec2([1.0, 2.0]),
            UniformType::IntVec2([1, 2])
        );
    }
    #[test]
    fn uniform_create_preserves_empty_unicode_and_huge_names() {
        let huge = "n".repeat(100_000);
        for name in ["", "u_color", "\u{1F600}", "e\u{0301}", huge.as_str()] {
            let u = Uniform::create(name.to_string(), UniformType::Int(0));
            assert_eq!(u.uniform_name.as_str(), name);
        }
    }
    // =====================================================================
    // GlShader -- the no-shader-compiler error path
    // =====================================================================
    #[test]
    fn gl_shader_new_reports_no_shader_compiler_instead_of_panicking() {
        // A driver that reports no shader compiler (GL_SHADER_COMPILER == FALSE)
        // must produce a clean Err -- for ANY source, including empty, garbage,
        // unicode and very large ones.
        let ctx = null_ctx();
        let huge = "x".repeat(200_000);
        for (vert, frag) in [
            ("", ""),
            ("   \t\n  ", "\n\n"),
            ("not glsl at all ;;;{{{", "\u{1F600}"),
            ("void main(){}", "void main(){}"),
            (huge.as_str(), huge.as_str()),
        ] {
            let err = GlShader::new(&ctx, vert, frag).unwrap_err();
            assert_eq!(err, GlShaderCreateError::NoShaderCompiler);
        }
    }
    #[test]
    fn shader_error_types_format_without_panicking_on_unicode_and_extremes() {
        let vert = VertexShaderCompileError {
            error_id: i32::MIN,
            info_log: AzString::from("\u{1F600} log".to_string()),
        };
        let frag = FragmentShaderCompileError {
            error_id: i32::MAX,
            info_log: AzString::from(String::new()),
        };
        let link = GlShaderLinkError {
            error_id: -1,
            info_log: AzString::from("multi\nline\0log".to_string()),
        };
        assert!(alloc::format!("{vert}").contains("-2147483648"));
        assert!(alloc::format!("{vert}").contains("\u{1F600}"));
        assert!(alloc::format!("{frag}").contains("2147483647"));
        let compile = GlShaderCompileError::Vertex(vert);
        assert!(alloc::format!("{compile}").contains("Failed to compile vertex shader"));
        // Debug delegates to Display -- must agree, and must not recurse.
        assert_eq!(alloc::format!("{compile:?}"), alloc::format!("{compile}"));
        let frag_err = GlShaderCompileError::Fragment(frag);
        assert!(alloc::format!("{frag_err}").contains("Failed to compile fragment shader"));
        let create = GlShaderCreateError::Link(link);
        assert!(alloc::format!("{create}").contains("Shader linking error"));
        assert_eq!(alloc::format!("{create:?}"), alloc::format!("{create}"));
        assert!(alloc::format!("{}", GlShaderCreateError::NoShaderCompiler)
            .contains("doesn't include a shader compiler"));
    }
    // =====================================================================
    // Texture -- getters, refcounting, and the degenerate-driver paths
    // =====================================================================
    #[test]
    fn texture_descriptor_mirrors_the_texture_including_extreme_sizes() {
        let tex = test_texture(42, 640, 480);
        let d = tex.get_descriptor();
        assert_eq!(d.width, 640);
        assert_eq!(d.height, 480);
        assert_eq!(d.format, RawImageFormat::RGBA8);
        assert_eq!(d.offset, 0);
        assert!(!d.flags.is_opaque);
        assert!(!d.flags.allow_mipmaps, "textures map 1:1, never mipmapped");
        // Zero-size and u32::MAX-size must not panic or wrap in the descriptor.
        let zero = test_texture(1, 0, 0);
        assert_eq!(zero.get_descriptor().width, 0);
        assert_eq!(zero.get_descriptor().height, 0);
        let huge = test_texture(1, u32::MAX, u32::MAX);
        assert_eq!(huge.get_descriptor().width, u32::MAX as usize);
        assert_eq!(huge.get_descriptor().height, u32::MAX as usize);
        // is_opaque must be carried through from the flags, not hardcoded.
        let opaque = Texture::create(
            7,
            TextureFlags {
                is_opaque: true,
                is_video_texture: true,
            },
            PhysicalSizeU32 {
                width: 2,
                height: 2,
            },
            ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            },
            null_ctx(),
            RawImageFormat::BGRA8,
        );
        assert!(opaque.get_descriptor().flags.is_opaque);
        assert_eq!(opaque.get_descriptor().format, RawImageFormat::BGRA8);
    }
    #[test]
    fn texture_clone_and_drop_share_one_refcount_without_double_freeing() {
        // Texture is refcounted through a raw Box<AtomicUsize>; a miscount here
        // is a double-free (or a leaked GL texture). Exercise fan-out + drop.
        let tex = test_texture(9, 4, 4);
        let clones: Vec<Texture> = (0..16).map(|_| tex.clone()).collect();
        for c in &clones {
            assert_eq!(c.texture_id, 9);
            assert_eq!(c.size, tex.size);
            assert_eq!(c.format, tex.format);
            assert!(c.run_destructor);
        }
        // Equality/Hash are by texture id.
        assert_eq!(clones[0], tex);
        assert_eq!(clones[0], clones[1]);
        assert_ne!(tex, test_texture(10, 4, 4));
        drop(clones); // 16 drops...
        drop(tex); // ...then the last one actually frees.
    }
    #[test]
    fn texture_display_and_debug_render_id_and_size() {
        let tex = test_texture(3, 16, 32);
        assert_eq!(alloc::format!("{tex}"), "Texture { id: 3, 16x32 }");
        // Debug delegates to Display.
        assert_eq!(alloc::format!("{tex:?}"), alloc::format!("{tex}"));
    }
    #[test]
    fn texture_paint_stroke_is_a_noop_when_gl_is_unusable() {
        // Documented: "No-op if the GL context is unusable". With no brush shader
        // (program id 0) this must bail out before touching GL -- including for
        // NaN / infinite / negative radii and coordinates, which must not produce
        // a huge dab loop. (`!(radius > 0.0)` is written that way precisely so it
        // also rejects NaN.)
        let mut tex = test_texture(5, 8, 8);
        assert_eq!(tex.gl_context.get_brush_shader(), 0);
        for radius in [1.0, 0.0, -1.0, f32::NAN, f32::INFINITY, f32::MAX] {
            let mut brush = Brush::new(
                ColorU {
                    r: 255,
                    g: 0,
                    b: 0,
                    a: 255,
                },
                radius,
            );
            brush.hardness = f32::NAN;
            brush.flow = f32::INFINITY;
            brush.spacing = 0.0; // would be a divide-by-zero step without the .max(0.01)
            tex.paint_stroke(f32::NAN, f32::NEG_INFINITY, f32::MAX, -0.0, brush);
            tex.paint_dot(f32::NAN, f32::NAN, brush);
        }
        // A zero-sized texture is the other early-out (tw/th <= 0).
        let mut zero = test_texture(6, 0, 0);
        zero.paint_dot(
            0.0,
            0.0,
            Brush::new(
                ColorU {
                    r: 1,
                    g: 1,
                    b: 1,
                    a: 1,
                },
                4.0,
            ),
        );
    }
    #[test]
    fn texture_copy_to_raw_image_returns_a_null_image_on_every_degenerate_input() {
        // The `w <= 0 || h <= 0` guard is load-bearing: size is a u32 but is cast
        // to i32 for glReadPixels, so a width >= 2^31 goes NEGATIVE. Without the
        // guard that reaches gl-context-loader's
        //   `vec![0; width as usize * height as usize * bit_depth]`
        // which sign-extends the negative width to ~usize::MAX -> overflow panic
        // (debug) / exabyte allocation (release). Prove the guard holds.
        let is_null_image = |img: &RawImage| img.width == 0 && img.height == 0;
        // texture id 0 -> null image
        assert!(is_null_image(&test_texture(0, 16, 16).copy_to_raw_image()));
        // zero size -> null image
        assert!(is_null_image(&test_texture(1, 0, 0).copy_to_raw_image()));
        assert!(is_null_image(&test_texture(1, 16, 0).copy_to_raw_image()));
        assert!(is_null_image(&test_texture(1, 0, 16).copy_to_raw_image()));
        // u32::MAX / 2^31 both cast to a NEGATIVE i32 and MUST be caught by the guard.
        assert!(is_null_image(
            &test_texture(1, u32::MAX, u32::MAX).copy_to_raw_image()
        ));
        assert!(is_null_image(
            &test_texture(1, 1 << 31, 1 << 31).copy_to_raw_image()
        ));
        // Valid id + valid size, but the driver hands back no framebuffer
        // (`fbo == 0`) -> still a clean null image, no unwrap panic.
        assert!(is_null_image(&test_texture(1, 4, 4).copy_to_raw_image()));
    }
    #[test]
    #[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
    fn texture_clear_panics_when_the_driver_allocates_no_framebuffer() {
        // DOCUMENTED panic: "Panics if no framebuffer/depthbuffer was allocated
        // (the GL object lists are empty)." A driver that generates nothing makes
        // gen_framebuffers(1) return an EMPTY list, so `.get(0).unwrap()` panics.
        // Pinned as documented behavior -- note that the sibling paths
        // (paint_stroke / copy_to_raw_image) degrade gracefully instead.
        test_texture(1, 4, 4).clear();
    }
    // =====================================================================
    // VertexArrayObject / VertexBuffer
    // =====================================================================
    #[test]
    fn vertex_array_object_clone_and_drop_share_one_refcount() {
        let layout = VertexLayout {
            fields: VertexAttributeVec::from_const_slice(&[]),
        };
        let vao = VertexArrayObject::new(layout, 77, null_ctx());
        assert_eq!(vao.vao_id, 77);
        assert!(vao.run_destructor);
        let clones: Vec<VertexArrayObject> = (0..8).map(|_| vao.clone()).collect();
        assert!(clones.iter().all(|c| c.vao_id == 77));
        assert_eq!(clones[0], vao);
        drop(clones);
        drop(vao);
    }
    #[test]
    fn vertex_buffer_new_raw_keeps_its_fields_and_refcounts_its_clones() {
        let vao = VertexArrayObject::new(
            VertexLayout {
                fields: VertexAttributeVec::from_const_slice(&[]),
            },
            1,
            null_ctx(),
        );
        let vb = VertexBuffer::new_raw(11, 300, vao, 22, 40, IndexBufferFormat::TriangleStrip);
        assert_eq!(vb.vertex_buffer_id, 11);
        assert_eq!(vb.vertex_buffer_len, 300);
        assert_eq!(vb.index_buffer_id, 22);
        assert_eq!(vb.index_buffer_len, 40);
        assert_eq!(vb.index_buffer_format, IndexBufferFormat::TriangleStrip);
        assert_eq!(
            alloc::format!("{vb}"),
            "VertexBuffer { buffer: 11 (length: 300) }"
        );
        // Eq/Hash are by vertex_buffer_id.
        let clones: Vec<VertexBuffer> = (0..8).map(|_| vb.clone()).collect();
        assert_eq!(clones[0], vb);
        drop(clones);
        drop(vb);
        // A zero-length buffer is degenerate but legal.
        let empty_vao = VertexArrayObject::new(
            VertexLayout {
                fields: VertexAttributeVec::from_const_slice(&[]),
            },
            0,
            null_ctx(),
        );
        let empty = VertexBuffer::new_raw(0, 0, empty_vao, 0, 0, IndexBufferFormat::Points);
        assert_eq!(empty.vertex_buffer_len, 0);
    }
    #[allow(dead_code)] // the field only exists to give the vertex a realistic size/layout
    struct TestVertex {
        _xy: [f32; 2],
    }
    impl VertexLayoutDescription for TestVertex {
        fn get_description() -> VertexLayout {
            VertexLayout {
                fields: vec![VertexAttribute {
                    va_name: AzString::from_const_str("vAttrXY"),
                    layout_location: OptionUsize::None,
                    attribute_type: VertexAttributeType::Float,
                    item_count: 2,
                }]
                .into(),
            }
        }
    }
    #[test]
    #[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
    fn vertex_buffer_new_panics_when_the_driver_allocates_no_vao() {
        // DOCUMENTED panic: "Panics if the GL driver failed to create the
        // vertex-array/buffer objects (the returned id lists are empty)."
        let verts = [TestVertex { _xy: [0.0, 0.0] }];
        let _ = VertexBuffer::new(
            null_ctx(),
            0,
            &verts[..],
            &[0u32],
            IndexBufferFormat::Triangles,
        );
    }
    // =====================================================================
    // The process-global GL texture table.
    //
    // ACTIVE_GL_TEXTURES is a `static mut` with no lock (GL is single-threaded
    // by design), and cargo test runs #[test]s on parallel threads. So ALL of
    // its coverage lives in this ONE test -- splitting it up would race the
    // table against itself. No other test in this crate touches it.
    // =====================================================================
    #[test]
    fn gl_texture_cache_insert_lookup_and_eviction_lifecycle() {
        let doc = DocumentId {
            namespace_id: crate::resources::IdNamespace(7),
            id: 1,
        };
        let other_doc = DocumentId {
            namespace_id: crate::resources::IdNamespace(7),
            id: 2,
        };
        // --- Empty / uninitialized table: every accessor must degrade, not panic.
        gl_textures_clear_opengl_cache();
        let stale = ExternalImageId { inner: u64::MAX };
        assert!(get_opengl_texture(&stale).is_none());
        assert!(
            remove_single_texture_from_active_gl_textures(&doc, &Epoch::from(0), &stale).is_none()
        );
        gl_textures_remove_epochs_from_pipeline(&doc, Epoch::from(0));
        gl_textures_remove_active_pipeline(&doc);
        gl_textures_clear_opengl_cache(); // idempotent
        // --- Insert into an UNINITIALIZED table.
        // NOTE: the doc comment on insert_into_active_gl_textures claims it
        // "Panics if the global active-GL-texture table has not been
        // initialized" -- it does not; it initializes the table itself. The doc
        // is stale (see the report). Pin the real behavior.
        let id5 = insert_into_active_gl_textures(doc, Epoch::from(5), test_texture(11, 4, 8));
        let id7 = insert_into_active_gl_textures(doc, Epoch::from(7), test_texture(22, 16, 32));
        assert_ne!(id5, id7, "each insert must mint a unique ExternalImageId");
        // --- Lookup: id -> (texture id, (w, h) as f32).
        assert_eq!(get_opengl_texture(&id5), Some((11, (4.0, 8.0))));
        assert_eq!(get_opengl_texture(&id7), Some((22, (16.0, 32.0))));
        assert!(get_opengl_texture(&stale).is_none());
        // A u32::MAX-sized texture goes through a lossy u32 -> f32 cast:
        // u32::MAX (2^32 - 1) has no exact f32, so it rounds UP to 2^32.
        let id_huge =
            insert_into_active_gl_textures(doc, Epoch::from(5), test_texture(33, u32::MAX, 1));
        assert_eq!(
            get_opengl_texture(&id_huge),
            Some((33, (4_294_967_296.0, 1.0)))
        );
        // --- Epoch eviction is STRICTLY older-than: epoch 5 goes, epoch 7 stays.
        gl_textures_remove_epochs_from_pipeline(&doc, Epoch::from(7));
        assert!(
            get_opengl_texture(&id5).is_none(),
            "epoch 5 < 7 must be evicted"
        );
        assert!(
            get_opengl_texture(&id_huge).is_none(),
            "epoch 5 < 7 must be evicted"
        );
        assert_eq!(
            get_opengl_texture(&id7),
            Some((22, (16.0, 32.0))),
            "epoch 7 is NOT < 7, so it must survive"
        );
        // Evicting for an unknown document must be a no-op, not a panic.
        gl_textures_remove_epochs_from_pipeline(&other_doc, Epoch::from(u32::MAX));
        assert_eq!(get_opengl_texture(&id7), Some((22, (16.0, 32.0))));
        // --- remove_single: Some(()) when the (doc, epoch) path exists...
        assert_eq!(
            remove_single_texture_from_active_gl_textures(&doc, &Epoch::from(7), &id7),
            Some(())
        );
        assert!(get_opengl_texture(&id7).is_none());
        // ...including a second removal of an already-gone image (the path is
        // still there, so it reports Some(()) rather than None)...
        assert_eq!(
            remove_single_texture_from_active_gl_textures(&doc, &Epoch::from(7), &id7),
            Some(())
        );
        // ...but None when the document or the epoch is unknown.
        assert!(
            remove_single_texture_from_active_gl_textures(&other_doc, &Epoch::from(7), &id7)
                .is_none()
        );
        assert!(
            remove_single_texture_from_active_gl_textures(&doc, &Epoch::from(u32::MAX), &id7)
                .is_none()
        );
        // --- remove_active_pipeline drops the whole document.
        let id_a = insert_into_active_gl_textures(doc, Epoch::from(1), test_texture(44, 2, 2));
        let id_b =
            insert_into_active_gl_textures(other_doc, Epoch::from(1), test_texture(55, 2, 2));
        assert!(get_opengl_texture(&id_a).is_some());
        gl_textures_remove_active_pipeline(&doc);
        assert!(get_opengl_texture(&id_a).is_none(), "doc was removed");
        assert!(
            get_opengl_texture(&id_b).is_some(),
            "other_doc must be untouched"
        );
        // --- clear drops everything.
        gl_textures_clear_opengl_cache();
        assert!(get_opengl_texture(&id_b).is_none());
        // Leave the table clean for anything that runs after us.
        gl_textures_clear_opengl_cache();
    }
}