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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{cmp::Ordering, ops, slice};

use crate::{
    ffi, gobject_ffi, prelude::*, translate::*, ParamSpecValueArray, ParamSpecValueArrayBuilder,
    Type, Value,
};

wrapper! {
    #[derive(Debug)]
    #[doc(alias = "GValueArray")]
    pub struct ValueArray(Boxed<gobject_ffi::GValueArray>);

    match fn {
        copy => |ptr| gobject_ffi::g_value_array_copy(mut_override(ptr)),
        free => |ptr| gobject_ffi::g_value_array_free(ptr),
    }
}

impl ValueArray {
    #[inline]
    pub fn new(values: impl IntoIterator<Item = impl ToValue>) -> Self {
        let iter = values.into_iter();
        let mut array = Self::with_capacity(iter.size_hint().0);
        for v in iter {
            array.append(v.to_value());
        }

        array
    }

    #[inline]
    pub fn from_values(values: impl IntoIterator<Item = Value>) -> Self {
        Self::new(values)
    }

    #[doc(alias = "g_value_array_new")]
    #[inline]
    pub fn with_capacity(capacity: usize) -> ValueArray {
        assert!(capacity <= u32::MAX as usize);

        unsafe { from_glib_full(gobject_ffi::g_value_array_new(capacity as u32)) }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.inner.n_values as usize
    }

    #[doc(alias = "g_value_array_append")]
    #[inline]
    pub fn append(&mut self, value: impl ToValue) {
        self.append_value(&value.to_value());
    }

    #[doc(alias = "g_value_array_append")]
    #[inline]
    pub fn append_value(&mut self, value: &Value) {
        unsafe {
            gobject_ffi::g_value_array_append(self.to_glib_none_mut().0, value.to_glib_none().0);
        }
    }

    #[doc(alias = "g_value_array_insert")]
    #[inline]
    pub fn insert(&mut self, index_: usize, value: impl ToValue) {
        self.insert_value(index_, &value.to_value());
    }

    #[doc(alias = "g_value_array_insert")]
    #[inline]
    pub fn insert_value(&mut self, index_: usize, value: &Value) {
        assert!(index_ <= self.len());

        unsafe {
            gobject_ffi::g_value_array_insert(
                self.to_glib_none_mut().0,
                index_ as u32,
                value.to_glib_none().0,
            );
        }
    }

    #[doc(alias = "g_value_array_prepend")]
    #[inline]
    pub fn prepend(&mut self, value: impl ToValue) {
        self.prepend_value(&value.to_value());
    }

    #[doc(alias = "g_value_array_prepend")]
    #[inline]
    pub fn prepend_value(&mut self, value: &Value) {
        unsafe {
            gobject_ffi::g_value_array_prepend(self.to_glib_none_mut().0, value.to_glib_none().0);
        }
    }

    #[doc(alias = "g_value_array_remove")]
    #[inline]
    pub fn remove(&mut self, index_: usize) {
        assert!(index_ < self.len());

        unsafe {
            gobject_ffi::g_value_array_remove(self.to_glib_none_mut().0, index_ as u32);
        }
    }

    #[doc(alias = "g_value_array_sort_with_data")]
    pub fn sort_with_data<F: FnMut(&Value, &Value) -> Ordering>(&mut self, compare_func: F) {
        unsafe extern "C" fn compare_func_trampoline(
            a: ffi::gconstpointer,
            b: ffi::gconstpointer,
            func: ffi::gpointer,
        ) -> i32 {
            let func = func as *mut &mut (dyn FnMut(&Value, &Value) -> Ordering);

            let a = &*(a as *const Value);
            let b = &*(b as *const Value);

            (*func)(a, b).into_glib()
        }
        unsafe {
            let mut func = compare_func;
            let func_obj: &mut (dyn FnMut(&Value, &Value) -> Ordering) = &mut func;
            let func_ptr =
                &func_obj as *const &mut (dyn FnMut(&Value, &Value) -> Ordering) as ffi::gpointer;

            gobject_ffi::g_value_array_sort_with_data(
                self.to_glib_none_mut().0,
                Some(compare_func_trampoline),
                func_ptr,
            );
        }
    }

    #[inline]
    pub fn as_slice(&self) -> &[Value] {
        if self.is_empty() {
            return &[];
        }

        unsafe {
            slice::from_raw_parts(
                (*self.as_ptr()).values as *const Value,
                (*self.as_ptr()).n_values as usize,
            )
        }
    }

    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [Value] {
        if self.is_empty() {
            return &mut [];
        }

        unsafe {
            slice::from_raw_parts_mut(
                (*self.as_ptr()).values as *mut Value,
                (*self.as_ptr()).n_values as usize,
            )
        }
    }
}

impl ops::Deref for ValueArray {
    type Target = [Value];

