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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use {AsRaw, Device, DeviceDestroyedError, Format, Modifier, Ptr, WeakPtr};

#[cfg(feature = "drm-support")]
use drm::buffer::{Buffer as DrmBuffer, Handle, PlanarBuffer as DrmPlanarBuffer};

use std::error;
use std::fmt;
use std::io::{Error as IoError, Result as IoResult};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::os::unix::io::{AsRawFd, RawFd};
use std::ptr;
use std::slice;

/// A GBM buffer object
pub struct BufferObject<T: 'static> {
    pub(crate) ffi: Ptr<ffi::gbm_bo>,
    pub(crate) _device: WeakPtr<::ffi::gbm_device>,
    pub(crate) _userdata: PhantomData<T>,
}

impl<T> fmt::Debug for BufferObject<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("BufferObject")
            .field("ptr", &format_args!("{:p}", self.ffi))
            .field("device", &format_args!("{:p}", &self._device))
            .field("width", &self.width().unwrap_or(0))
            .field("height", &self.height().unwrap_or(0))
            .field("offsets", &self.offsets())
            .field("stride", &self.stride().unwrap_or(0))
            .field("format", &self.format().ok())
            .field("modifier", &self.modifier().ok())
            .finish()
    }
}

unsafe impl Send for Ptr<::ffi::gbm_bo> {}

bitflags! {
    /// Flags to indicate the intended use for the buffer - these are passed into
    /// [`Device::create_buffer_object()`].
    ///
    /// Use [`Device::is_format_supported()`] to check if the combination of format
    /// and use flags are supported
    pub struct BufferObjectFlags: u32 {
        /// Buffer is going to be presented to the screen using an API such as KMS
        const SCANOUT      = ::ffi::gbm_bo_flags::GBM_BO_USE_SCANOUT as u32;
        /// Buffer is going to be used as cursor
        const CURSOR       = ::ffi::gbm_bo_flags::GBM_BO_USE_CURSOR as u32;
        /// Buffer is going to be used as cursor (deprecated)
        #[deprecated = "Use CURSOR instead"]
        const CURSOR_64X64 = ::ffi::gbm_bo_flags::GBM_BO_USE_CURSOR_64X64 as u32;
        /// Buffer is to be used for rendering - for example it is going to be used
        /// as the storage for a color buffer
        const RENDERING    = ::ffi::gbm_bo_flags::GBM_BO_USE_RENDERING as u32;
        /// Buffer can be used for [`BufferObject::write()`].  This is guaranteed to work
        /// with [`Self::CURSOR`], but may not work for other combinations.
        const WRITE        = ::ffi::gbm_bo_flags::GBM_BO_USE_WRITE as u32;
        /// Buffer is linear, i.e. not tiled.
        const LINEAR       = ::ffi::gbm_bo_flags::GBM_BO_USE_LINEAR as u32;
        /// Buffer is protected
        const PROTECTED    = ::ffi::gbm_bo_flags::GBM_BO_USE_PROTECTED as u32;
    }
}

/// Abstraction representing the handle to a buffer allocated by the manager
pub type BufferObjectHandle = ::ffi::gbm_bo_handle;

enum BORef<'a, T: 'static> {
    Ref(&'a BufferObject<T>),
    Mut(&'a mut BufferObject<T>),
}

/// A mapped buffer object
pub struct MappedBufferObject<'a, T: 'static> {
    bo: BORef<'a, T>,
    buffer: &'a mut [u8],
    data: *mut ::libc::c_void,
    stride: u32,
    height: u32,
    width: u32,
    x: u32,
    y: u32,
}

impl<'a, T> fmt::Debug for MappedBufferObject<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("MappedBufferObject")
            .field(
                "mode",
                &match self.bo {
                    BORef::Ref(_) => format_args!("read"),
                    BORef::Mut(_) => format_args!("write"),
                },
            )
            .field(
                "buffer",
                match &self.bo {
                    BORef::Ref(bo) => bo,
                    BORef::Mut(bo) => &*bo,
                },
            )
            .finish()
    }
}

impl<'a, T: 'static> MappedBufferObject<'a, T> {
    /// Get the stride of the buffer object
    ///
    /// This is calculated by the backend when it does the allocation of the buffer.
    pub fn stride(&self) -> u32 {
        self.stride
    }

    /// The height of the mapped region for the buffer
    pub fn height(&self) -> u32 {
        self.height
    }

    /// The width of the mapped region for the buffer
    pub fn width(&self) -> u32 {
        self.width
    }

    /// The X (top left origin) starting position of the mapped region for the buffer
    pub fn x(&self) -> u32 {
        self.x
    }

    /// The Y (top left origin) starting position of the mapped region for the buffer
    pub fn y(&self) -> u32 {
        self.y
    }

    /// Access to the underlying image buffer
    pub fn buffer(&self) -> &[u8] {
        self.buffer
    }

    /// Mutable access to the underlying image buffer
    pub fn buffer_mut(&mut self) -> &mut [u8] {
        self.buffer
    }
}

