smithay_clipboard/
text.rs

1use std::borrow::Cow;
2
3use crate::mime::{self, normalize_to_lf, AllowedMimeTypes, AsMimeTypes, Error, MimeType};
4
5pub struct Text(pub String);
6
7impl TryFrom<(Vec<u8>, MimeType)> for Text {
8    type Error = Error;
9
10    fn try_from((content, mime_type): (Vec<u8>, MimeType)) -> Result<Self, Self::Error> {
11        let utf8 = String::from_utf8_lossy(&content);
12        let content = match utf8 {
13            Cow::Borrowed(_) => String::from_utf8(content).unwrap(),
14            Cow::Owned(content) => content,
15        };
16
17        // Post-process the content according to mime type.
18        let content = match mime_type {
19            MimeType::Text(mime::Text::TextPlainUtf8 | mime::Text::TextPlain) => {
20                normalize_to_lf(content)
21            },
22            MimeType::Text(mime::Text::Utf8String) => content,
23            MimeType::Other(_) => return Err(Error),
24        };
25        Ok(Text(content))
26    }
27}
28
29impl AllowedMimeTypes for Text {
30    fn allowed() -> Cow<'static, [MimeType]> {
31        Cow::Borrowed(&[
32            MimeType::Text(mime::Text::TextPlainUtf8),
33            MimeType::Text(mime::Text::Utf8String),
34            MimeType::Text(mime::Text::TextPlain),
35        ])
36    }
37}
38
39impl AsMimeTypes for Text {
40    fn available(&self) -> Cow<'static, [MimeType]> {
41        Self::allowed()
42    }
43
44    fn as_bytes(&self, mime_type: &MimeType) -> Option<Cow<'static, [u8]>> {
45        match mime_type {
46            MimeType::Text(
47                mime::Text::TextPlainUtf8 | mime::Text::Utf8String | mime::Text::TextPlain,
48            ) => Some(Cow::Owned(self.0.as_bytes().to_owned())),
49            MimeType::Other(_) => None,
50        }
51    }
52}