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
//! Info lists.

use std::convert::TryFrom;
use std::ops::Deref;
use std::str::Split;

use crate::str::{HexStr, HexString};

/// A list that can be retrieved from HexChat.
///
/// Used with [`PluginHandle::get_list`](crate::PluginHandle::get_list).
///
/// This trait is sealed and cannot be implemented outside of `hexavalent`.
pub trait List: private::ListImpl + 'static
where
    Self::Elem: private::FromListElem,
{
    /// The type of elements of the list.
    // todo with GATs, it _might_ be nice to have Elem/BorrowedElem<'a>, so that we can avoid allocation
    //  (but we'd probably have to make get_list_with unsafe due to invalidation of the string)
    type Elem: 'static;
}

pub(crate) mod private {
    use crate::ffi::ListElem;
    use std::ffi::CStr;

    pub trait ListImpl {
        const NAME: &'static CStr;
    }

    #[allow(unreachable_pub)]
    pub trait FromListElem: Sized {
        fn from_list_elem(elem: ListElem<'_>) -> Self;
    }
}

macro_rules! list {
    (
        $struct_name:ident,
        $list_name:literal,
        $description:literal,
        $elem_desc:literal,
        $elem_ty:ident {
            $(
                [ $( $field_key:literal )? $( $custom:ident )?, $field_desc:literal, $( $field_type:ident )? $( |$elem:ident| $extract:expr )? ]
                $rust_field_name:ident : $rust_field_type:ty => $rust_method_type:ty
            ),* $(,)?
        }
    ) => {
        #[doc = "`"]
        #[doc = $list_name]
        #[doc = "`"]
        #[doc = ""]
        #[doc = $description]
        #[derive(Debug, Copy, Clone)]
        pub struct $struct_name;

        impl crate::list::private::ListImpl for $struct_name {
            const NAME: &'static ::std::ffi::CStr = match ::std::ffi::CStr::from_bytes_with_nul(concat!($list_name, "\0").as_bytes()) {
                Ok(name) => name,
                Err(_) => unreachable!(),
            };
        }

        impl crate::list::List for $struct_name {
            type Elem = $elem_ty;
        }

        #[doc = $elem_desc]
        ///
        /// See the [`List`](crate::list::List) trait for usage.
        #[derive(Debug, Clone)]
        pub struct $elem_ty {
            $(
                $rust_field_name: $rust_field_type,
            )*
        }

        impl $elem_ty {
            $(
                #[doc = $field_desc]
                pub fn $rust_field_name(&self) -> $rust_method_type {
                    crate::list::ProjectListElemField::project_list_elem_field(&self.$rust_field_name)
                }
            )*
        }

        impl crate::list::private::FromListElem for $elem_ty {
            fn from_list_elem(elem: crate::ffi::ListElem<'_>) -> Self {
                Self {
                    $(
                        $rust_field_name: {
                            let raw_value = list!(@generateFieldExtraction, elem, $( $field_key )? $( $custom )?, $( $field_type )? $( |$elem| $extract )?);
                            crate::list::FromListElemField::from_list_elem_field(raw_value)
                        },
                    )*
                }
            }
        }
    };

    (
        @generateFieldExtraction,
        $elem:ident,
        custom,
        |$elem2:ident| $extract:expr
    ) => {
        {
            let $elem2 = & $elem;
            $extract
        }
    };

    (
        @generateFieldExtraction,
        $elem:ident,
        $field_key:literal,
        $field_type:ident
    ) => {
        {
            const NAME: &::std::ffi::CStr = match ::std::ffi::CStr::from_bytes_with_nul(concat!($field_key, "\0").as_bytes()) {
                Ok(name) => name,
                Err(_) => unreachable!(),
            };
            $elem.$field_type(NAME)
        }
    }
}

#[derive(Debug, Clone)]
struct SplitByCommas(String);

trait FromListElemField<T> {
    fn from_list_elem_field(field: T) -> Self;
}

impl<T> FromListElemField<T> for T {
    fn from_list_elem_field(field: T) -> Self {
        field
    }
}

impl FromListElemField<Option<&HexStr>> for HexString {
    fn from_list_elem_field(field: Option<&HexStr>) -> Self {
        field
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| panic!("Unexpected null string in list"))
    }
}

impl FromListElemField<Option<&HexStr>> for Option<HexString> {
    fn from_list_elem_field(field: Option<&HexStr>) -> Self {
        field.map(ToOwned::to_owned)
    }
}

impl FromListElemField<Option<&HexStr>> for Option<char> {
    fn from_list_elem_field(field: Option<&HexStr>) -> Self {
        match field {
            Some(field) => match field.as_bytes() {
                &[] => None,
                &[single_byte] => Some(single_byte.into()),
                bytes => panic!(
                    "Expected 0 or 1 byte char in list, found {} bytes",
                    bytes.len()
                ),
            },
            None => panic!("Unexpected null string (char) in list"),
        }
    }
}

impl FromListElemField<i32> for u32 {
    fn from_list_elem_field(field: i32) -> Self {
        Self::try_from(field)
            .unwrap_or_else(|e| panic!("Unexpected negative integer in list: {}", e))
    }
}

impl FromListElemField<i32> for bool {
    fn from_list_elem_field(field: i32) -> Self {
        field != 0
    }
}

impl FromListElemField<Option<&HexStr>> for SplitByCommas {
    fn from_list_elem_field(field: Option<&HexStr>) -> SplitByCommas {
        SplitByCommas(field.map(|s| s.deref().to_owned()).unwrap_or_default())
    }
}

trait ProjectListElemField<'a, T> {
    fn project_list_elem_field(&'a self) -> T;
}

impl<'a, T: Copy> ProjectListElemField<'a, T> for T {
    fn project_list_elem_field(&self) -> T {
        *self
    }
}

impl<'a> ProjectListElemField<'a, &'a HexStr> for HexString {
    fn project_list_elem_field(&self) -> &HexStr {
        self
    }
}

impl<'a> ProjectListElemField<'a, Option<&'a HexStr>> for Option<HexString> {
    fn project_list_elem_field(&self) -> Option<&HexStr> {
        self.as_deref()
    }
}

impl<'a> ProjectListElemField<'a, Split<'a, char>> for SplitByCommas {
    fn project_list_elem_field(&'a self) -> Split<'a, char> {
        self.0.split(',')
    }
}

mod impls;

pub use impls::*;