hexchat_api/
list_item.rs

1
2//! A list item for the `ListIterator` and `ThreadSafeListIterator` items that
3//! can populate a vector generated using `ThreadSafeListIterator.to_vec()`,
4//! or using the same function of `ListIterator`. `ListItem`s can also be
5//! obtained using the `.get_item()` method of the list classes.
6
7use std::collections::BTreeMap;
8use std::ops::Index;
9
10use crate::list_iterator::ListIterator;
11use crate::list_iterator::FieldValue;
12
13/// An eagerly constructed list item for vectors created from a `ListIterator`.
14/// For `ThreadSafeListIterator` it can sometimes be quicker to eagerly convert
15/// it to a `Vec<ListItem>` using `ThreadSafeListIterator.to_vec()` and then
16/// iterate over the resulting vector. The conversion happens on the main thread
17/// and is done all at once.
18///
19#[derive(Clone, Debug)]
20pub struct ListItem {
21    fields : BTreeMap<String, FieldValue>,
22}
23
24unsafe impl Send for ListItem {}
25unsafe impl Sync for ListItem {}
26
27impl ListItem {
28    /// Construct a new list item.
29    ///
30    fn new() -> ListItem {
31        ListItem { fields: BTreeMap::new() }
32    }
33    /// Add a field to the list item.
34    ///
35    fn add(&mut self, name: &str, field: FieldValue) {
36        self.fields.insert(name.to_string(), field);
37    }
38    /// Returns `Some(&FieldValue)` if the field exists in the item, or `None`
39    /// instead.
40    ///
41    pub fn get(&self, name: &str) -> Option<&FieldValue> {
42        self.fields.get(name)
43    }
44}
45
46impl Index<&str> for ListItem {
47    type Output = FieldValue;
48    /// The `ListItem` class supports indexing operations using the name of
49    /// the field. This will panic if the field doesn't exist. Alternatively,
50    /// `ListItem.get()` can be used, which returns an option.
51    ///
52    fn index(&self, i: &str) -> &Self::Output {
53        self.fields.get(i).expect("Field doesn't exist.")
54    }
55}
56
57impl From<ListIterator> for ListItem {
58    /// Consructs a list item from the given `ListIterator` instance and
59    /// consumes it. The item is constructed from the fields retrieved from
60    /// the iterator at its current position.
61    ///
62    fn from(list: ListIterator) -> Self {
63        let mut item = ListItem::new();
64        for name in list.get_field_names() {
65            item.add(name, list.get_field(name).unwrap());
66        }
67        item
68    }
69}
70
71impl From<&ListIterator> for ListItem {
72    /// Constructs a list item from the iterator reference at its current
73    /// position.
74    ///
75    fn from(list: &ListIterator) -> Self {
76        let mut item = ListItem::new();
77        for name in list.get_field_names() {
78            item.add(name, list.get_field(name).unwrap());
79        }
80        item
81    }
82}
83