waybackend 0.10.1

A simple, low-level wayland client implementation
Documentation
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! This module contains structs for communicating through the wayland file descriptor

use crate::types::{
    NewId, ObjectId, WlFixed, WlSlice, WlStr, i32_slice_to_u8_mut, u32_slice_to_u8,
    u32_slice_to_u8_mut,
};

use core::{mem::MaybeUninit, num::NonZeroU32};
use rustix::fd::{AsFd, AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use rustix::io;

/// according to wayland-util.h, WL_MAX_MESSAGE_SIZE == 4096
const WL_MAX_MESSAGE_SIZE: usize = 4096;
const WL_MAX_MESSAGE_SIZE_U32: usize = WL_MAX_MESSAGE_SIZE / core::mem::size_of::<u32>();

/// We store one of these in `WireReceiver` and another in `WireSender`, for a total of 8.5kb.
/// This is all in the stack, so no allocations are necessary!
type WaylandBuffer = [u32; WL_MAX_MESSAGE_SIZE_U32];

#[derive(Debug)]
pub struct Payload {
    bytes: WaylandBuffer,
    fds: [RawFd; 32],
    cur: u16,
    cur_fd: u8,
}

/// A receiver for receiving wayland messages
#[derive(Debug)]
pub struct Receiver {
    payload: Payload,
}

/// A Wayland protocol message decoder
///
/// This is an iterator that will return `Some(sender_id)` as long as there messages to be decoded.
/// It will return Some(Error) only if the `sender_id` is null. This is a protocol error anyway, so
/// you could just log it.
///
/// To decode a message, you must first know which protocol it refers to. The
/// [ObjectManager](`crate::objman::ObjectManager`) is the one responsible for that. Use it with
/// the returned received `sender_id`.
///
/// Once you know the protocol, you must call `relevant_wayland_procol::ev::(event_handler, &mut msg)`.
#[derive(Debug)]
pub struct Messages<'a> {
    sender_id: ObjectId,
    op: u16,
    bytes_received: u16,
    fds_received: u8,
    payload: &'a mut Payload,
}

impl Payload {
    fn new() -> Self {
        Self {
            bytes: [0; WL_MAX_MESSAGE_SIZE_U32],
            fds: [0; 32],
            cur: 0,
            cur_fd: 0,
        }
    }

    #[inline]
    #[must_use]
    pub fn bytes(&self) -> &[u32] {
        self.bytes.as_slice()
    }

    #[inline]
    #[must_use]
    pub fn fds(&self) -> &[RawFd] {
        self.fds.as_slice()
    }

    #[inline]
    #[must_use]
    /// SAFETY: make sure `self.cur` + offset < `self.bytes.len()`
    unsafe fn get_cur_byte_offset(&self, offset: isize) -> u32 {
        let i = (self.cur as isize + offset) as usize;
        unsafe { *self.bytes.get_unchecked(i) }
    }

    #[inline]
    #[must_use]
    /// SAFETY: make sure `self.cur_fd` is < 32
    unsafe fn get_cur_fd(&self) -> i32 {
        unsafe { *self.fds.get_unchecked(self.cur_fd as usize) }
    }
}

