Skip to main content

feedparser_rs/types/
generics.rs

1//! Generic type abstractions for DRY principle
2//!
3//! This module provides reusable generic types that eliminate code duplication
4//! across feed types and parsing logic.
5
6use std::fmt::Debug;
7
8/// A field with an optional detailed representation
9///
10/// Many feed fields follow the pattern of having a simple value (like a string)
11/// and an optional detailed struct with additional metadata. This generic wrapper
12/// captures that pattern.
13///
14/// # Type Parameters
15///
16/// * `V` - The simple value type (usually `String`)
17/// * `D` - The detailed representation type (e.g., `TextConstruct`, `Person`)
18///
19/// # Examples
20///
21/// ```
22/// use feedparser_rs::types::generics::DetailedField;
23///
24/// // Simple value only
25/// let title: DetailedField<String, ()> = DetailedField::from_value("My Title".to_string());
26/// assert_eq!(title.value(), "My Title");
27/// assert!(title.detail().is_none());
28///
29/// // With detail
30/// let title = DetailedField::with_detail("My Title".to_string(), "extra info");
31/// assert_eq!(title.detail(), Some(&"extra info"));
32/// ```
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct DetailedField<V, D> {
35    value: V,
36    detail: Option<D>,
37}
38
39impl<V, D> DetailedField<V, D> {
40    /// Create a field with only a simple value
41    #[inline]
42    #[must_use]
43    pub const fn from_value(value: V) -> Self {
44        Self {
45            value,
46            detail: None,
47        }
48    }
49
50    /// Create a field with both value and detail
51    #[inline]
52    #[must_use]
53    pub const fn with_detail(value: V, detail: D) -> Self {
54        Self {
55            value,
56            detail: Some(detail),
57        }
58    }
59
60    /// Get reference to the simple value
61    #[inline]
62    #[must_use]
63    pub const fn value(&self) -> &V {
64        &self.value
65    }
66
67    /// Get mutable reference to the simple value
68    #[inline]
69    pub const fn value_mut(&mut self) -> &mut V {
70        &mut self.value
71    }
72
73    /// Get reference to the detail if present
74    #[inline]
75    #[must_use]
76    pub const fn detail(&self) -> Option<&D> {
77        self.detail.as_ref()
78    }
79
80    /// Get mutable reference to the detail if present
81    #[inline]
82    pub const fn detail_mut(&mut self) -> Option<&mut D> {
83        self.detail.as_mut()
84    }
85
86    /// Set the detail
87    #[inline]
88    pub fn set_detail(&mut self, detail: D) {
89        self.detail = Some(detail);
90    }
91
92    /// Take the detail, leaving None in its place
93    #[inline]
94    pub const fn take_detail(&mut self) -> Option<D> {
95        self.detail.take()
96    }
97
98    /// Convert into a tuple of (value, `Option<detail>`)
99    #[inline]
100    #[must_use]
101    pub fn into_parts(self) -> (V, Option<D>) {
102        (self.value, self.detail)
103    }
104}
105
106impl<V: Default, D> Default for DetailedField<V, D> {
107    fn default() -> Self {
108        Self {
109            value: V::default(),
110            detail: None,
111        }
112    }
113}
114
115impl<V, D> From<V> for DetailedField<V, D> {
116    fn from(value: V) -> Self {
117        Self::from_value(value)
118    }
119}
120
121impl<V, D> From<(V, D)> for DetailedField<V, D> {
122    fn from((value, detail): (V, D)) -> Self {
123        Self::with_detail(value, detail)
124    }
125}
126
127/// Extension trait for collections with size limits
128///
129/// Provides methods for safely adding items to collections while respecting
130/// configured limits, which is essential for `DoS` protection.
131///
132/// # Examples
133///
134/// ```
135/// use feedparser_rs::types::LimitedCollectionExt;
136///
137/// let mut vec = Vec::new();
138/// assert!(vec.try_push_limited("first", 2));
139/// assert!(vec.try_push_limited("second", 2));
140/// assert!(!vec.try_push_limited("third", 2)); // Exceeds limit
141/// assert_eq!(vec.len(), 2);
142/// ```
143pub trait LimitedCollectionExt<T> {
144    /// Try to push an item if the collection is below the limit
145    ///
146    /// Returns `true` if the item was added, `false` if limit was reached.
147    fn try_push_limited(&mut self, item: T, limit: usize) -> bool;
148
149    /// Check if the collection has reached its limit
150    fn is_at_limit(&self, limit: usize) -> bool;
151
152    /// Get remaining capacity before reaching the limit
153    fn remaining_capacity(&self, limit: usize) -> usize;
154}
155
156impl<T> LimitedCollectionExt<T> for Vec<T> {
157    #[inline]
158    fn try_push_limited(&mut self, item: T, limit: usize) -> bool {
159        if self.len() < limit {
160            self.push(item);
161            true
162        } else {
163            false
164        }
165    }
166
167    #[inline]
168    fn is_at_limit(&self, limit: usize) -> bool {
169        self.len() >= limit
170    }
171
172    #[inline]
173    fn remaining_capacity(&self, limit: usize) -> usize {
174        limit.saturating_sub(self.len())
175    }
176}
177
178/// Trait for types that can be built from XML attributes
179///
180/// Implement this trait for structs that are parsed from XML element attributes,
181/// providing a consistent interface for attribute extraction with limit validation.
182pub trait FromAttributes: Sized {
183    /// Parse from XML attributes with limit validation
184    ///
185    /// # Arguments
186    ///
187    /// * `attrs` - Iterator over XML attributes
188    /// * `max_attr_length` - Maximum allowed attribute value length
189    ///
190    /// # Returns
191    ///
192    /// * `Some(Self)` - Successfully parsed struct
193    /// * `None` - Required attributes missing or validation failed
194    fn from_attributes<'a, I>(attrs: I, max_attr_length: usize) -> Option<Self>
195    where
196        I: Iterator<Item = quick_xml::events::attributes::Attribute<'a>>;
197}
198
199/// Generic trait for parsing types from various sources using GAT
200///
201/// This trait provides a unified interface for constructing types from
202/// different data sources (JSON values, XML elements, etc.) using
203/// Generic Associated Types (GAT) for flexible lifetime handling.
204///
205/// # Examples
206///
207/// ```
208/// use feedparser_rs::types::generics::ParseFrom;
209/// use feedparser_rs::types::Person;
210/// use serde_json::json;
211///
212/// let json = json!({"name": "John Doe", "url": "https://example.com"});
213/// let person = Person::parse_from(&json);
214/// assert!(person.is_some());
215/// assert_eq!(person.unwrap().name.as_deref(), Some("John Doe"));
216/// ```
217pub trait ParseFrom<Source>: Sized {
218    /// Parse from the given source
219    ///
220    /// # Arguments
221    ///
222    /// * `source` - The source data to parse from
223    ///
224    /// # Returns
225    ///
226    /// * `Some(Self)` - Successfully parsed instance
227    /// * `None` - Failed to parse (missing required fields, wrong type, etc.)
228    fn parse_from(source: Source) -> Option<Self>;
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn test_detailed_field_from_value() {
237        let field: DetailedField<String, i32> = DetailedField::from_value("test".to_string());
238        assert_eq!(field.value(), "test");
239        assert!(field.detail().is_none());
240    }
241
242    #[test]
243    fn test_detailed_field_with_detail() {
244        let field = DetailedField::with_detail("test".to_string(), 42);
245        assert_eq!(field.value(), "test");
246        assert_eq!(field.detail(), Some(&42));
247    }
248
249    #[test]
250    fn test_detailed_field_from_tuple() {
251        let field: DetailedField<String, i32> = ("test".to_string(), 42).into();
252        assert_eq!(field.value(), "test");
253        assert_eq!(field.detail(), Some(&42));
254    }
255
256    #[test]
257    fn test_detailed_field_into_parts() {
258        let field = DetailedField::with_detail("test".to_string(), 42);
259        let (value, detail) = field.into_parts();
260        assert_eq!(value, "test");
261        assert_eq!(detail, Some(42));
262    }
263
264    #[test]
265    fn test_limited_collection_try_push() {
266        let mut vec: Vec<i32> = Vec::new();
267        assert!(vec.try_push_limited(1, 3));
268        assert!(vec.try_push_limited(2, 3));
269        assert!(vec.try_push_limited(3, 3));
270        assert!(!vec.try_push_limited(4, 3));
271        assert_eq!(vec.len(), 3);
272    }
273
274    #[test]
275    fn test_limited_collection_is_at_limit() {
276        let mut vec: Vec<i32> = Vec::new();
277        assert!(!vec.is_at_limit(2));
278        vec.push(1);
279        assert!(!vec.is_at_limit(2));
280        vec.push(2);
281        assert!(vec.is_at_limit(2));
282    }
283
284    #[test]
285    fn test_limited_collection_remaining_capacity() {
286        let mut vec: Vec<i32> = Vec::new();
287        assert_eq!(vec.remaining_capacity(5), 5);
288        vec.push(1);
289        vec.push(2);
290        assert_eq!(vec.remaining_capacity(5), 3);
291    }
292
293    #[test]
294    fn test_detailed_field_default() {
295        let field: DetailedField<String, i32> = DetailedField::default();
296        assert_eq!(field.value(), "");
297        assert!(field.detail().is_none());
298    }
299
300    #[test]
301    fn test_detailed_field_mutability() {
302        let mut field = DetailedField::from_value("original".to_string());
303        *field.value_mut() = "modified".to_string();
304        assert_eq!(field.value(), "modified");
305
306        field.set_detail(100);
307        assert_eq!(field.detail(), Some(&100));
308
309        let taken = field.take_detail();
310        assert_eq!(taken, Some(100));
311        assert!(field.detail().is_none());
312    }
313}