impl<'a, T: 'static> Deref for MappedBufferObject<'a, T> {
    type Target = BufferObject<T>;
    fn deref(&self) -> &BufferObject<T> {
        match &self.bo {
            BORef::Ref(bo) => bo,
            BORef::Mut(bo) => bo,
        }
    }
}

impl<'a, T: 'static> DerefMut for MappedBufferObject<'a, T> {
    fn deref_mut(&mut self) -> &mut BufferObject<T> {
        match &mut self.bo {
            BORef::Ref(_) => unreachable!(),
            BORef::Mut(bo) => bo,
        }
    }
}

impl<'a, T: 'static> Drop for MappedBufferObject<'a, T> {
    fn drop(&mut self) {
        let ffi = match &self.bo {
            BORef::Ref(bo) => &bo.ffi,
            BORef::Mut(bo) => &bo.ffi,
        };
        unsafe { ::ffi::gbm_bo_unmap(**ffi, self.data) }
    }
}

unsafe extern "C" fn destroy<T: 'static>(_: *mut ::ffi::gbm_bo, ptr: *mut ::libc::c_void) {
    let ptr = ptr as *mut T;
    if !ptr.is_null() {
        let _ = Box::from_raw(ptr);
    }
}

impl<T: 'static> BufferObject<T> {
    /// Get the width of the buffer object
    pub fn width(&self) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_width(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the height of the buffer object
    pub fn height(&self) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_height(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the stride of the buffer object
    pub fn stride(&self) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_stride(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the stride of the buffer object
    pub fn stride_for_plane(&self, plane: i32) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_stride_for_plane(*self.ffi, plane) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the format of the buffer object
    pub fn format(&self) -> Result<Format, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            use std::convert::TryFrom;
            Ok(
                Format::try_from(unsafe { ::ffi::gbm_bo_get_format(*self.ffi) })
                    .expect("libgbm returned invalid buffer format"),
            )
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the bits per pixel of the buffer object
    pub fn bpp(&self) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_bpp(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the offset for a plane of the buffer object
    pub fn offset(&self, plane: i32) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_offset(*self.ffi, plane) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the plane count of the buffer object
    pub fn plane_count(&self) -> Result<u32, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_plane_count(*self.ffi) as u32 })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the modifier of the buffer object
    pub fn modifier(&self) -> Result<Modifier, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(Modifier::from(unsafe {
                ::ffi::gbm_bo_get_modifier(*self.ffi)
            }))
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get a DMA-BUF file descriptor for the buffer object
    ///
    /// This function creates a DMA-BUF (also known as PRIME) file descriptor
    /// handle for the buffer object.  Each call to [`Self::fd()`] returns a new
    /// file descriptor and the caller is responsible for closing the file
    /// descriptor.
    pub fn fd(&self) -> Result<RawFd, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_fd(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the handle of the buffer object
    ///
    /// This is stored in the platform generic union [`BufferObjectHandle`] type.  However
    /// the format of this handle is platform specific.
    pub fn handle(&self) -> Result<BufferObjectHandle, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_handle(*self.ffi) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Get the handle of a plane of the buffer object
    ///
    /// This is stored in the platform generic union [`BufferObjectHandle`] type.  However
    /// the format of this handle is platform specific.
    pub fn handle_for_plane(&self, plane: i32) -> Result<BufferObjectHandle, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            Ok(unsafe { ::ffi::gbm_bo_get_handle_for_plane(*self.ffi, plane) })
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Map a region of a GBM buffer object for cpu access
    ///
    /// This function maps a region of a GBM bo for cpu read access.
    pub fn map<'a, D, F, S>(
        &'a self,
        device: &Device<D>,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        f: F,
    ) -> Result<IoResult<S>, WrongDeviceError>
    where
        D: AsRawFd + 'static,
        F: FnOnce(&MappedBufferObject<'a, T>) -> S,
    {
        let device_ref = self._device.upgrade();
        if let Some(_device) = device_ref {
            if *_device != device.as_raw_mut() {
                // not matching
                return Err(WrongDeviceError);
            }
        } else {
            // not matching
            return Err(WrongDeviceError);
        }

        unsafe {
            let mut data: *mut ::libc::c_void = ptr::null_mut();
            let mut stride = 0;
            let ptr = ::ffi::gbm_bo_map(
                *self.ffi,
                x,
                y,
                width,
                height,
                ::ffi::gbm_bo_transfer_flags::GBM_BO_TRANSFER_READ as u32,
                &mut stride as *mut _,
                &mut data as *mut _,
            );

            if ptr.is_null() {
                Ok(Err(IoError::last_os_error()))
            } else {
                Ok(Ok(f(&MappedBufferObject {
                    bo: BORef::Ref(self),
                    buffer: slice::from_raw_parts_mut(ptr as *mut _, (height * stride) as usize),
                    data,
                    stride,
                    height,
                    width,
                    x,
                    y,
                })))
            }
        }
    }

    /// Map a region of a GBM buffer object for cpu access
    ///
    /// This function maps a region of a GBM bo for cpu read/write access.
    pub fn map_mut<'a, D, F, S>(
        &'a mut self,
        device: &Device<D>,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        f: F,
    ) -> Result<IoResult<S>, WrongDeviceError>
    where
        D: AsRawFd + 'static,
        F: FnOnce(&mut MappedBufferObject<'a, T>) -> S,
    {
        let device_ref = self._device.upgrade();
        if let Some(_device) = device_ref {
            if *_device != device.as_raw_mut() {
                // not matching
                return Err(WrongDeviceError);
            }
        } else {
            // not matching
            return Err(WrongDeviceError);
        }

        unsafe {
            let mut data: *mut ::libc::c_void = ptr::null_mut();
            let mut stride = 0;
            let ptr = ::ffi::gbm_bo_map(
                *self.ffi,
                x,
                y,
                width,
                height,
                ::ffi::gbm_bo_transfer_flags::GBM_BO_TRANSFER_READ_WRITE as u32,
                &mut stride as *mut _,
                &mut data as *mut _,
            );

            if ptr.is_null() {
                Ok(Err(IoError::last_os_error()))
            } else {
                Ok(Ok(f(&mut MappedBufferObject {
                    bo: BORef::Mut(self),
                    buffer: slice::from_raw_parts_mut(ptr as *mut _, (height * stride) as usize),
                    data,
                    stride,
                    height,
                    width,
                    x,
                    y,
                })))
            }
        }
    }

    ///  Write data into the buffer object
    ///
    /// If the buffer object was created with the [`BufferObjectFlags::WRITE`] flag,
    /// this function can be used to write data into the buffer object.  The
    /// data is copied directly into the object and it's the responsibility
    /// of the caller to make sure the data represents valid pixel data,
    /// according to the width, height, stride and format of the buffer object.
    pub fn write(&mut self, buffer: &[u8]) -> Result<IoResult<()>, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let result = unsafe {
                ::ffi::gbm_bo_write(*self.ffi, buffer.as_ptr() as *const _, buffer.len() as _)
            };
            if result != 0 {
                Ok(Err(IoError::last_os_error()))
            } else {
                Ok(Ok(()))
            }
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Sets the userdata of the buffer object.
    ///
    /// If previously userdata was set, it is returned.
    pub fn set_userdata(&mut self, userdata: T) -> Result<Option<T>, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let old = self.take_userdata();

            let boxed = Box::new(userdata);
            unsafe {
                ::ffi::gbm_bo_set_user_data(
                    *self.ffi,
                    Box::into_raw(boxed) as *mut _,
                    Some(destroy::<T>),
                );
            }

            old
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Clears the set userdata of the buffer object.
    pub fn clear_userdata(&mut self) -> Result<(), DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let _ = self.take_userdata();
            Ok(())
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Returns a reference to set userdata, if any.
    pub fn userdata(&self) -> Result<Option<&T>, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let raw = unsafe { ::ffi::gbm_bo_get_user_data(*self.ffi) };

            if raw.is_null() {
                Ok(None)
            } else {
                unsafe { Ok(Some(&*(raw as *mut T))) }
            }
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Returns a mutable reference to set userdata, if any.
    pub fn userdata_mut(&mut self) -> Result<Option<&mut T>, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let raw = unsafe { ::ffi::gbm_bo_get_user_data(*self.ffi) };

            if raw.is_null() {
                Ok(None)
            } else {
                unsafe { Ok(Some(&mut *(raw as *mut T))) }
            }
        } else {
            Err(DeviceDestroyedError)
        }
    }

    /// Takes ownership of previously set userdata, if any.
    ///
    /// This removes the userdata from the buffer object.
    pub fn take_userdata(&mut self) -> Result<Option<T>, DeviceDestroyedError> {
        let device = self._device.upgrade();
        if device.is_some() {
            let raw = unsafe { ::ffi::gbm_bo_get_user_data(*self.ffi) };

            if raw.is_null() {
                Ok(None)
            } else {
                unsafe {
                    let boxed = Box::from_raw(raw as *mut T);
                    ::ffi::gbm_bo_set_user_data(*self.ffi, ptr::null_mut(), None);
                    Ok(Some(*boxed))
                }
            }
        } else {
            Err(DeviceDestroyedError)
        }
    }

    pub(crate) unsafe fn new(
        ffi: *mut ::ffi::gbm_bo,
        device: WeakPtr<::ffi::gbm_device>,
    ) -> BufferObject<T> {
        BufferObject {
            ffi: Ptr::<::ffi::gbm_bo>::new(ffi, |ptr| ::ffi::gbm_bo_destroy(ptr)),
            _device: device,
            _userdata: PhantomData,
        }
    }
}

