Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::borrow::Cow<'_, str> now implements TextBuffer #3164

Merged
merged 5 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ NOTE: [`epaint`](crates/epaint/CHANGELOG.md), [`eframe`](crates/eframe/CHANGELOG
* Plot widget - allow disabling zoom and drag for x and y separately [#2901](https://github.com/emilk/egui/pull/2901) (thanks [@OmegaJak](https://github.com/OmegaJak)!)
* Add character limit to `TextEdit` [#2816](https://github.com/emilk/egui/pull/2816) (thanks [@wzid](https://github.com/wzid)!)
* Add `egui::Modifiers::contains` [#2989](https://github.com/emilk/egui/pull/2989) (thanks [@Wumpf](https://github.com/Wumpf)!)
* `std::borrow::Cow<'_, str>` now implements `TextBuffer` [#3164](https://github.com/emilk/pull/3164)
emilk marked this conversation as resolved.
Show resolved Hide resolved

### 🔧 Changed
* Improve vertical alignment of fonts [#2724](https://github.com/emilk/egui/pull/2724) (thanks [@lictex](https://github.com/lictex)!)
Expand Down
32 changes: 31 additions & 1 deletion crates/egui/src/widgets/text_edit/text_buffer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ops::Range;
use std::{borrow::Cow, ops::Range};

/// Trait constraining what types [`crate::TextEdit`] may use as
/// an underlying buffer.
Expand Down Expand Up @@ -100,6 +100,36 @@ impl TextBuffer for String {
}
}

impl<'a> TextBuffer for Cow<'a, str> {
fn is_mutable(&self) -> bool {
true
}

fn as_str(&self) -> &str {
self.as_ref()
}

fn insert_text(&mut self, text: &str, char_index: usize) -> usize {
<String as TextBuffer>::insert_text(self.to_mut(), text, char_index)
}

fn delete_char_range(&mut self, char_range: Range<usize>) {
<String as TextBuffer>::delete_char_range(self.to_mut(), char_range)
}

fn clear(&mut self) {
<String as TextBuffer>::clear(self.to_mut());
}

fn replace(&mut self, text: &str) {
*self = Cow::Owned(text.to_owned());
}

fn take(&mut self) -> String {
std::mem::take(self).into_owned()
}
}

/// Immutable view of a `&str`!
impl<'a> TextBuffer for &'a str {
fn is_mutable(&self) -> bool {
Expand Down