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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Take a look at the license at the top of the repository in the LICENSE file.

//! # Examples
//!
//! ```
//! use glib::prelude::*; // or `use gtk::prelude::*;`
//! use glib::ByteArray;
//!
//! let ba = ByteArray::from(b"def");
//! ba.append(b"ghi").prepend(b"abc");
//! ba.remove_range(3, 3);
//! assert_eq!(ba, "abcghi".as_bytes());
//! ```

use crate::translate::*;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;
use std::ptr::NonNull;
use std::slice;

use crate::Bytes;

wrapper! {
    /// Contains the public fields of a GByteArray.
    #[doc(alias = "GByteArray")]
    pub struct ByteArray(Shared<ffi::GByteArray>);

    match fn {
        ref => |ptr| ffi::g_byte_array_ref(ptr),
        unref => |ptr| ffi::g_byte_array_unref(ptr),
        type_ => || ffi::g_byte_array_get_type(),
    }
}

impl ByteArray {
    /// Creates a new [`ByteArray`][crate::ByteArray] with a reference count of 1.
    ///
    /// # Returns
    ///
    /// the new [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_new")]
    pub fn new() -> Self {
        unsafe { from_glib_full(ffi::g_byte_array_new()) }
    }

    #[doc(alias = "g_byte_array_sized_new")]
    pub fn with_capacity(size: usize) -> Self {
        unsafe { from_glib_full(ffi::g_byte_array_sized_new(size as u32)) }
    }

    #[doc(alias = "g_byte_array_free_to_bytes")]
    pub fn into_gbytes(self) -> Bytes {
        unsafe {
            let s = mem::ManuallyDrop::new(self);
            from_glib_full(ffi::g_byte_array_free_to_bytes(mut_override(
                s.to_glib_none().0,
            )))
        }
    }

    /// Adds the given bytes to the end of the [`ByteArray`][crate::ByteArray].
    /// The array will grow in size automatically if necessary.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `data`
    /// the byte data to be added
    /// ## `len`
    /// the number of bytes to add
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_append")]
    pub fn append<T: ?Sized + AsRef<[u8]>>(&self, data: &T) -> &Self {
        let bytes = data.as_ref();
        unsafe {
            ffi::g_byte_array_append(
                self.to_glib_none().0,
                bytes.as_ptr() as *const _,
                bytes.len() as u32,
            );
        }
        self
    }

    /// Adds the given data to the start of the [`ByteArray`][crate::ByteArray].
    /// The array will grow in size automatically if necessary.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `data`
    /// the byte data to be added
    /// ## `len`
    /// the number of bytes to add
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_prepend")]
    pub fn prepend<T: ?Sized + AsRef<[u8]>>(&self, data: &T) -> &Self {
        let bytes = data.as_ref();
        unsafe {
            ffi::g_byte_array_prepend(
                self.to_glib_none().0,
                bytes.as_ptr() as *const _,
                bytes.len() as u32,
            );
        }
        self
    }

    /// Removes the byte at the given index from a [`ByteArray`][crate::ByteArray].
    /// The following bytes are moved down one place.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `index_`
    /// the index of the byte to remove
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_remove_index")]
    pub fn remove_index(&self, index: usize) {
        unsafe {
            ffi::g_byte_array_remove_index(self.to_glib_none().0, index as u32);
        }
    }

    /// Removes the byte at the given index from a [`ByteArray`][crate::ByteArray]. The last
    /// element in the array is used to fill in the space, so this function
    /// does not preserve the order of the [`ByteArray`][crate::ByteArray]. But it is faster
    /// than [`remove_index()`][Self::remove_index()].
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `index_`
    /// the index of the byte to remove
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_remove_index_fast")]
    pub fn remove_index_fast(&self, index: usize) {
        unsafe {
            ffi::g_byte_array_remove_index_fast(self.to_glib_none().0, index as u32);
        }
    }

    /// Removes the given number of bytes starting at the given index from a
    /// [`ByteArray`][crate::ByteArray]. The following elements are moved to close the gap.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `index_`
    /// the index of the first byte to remove
    /// ## `length`
    /// the number of bytes to remove
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_remove_range")]
    pub fn remove_range(&self, index: usize, length: usize) {
        unsafe {
            ffi::g_byte_array_remove_range(self.to_glib_none().0, index as u32, length as u32);
        }
    }

    /// Sets the size of the [`ByteArray`][crate::ByteArray], expanding it if necessary.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `length`
    /// the new size of the [`ByteArray`][crate::ByteArray]
    ///
    /// # Returns
    ///
    /// the [`ByteArray`][crate::ByteArray]
    #[doc(alias = "g_byte_array_set_size")]
    pub unsafe fn set_size(&self, size: usize) {
        ffi::g_byte_array_set_size(self.to_glib_none().0, size as u32);
    }

