Skip to main content

feedparser_rs/util/
text.rs

1//! Text processing utilities
2//!
3//! This module provides functions for text manipulation,
4//! such as trimming, normalizing whitespace, and encoding conversion.
5
6use crate::types::{Email, Person};
7
8/// Efficient bytes to string conversion - zero-copy for valid UTF-8
9///
10/// Uses `std::str::from_utf8()` for zero-copy conversion when the input
11/// is valid UTF-8, falling back to lossy conversion otherwise.
12///
13/// # Examples
14///
15/// ```
16/// use feedparser_rs::util::text::bytes_to_string;
17///
18/// let valid_utf8 = b"Hello, world!";
19/// assert_eq!(bytes_to_string(valid_utf8), "Hello, world!");
20///
21/// let invalid_utf8 = &[0xFF, 0xFE, 0xFD];
22/// let result = bytes_to_string(invalid_utf8);
23/// assert!(!result.is_empty()); // Lossy conversion succeeded
24/// ```
25#[inline]
26pub fn bytes_to_string(value: &[u8]) -> String {
27    std::str::from_utf8(value).map_or_else(
28        |_| String::from_utf8_lossy(value).into_owned(),
29        std::string::ToString::to_string,
30    )
31}
32
33/// Truncates a string to at most `max_len` bytes, cutting at a `char` boundary
34///
35/// Enforces the byte limits of [`crate::ParserLimits`] on copied values, so
36/// multibyte text cannot exceed them. A character that does not fit entirely is
37/// left out, so the result may be shorter than `max_len` bytes.
38///
39/// # Examples
40///
41/// ```
42/// use feedparser_rs::util::text::truncate_to_length;
43///
44/// assert_eq!(truncate_to_length("hello world", 5), "hello");
45/// assert_eq!(truncate_to_length("hi", 100), "hi");
46/// assert_eq!(truncate_to_length("ééé", 5), "éé");
47/// ```
48#[inline]
49#[must_use]
50#[expect(
51    clippy::string_slice,
52    reason = "`floor_char_boundary` always returns a char boundary"
53)]
54pub fn truncate_to_length(s: &str, max_len: usize) -> String {
55    s[..s.floor_char_boundary(max_len)].to_owned()
56}
57
58/// Parses an RSS person string into a structured `Person`.
59///
60/// Recognizes common RSS author formats:
61/// - `email (Name)` → `Person { name: Some("Name"), email: Some("email") }`
62/// - `Name <email>` → `Person { name: Some("Name"), email: Some("email") }`
63/// - bare email (contains `@`) → `Person { email: Some(text) }`
64/// - plain string → `Person { name: Some(text) }`
65///
66/// # Examples
67///
68/// ```
69/// use feedparser_rs::util::text::parse_rss_person;
70///
71/// let p = parse_rss_person("editor@example.com (John Editor)");
72/// assert_eq!(p.name.as_deref(), Some("John Editor"));
73/// assert_eq!(p.email.as_deref(), Some("editor@example.com"));
74///
75/// let p = parse_rss_person("John Editor <editor@example.com>");
76/// assert_eq!(p.name.as_deref(), Some("John Editor"));
77/// assert_eq!(p.email.as_deref(), Some("editor@example.com"));
78///
79/// let p = parse_rss_person("just-a-name");
80/// assert_eq!(p.name.as_deref(), Some("just-a-name"));
81/// assert!(p.email.is_none());
82/// ```
83#[must_use]
84pub fn parse_rss_person(text: &str) -> Person {
85    let text = text.trim();
86
87    // Pattern: "email (Name)"
88    if let Some(inner) = text.strip_suffix(')')
89        && let Some((email_part, name_part)) = inner.split_once('(')
90    {
91        let email_part = email_part.trim();
92        let name_part = name_part.trim();
93        if !email_part.is_empty() {
94            return Person {
95                name: if name_part.is_empty() {
96                    None
97                } else {
98                    Some(name_part.into())
99                },
100                email: Some(Email::new(email_part.to_string())),
101                uri: None,
102                avatar: None,
103                ..Person::default()
104            };
105        }
106    }
107
108    // Pattern: "Name <email>"
109    if let Some(inner) = text.strip_suffix('>')
110        && let Some((name_part, email_part)) = inner.rsplit_once('<')
111    {
112        let name_part = name_part.trim();
113        let email_part = email_part.trim();
114        if !email_part.is_empty() {
115            return Person {
116                name: if name_part.is_empty() {
117                    None
118                } else {
119                    Some(name_part.into())
120                },
121                email: Some(Email::new(email_part.to_string())),
122                uri: None,
123                avatar: None,
124                ..Person::default()
125            };
126        }
127    }
128
129    // Bare email or plain name
130    if text.contains('@') {
131        Person {
132            name: None,
133            email: Some(Email::new(text.to_string())),
134            uri: None,
135            avatar: None,
136            ..Person::default()
137        }
138    } else {
139        Person::from_name(text)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn test_parse_rss_person_email_paren_name() {
149        let p = parse_rss_person("editor@example.com (John Editor)");
150        assert_eq!(p.name.as_deref(), Some("John Editor"));
151        assert_eq!(p.email.as_deref(), Some("editor@example.com"));
152    }
153
154    #[test]
155    fn test_parse_rss_person_name_angle_email() {
156        let p = parse_rss_person("John Editor <editor@example.com>");
157        assert_eq!(p.name.as_deref(), Some("John Editor"));
158        assert_eq!(p.email.as_deref(), Some("editor@example.com"));
159    }
160
161    #[test]
162    fn test_parse_rss_person_bare_email() {
163        let p = parse_rss_person("editor@example.com");
164        assert!(p.name.is_none());
165        assert_eq!(p.email.as_deref(), Some("editor@example.com"));
166    }
167
168    #[test]
169    fn test_parse_rss_person_plain_name() {
170        let p = parse_rss_person("John Editor");
171        assert_eq!(p.name.as_deref(), Some("John Editor"));
172        assert!(p.email.is_none());
173    }
174
175    #[test]
176    fn test_parse_rss_person_empty_name_in_parens() {
177        let p = parse_rss_person("editor@example.com ()");
178        assert!(p.name.is_none());
179        assert_eq!(p.email.as_deref(), Some("editor@example.com"));
180    }
181}