impl Receiver {
    #[inline]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            payload: Payload::new(),
        }
    }

    /// Receive wayland messages, in a **blocking** manner.
    ///
    /// This will fill up the buffer with as many wayland messages as it can.
    /// Returns a [Messages] struct that can decode the received wayland messages.
    #[inline]
    pub fn recv<'a>(
        &'a mut self,
        wayland_fd: &impl rustix::fd::AsFd,
    ) -> Result<Messages<'a>, Error> {
        use rustix::net;

        let mut ancillary_buf = [MaybeUninit::uninit(); 32];
        let iov = io::IoSliceMut::new(u32_slice_to_u8_mut(
            &mut self.payload.bytes[self.payload.cur as usize..],
        ));
        let mut control = net::RecvAncillaryBuffer::new(i32_slice_to_u8_mut(&mut ancillary_buf));
        let bytes = net::recvmsg(
            wayland_fd,
            &mut [iov],
            &mut control,
            net::RecvFlags::empty(),
        )
        .map_err(Error::RustixIoErrno)?;
        let mut fd_index = 0;
        for msg in control.drain() {
            if let net::RecvAncillaryMessage::ScmRights(iter) = msg {
                let i = self.payload.cur_fd as usize;
                for fd in iter {
                    // SAFETY: we know self.payload.fds has size 32, and the ancillary_buf also has
                    // size 32, so this can never panic
                    *unsafe { self.payload.fds.get_unchecked_mut(i + fd_index) } = fd.into_raw_fd();
                    fd_index += 1;
                }
            }
        }

        let bytes_received = self.payload.cur + (bytes.bytes / core::mem::size_of::<u32>()) as u16;
        let fds_received = self.payload.cur_fd + fd_index as u8;

        self.payload.cur = 0;
        self.payload.cur_fd = 0;

        Ok(Messages {
            sender_id: ObjectId::new(NonZeroU32::new(1).unwrap()),
            op: 0,
            bytes_received,
            fds_received,
            payload: &mut self.payload,
        })
    }

    #[inline]
    #[must_use]
    pub fn payload(&self) -> &Payload {
        &self.payload
    }
}

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

impl Iterator for Messages<'_> {
    type Item = Result<ObjectId, Error>;

    /// This will panic if we receive a wayland message larger the the WL_MAX_MESSAGE_SIZE.
    /// I do not believe there is any other reasonable course of action, as it implies our wayland
    /// connection is operating on fundamentally different assumptions, and things will be very
    /// unreliable.
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.payload.cur + 1 >= self.bytes_received {
            return None;
        }
        // SAFETY: we just checked above that this is safe
        let byte = unsafe { self.payload.get_cur_byte_offset(1) };
        let len = byte >> 16;

        assert!(
            len <= WL_MAX_MESSAGE_SIZE as u32,
            "Received wayland message is too large: {len}. WL_MAX_MESSAGE_SIZE is {WL_MAX_MESSAGE_SIZE}"
        );

        // Note: if we pass through here, it means can decode the full message. This is what allows
        // us to use unsafe code when decoding the messages
        if self.payload.cur + len as u16 / 4 > self.bytes_received {
            return None;
        }

        // SAFETY: if we can read position cur + 1, we can read position cur
        match ObjectId::try_new(unsafe { self.payload.get_cur_byte_offset(0) }) {
            Ok(sender_id) => {
                self.sender_id = sender_id;
                self.op = (byte & 0xFFFF) as u16;
                self.payload.cur += 2;
                Some(Ok(sender_id))
            }
            Err(_) => Some(Err(Error::NullObjectId)),
        }
    }
}

