cranpose_ui/text/
shared_text.rs1use std::{fmt, ops::Deref};
2
3use super::AnnotatedString;
4use crate::widgets::text::{IntoTextSource, StaticText, TextSource};
5
6#[derive(Clone, Debug)]
8pub struct SharedText(Storage);
9
10#[derive(Clone, Debug)]
11enum Storage {
12 Static(&'static str),
13 Annotated(AnnotatedString),
14}
15
16impl SharedText {
17 pub fn as_str(&self) -> &str {
19 match &self.0 {
20 Storage::Static(text) => text,
21 Storage::Annotated(text) => text.text(),
22 }
23 }
24}
25
26impl PartialEq for SharedText {
27 fn eq(&self, other: &Self) -> bool {
28 match (&self.0, &other.0) {
29 (Storage::Static(a), Storage::Static(b)) => a == b,
30 (Storage::Annotated(a), Storage::Annotated(b)) => a == b,
31 (Storage::Static(plain), Storage::Annotated(annotated))
32 | (Storage::Annotated(annotated), Storage::Static(plain)) => annotated.is_plain(plain),
33 }
34 }
35}
36
37impl From<String> for SharedText {
38 fn from(value: String) -> Self {
39 Self(Storage::Annotated(AnnotatedString::from(value)))
40 }
41}
42
43impl From<&'static str> for SharedText {
44 fn from(value: &'static str) -> Self {
45 Self(Storage::Static(value))
46 }
47}
48
49impl From<AnnotatedString> for SharedText {
50 fn from(value: AnnotatedString) -> Self {
51 Self(Storage::Annotated(value))
52 }
53}
54
55impl From<SharedText> for String {
56 fn from(value: SharedText) -> Self {
57 match value.0 {
58 Storage::Static(text) => text.to_owned(),
59 Storage::Annotated(annotated) => annotated.text().to_owned(),
60 }
61 }
62}
63
64impl Deref for SharedText {
65 type Target = str;
66 fn deref(&self) -> &str {
67 self.as_str()
68 }
69}
70
71impl AsRef<str> for SharedText {
72 fn as_ref(&self) -> &str {
73 self.as_str()
74 }
75}
76
77impl fmt::Display for SharedText {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79 formatter.write_str(self.as_str())
80 }
81}
82
83impl IntoTextSource for SharedText {
84 fn into_text_source(self) -> TextSource {
85 match self.0 {
86 Storage::Static(text) => text.into_text_source(),
87 Storage::Annotated(text) => TextSource::Static(text),
88 }
89 }
90
91 fn into_static_text(self) -> Result<StaticText, Self> {
92 Ok(match self.0 {
93 Storage::Static(text) => StaticText::Borrowed(text),
94 Storage::Annotated(text) => StaticText::Annotated(text),
95 })
96 }
97}