dear-imgui-rs 0.12.0

High-level Rust bindings to Dear ImGui v1.92.7 with docking, WGPU/GL backends, and extensions (ImPlot/ImPlot3D, ImNodes, ImGuizmo, file browser, reflection-based UI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Draw data structures for Dear ImGui rendering
//!
//! This module provides safe Rust wrappers around Dear ImGui's draw data structures,
//! which contain all the information needed to render a frame.

use crate::internal::{RawCast, RawWrapper};
use crate::sys;
use crate::texture::TextureId;
use std::marker::PhantomData;
use std::rc::Rc;
use std::slice;
use std::sync::atomic::{AtomicBool, Ordering};

static TEXTURE_DATA_BORROWED: AtomicBool = AtomicBool::new(false);

pub(crate) fn assert_texture_data_not_borrowed() {
    if TEXTURE_DATA_BORROWED.load(Ordering::Acquire) {
        panic!(
            "TextureData is already mutably borrowed; \
             do not mix DrawData::textures()/PlatformIo::textures() with DrawData::texture()/PlatformIo::texture() calls"
        );
    }
}

/// All draw data to render a Dear ImGui frame.
#[repr(C)]
pub struct DrawData {
    /// Only valid after render() is called and before the next new frame() is called.
    valid: bool,
    /// Number of DrawList to render.
    cmd_lists_count: i32,
    /// For convenience, sum of all draw list index buffer sizes.
    pub total_idx_count: i32,
    /// For convenience, sum of all draw list vertex buffer sizes.
    pub total_vtx_count: i32,
    // Array of DrawList.
    cmd_lists: crate::internal::ImVector<*mut sys::ImDrawList>,
    /// Upper-left position of the viewport to render.
    ///
    /// (= upper-left corner of the orthogonal projection matrix to use)
    pub display_pos: [f32; 2],
    /// Size of the viewport to render.
    ///
    /// (= display_pos + display_size == lower-right corner of the orthogonal matrix to use)
    pub display_size: [f32; 2],
    /// Amount of pixels for each unit of display_size.
    ///
    /// Based on io.display_frame_buffer_scale. Typically [1.0, 1.0] on normal displays, and
    /// [2.0, 2.0] on Retina displays, but fractional values are also possible.
    pub framebuffer_scale: [f32; 2],

    /// Viewport carrying the DrawData instance, might be of use to the renderer (generally not).
    owner_viewport: *mut sys::ImGuiViewport,
    /// Texture data (internal use)
    textures: *mut crate::internal::ImVector<*mut sys::ImTextureData>,
}

// Keep this struct layout-compatible with the sys bindings (`ImDrawData`).
const _: [(); std::mem::size_of::<sys::ImDrawData>()] = [(); std::mem::size_of::<DrawData>()];
const _: [(); std::mem::align_of::<sys::ImDrawData>()] = [(); std::mem::align_of::<DrawData>()];

unsafe impl RawCast<sys::ImDrawData> for DrawData {}

impl RawWrapper for DrawData {
    type Raw = sys::ImDrawData;

    unsafe fn raw(&self) -> &Self::Raw {
        unsafe { <Self as RawCast<Self::Raw>>::raw(self) }
    }

    unsafe fn raw_mut(&mut self) -> &mut Self::Raw {
        unsafe { <Self as RawCast<Self::Raw>>::raw_mut(self) }
    }
}

impl DrawData {
    /// Check if the draw data is valid
    ///
    /// Draw data is only valid after `Context::render()` is called and before
    /// the next `Context::new_frame()` is called.
    #[inline]
    pub fn valid(&self) -> bool {
        self.valid
    }

    /// Returns an iterator over the draw lists included in the draw data.
    #[inline]
    pub fn draw_lists(&self) -> DrawListIterator<'_> {
        unsafe {
            DrawListIterator {
                iter: self.cmd_lists().iter(),
            }
        }
    }
    /// Returns the number of draw lists included in the draw data.
    #[inline]
    pub fn draw_lists_count(&self) -> usize {
        unsafe { self.cmd_lists().len() }
    }

    /// Returns an iterator over the textures that need to be updated
    ///
    /// This is used by renderer backends to process texture creation, updates, and destruction.
    /// Each item is an `ImTextureData*` carrying a `Status` which can be one of:
    /// - `OK`: nothing to do.
    /// - `WantCreate`: create a GPU texture and upload all pixels.
    /// - `WantUpdates`: upload specified `UpdateRect` regions.
    /// - `WantDestroy`: destroy the GPU texture (may be delayed until unused).
    /// Most of the time this list has only 1 texture and it doesn't need any update.
    ///
    /// Note: items returned by this iterator provide a guarded mutable view; do not store them or
    /// hold them across iterations.
    pub fn textures(&self) -> TextureIterator<'_> {
        unsafe {
            if self.textures.is_null() {
                TextureIterator::new(std::ptr::null(), std::ptr::null())
            } else {
                let vector = &*self.textures;
                if vector.size <= 0 || vector.data.is_null() {
                    TextureIterator::new(std::ptr::null(), std::ptr::null())
                } else {
                    TextureIterator::new(vector.data, vector.data.add(vector.size as usize))
                }
            }
        }
    }

    /// Returns the number of textures in the texture list
    pub fn textures_count(&self) -> usize {
        unsafe {
            if self.textures.is_null() {
                0
            } else {
                let vector = &*self.textures;
                if vector.size <= 0 || vector.data.is_null() {
                    0
                } else {
                    vector.size as usize
                }
            }
        }
    }

    /// Get a specific texture by index
    ///
    /// Returns None if the index is out of bounds or no textures are available.
    pub fn texture(&self, index: usize) -> Option<&crate::texture::TextureData> {
        unsafe {
            assert_texture_data_not_borrowed();
            if self.textures.is_null() {
                return None;
            }
            let vector = &*self.textures;
            let size = usize::try_from(vector.size).ok()?;
            if size == 0 || vector.data.is_null() {
                return None;
            }
            if index >= size {
                return None;
            }
            let texture_ptr = *vector.data.add(index);
            if texture_ptr.is_null() {
                return None;
            }
            Some(crate::texture::TextureData::from_raw_ref(
                texture_ptr as *const _,
            ))
        }
    }

    /// Get a mutable reference to a specific texture by index
    ///
    /// Returns None if the index is out of bounds or no textures are available.
    pub fn texture_mut(&mut self, index: usize) -> Option<&mut crate::texture::TextureData> {
        unsafe {
            if self.textures.is_null() {
                return None;
            }
            let vector = &*self.textures;
            let size = usize::try_from(vector.size).ok()?;
            if size == 0 || vector.data.is_null() {
                return None;
            }
            if index >= size {
                return None;
            }
            let texture_ptr = *vector.data.add(index);
            if texture_ptr.is_null() {
                return None;
            }
            Some(crate::texture::TextureData::from_raw(texture_ptr))
        }
    }
    /// Get the display position as an array
    #[inline]
    pub fn display_pos(&self) -> [f32; 2] {
        self.display_pos
    }

    /// Get the display size as an array
    #[inline]
    pub fn display_size(&self) -> [f32; 2] {
        self.display_size
    }

    /// Get the framebuffer scale as an array
    #[inline]
    pub fn framebuffer_scale(&self) -> [f32; 2] {
        self.framebuffer_scale
    }

    #[inline]
    pub(crate) unsafe fn cmd_lists(&self) -> &[*mut sys::ImDrawList] {
        unsafe {
            if self.cmd_lists_count <= 0 || self.cmd_lists.data.is_null() {
                return &[];
            }
            let len = match usize::try_from(self.cmd_lists_count) {
                Ok(len) => len,
                Err(_) => return &[],
            };
            slice::from_raw_parts(self.cmd_lists.data, len)
        }
    }

    /// Converts all buffers from indexed to non-indexed, in case you cannot render indexed buffers
    ///
    /// **This is slow and most likely a waste of resources. Always prefer indexed rendering!**
    #[doc(alias = "DeIndexAllBuffers")]
    pub fn deindex_all_buffers(&mut self) {
        unsafe {
            sys::ImDrawData_DeIndexAllBuffers(RawWrapper::raw_mut(self));
        }
    }

    /// Scales the clip rect of each draw command
    ///
    /// Can be used if your final output buffer is at a different scale than Dear ImGui expects,
    /// or if there is a difference between your window resolution and framebuffer resolution.
    #[doc(alias = "ScaleClipRects")]
    pub fn scale_clip_rects(&mut self, fb_scale: [f32; 2]) {
        unsafe {
            let scale = sys::ImVec2 {
                x: fb_scale[0],
                y: fb_scale[1],
            };
            sys::ImDrawData_ScaleClipRects(RawWrapper::raw_mut(self), scale);
        }
    }
}