/// NOTE: in the implementations below, we use get_unchecked to bypass the array checking. This is
/// because, in a wayland application, this will run many, many times, and the extra time adds up.
///
/// Instead, the [validate_len](Messages::validate_len) function should be called once, to do all
/// the array checking ahead of time, once. Note it needn't be called when the message has no
/// arrays or strings, since then the simple validation we did when we called [Messages::next]
/// should suffice.
impl Messages<'_> {
    /// This function verifies that the full message can be decoded with the number of bytes we have
    /// received. It only needs to be called if the message contains strings or arrays, as
    /// otherwise the [Messages::next] function will suffice for verification.
    ///
    /// # Parameters
    ///
    ///   * `array_types`: `false` if the type is a scalar, `true` otherwise
    ///
    /// # Implementation Notes
    ///
    /// This is implemented with a constant parameter because it allows for some extra
    /// optimizations. In particular, by unrolling the loop the compiler can bypass the `if`
    /// branches, and merge multiple `sum += 1;` statements into one.
    #[inline]
    #[doc(hidden)]
    pub fn validate_len<const N: usize>(&self, is_array_type: [bool; N]) -> Result<(), Error> {
        let mut sum = 0;
        let mut i = 0;
        while i < is_array_type.len() {
            if !is_array_type[i] {
                sum += 1;
            } else {
                let len = unsafe { self.payload.get_cur_byte_offset(sum as isize) as usize };
                sum += 1 + ((len + 3) >> 2);

                if sum + is_array_type.len() - i > self.bytes_received as usize {
                    return Err(Error::InvalidArrayOrStringLength);
                }
            }
            i += 1;
        }

        Ok(())
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_fd(&mut self) -> OwnedFd {
        let fd = unsafe { self.payload.get_cur_fd() };
        self.payload.cur_fd += 1;
        // SAFETY: we only create this once, because self.payload.cur_fd is always increasing
        // Therefore, it was never closed before this call
        unsafe { OwnedFd::from_raw_fd(fd) }
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn sender_id(&self) -> ObjectId {
        self.sender_id
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn op(&self) -> u16 {
        self.op
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_i32(&mut self) -> i32 {
        self.next_u32() as i32
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_u32(&mut self) -> u32 {
        self.payload.cur += 1;
        unsafe { self.payload.get_cur_byte_offset(-1) }
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_fixed(&mut self) -> WlFixed {
        WlFixed(self.next_i32())
    }

    #[inline]
    #[doc(hidden)]
    pub fn next_string<'a>(&mut self) -> Result<&'a str, Error> {
        let len = unsafe { self.payload.get_cur_byte_offset(0) as usize };

        unsafe {
            // remember to skip the length
            let ptr = self
                .payload
                .bytes()
                .as_ptr()
                .add(self.payload.cur as usize + 1);

            // the len sent by the protocol includes the '0', but we do not need it
            let cast = core::slice::from_raw_parts(ptr.cast(), len - 1);
            self.payload.cur += 1 + ((len + 3) >> 2) as u16;
            core::str::from_utf8(cast).map_err(Error::InvalidUTF8FromWire)
        }
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_object(&mut self) -> Option<ObjectId> {
        ObjectId::try_new(self.next_u32()).ok()
    }

    #[inline]
    #[doc(hidden)]
    pub fn next_new_specified_id(&mut self) -> Result<ObjectId, Error> {
        ObjectId::try_new(self.next_u32())
    }

    #[inline]
    #[doc(hidden)]
    pub fn next_new_unspecified_id<'a>(&mut self) -> Result<NewId<'a>, Error> {
        let interface = self.next_string()?;
        let version = self.next_u32();
        let id = self.next_new_specified_id()?;

        Ok(NewId {
            id,
            interface,
            version,
        })
    }

    #[inline]
    #[must_use]
    #[doc(hidden)]
    pub fn next_array<'a>(&mut self) -> &'a [u8] {
        let len = unsafe { self.payload.get_cur_byte_offset(0) as usize };

        unsafe {
            let ptr = self
                .payload
                .bytes()
                .as_ptr()
                .add(self.payload.cur as usize + 1); // skip the length
            self.payload.cur += 1 + ((len + 3) >> 2) as u16;
            core::slice::from_raw_parts(ptr.cast(), len)
        }
    }
}

impl Drop for Messages<'_> {
    fn drop(&mut self) {
        let remaining_byte_len = (self.bytes_received).saturating_sub(self.payload.cur);
        let remaining_fds_len = (self.fds_received).saturating_sub(self.payload.cur_fd);

        unsafe {
            let (lo, hi) = self
                .payload
                .bytes
                .split_at_mut_unchecked(self.payload.cur as usize);
            lo.as_mut_ptr()
                .copy_from(hi.as_ptr(), remaining_byte_len as usize)
        }
        unsafe {
            let (lo, hi) = self
                .payload
                .fds
                .split_at_mut_unchecked(self.payload.cur_fd as usize);
            lo.as_mut_ptr()
                .copy_from(hi.as_ptr(), remaining_fds_len as usize)
        }

        self.payload.cur = remaining_byte_len;
        self.payload.cur_fd = remaining_fds_len;
    }
}

pub struct MessageBuilder {
    msg: WaylandBuffer,
    fds: [RawFd; 32],
    msg_len: u16,
    fds_len: u8,
}

impl MessageBuilder {
    #[inline]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            msg: [0; WL_MAX_MESSAGE_SIZE_U32],
            fds: [0; 32],
            msg_len: 0,
            fds_len: 0,
        }
    }

    /// Ensures we have enough space left in the buffer to encode the full message, by flushing the
    /// buffer if necessary
    ///
    /// **Note `byte_size` is in groups of 4 bytes**.
    ///
    /// # Errors
    ///
    /// We return EOVERFLOW if the message size is too large for the wayland connection
    #[inline]
    #[doc(hidden)]
    pub fn ensure_space<Fd: AsFd>(
        &mut self,
        wayland_fd: &Fd,
        byte_size: usize,
        fds: usize,
    ) -> io::Result<()> {
        if byte_size > WL_MAX_MESSAGE_SIZE_U32 || fds > self.fds.len() {
            return Err(io::Errno::OVERFLOW);
        }

        if byte_size + self.msg_len as usize >= self.msg.len()
            || fds + self.fds_len as usize >= self.fds.len()
        {
            self.flush(wayland_fd)?;
        }

        Ok(())
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_header(&mut self, sender_id: ObjectId, op: u16, len: u16) {
        unsafe {
            self.add_u32(sender_id.get().get());
            self.add_u32((op as u32) | ((len as u32) << 16));
        }
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_i32(&mut self, i: i32) {
        unsafe { self.add_u32(i as u32) };
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_u32(&mut self, u: u32) {
        *unsafe { self.msg.get_unchecked_mut(self.msg_len as usize) } = u;
        self.msg_len += 1;
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_fixed(&mut self, fixed: WlFixed) {
        unsafe { self.add_i32(fixed.0) };
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_string(&mut self, s: &str) {
        let str = WlStr(s);
        let bytes = str.encode(unsafe { self.msg.get_unchecked_mut(self.msg_len as usize..) });
        self.msg_len += (bytes >> 2) as u16;
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_object(&mut self, object_id: Option<ObjectId>) {
        unsafe {
            match object_id {
                Some(id) => self.add_u32(id.get().get()),
                None => self.add_u32(0),
            }
        }
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_new_specified_id(&mut self, object_id: ObjectId) {
        unsafe { self.add_u32(object_id.get().get()) };
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_new_unspecified_id(
        &mut self,
        object_id: ObjectId,
        interface: &str,
        version: u32,
    ) {
        unsafe {
            self.add_string(interface);
            self.add_u32(version);
            self.add_new_specified_id(object_id);
        }
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_array(&mut self, array: &[u8]) {
        let slice = WlSlice(array);
        let bytes = slice.encode(unsafe { self.msg.get_unchecked_mut(self.msg_len as usize..) });
        self.msg_len += (bytes >> 2) as u16;
    }

    /// # Safety
    ///
    /// This is safe to call if you called [ensure_space](Self::ensure_space) with the correct size
    /// before calling this function
    #[inline]
    #[doc(hidden)]
    pub unsafe fn add_fd<'a, 'b>(&'a mut self, fd: &'b impl AsRawFd) -> io::Result<()>
    where
        'b: 'a,
    {
        *unsafe { self.fds.get_unchecked_mut(self.fds_len as usize) } = fd.as_raw_fd();
        self.fds_len += 1;
        Ok(())
    }

    #[doc(hidden)]
    pub fn flush<Fd: rustix::fd::AsFd>(&mut self, wayland_fd: &Fd) -> io::Result<()> {
        use rustix::net;
        const FLAGS: net::SendFlags = net::SendFlags::NOSIGNAL;
        let Self {
            msg,
            fds,
            msg_len,
            fds_len,
        } = self;

        let msg_slice = u32_slice_to_u8(unsafe { msg.get_unchecked(0..*msg_len as usize) });
        if *fds_len == 0 {
            net::send(wayland_fd, msg_slice, FLAGS)?;
        } else {
            let iov = io::IoSlice::new(msg_slice);
            let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(32))];
            let mut control = net::SendAncillaryBuffer::new(&mut space);
            control.push(net::SendAncillaryMessage::ScmRights(unsafe {
                core::mem::transmute::<&[i32], &[rustix::fd::BorrowedFd<'_>]>(
                    fds.get_unchecked(..*fds_len as usize),
                )
            }));
            net::sendmsg(wayland_fd, &[iov], &mut control, FLAGS)?;
        }

        *msg_len = 0;
        *fds_len = 0;

        Ok(())
    }
}

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

#[derive(Debug)]
pub enum Error {
    UnrecognizedEventOpCode(&'static str, u16),
    InvalidEnumDiscriminant(&'static str, u32),
    RustixIoErrno(io::Errno),
    InvalidUTF8FromWire(core::str::Utf8Error),
    InvalidArrayOrStringLength,
    NullObjectId,
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            Error::UnrecognizedEventOpCode(event, opcode) => {
                write!(f, "unrecognized opcode {opcode} for event {event}")
            }
            Error::InvalidEnumDiscriminant(enum_name, number) => {
                write!(f, "invalid discriminant {number} for enum {enum_name}")
            }
            Error::RustixIoErrno(errno) => core::fmt::Display::fmt(errno, f),
            Error::InvalidUTF8FromWire(utf8_error) => write!(
                f,
                "received invalid utf8 string from the wire: {utf8_error}"
            ),
            Error::NullObjectId => f.write_str("received unexpected null ObjectId"),
            Error::InvalidArrayOrStringLength => f.write_str(
                "received an array or string from the\
                wayland protocol larger than the message length itself",
            ),
        }
    }
}

impl core::error::Error for Error {}

#[cfg(test)]
mod tests {
    extern crate std;
    use core::{ffi::c_int, mem::ManuallyDrop, num::NonZeroU32};
    use std::{path::Path, string::ToString};

    use tempdir::TempDir;

    use super::*;

    /// This is a dummy, **INVALID** file descriptor. We just use it make testing easier. It will
    /// cause an error if it is ever written to
    const DUMMY_FD: ManuallyDrop<OwnedFd> =
        unsafe { ManuallyDrop::new(std::mem::transmute::<i32, OwnedFd>(c_int::MAX)) };

    const DUMMY_OBJ: ObjectId = ObjectId::new(NonZeroU32::new(1).unwrap());

    fn bind_dummy_wayland_socket<P: AsRef<Path>>(tmp_dir: &TempDir, path: P) -> OwnedFd {
        let path = tmp_dir.path().join(path);
        let unix_addr =
            rustix::net::SocketAddrUnix::new(path.display().to_string().as_str()).unwrap();
        let socket = rustix::net::socket_with(
            rustix::net::AddressFamily::UNIX,
            rustix::net::SocketType::STREAM,
            rustix::net::SocketFlags::CLOEXEC,
            None,
        )
        .unwrap();
        rustix::net::bind(&socket, &unix_addr).unwrap();
        rustix::net::listen(&socket, 0).unwrap();
        socket
    }

    fn connect_dummy_wayland_socket<P: AsRef<Path>>(tmp_dir: &TempDir, path: P) -> OwnedFd {
        let path = tmp_dir.path().join(path);
        let stream = std::os::unix::net::UnixStream::connect(path).unwrap();
        stream.set_nonblocking(true).unwrap();
        let fd = std::os::fd::IntoRawFd::into_raw_fd(stream);
        unsafe { OwnedFd::from_raw_fd(fd) }
    }

    #[test]
    fn msg_builder_header() {
        let mut builder = MessageBuilder::new();
        unsafe { builder.add_header(DUMMY_OBJ, 0, 8) };
        assert_eq!(
            &builder.msg[..builder.msg_len as usize],
            &[DUMMY_OBJ.get().get(), 8 << 16]
        );

        unsafe { builder.add_header(DUMMY_OBJ, 1, 8) };
        assert_eq!(
            &builder.msg[..builder.msg_len as usize],
            &[
                DUMMY_OBJ.get().get(),
                8 << 16,
                DUMMY_OBJ.get().get(),
                1 | (8 << 16)
            ]
        );
    }

    #[test]
    fn msg_builder_arrays() {
        let mut builder = MessageBuilder::new();
        unsafe { builder.add_header(DUMMY_OBJ, 1, 8 + 4 * 5 + 4 * 4) };
        unsafe { builder.add_array(&[]) };
        unsafe { builder.add_array(&[1]) };
        unsafe { builder.add_array(&[1, 2]) };
        unsafe { builder.add_array(&[1, 2, 3]) };
        unsafe { builder.add_array(&[1, 2, 3, 4]) };
        assert_eq!(builder.msg_len, (8 + 4 * 5 + 4 * 4) / 4);
        assert_eq!(
            &builder.msg[..builder.msg_len as usize],
            &[
                DUMMY_OBJ.get().get(),
                1 | ((8 + 4 + 8 + 8 + 8 + 8) << 16),
                0, // first array
                1, // second array
                u32::from_ne_bytes([1, 0, 0, 0]),
                2, // third array
                u32::from_ne_bytes([1, 2, 0, 0]),
                3, // fourth array
                u32::from_ne_bytes([1, 2, 3, 0]),
                4, // fifth array
                u32::from_ne_bytes([1, 2, 3, 4]),
            ]
        );
    }

    #[test]
    fn msg_builder_strings() {
        let mut builder = MessageBuilder::new();
        unsafe { builder.add_header(DUMMY_OBJ, 1, 8 + 4 * 5 + 4 * 4 + 8) };
        unsafe { builder.add_string("") };
        unsafe { builder.add_string("1") };
        unsafe { builder.add_string("12") };
        unsafe { builder.add_string("123") };
        unsafe { builder.add_string("1234") };
        assert_eq!(builder.msg_len, (8 + 4 * 5 + 4 * 4 + 8) / 4);
        assert_eq!(
            &builder.msg[..builder.msg_len as usize],
            &[
                DUMMY_OBJ.get().get(),
                1 | ((8 + 8 + 8 + 8 + 8 + 12) << 16),
                1, // first array
                0,
                2, // second array
                u32::from_ne_bytes([b'1', 0, 0, 0]),
                3, // third array
                u32::from_ne_bytes([b'1', b'2', 0, 0]),
                4, // fourth array
                u32::from_ne_bytes([b'1', b'2', b'3', 0]),
                5, // fifth array
                u32::from_ne_bytes([b'1', b'2', b'3', b'4']),
                0,
            ]
        );
    }

    #[test]
    fn msg_builder_scalars() {
        let mut builder = MessageBuilder::new();
        unsafe { builder.add_header(DUMMY_OBJ, 1, 28) };
        unsafe { builder.add_u32(1) };
        unsafe { builder.add_i32(2) };
        unsafe { builder.add_i32(-1) };
        unsafe { builder.add_fixed(WlFixed::from(1i32)) };
        unsafe { builder.add_object(Some(ObjectId::new(10.try_into().unwrap()))) };
        unsafe { builder.add_fd(&*DUMMY_FD).unwrap() };
        assert_eq!(
            &builder.msg[..builder.msg_len as usize],
            &[
                DUMMY_OBJ.get().get(),
                1 | ((8 + 4 + 4 + 4 + 4 + 4) << 16),
                1,
                2,
                -1i32 as u32,
                WlFixed::from(1i32).0 as u32,
                ObjectId::new(10.try_into().unwrap()).get().get()
            ]
        );

        assert_eq!(
            &builder.fds[..builder.fds_len as usize],
            &[DUMMY_FD.as_raw_fd()]
        )
    }

    #[test]
    fn overflowing_msg() {
        let tmpdir = TempDir::new("test_overflowing_msg").unwrap();
        let arr = std::vec![0u8; 4000];
        let receiver_fd = bind_dummy_wayland_socket(&tmpdir, "tmp");

        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            let mut builder = MessageBuilder::new();
            unsafe { builder.add_header(DUMMY_OBJ, 0, 8 + arr.len() as u16 + 4) };
            unsafe { builder.add_array(&arr) };

            unsafe { builder.add_header(DUMMY_OBJ, 1, 8) };

            builder
                .ensure_space(&sender_fd, 2 + 1 + arr.len().div_ceil(4), 0)
                .unwrap();
            unsafe { builder.add_header(DUMMY_OBJ, 0, 8 + arr.len() as u16 + 4) };
            unsafe { builder.add_array(&arr) };
            builder.flush(&sender_fd).unwrap();
        }

        {
            let fd = rustix::net::accept(receiver_fd).unwrap();
            let mut receiver = Receiver::new();
            let end = {
                let mut msg = receiver.recv(&fd).unwrap();
                assert!(msg.next().unwrap().is_ok());
                let expected = &arr;
                let array = msg.next_array();
                assert_eq!(array.len(), expected.len());
                assert_eq!(array, expected);

                assert!(msg.next().unwrap().is_ok());
                assert_eq!(
                    &msg.payload.bytes()[msg.payload.cur as usize - 2..msg.payload.cur as usize],
                    &[DUMMY_OBJ.get().get(), 1 | (8 << 16)]
                );
                assert!(msg.next().is_none());
                msg.payload.cur
            };
            assert_eq!(receiver.payload.cur, WL_MAX_MESSAGE_SIZE_U32 as u16 - end);
            let mut msg = receiver.recv(&fd).unwrap();
            assert!(msg.next().unwrap().is_ok());
            let expected = &arr;
            let array = msg.next_array();
            assert_eq!(array.len(), expected.len());
            assert_eq!(array, expected);
        }
    }

    #[test]
    fn receiving_incomplete_messages() {
        let tmpdir = TempDir::new("test_receiving_incomplete_messages").unwrap();
        let receiver_fd = bind_dummy_wayland_socket(&tmpdir, "tmp");
        let mut receiver = Receiver::new();
        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            rustix::net::send(
                &sender_fd,
                u32_slice_to_u8(&[1, 12 << 16]),
                rustix::net::SendFlags::empty(),
            )
            .unwrap();
        }
        {
            {
                let fd = rustix::net::accept(&receiver_fd).unwrap();
                let mut msg = receiver.recv(&fd).unwrap();
                assert!(msg.next().is_none());
            }
            assert_eq!(receiver.payload.cur_fd, 0);
            assert_eq!(receiver.payload.cur, 2);
        }
        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            rustix::net::send(
                &sender_fd,
                u32_slice_to_u8(&[2]),
                rustix::net::SendFlags::empty(),
            )
            .unwrap();
        }
        {
            let fd = rustix::net::accept(&receiver_fd).unwrap();
            let mut msg = receiver.recv(&fd).unwrap();
            assert!(msg.next().unwrap().is_ok());
            let obj = msg.sender_id();
            let op = msg.op();
            let value = msg.next_u32();
            assert_eq!(obj, ObjectId::new(NonZeroU32::new(1).unwrap()));
            assert_eq!(op, 0);
            assert_eq!(value, 2);
            assert!(msg.next().is_none());
        }
        assert_eq!(receiver.payload.cur_fd, 0);
        assert_eq!(receiver.payload.cur, 0);
    }

    #[test]
    fn receiving_multiple_messages() {
        let tmpdir = TempDir::new("test_receiving_multiple_messages").unwrap();
        let receiver_fd = bind_dummy_wayland_socket(&tmpdir, "tmp");
        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            rustix::net::send(
                &sender_fd,
                u32_slice_to_u8(&[1, 12 << 16, 2, 3, 12 << 16, 4]),
                rustix::net::SendFlags::empty(),
            )
            .unwrap();
        }
        let mut receiver = Receiver::new();
        {
            let fd = rustix::net::accept(&receiver_fd).unwrap();
            let mut msg = receiver.recv(&fd).unwrap();
            assert!(msg.next().unwrap().is_ok());
            let obj = msg.sender_id();
            let op = msg.op();
            let value = msg.next_u32();
            assert_eq!(obj, ObjectId::new(NonZeroU32::new(1).unwrap()));
            assert_eq!(op, 0);
            assert_eq!(value, 2);
            assert!(msg.next().unwrap().is_ok());
            let obj = msg.sender_id();
            let op = msg.op();
            let value = msg.next_u32();
            assert_eq!(obj, ObjectId::new(NonZeroU32::new(3).unwrap()));
            assert_eq!(op, 0);
            assert_eq!(value, 4);
        }
        assert_eq!(receiver.payload.cur_fd, 0);
        assert_eq!(receiver.payload.cur, 0);
    }

    #[test]
    fn receive_invalid_string() {
        let tmpdir = TempDir::new("test_receiving_multiple_messages").unwrap();
        let receiver_fd = bind_dummy_wayland_socket(&tmpdir, "tmp");
        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            rustix::net::send(
                &sender_fd,
                u32_slice_to_u8(&[1, 12 << 16, 5]),
                rustix::net::SendFlags::empty(),
            )
            .unwrap();
        }
        let mut receiver = Receiver::new();
        {
            let fd = rustix::net::accept(&receiver_fd).unwrap();
            let mut msg = receiver.recv(&fd).unwrap();
            assert!(msg.next().unwrap().is_ok());
            let obj = msg.sender_id();
            let op = msg.op();
            // The message is invalid, so this should return an error
            assert!(matches!(
                msg.validate_len([true]),
                Err(Error::InvalidArrayOrStringLength)
            ));
            let value = msg.next_u32();
            assert_eq!(obj, ObjectId::new(NonZeroU32::new(1).unwrap()));
            assert_eq!(op, 0);
            assert_eq!(value, 5);
        }
        assert_eq!(receiver.payload.cur_fd, 0);
        assert_eq!(receiver.payload.cur, 0);
    }

    #[test]
    #[should_panic]
    fn receive_too_large_message() {
        let tmpdir = TempDir::new("test_receiving_multiple_messages").unwrap();
        let receiver_fd = bind_dummy_wayland_socket(&tmpdir, "tmp");
        {
            let sender_fd = connect_dummy_wayland_socket(&tmpdir, "tmp");
            rustix::net::send(
                &sender_fd,
                u32_slice_to_u8(&[1, (WL_MAX_MESSAGE_SIZE as u32 + 1) << 16, 5]),
                rustix::net::SendFlags::empty(),
            )
            .unwrap();
        }
        let mut receiver = Receiver::new();
        let fd = rustix::net::accept(&receiver_fd).unwrap();
        let mut msg = receiver.recv(&fd).unwrap();
        let _ = msg.next();
    }

    #[test]
    #[should_panic]
    fn message_larger_than_the_protocol_maximum() {
        let mut builder = MessageBuilder::new();
        builder
            .ensure_space(&DUMMY_FD.as_fd(), WL_MAX_MESSAGE_SIZE_U32 + 1, 0)
            .unwrap();
    }

    #[test]
    #[should_panic]
    fn more_fds_than_we_can_handle() {
        let mut builder = MessageBuilder::new();
        builder
            .ensure_space(&DUMMY_FD.as_fd(), 12, builder.fds.len() + 1)
            .unwrap();
    }
}