glib/
bytes.rs

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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    borrow::Borrow,
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    ops::Deref,
    slice,
};

use crate::{ffi, translate::*};

wrapper! {
    // rustdoc-stripper-ignore-next
    /// A shared immutable byte slice (the equivalent of `Rc<[u8]>`).
    ///
    /// `From` implementations that take references (e.g. `&[u8]`) copy the
    /// data. The `from_static` constructor avoids copying static data.
    ///
    /// ```
    /// use glib::Bytes;
    ///
    /// let v = vec![1, 2, 3];
    /// let b = Bytes::from(&v);
    /// assert_eq!(v, b);
    ///
    /// let s = b"xyz";
    /// let b = Bytes::from_static(s);
    /// assert_eq!(&s[..], b);
    /// ```
    // rustdoc-stripper-ignore-next-stop
    /// A simple reference counted data type representing an immutable sequence of
    /// zero or more bytes from an unspecified origin.
    ///
    /// The purpose of a `GBytes` is to keep the memory region that it holds
    /// alive for as long as anyone holds a reference to the bytes.  When
    /// the last reference count is dropped, the memory is released. Multiple
    /// unrelated callers can use byte data in the `GBytes` without coordinating
    /// their activities, resting assured that the byte data will not change or
    /// move while they hold a reference.
    ///
    /// A `GBytes` can come from many different origins that may have
    /// different procedures for freeing the memory region.  Examples are
    /// memory from `malloc()`, from memory slices, from a
    /// `GLib::MappedFile` or memory from other allocators.
    ///
    /// `GBytes` work well as keys in `GLib::HashTable`. Use
    /// `GLib::Bytes::equal()` and `GLib::Bytes::hash()` as parameters to
    /// `GLib::HashTable::new()` or `GLib::HashTable::new_full()`.
    /// `GBytes` can also be used as keys in a `GLib::Tree` by passing the
    /// `GLib::Bytes::compare()` function to `GLib::Tree::new()`.
    ///
    /// The data pointed to by this bytes must not be modified. For a mutable
    /// array of bytes see [`ByteArray`][crate::ByteArray]. Use
    /// [`unref_to_array()`][Self::unref_to_array()] to create a mutable array for a `GBytes`
    /// sequence. To create an immutable `GBytes` from a mutable
    /// [`ByteArray`][crate::ByteArray], use the [`ByteArray::free_to_bytes()`][crate::ByteArray::free_to_bytes()]
    /// function.
    #[doc(alias = "GBytes")]
    pub struct Bytes(Shared<ffi::GBytes>);

    match fn {
        ref => |ptr| ffi::g_bytes_ref(ptr),
        unref => |ptr| ffi::g_bytes_unref(ptr),
        type_ => || ffi::g_bytes_get_type(),
    }
}

impl Bytes {
    // rustdoc-stripper-ignore-next
    /// Copies `data` into a new shared slice.
    // rustdoc-stripper-ignore-next-stop
    /// Creates a new [`Bytes`][crate::Bytes] from @data.
    ///
    /// @data is copied. If @size is 0, @data may be `NULL`.
    ///
    /// As an optimization, `GLib::Bytes::new()` may avoid an extra allocation by
    /// copying the data within the resulting bytes structure if sufficiently small
    /// (since GLib 2.84).
    /// ## `data`
    ///
    ///   the data to be used for the bytes
    ///
    /// # Returns
    ///
    /// a new [`Bytes`][crate::Bytes]
    #[doc(alias = "g_bytes_new")]
    #[inline]
    fn new<T: AsRef<[u8]>>(data: T) -> Bytes {
        let data = data.as_ref();
        unsafe { from_glib_full(ffi::g_bytes_new(data.as_ptr() as *const _, data.len())) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a view into static `data` without copying.
    #[doc(alias = "g_bytes_new_static")]
    #[inline]
    pub fn from_static(data: &'static [u8]) -> Bytes {
        unsafe {
            from_glib_full(ffi::g_bytes_new_static(
                data.as_ptr() as *const _,
                data.len(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Takes ownership of `data` and creates a new `Bytes` without copying.
    pub fn from_owned<T: AsRef<[u8]> + Send + 'static>(data: T) -> Bytes {
        let data: Box<T> = Box::new(data);
        let (size, data_ptr) = {
            let data = (*data).as_ref();
            (data.len(), data.as_ptr())
        };

        unsafe extern "C" fn drop_box<T: AsRef<[u8]> + Send + 'static>(b: ffi::gpointer) {
            let _: Box<T> = Box::from_raw(b as *mut _);
        }

        unsafe {
            from_glib_full(ffi::g_bytes_new_with_free_func(
                data_ptr as *const _,
                size,
                Some(drop_box::<T>),
                Box::into_raw(data) as *mut _,
            ))
        }
    }
}

unsafe impl Send for Bytes {}
unsafe impl Sync for Bytes {}

impl<'a, T: ?Sized + Borrow<[u8]> + 'a> From<&'a T> for Bytes {
    #[inline]
    fn from(value: &'a T) -> Bytes {
        Bytes::new(value.borrow())
    }
}

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

impl AsRef<[u8]> for Bytes {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self
    }
}

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

    #[inline]
    fn deref(&self) -> &[u8] {
        unsafe {
            let mut len = 0;
            let ptr = ffi::g_bytes_get_data(self.to_glib_none().0, &mut len);
            if ptr.is_null() || len == 0 {
                &[]
            } else {
                slice::from_raw_parts(ptr as *const u8, len)
            }
        }
    }
}

impl PartialEq for Bytes {
    #[doc(alias = "g_bytes_equal")]
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::g_bytes_equal(
                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
            ))
        }
    }
}

impl Eq for Bytes {}

impl PartialOrd for Bytes {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Bytes {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        unsafe {
            let ret = ffi::g_bytes_compare(
                ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
                ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
            );
            ret.cmp(&0)
        }
    }
}

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

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

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

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

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

impl Hash for Bytes {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.len().hash(state);
        Hash::hash_slice(self, state)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;

    #[test]
    fn eq() {
        let abc: &[u8] = b"abc";
        let def: &[u8] = b"def";
        let a1 = Bytes::from(abc);
        let a2 = Bytes::from(abc);
        let d = Bytes::from(def);
        assert_eq!(a1, a2);
        assert_eq!(def, d);
        assert_ne!(a1, d);
        assert_ne!(a1, def);
    }

    #[test]
    fn ord() {
        let abc: &[u8] = b"abc";
        let def: &[u8] = b"def";
        let a = Bytes::from(abc);
        let d = Bytes::from(def);
        assert!(a < d);
        assert!(a < def);
        assert!(abc < d);
        assert!(d > a);
        assert!(d > abc);
        assert!(def > a);
    }

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

    #[test]
    fn from_static() {
        let b1 = Bytes::from_static(b"this is a test");
        let b2 = Bytes::from(b"this is a test");
        assert_eq!(b1, b2);
    }

    #[test]
    fn from_owned() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        assert_eq!(b, [1u8, 2u8, 3u8].as_ref());
    }
}