/// Iterator over draw lists
pub struct DrawListIterator<'a> {
    iter: std::slice::Iter<'a, *mut sys::ImDrawList>,
}

impl<'a> Iterator for DrawListIterator<'a> {
    type Item = &'a DrawList;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().and_then(|&ptr| {
            if ptr.is_null() {
                None
            } else {
                Some(unsafe { DrawList::from_raw(ptr.cast_const()) })
            }
        })
    }
}

impl<'a> ExactSizeIterator for DrawListIterator<'a> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// Draw command list
#[repr(transparent)]
pub struct DrawList(sys::ImDrawList);

// Ensure the wrapper stays layout-compatible with the sys bindings.
const _: [(); std::mem::size_of::<sys::ImDrawList>()] = [(); std::mem::size_of::<DrawList>()];
const _: [(); std::mem::align_of::<sys::ImDrawList>()] = [(); std::mem::align_of::<DrawList>()];

impl RawWrapper for DrawList {
    type Raw = sys::ImDrawList;
    #[inline]
    unsafe fn raw(&self) -> &sys::ImDrawList {
        &self.0
    }
    #[inline]
    unsafe fn raw_mut(&mut self) -> &mut sys::ImDrawList {
        &mut self.0
    }
}

impl DrawList {
    #[inline]
    pub(crate) unsafe fn from_raw<'a>(raw: *const sys::ImDrawList) -> &'a Self {
        unsafe { &*(raw as *const Self) }
    }

