rss_gen/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright © 2024 RSS Gen. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

// src/lib.rs

#![doc = include_str!("../README.md")]
#![doc(
    html_favicon_url = "https://kura.pro/rssgen/images/favicon.ico",
    html_logo_url = "https://kura.pro/rssgen/images/logos/rssgen.svg",
    html_root_url = "https://docs.rs/rss-gen"
)]
#![crate_name = "rss_gen"]
#![crate_type = "lib"]
#![warn(missing_docs)]
#![forbid(unsafe_code)]
#![deny(clippy::all)]
#![deny(clippy::cargo)]
#![deny(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]

/// Contains the main types and data structures used to represent RSS feeds.
pub mod data;
/// Defines error types used throughout the library.
pub mod error;
/// Implements RSS feed generation functionality.
pub mod generator;
/// Provides procedural macros for simplifying RSS operations.
pub mod macros;
/// Implements RSS feed parsing functionality.
pub mod parser;
/// Provides utilities for validating RSS feeds.
pub mod validator;

pub use data::{RssData, RssItem, RssVersion};
pub use error::{Result, RssError};
pub use generator::generate_rss;
pub use parser::parse_rss;

/// The current version of the rss-gen crate, set at compile-time from Cargo.toml.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Maximum length for title fields in the RSS feed.
pub const MAX_TITLE_LENGTH: usize = 256;
/// Maximum length for link fields in the RSS feed.
pub const MAX_LINK_LENGTH: usize = 2048;
/// Maximum length for description fields in the RSS feed.
pub const MAX_DESCRIPTION_LENGTH: usize = 100_000;
/// Maximum length for general fields in the RSS feed.
pub const MAX_GENERAL_LENGTH: usize = 1024;
/// Maximum size for the entire RSS feed.
pub const MAX_FEED_SIZE: usize = 1_048_576; // 1 MB

/// A convenience function to generate a minimal valid RSS 2.0 feed.
///
/// This function creates an RSS 2.0 feed with the provided title, link, and description,
/// and includes one example item.
///
/// # Arguments
///
/// * `title` - The title of the RSS feed.
/// * `link` - The link to the website associated with the RSS feed.
/// * `description` - A brief description of the RSS feed.
///
/// # Returns
///
/// A `Result` containing the generated RSS feed as a `String` if successful,
/// or an `RssError` if generation fails.
///
/// # Examples
///
/// ```rust
/// use rss_gen::quick_rss;
///
/// let rss = quick_rss(
///     "My Rust Blog",
///     "https://myrustblog.com",
///     "A blog about Rust programming"
/// );
///
/// match rss {
///     Ok(feed) => println!("Generated RSS feed: {}", feed),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - Any of the input strings are empty
/// - Any of the input strings exceed their respective maximum lengths
/// - The `link` is not a valid URL starting with "http://" or "https://"
/// - RSS generation fails for any reason
///
/// # Security
///
/// This function performs basic input validation, but it's recommended to sanitize
/// the input parameters before passing them to this function, especially if they
/// come from untrusted sources.
#[must_use = "This function returns a Result that should be handled"]
pub fn quick_rss(
    title: &str,
    link: &str,
    description: &str,
) -> Result<String> {
    // Validate input
    if title.is_empty() || link.is_empty() || description.is_empty() {
        return Err(RssError::InvalidInput(
            "Title, link, and description must not be empty"
                .to_string(),
        ));
    }

    if title.len() > MAX_TITLE_LENGTH
        || link.len() > MAX_LINK_LENGTH
        || description.len() > MAX_DESCRIPTION_LENGTH
    {
        return Err(RssError::InvalidInput(
            "Input exceeds maximum allowed length".to_string(),
        ));
    }

    // Basic URL validation
    if !link.starts_with("http://") && !link.starts_with("https://") {
        return Err(RssError::InvalidInput(
            "Link must start with http:// or https://".to_string(),
        ));
    }

    let mut rss_data = RssData::new(Some(RssVersion::RSS2_0))
        .title(title)
        .link(link)
        .description(description);

    // Add an example item
    rss_data.add_item(
        RssItem::new()
            .title("Example Item")
            .link(format!("{}/example-item", link))
            .description("This is an example item in the RSS feed")
            .guid(format!("{}/example-item", link)),
    );

    generate_rss(&rss_data)
}