    /// Sorts a byte array, using `compare_func` which should be a
    /// `qsort()`-style comparison function (returns less than zero for first
    /// arg is less than second arg, zero for equal, greater than zero if
    /// first arg is greater than second arg).
    ///
    /// If two array elements compare equal, their order in the sorted array
    /// is undefined. If you want equal elements to keep their order (i.e.
    /// you want a stable sort) you can write a comparison function that,
    /// if two elements would otherwise compare equal, compares them by
    /// their addresses.
    /// ## `array`
    /// a [`ByteArray`][crate::ByteArray]
    /// ## `compare_func`
    /// comparison function
    #[doc(alias = "g_byte_array_sort_with_data")]
    pub fn sort<F: FnMut(&u8, &u8) -> Ordering>(&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(&u8, &u8) -> Ordering);

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

            match (*func)(a, b) {
                Ordering::Less => -1,
                Ordering::Equal => 0,
                Ordering::Greater => 1,
            }
        }
        unsafe {
            let mut func = compare_func;
            let func_obj: &mut (dyn FnMut(&u8, &u8) -> Ordering) = &mut func;
            let func_ptr =
                &func_obj as *const &mut (dyn FnMut(&u8, &u8) -> Ordering) as ffi::gpointer;

            ffi::g_byte_array_sort_with_data(
                self.to_glib_none().0,
                Some(compare_func_trampoline),
                func_ptr,
            );
        }
    }
}

impl AsRef<[u8]> for ByteArray {
    fn as_ref(&self) -> &[u8] {
        &*self
    }
}

impl<'a, T: ?Sized + Borrow<[u8]> + 'a> From<&'a T> for ByteArray {
    fn from(value: &'a T) -> ByteArray {
        let ba = ByteArray::new();
        ba.append(value.borrow());
        ba
    }
}

impl Deref for ByteArray {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        unsafe {
            let mut ptr = (*self.to_glib_none().0).data;
            let len = (*self.to_glib_none().0).len as usize;
            debug_assert!(!ptr.is_null() || len == 0);
            if ptr.is_null() {
                ptr = NonNull::dangling().as_ptr();
            }
            slice::from_raw_parts(ptr as *const u8, len)
        }
    }
}

impl Default for ByteArray {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for ByteArray {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ByteArray")
            .field("ptr", &self.to_glib_none().0)
            .field("data", &&self[..])
            .finish()
    }
}

macro_rules! impl_cmp {
    ($lhs:ty, $rhs: ty) => {
        #[allow(clippy::redundant_slicing)]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                self[..].eq(&other[..])
            }
        }

        #[allow(clippy::redundant_slicing)]
        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                self[..].eq(&other[..])
            }
        }

        #[allow(clippy::redundant_slicing)]
        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
            #[inline]
            fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
                self[..].partial_cmp(&other[..])
            }
        }

        #[allow(clippy::redundant_slicing)]
        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
            #[inline]
            fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
                self[..].partial_cmp(&other[..])
            }
        }
    };
}

impl_cmp!(ByteArray, [u8]);
impl_cmp!(ByteArray, &'a [u8]);
impl_cmp!(&'a ByteArray, [u8]);
impl_cmp!(ByteArray, Vec<u8>);
impl_cmp!(&'a ByteArray, Vec<u8>);

impl PartialEq for ByteArray {
    fn eq(&self, other: &Self) -> bool {
        self[..] == other[..]
    }
}

impl Eq for ByteArray {}

impl Hash for ByteArray {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.len().hash(state);
        Hash::hash_slice(&self[..], state)
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn various() {
        let ba: ByteArray = Default::default();
        ba.append("foo").append("bar").prepend("baz");
        ba.remove_index(0);
        ba.remove_index_fast(1);
        ba.remove_range(1, 2);
        ba.sort(|a, b| a.cmp(b));
        unsafe { ba.set_size(3) };
        assert_eq!(ba, b"aab" as &[u8]);
        let abc: &[u8] = b"abc";
        assert_eq!(ByteArray::from(abc), b"abc" as &[u8]);
    }

    #[test]
    fn hash() {
        let b1 = ByteArray::from(b"this is a test");
        let b2 = ByteArray::from(b"this is a test");
        let b3 = ByteArray::from(b"test");
        let mut set = HashSet::new();
        set.insert(b1);
        assert!(set.contains(&b2));
        assert!(!set.contains(&b3));
    }
}