1use std::{
4 borrow::Borrow,
5 cmp::Ordering,
6 fmt,
7 hash::{Hash, Hasher},
8 mem,
9 ops::{Bound, Deref, RangeBounds},
10 slice,
11};
12
13use crate::{ffi, translate::*};
14
15wrapper! {
16 #[doc(alias = "GBytes")]
62 pub struct Bytes(Shared<ffi::GBytes>);
63
64 match fn {
65 ref => |ptr| ffi::g_bytes_ref(ptr),
66 unref => |ptr| ffi::g_bytes_unref(ptr),
67 type_ => || ffi::g_bytes_get_type(),
68 }
69}
70
71impl Bytes {
72 #[doc(alias = "g_bytes_new")]
90 #[inline]
91 fn new<T: AsRef<[u8]>>(data: T) -> Bytes {
92 let data = data.as_ref();
93 unsafe { from_glib_full(ffi::g_bytes_new(data.as_ptr() as *const _, data.len())) }
94 }
95
96 #[doc(alias = "g_bytes_new_static")]
99 #[inline]
100 pub fn from_static(data: &'static [u8]) -> Bytes {
101 unsafe {
102 from_glib_full(ffi::g_bytes_new_static(
103 data.as_ptr() as *const _,
104 data.len(),
105 ))
106 }
107 }
108
109 #[doc(alias = "g_bytes_new")]
112 pub fn from_owned<T: AsRef<[u8]> + Send + 'static>(data: T) -> Bytes {
113 let data: Box<T> = Box::new(data);
114 let (size, data_ptr) = {
115 let data = (*data).as_ref();
116 (data.len(), data.as_ptr())
117 };
118
119 unsafe extern "C" fn drop_box<T: AsRef<[u8]> + Send + 'static>(b: ffi::gpointer) {
120 let _: Box<T> = Box::from_raw(b as *mut _);
121 }
122
123 unsafe {
124 from_glib_full(ffi::g_bytes_new_with_free_func(
125 data_ptr as *const _,
126 size,
127 Some(drop_box::<T>),
128 Box::into_raw(data) as *mut _,
129 ))
130 }
131 }
132
133 #[doc(alias = "g_bytes_unref_to_data")]
139 pub fn into_data(self) -> crate::collections::Slice<u8> {
140 unsafe {
141 let mut size = mem::MaybeUninit::uninit();
142 let ret = ffi::g_bytes_unref_to_data(self.into_glib_ptr(), size.as_mut_ptr());
143 crate::collections::Slice::from_glib_full_num(ret as *mut u8, size.assume_init())
144 }
145 }
146
147 fn calculate_offset_size(&self, range: impl RangeBounds<usize>) -> (usize, usize) {
148 let len = self.len();
149
150 let start_offset = match range.start_bound() {
151 Bound::Included(v) => *v,
152 Bound::Excluded(v) => v.checked_add(1).expect("Invalid start offset"),
153 Bound::Unbounded => 0,
154 };
155 assert!(start_offset < len, "Start offset after valid range");
156
157 let end_offset = match range.end_bound() {
158 Bound::Included(v) => v.checked_add(1).expect("Invalid end offset"),
159 Bound::Excluded(v) => *v,
160 Bound::Unbounded => len,
161 };
162 assert!(end_offset <= len, "End offset after valid range");
163
164 let size = end_offset.saturating_sub(start_offset);
165
166 (start_offset, size)
167 }
168
169 #[doc(alias = "g_bytes_new_from_bytes")]
172 pub fn from_bytes(bytes: &Self, range: impl RangeBounds<usize>) -> Self {
173 let (offset, size) = bytes.calculate_offset_size(range);
174 unsafe {
175 from_glib_full(ffi::g_bytes_new_from_bytes(
176 bytes.to_glib_none().0,
177 offset,
178 size,
179 ))
180 }
181 }
182}
183
184unsafe impl Send for Bytes {}
185unsafe impl Sync for Bytes {}
186
187impl<'a, T: ?Sized + Borrow<[u8]> + 'a> From<&'a T> for Bytes {
188 #[inline]
189 fn from(value: &'a T) -> Bytes {
190 Bytes::new(value.borrow())
191 }
192}
193
194impl fmt::Debug for Bytes {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 f.debug_struct("Bytes")
197 .field("ptr", &ToGlibPtr::<*const _>::to_glib_none(self).0)
198 .field("data", &&self[..])
199 .finish()
200 }
201}
202
203impl AsRef<[u8]> for Bytes {
204 #[inline]
205 fn as_ref(&self) -> &[u8] {
206 self
207 }
208}
209
210impl Deref for Bytes {
211 type Target = [u8];
212
213 #[inline]
214 fn deref(&self) -> &[u8] {
215 unsafe {
216 let mut len = 0;
217 let ptr = ffi::g_bytes_get_data(self.to_glib_none().0, &mut len);
218 if ptr.is_null() || len == 0 {
219 &[]
220 } else {
221 slice::from_raw_parts(ptr as *const u8, len)
222 }
223 }
224 }
225}
226
227impl PartialEq for Bytes {
228 #[doc(alias = "g_bytes_equal")]
229 #[inline]
230 fn eq(&self, other: &Self) -> bool {
231 unsafe {
232 from_glib(ffi::g_bytes_equal(
233 ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
234 ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
235 ))
236 }
237 }
238}
239
240impl Eq for Bytes {}
241
242impl PartialOrd for Bytes {
243 #[inline]
244 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
245 Some(self.cmp(other))
246 }
247}
248
249impl Ord for Bytes {
250 #[inline]
251 fn cmp(&self, other: &Self) -> Ordering {
252 unsafe {
253 let ret = ffi::g_bytes_compare(
254 ToGlibPtr::<*const _>::to_glib_none(self).0 as *const _,
255 ToGlibPtr::<*const _>::to_glib_none(other).0 as *const _,
256 );
257 ret.cmp(&0)
258 }
259 }
260}
261
262macro_rules! impl_cmp {
263 ($lhs:ty, $rhs: ty) => {
264 #[allow(clippy::redundant_slicing)]
265 #[allow(clippy::extra_unused_lifetimes)]
266 impl<'a, 'b> PartialEq<$rhs> for $lhs {
267 #[inline]
268 fn eq(&self, other: &$rhs) -> bool {
269 self[..].eq(&other[..])
270 }
271 }
272
273 #[allow(clippy::redundant_slicing)]
274 #[allow(clippy::extra_unused_lifetimes)]
275 impl<'a, 'b> PartialEq<$lhs> for $rhs {
276 #[inline]
277 fn eq(&self, other: &$lhs) -> bool {
278 self[..].eq(&other[..])
279 }
280 }
281
282 #[allow(clippy::redundant_slicing)]
283 #[allow(clippy::extra_unused_lifetimes)]
284 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
285 #[inline]
286 fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
287 self[..].partial_cmp(&other[..])
288 }
289 }
290
291 #[allow(clippy::redundant_slicing)]
292 #[allow(clippy::extra_unused_lifetimes)]
293 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
294 #[inline]
295 fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
296 self[..].partial_cmp(&other[..])
297 }
298 }
299 };
300}
301
302impl_cmp!(Bytes, [u8]);
303impl_cmp!(Bytes, &'a [u8]);
304impl_cmp!(&'a Bytes, [u8]);
305impl_cmp!(Bytes, Vec<u8>);
306impl_cmp!(&'a Bytes, Vec<u8>);
307
308impl Hash for Bytes {
309 #[inline]
310 fn hash<H: Hasher>(&self, state: &mut H) {
311 self.len().hash(state);
312 Hash::hash_slice(self, state)
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use std::collections::HashSet;
319
320 use super::*;
321
322 #[test]
323 fn eq() {
324 let abc: &[u8] = b"abc";
325 let def: &[u8] = b"def";
326 let a1 = Bytes::from(abc);
327 let a2 = Bytes::from(abc);
328 let d = Bytes::from(def);
329 assert_eq!(a1, a2);
330 assert_eq!(def, d);
331 assert_ne!(a1, d);
332 assert_ne!(a1, def);
333 }
334
335 #[test]
336 fn ord() {
337 let abc: &[u8] = b"abc";
338 let def: &[u8] = b"def";
339 let a = Bytes::from(abc);
340 let d = Bytes::from(def);
341 assert!(a < d);
342 assert!(a < def);
343 assert!(abc < d);
344 assert!(d > a);
345 assert!(d > abc);
346 assert!(def > a);
347 }
348
349 #[test]
350 fn hash() {
351 let b1 = Bytes::from(b"this is a test");
352 let b2 = Bytes::from(b"this is a test");
353 let b3 = Bytes::from(b"test");
354 let mut set = HashSet::new();
355 set.insert(b1);
356 assert!(set.contains(&b2));
357 assert!(!set.contains(&b3));
358 }
359
360 #[test]
361 fn from_static() {
362 let b1 = Bytes::from_static(b"this is a test");
363 let b2 = Bytes::from(b"this is a test");
364 assert_eq!(b1, b2);
365 }
366
367 #[test]
368 fn from_owned() {
369 let b = Bytes::from_owned(vec![1, 2, 3]);
370 assert_eq!(b, [1u8, 2u8, 3u8].as_ref());
371 }
372
373 #[test]
374 fn from_bytes() {
375 let b1 = Bytes::from_owned(vec![1, 2, 3]);
376 let b2 = Bytes::from_bytes(&b1, 1..=1);
377 assert_eq!(b2, [2u8].as_ref());
378 let b2 = Bytes::from_bytes(&b1, 1..);
379 assert_eq!(b2, [2u8, 3u8].as_ref());
380 let b2 = Bytes::from_bytes(&b1, ..2);
381 assert_eq!(b2, [1u8, 2u8].as_ref());
382 let b2 = Bytes::from_bytes(&b1, ..);
383 assert_eq!(b2, [1u8, 2u8, 3u8].as_ref());
384 }
385
386 #[test]
387 pub fn into_data() {
388 let b = Bytes::from(b"this is a test");
389 let d = b.into_data();
390 assert_eq!(d.as_slice(), b"this is a test");
391 }
392}