    #[inline]
    pub(crate) unsafe fn cmd_buffer(&self) -> &[sys::ImDrawCmd] {
        unsafe {
            let cmd_buffer = &self.0.CmdBuffer;
            if cmd_buffer.Size <= 0 || cmd_buffer.Data.is_null() {
                return &[];
            }
            let len = match usize::try_from(cmd_buffer.Size) {
                Ok(len) => len,
                Err(_) => return &[],
            };
            slice::from_raw_parts(cmd_buffer.Data, len)
        }
    }

    /// Returns an iterator over the draw commands in this draw list
    pub fn commands(&self) -> DrawCmdIterator<'_> {
        unsafe {
            DrawCmdIterator {
                iter: self.cmd_buffer().iter(),
            }
        }
    }

    /// Get vertex buffer as slice
    pub fn vtx_buffer(&self) -> &[DrawVert] {
        unsafe {
            let vtx_buffer = &self.0.VtxBuffer;
            if vtx_buffer.Size <= 0 || vtx_buffer.Data.is_null() {
                return &[];
            }
            let len = match usize::try_from(vtx_buffer.Size) {
                Ok(len) => len,
                Err(_) => return &[],
            };
            slice::from_raw_parts(vtx_buffer.Data as *const DrawVert, len)
        }
    }

    /// Get index buffer as slice
    pub fn idx_buffer(&self) -> &[DrawIdx] {
        unsafe {
            let idx_buffer = &self.0.IdxBuffer;
            if idx_buffer.Size <= 0 || idx_buffer.Data.is_null() {
                return &[];
            }
            let len = match usize::try_from(idx_buffer.Size) {
                Ok(len) => len,
                Err(_) => return &[],
            };
            slice::from_raw_parts(idx_buffer.Data, len)
        }
    }
}

/// Iterator over draw commands
pub struct DrawCmdIterator<'a> {
    iter: slice::Iter<'a, sys::ImDrawCmd>,
}

