From 592af956977f7ba0c6d64e5ac9a8fbd51014d535 Mon Sep 17 00:00:00 2001 From: Will Cassels Date: Sun, 10 Apr 2022 17:24:16 +0100 Subject: [PATCH] Fix problematic TextCallbackData::selection implementation --- imgui/src/input_widget.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/imgui/src/input_widget.rs b/imgui/src/input_widget.rs index 59e8c29..043e5ef 100644 --- a/imgui/src/input_widget.rs +++ b/imgui/src/input_widget.rs @@ -1051,7 +1051,20 @@ impl TextCallbackData { /// This Range is given in `usize` so that it might be used in indexing /// operations more easily. To quickly grab the selected text, use [selected](Self::selected). pub fn selection(&self) -> Range { - unsafe { (*(self.0)).SelectionStart as usize..(*(self.0)).SelectionEnd as usize } + let (start, end) = unsafe { + ( + (*(self.0)).SelectionStart as usize, + (*(self.0)).SelectionEnd as usize, + ) + }; + // Avoid returning a range with start > end, which would be problematic. For example, it + // would cause panics when used to index the string buffer and would also cause Self::has_selection + // to return a false negative. + if start < end { + start..end + } else { + end..start + } } /// Returns the selected text directly. Note that if no text is selected,