/// Prelude module for convenient importing of common types and functions.
pub mod prelude {
    pub use crate::data::{RssData, RssItem, RssVersion};
    pub use crate::error::{Result, RssError};
    pub use crate::generate_rss;
    pub use crate::parse_rss;
    pub use crate::quick_rss;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_quick_rss() {
        let result = quick_rss(
            "Test Feed",
            "https://example.com",
            "A test RSS feed",
        );
        assert!(result.is_ok());
        let feed = result.unwrap();
        assert!(feed.contains("<title>Test Feed</title>"));
        assert!(feed.contains("<link>https://example.com</link>"));
        assert!(
            feed.contains("<description>A test RSS feed</description>")
        );
        assert!(feed.contains("<item>"));
        assert!(feed.contains("<title>Example Item</title>"));
        assert!(feed
            .contains("<link>https://example.com/example-item</link>"));
        assert!(feed.contains("<description>This is an example item in the RSS feed</description>"));
    }

    #[test]
    fn test_quick_rss_invalid_input() {
        let result =
            quick_rss("", "https://example.com", "Description");
        assert!(result.is_err());
        assert!(matches!(result, Err(RssError::InvalidInput(_))));

        let result = quick_rss("Title", "not-a-url", "Description");
        assert!(result.is_err());
        assert!(matches!(result, Err(RssError::InvalidInput(_))));
    }

    #[test]
    fn test_version_constant() {
        assert!(VERSION.starts_with(char::is_numeric));
        assert!(VERSION.split('.').count() >= 2);
    }

    #[test]
    fn test_quick_rss_max_title_length() {
        let long_title = "a".repeat(MAX_TITLE_LENGTH + 1);
        let result = quick_rss(
            &long_title,
            "https://example.com",
            "Description",
        );
        assert!(result.is_err());
        assert!(matches!(result, Err(RssError::InvalidInput(_))));

        let max_title = "a".repeat(MAX_TITLE_LENGTH);
        let result =
            quick_rss(&max_title, "https://example.com", "Description");
        assert!(result.is_ok());
    }

    #[test]
    fn test_quick_rss_max_link_length() {
        let long_link = format!(
            "https://example.com/{}",
            "a".repeat(MAX_LINK_LENGTH - 19)
        );
        let result = quick_rss("Title", &long_link, "Description");
        assert!(result.is_err());
        assert!(matches!(result, Err(RssError::InvalidInput(_))));

        let max_link = format!(
            "https://example.com/{}",
            "a".repeat(MAX_LINK_LENGTH - 20)
        );
        let result = quick_rss("Title", &max_link, "Description");
        assert!(result.is_ok());
    }

    #[test]
    fn test_quick_rss_max_description_length() {
        let long_description = "a".repeat(MAX_DESCRIPTION_LENGTH + 1);
        let result = quick_rss(
            "Title",
            "https://example.com",
            &long_description,
        );
        assert!(result.is_err());
        assert!(matches!(result, Err(RssError::InvalidInput(_))));

        let max_description = "a".repeat(MAX_DESCRIPTION_LENGTH);
        let result =
            quick_rss("Title", "https://example.com", &max_description);
        assert!(result.is_ok());
    }

    #[test]
    fn test_quick_rss_https() {
        let result = quick_rss(
            "Test Feed",
            "https://example.com",
            "A test RSS feed",
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_quick_rss_http() {
        let result = quick_rss(
            "Test Feed",
            "http://example.com",
            "A test RSS feed",
        );
        assert!(result.is_ok());
    }

    // Note: The following tests depend on the implementation of RssData and its methods,
    // which are not shown in the provided code. You may need to adjust these tests
    // based on your actual implementation.

    #[test]
    fn test_rss_data_validate_size() {
        let mut rss_data = RssData::new(Some(RssVersion::RSS2_0))
            .title("Test Feed")
            .link("https://example.com")
            .description("A test RSS feed");

        // Add items until we exceed MAX_FEED_SIZE
        let item_content = "a".repeat(10000);
        for _ in 0..100 {
            rss_data.add_item(
                RssItem::new()
                    .title(&item_content)
                    .link("https://example.com/item")
                    .description(&item_content),
            );
        }

        assert!(rss_data.validate_size().is_err());
    }

    #[test]
    fn test_max_general_length() {
        let mut rss_data = RssData::new(Some(RssVersion::RSS2_0))
            .title("Test Feed")
            .link("https://example.com")
            .description("A test RSS feed");

        let long_general_field = "a".repeat(MAX_GENERAL_LENGTH + 1);
        rss_data.category.clone_from(&long_general_field);

        assert!(rss_data.validate().is_err());

        rss_data.category = "a".repeat(MAX_GENERAL_LENGTH);
        assert!(rss_data.validate().is_ok());
    }
}