impl<'a> Iterator for DrawCmdIterator<'a> {
    type Item = DrawCmd;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|cmd| {
            let cmd_params = DrawCmdParams {
                clip_rect: [
                    cmd.ClipRect.x,
                    cmd.ClipRect.y,
                    cmd.ClipRect.z,
                    cmd.ClipRect.w,
                ],
                // Use raw field; backends may resolve effective TexID later
                texture_id: TextureId::from(cmd.TexRef._TexID),
                vtx_offset: cmd.VtxOffset as usize,
                idx_offset: cmd.IdxOffset as usize,
            };

            // Check for special callback values
            match cmd.UserCallback {
                Some(raw_callback) if raw_callback as usize == (-1isize) as usize => {
                    DrawCmd::ResetRenderState
                }
                Some(raw_callback) => DrawCmd::RawCallback {
                    callback: raw_callback,
                    raw_cmd: cmd,
                },
                None => DrawCmd::Elements {
                    count: cmd.ElemCount as usize,
                    cmd_params,
                    raw_cmd: cmd as *const sys::ImDrawCmd,
                },
            }
        })
    }
}

/// Parameters for a draw command
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DrawCmdParams {
    /// Clipping rectangle [left, top, right, bottom]
    pub clip_rect: [f32; 4],
    /// Texture ID to use for rendering
    ///
    /// Notes:
    /// - For legacy paths (plain `TextureId`), this is the effective id.
    /// - With the modern texture system (ImTextureRef/ImTextureData), this may be 0.
    ///   Renderer backends should resolve the effective id at bind time using
    ///   `ImDrawCmd_GetTexID` with the `raw_cmd` pointer and the backend render state.
    pub texture_id: TextureId,
    /// Vertex buffer offset
    pub vtx_offset: usize,
    /// Index buffer offset
    pub idx_offset: usize,
}

/// A draw command
#[derive(Clone, Debug)]
pub enum DrawCmd {
    /// Elements to draw
    Elements {
        /// The number of indices used for this draw command
        count: usize,
        cmd_params: DrawCmdParams,
        /// Raw command pointer for backends
        ///
        /// Backend note: when using the modern texture system, resolve the effective
        /// texture id at bind time via `ImDrawCmd_GetTexID(raw_cmd)` together with your
        /// renderer state. This pointer is only valid during the `render_draw_data()`
        /// call that produced it; do not store it.
        raw_cmd: *const sys::ImDrawCmd,
    },
    /// Reset render state
    ResetRenderState,
    /// Raw callback
    RawCallback {
        callback: unsafe extern "C" fn(*const sys::ImDrawList, cmd: *const sys::ImDrawCmd),
        raw_cmd: *const sys::ImDrawCmd,
    },
}

/// Vertex format used by Dear ImGui
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DrawVert {
    /// Position (2D)
    pub pos: [f32; 2],
    /// UV coordinates
    pub uv: [f32; 2],
    /// Color (packed RGBA)
    pub col: u32,
}

// Ensure our Rust-side vertex/index types stay layout-compatible with the raw sys bindings.
const _: [(); std::mem::size_of::<sys::ImDrawVert>()] = [(); std::mem::size_of::<DrawVert>()];
const _: [(); std::mem::align_of::<sys::ImDrawVert>()] = [(); std::mem::align_of::<DrawVert>()];

impl DrawVert {
    /// Creates a new draw vertex with u32 color
    pub fn new(pos: [f32; 2], uv: [f32; 2], col: u32) -> Self {
        Self { pos, uv, col }
    }

    /// Creates a new draw vertex from RGBA bytes
    pub fn from_rgba(pos: [f32; 2], uv: [f32; 2], rgba: [u8; 4]) -> Self {
        let col = ((rgba[3] as u32) << 24)
            | ((rgba[2] as u32) << 16)
            | ((rgba[1] as u32) << 8)
            | (rgba[0] as u32);
        Self { pos, uv, col }
    }

    /// Extracts RGBA bytes from the packed color
    pub fn rgba(&self) -> [u8; 4] {
        [
            (self.col & 0xFF) as u8,
            ((self.col >> 8) & 0xFF) as u8,
            ((self.col >> 16) & 0xFF) as u8,
            ((self.col >> 24) & 0xFF) as u8,
        ]
    }
}

/// Index type used by Dear ImGui
pub type DrawIdx = u16;