impl<T: 'static> AsRawFd for BufferObject<T> {
    fn as_raw_fd(&self) -> RawFd {
        unsafe { ::ffi::gbm_bo_get_fd(*self.ffi) }
    }
}

impl<T: 'static> AsRaw<::ffi::gbm_bo> for BufferObject<T> {
    fn as_raw(&self) -> *const ::ffi::gbm_bo {
        *self.ffi
    }
}

#[cfg(feature = "drm-support")]
impl<T: 'static> DrmBuffer for BufferObject<T> {
    fn size(&self) -> (u32, u32) {
        (
            self.width().expect("GbmDevice does not exist anymore"),
            self.height().expect("GbmDevice does not exist anymore"),
        )
    }

    fn format(&self) -> Format {
        BufferObject::<T>::format(self).expect("GbmDevice does not exist anymore")
    }

    fn pitch(&self) -> u32 {
        self.stride().expect("GbmDevice does not exist anymore")
    }

    fn handle(&self) -> Handle {
        use std::num::NonZeroU32;
        unsafe {
            Handle::from(NonZeroU32::new_unchecked(
                self.handle()
                    .expect("GbmDevice does not exist anymore")
                    .u32_,
            ))
        }
    }
}

#[cfg(feature = "drm-support")]
impl<T: 'static> DrmPlanarBuffer for BufferObject<T> {
    fn size(&self) -> (u32, u32) {
        (
            self.width().expect("GbmDevice does not exist anymore"),
            self.height().expect("GbmDevice does not exist anymore"),
        )
    }
    fn format(&self) -> Format {
        BufferObject::<T>::format(self).expect("GbmDevice does not exist anymore")
    }
    fn pitches(&self) -> [u32; 4] {
        let num = self
            .plane_count()
            .expect("GbmDevice does not exist anymore");
        [
            BufferObject::<T>::stride_for_plane(self, 0).unwrap(),
            if num > 1 {
                BufferObject::<T>::stride_for_plane(self, 1).unwrap()
            } else {
                0
            },
            if num > 2 {
                BufferObject::<T>::stride_for_plane(self, 2).unwrap()
            } else {
                0
            },
            if num > 3 {
                BufferObject::<T>::stride_for_plane(self, 3).unwrap()
            } else {
                0
            },
        ]
    }
    fn handles(&self) -> [Option<Handle>; 4] {
        use std::num::NonZeroU32;
        let num = self
            .plane_count()
            .expect("GbmDevice does not exist anymore");
        [
            Some(unsafe {
                Handle::from(NonZeroU32::new_unchecked(
                    BufferObject::<T>::handle_for_plane(self, 0).unwrap().u32_,
                ))
            }),
            if num > 1 {
                Some(unsafe {
                    Handle::from(NonZeroU32::new_unchecked(
                        BufferObject::<T>::handle_for_plane(self, 1).unwrap().u32_,
                    ))
                })
            } else {
                None
            },
            if num > 2 {
                Some(unsafe {
                    Handle::from(NonZeroU32::new_unchecked(
                        BufferObject::<T>::handle_for_plane(self, 2).unwrap().u32_,
                    ))
                })
            } else {
                None
            },
            if num > 3 {
                Some(unsafe {
                    Handle::from(NonZeroU32::new_unchecked(
                        BufferObject::<T>::handle_for_plane(self, 3).unwrap().u32_,
                    ))
                })
            } else {
                None
            },
        ]
    }
    fn offsets(&self) -> [u32; 4] {
        let num = self
            .plane_count()
            .expect("GbmDevice does not exist anymore");
        [
            BufferObject::<T>::offset(self, 0).unwrap(),
            if num > 1 {
                BufferObject::<T>::offset(self, 1).unwrap()
            } else {
                0
            },
            if num > 2 {
                BufferObject::<T>::offset(self, 2).unwrap()
            } else {
                0
            },
            if num > 3 {
                BufferObject::<T>::offset(self, 3).unwrap()
            } else {
                0
            },
        ]
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Thrown when the GBM device does not belong to the buffer object
pub struct WrongDeviceError;

impl fmt::Display for WrongDeviceError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "The gbm device specified is not the one this buffer object belongs to"
        )
    }
}

impl error::Error for WrongDeviceError {
    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}