Avoid extra text allocations in websocket example

This commit is contained in:
Héctor Ramón Jiménez 2024-04-02 09:29:16 +02:00
parent dee43d5f66
commit 488cac7148
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
2 changed files with 18 additions and 9 deletions

View file

@ -2,6 +2,7 @@ pub mod server;
use iced::futures; use iced::futures;
use iced::subscription::{self, Subscription}; use iced::subscription::{self, Subscription};
use iced::widget::text;
use futures::channel::mpsc; use futures::channel::mpsc;
use futures::sink::SinkExt; use futures::sink::SinkExt;
@ -136,16 +137,24 @@ impl Message {
pub fn disconnected() -> Self { pub fn disconnected() -> Self {
Message::Disconnected Message::Disconnected
} }
pub fn as_str(&self) -> &str {
match self {
Message::Connected => "Connected successfully!",
Message::Disconnected => "Connection lost... Retrying...",
Message::User(message) => message.as_str(),
}
}
} }
impl fmt::Display for Message { impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { f.write_str(self.as_str())
Message::Connected => write!(f, "Connected successfully!"), }
Message::Disconnected => { }
write!(f, "Connection lost... Retrying...")
} impl<'a> text::IntoFragment<'a> for &'a Message {
Message::User(message) => write!(f, "{message}"), fn into_fragment(self) -> text::Fragment<'a> {
} text::Fragment::Borrowed(self.as_str())
} }
} }

View file

@ -2,7 +2,7 @@ mod echo;
use iced::alignment::{self, Alignment}; use iced::alignment::{self, Alignment};
use iced::widget::{ use iced::widget::{
button, column, container, row, scrollable, text, text_input, value, button, column, container, row, scrollable, text, text_input,
}; };
use iced::{color, Command, Element, Length, Subscription}; use iced::{color, Command, Element, Length, Subscription};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -96,7 +96,7 @@ impl WebSocket {
.into() .into()
} else { } else {
scrollable( scrollable(
column(self.messages.iter().map(value).map(Element::from)) column(self.messages.iter().map(text).map(Element::from))
.spacing(10), .spacing(10),
) )
.id(MESSAGE_LOG.clone()) .id(MESSAGE_LOG.clone())