const _: [(); std::mem::size_of::<sys::ImDrawIdx>()] = [(); std::mem::size_of::<DrawIdx>()];
const _: [(); std::mem::align_of::<sys::ImDrawIdx>()] = [(); std::mem::align_of::<DrawIdx>()];

/// A container for a heap-allocated deep copy of a `DrawData` struct.
///
/// Notes on thread-safety:
/// - This type intentionally does NOT implement `Send`/`Sync` because it currently retains
///   a pointer to the engine-managed textures list (`ImVector<ImTextureData*>`) instead of
///   deep-copying it. That list can be mutated by the UI thread across frames.
/// - You may move vertices/indices to another thread by extracting them into your own buffers
///   or by implementing a custom deep copy which snapshots the textures list as well.
///
/// The underlying copy is released when this struct is dropped.
pub struct OwnedDrawData {
    draw_data: *mut sys::ImDrawData,
    // Prevent Send/Sync: this struct retains a pointer to a shared textures list.
    _no_send_sync: PhantomData<Rc<()>>,
}

impl OwnedDrawData {
    /// If this struct contains a `DrawData` object, then this function returns a reference to it.
    ///
    /// Otherwise, this struct is empty and so this function returns `None`.
    #[inline]
    pub fn draw_data(&self) -> Option<&DrawData> {
        if !self.draw_data.is_null() {
            Some(unsafe { &*(self.draw_data as *const DrawData) })
        } else {
            None
        }
    }
}

impl Default for OwnedDrawData {
    /// The default `OwnedDrawData` struct is empty.
    #[inline]
    fn default() -> Self {
        Self {
            draw_data: std::ptr::null_mut(),
            _no_send_sync: PhantomData,
        }
    }
}

impl From<&DrawData> for OwnedDrawData {
    /// Construct `OwnedDrawData` from `DrawData` by creating a heap-allocated deep copy of the given `DrawData`
    fn from(value: &DrawData) -> Self {
        unsafe {
            // Allocate a new ImDrawData using the constructor
            let result = sys::ImDrawData_ImDrawData();
            if result.is_null() {
                panic!("Failed to allocate ImDrawData for OwnedDrawData");
            }

            // Copy basic fields from the source
            let source_ptr = RawWrapper::raw(value);
            (*result).Valid = source_ptr.Valid;
            (*result).TotalIdxCount = source_ptr.TotalIdxCount;
            (*result).TotalVtxCount = source_ptr.TotalVtxCount;
            (*result).DisplayPos = source_ptr.DisplayPos;
            (*result).DisplaySize = source_ptr.DisplaySize;
            (*result).FramebufferScale = source_ptr.FramebufferScale;
            (*result).OwnerViewport = source_ptr.OwnerViewport;

            // Copy draw lists by cloning each list to ensure OwnedDrawData owns its memory
            (*result).CmdListsCount = 0;
            if source_ptr.CmdListsCount > 0 && !source_ptr.CmdLists.Data.is_null() {
                for i in 0..(source_ptr.CmdListsCount as usize) {
                    let src_list = *source_ptr.CmdLists.Data.add(i);
                    if !src_list.is_null() {
                        // Clone the output of the draw list to own it
                        let cloned = sys::ImDrawList_CloneOutput(src_list);
                        if !cloned.is_null() {
                            sys::ImDrawData_AddDrawList(result, cloned);
                        }
                    }
                }
            }

            // Textures list is shared, do not duplicate (renderer treats it as read-only)
            (*result).Textures = source_ptr.Textures;

            OwnedDrawData {
                draw_data: result,
                _no_send_sync: PhantomData,
            }
        }
    }
}

impl Drop for OwnedDrawData {
    /// Releases any heap-allocated memory consumed by this `OwnedDrawData` object
    fn drop(&mut self) {
        unsafe {
            if !self.draw_data.is_null() {
                // Destroy cloned draw lists if any
                if !(*self.draw_data).CmdLists.Data.is_null() {
                    for i in 0..(*self.draw_data).CmdListsCount as usize {
                        let ptr = *(*self.draw_data).CmdLists.Data.add(i);
                        if !ptr.is_null() {
                            sys::ImDrawList_destroy(ptr);
                        }
                    }
                }

                // Destroy the ImDrawData itself
                sys::ImDrawData_destroy(self.draw_data);
                self.draw_data = std::ptr::null_mut();
            }
        }
    }
}