    #[inline]
    fn deref(&self) -> &[Value] {
        self.as_slice()
    }
}

impl ops::DerefMut for ValueArray {
    #[inline]
    fn deref_mut(&mut self) -> &mut [Value] {
        self.as_mut_slice()
    }
}

impl Default for ValueArray {
    fn default() -> Self {
        Self::with_capacity(8)
    }
}

impl std::iter::FromIterator<Value> for ValueArray {
    fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
        Self::from_values(iter)
    }
}

impl std::iter::Extend<Value> for ValueArray {
    fn extend<T: IntoIterator<Item = Value>>(&mut self, iter: T) {
        for v in iter.into_iter() {
            self.append_value(&v);
        }
    }
}

// Implementing `Value` traits manually because of a custom ParamSpec
impl StaticType for ValueArray {
    #[inline]
    fn static_type() -> Type {
        unsafe { from_glib(gobject_ffi::g_value_array_get_type()) }
    }
}

#[doc(hidden)]
impl ValueType for ValueArray {
    type Type = Self;
}

#[doc(hidden)]
impl crate::value::ValueTypeOptional for ValueArray {}

#[doc(hidden)]
unsafe impl<'a> crate::value::FromValue<'a> for ValueArray {
    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;

    #[inline]
    unsafe fn from_value(value: &'a Value) -> Self {
        let ptr = gobject_ffi::g_value_dup_boxed(value.to_glib_none().0);
        debug_assert!(!ptr.is_null());
        from_glib_full(ptr as *mut gobject_ffi::GValueArray)
    }
}

#[doc(hidden)]
unsafe impl<'a> crate::value::FromValue<'a> for &'a ValueArray {
    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;

    #[inline]
    unsafe fn from_value(value: &'a Value) -> Self {
        debug_assert_eq!(
            std::mem::size_of::<Self>(),
            std::mem::size_of::<ffi::gpointer>()
        );
        let value = &*(value as *const Value as *const gobject_ffi::GValue);
        debug_assert!(!value.data[0].v_pointer.is_null());
        <ValueArray>::from_glib_ptr_borrow(
            &*(&value.data[0].v_pointer as *const ffi::gpointer
                as *const *mut gobject_ffi::GValueArray),
        )
    }
}

#[doc(hidden)]
impl ToValue for ValueArray {
    #[inline]
    fn to_value(&self) -> Value {
        unsafe {
            let mut value = Value::from_type_unchecked(<Self as StaticType>::static_type());
            gobject_ffi::g_value_take_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut gobject_ffi::GValueArray>::to_glib_full(self) as *mut _,
            );
            value
        }
    }

    #[inline]
    fn value_type(&self) -> Type {
        <Self as StaticType>::static_type()
    }
}

impl std::convert::From<ValueArray> for Value {
    #[inline]
    fn from(o: ValueArray) -> Self {
        unsafe {
            let mut value = Value::from_type_unchecked(<ValueArray as StaticType>::static_type());
            gobject_ffi::g_value_take_boxed(
                value.to_glib_none_mut().0,
                IntoGlibPtr::<*mut gobject_ffi::GValueArray>::into_glib_ptr(o) as *mut _,
            );
            value
        }
    }
}

#[doc(hidden)]
impl crate::value::ToValueOptional for ValueArray {
    #[inline]
    fn to_value_optional(s: Option<&Self>) -> Value {
        let mut value = Value::for_value_type::<Self>();
        unsafe {
            gobject_ffi::g_value_take_boxed(
                value.to_glib_none_mut().0,
                ToGlibPtr::<*mut gobject_ffi::GValueArray>::to_glib_full(&s) as *mut _,
            );
        }

        value
    }
}

impl HasParamSpec for ValueArray {
    type ParamSpec = ParamSpecValueArray;
    type SetValue = Self;
    type BuilderFn = fn(&str) -> ParamSpecValueArrayBuilder;

    fn param_spec_builder() -> Self::BuilderFn {
        Self::ParamSpec::builder
    }
}

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

    #[test]
    fn test_new() {
        let arr = ValueArray::new(["123", "456"]);
        assert_eq!(
            arr.first().and_then(|v| v.get::<String>().ok()),
            Some(String::from("123"))
        );
        assert_eq!(
            arr.get(1).and_then(|v| v.get::<String>().ok()),
            Some(String::from("456"))
        );
    }

    #[test]
    fn test_append() {
        let mut arr = ValueArray::default();
        arr.append("123");
        arr.append(123u32);
        arr.append_value(&Value::from(456u64));

        assert_eq!(
            arr.first().and_then(|v| v.get::<String>().ok()),
            Some(String::from("123"))
        );
        assert_eq!(arr.get(1).and_then(|v| v.get::<u32>().ok()), Some(123));
        assert_eq!(arr.get(2).and_then(|v| v.get::<u64>().ok()), Some(456));
    }
}