/// Iterator over textures in draw data
pub struct TextureIterator<'a> {
    ptr: *const *mut sys::ImTextureData,
    end: *const *mut sys::ImTextureData,
    _phantom: std::marker::PhantomData<&'a crate::texture::TextureData>,
}

impl<'a> TextureIterator<'a> {
    /// Create a new texture iterator from raw pointers
    ///
    /// # Safety
    ///
    /// The caller must ensure that the pointers are valid and that the range
    /// [ptr, end) contains valid texture data pointers.
    pub(crate) unsafe fn new(
        ptr: *const *mut sys::ImTextureData,
        end: *const *mut sys::ImTextureData,
    ) -> Self {
        Self {
            ptr,
            end,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<'a> Iterator for TextureIterator<'a> {
    type Item = TextureDataMut<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.ptr < self.end {
            let texture_ptr = unsafe { *self.ptr };
            self.ptr = unsafe { self.ptr.add(1) };
            if texture_ptr.is_null() {
                continue;
            }

            if TEXTURE_DATA_BORROWED
                .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
                .is_err()
            {
                panic!(
                    "TextureData is already mutably borrowed; \
                     do not hold items from DrawData::textures()/PlatformIo::textures() across iterations"
                );
            }

            return Some(TextureDataMut {
                raw: texture_ptr,
                _phantom: PhantomData,
            });
        }

        None
    }
}

impl<'a> std::iter::FusedIterator for TextureIterator<'a> {}

/// A guarded mutable view of a single `ImTextureData`.
///
/// This exists because the texture list is exposed from a shared `&DrawData` reference in order to
/// keep renderer APIs ergonomic, but the list still needs to be mutated by the backend. The guard
/// ensures at runtime that only one mutable view is alive at a time, preventing Rust aliasing UB.
pub struct TextureDataMut<'a> {
    raw: *mut sys::ImTextureData,
    _phantom: PhantomData<&'a mut crate::texture::TextureData>,
}

impl Drop for TextureDataMut<'_> {
    fn drop(&mut self) {
        TEXTURE_DATA_BORROWED.store(false, Ordering::Release);
    }
}

impl std::ops::Deref for TextureDataMut<'_> {
    type Target = crate::texture::TextureData;

    fn deref(&self) -> &Self::Target {
        unsafe { &*(self.raw as *const crate::texture::TextureData) }
    }
}

impl std::ops::DerefMut for TextureDataMut<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *(self.raw as *mut crate::texture::TextureData) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn draw_data_textures_empty_is_safe() {
        let mut textures_vec: crate::internal::ImVector<*mut sys::ImTextureData> =
            crate::internal::ImVector::default();

        let draw_data = DrawData {
            valid: false,
            cmd_lists_count: 0,
            total_idx_count: 0,
            total_vtx_count: 0,
            cmd_lists: crate::internal::ImVector::default(),
            display_pos: [0.0, 0.0],
            display_size: [0.0, 0.0],
            framebuffer_scale: [1.0, 1.0],
            owner_viewport: std::ptr::null_mut(),
            textures: &mut textures_vec,
        };

        assert_eq!(draw_data.textures().count(), 0);
        assert_eq!(draw_data.textures_count(), 0);

        let mut textures_vec: crate::internal::ImVector<*mut sys::ImTextureData> =
            crate::internal::ImVector {
                size: 1,
                data: std::ptr::null_mut(),
                ..crate::internal::ImVector::default()
            };
        let draw_data = DrawData {
            valid: false,
            cmd_lists_count: 0,
            total_idx_count: 0,
            total_vtx_count: 0,
            cmd_lists: crate::internal::ImVector::default(),
            display_pos: [0.0, 0.0],
            display_size: [0.0, 0.0],
            framebuffer_scale: [1.0, 1.0],
            owner_viewport: std::ptr::null_mut(),
            textures: &mut textures_vec,
        };
        assert_eq!(draw_data.textures().count(), 0);
        assert_eq!(draw_data.textures_count(), 0);
        assert!(draw_data.texture(0).is_none());
    }
}