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
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Marshal trait and implementations for the basic types

use crate::params;
use crate::wire::marshal::base::marshal_base_param;
use crate::wire::marshal::MarshalContext;

/// The Marshal trait allows to push any type onto an message_builder::OutMessage as a parameter.
/// There are some useful implementations here for slices and hashmaps which map to arrays and dicts in the dbus message.
///
/// The way dbus structs are represented is with rust tuples. This lib provides Marshal impls for tuples with up to 5 elements.
/// If you need more you can just copy the impl and extend it to how many different entries you need.
///
/// There is a crate (rustbus_derive) for deriving Marshal impls with #[derive(rustbus_derive::Marshal)]. This should work for most of your needs.
/// You can of course derive Signature as well.
///
/// If there are special needs, you can implement Marshal for your own structs:
/// ```rust
/// struct MyStruct {
///     x: u64,
///     y: String,
/// }
///
/// use rustbus::ByteOrder;
/// use rustbus::signature;
/// use rustbus::wire::util;
/// use rustbus::Marshal;
/// use rustbus::wire::marshal::MarshalContext;
/// use rustbus::wire::marshal::traits::SignatureBuffer;
/// use rustbus::Signature;
/// impl Signature for &MyStruct {
///     fn signature() -> signature::Type {
///         signature::Type::Container(signature::Container::Struct(signature::StructTypes::new(vec![
///             u64::signature(),
///             String::signature(),
///         ]).unwrap()))
///     }
///
///     fn alignment() -> usize {
///         8
///     }
///     fn sig_str(s_buf: &mut SignatureBuffer) {
///         s_buf.push_static("(ts)");
///     }
/// }    
/// impl Marshal for &MyStruct {
///     fn marshal(
///         &self,
///         ctx: &mut MarshalContext,
///     ) -> Result<(), rustbus::Error> {
///         // always align to 8 at the start of a struct!
///         ctx.align_to(8);
///         self.x.marshal(ctx)?;
///         self.y.marshal(ctx)?;
///         Ok(())
///     }
/// }
/// ```
/// # Implementing for your own structs
/// There are some rules you need to follow, or the messages will be malformed:
/// 1. Structs need to be aligned to 8 bytes. Use `ctx.align_to(8);` to do that. If your type is marshalled as a primitive type
///     you still need to align to that types alignment.
/// 1. If you write your own dict type, you need to align every key-value pair at 8 bytes like a struct
/// 1. The signature needs to be correct, or the message will be malformed
/// 1. The alignment must report the correct number. This does not need to be a constant like in the example, but it needs to be consistent with the type
///     the signature() function returns. If you are not sure, just use Self::signature().get_alignment().
pub trait Marshal: Signature {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error>;
    fn marshal_as_variant(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        let mut sig = SignatureBuffer::new();
        Self::sig_str(&mut sig);
        if sig.len() > 255 {
            let sig_err = crate::signature::Error::SignatureTooLong;
            return Err(sig_err.into());
        }
        debug_assert!(crate::params::validation::validate_signature(&sig).is_ok());
        crate::wire::util::write_signature(&sig, ctx.buf);
        self.marshal(ctx)
    }
}

/// `SignatureBuffer` is used to store static or dynamic signatures and avoid allocations if possible.
/// It is a wrapper around Cow.
#[derive(Debug)]
pub struct SignatureBuffer(Cow<'static, str>);

impl SignatureBuffer {
    #[inline]
    pub fn new() -> Self {
        Self(Cow::Borrowed(""))
    }
    /// Pushes a `&str` into the signature buffer.
    ///
    /// Avoids an allocation if the `self` was empty and was not allocated already,
    /// by storing the `&'static str` inside a `Cow::Borrowed` variant.
    #[inline]
    pub fn push_static(&mut self, sig: &'static str) {
        match &mut self.0 {
            Cow::Borrowed("") => self.0 = Cow::Borrowed(sig),
            Cow::Owned(s) if s.capacity() == 0 => self.0 = Cow::Borrowed(sig),
            cow => cow.to_mut().push_str(sig),
        }
    }

    /// Pushes a `&str` into the signature buffer.
    ///
    /// If `sig` has a `'static` lifetime then [`SignatureBuffer::push_static`] should almost always be used
    /// instead of this, because it can provide a performance benefit by avoiding allocation.
    #[inline]
    pub fn push_str(&mut self, sig: &str) {
        self.0.to_mut().push_str(sig);
    }

    /// Return a `&mut String` which can be used to modify the signature.
    ///
    /// Internally this is just a call to `Cow::to_mut`.
    #[inline]
    pub fn to_string_mut(&mut self) -> &mut String {
        self.0.to_mut()
    }

    /// Clear the signature.
    ///
    /// If an allocation was already made it is retained for future use.
    /// If you wish to deallocate when clearing, then simply use [`SignatureBuffer::new`].
    #[inline]
    pub fn clear(&mut self) {
        match &mut self.0 {
            Cow::Borrowed(_) => *self = Self::new(),
            Cow::Owned(s) => s.clear(),
        }
    }
    #[inline]
    pub fn from_string(sig: String) -> Self {
        Self(Cow::Owned(sig))
    }
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}
impl std::ops::Deref for SignatureBuffer {
    type Target = str;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}
impl AsRef<str> for SignatureBuffer {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}
impl Default for SignatureBuffer {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

use std::borrow::Cow;
pub trait Signature {
    fn signature() -> crate::signature::Type;
    fn alignment() -> usize;
    /// If this returns `true`,
    /// it indicates that for implementing type `T`,
    /// Rust's `[T]` is identical to DBus's array format
    /// and can be copied into a message after aligning the first element.
    ///
    /// The default implementation is `false` but can be overridden for a performance gain
    /// if it is valid.
    ///
    /// # Safety
    /// Calls to this function should always be safe. Implementors should respect this property.
    /// The reason this method is `unsafe` is to indicate to people implementing `Signature` that
    /// overriding it has the potential to induce unsound behavior
    /// if the following rules aren't followed:
    /// 1. The type `T` implementing `Signature` must be `Copy`.
    /// 2. The size of `T` must be **equivalent** to it's DBus alignment (see [here]).
    /// 3. Every possible bit-pattern must represent a valid instance of `T`.
    ///    For example `std::num::NonZeroU32` does not meet this requirement `0` is invalid.
    /// 4. The type should not contain an Fd receieved from the message.
    ///    When implementing `Unmarshal` the type should only dependent the `'buf` lifetime.
    ///    It should never require the use of `'fds`.
    ///
    /// # Notes
    /// * This method exists because of limitiation with Rust type system.
    ///   Should `#[feature(specialization)]` ever become stablized this will hopefully be unnecessary.
    /// * This method should use the `ByteOrder` to check if it matches native order before returning `true`.
    ///   `ByteOrder::NATIVE` can be used to detect the native order.
    ///
    /// [here]: https://dbus.freedesktop.org/doc/dbus-specification.html#idm702
    #[inline]
    unsafe fn valid_slice(_bo: crate::ByteOrder) -> bool {
        false
    }
    /// Appends the signature of the type to the `SignatureBuffer`.
    ///
    /// By using `SignatureBuffer`, implementations of this method can avoid unnecessary allocations
    /// by only allocating if a signature is dynamic.
    ///
    /// The default implementation of `sig_str` can be pretty slow.
    /// If type, that `Signature` is being implemented for, has a static (unchanging) signature
    /// then overriding this method can have a significant performance benefit when marshal/unmarshalling
    /// the type inside variants.
    fn sig_str(s_buf: &mut SignatureBuffer) {
        let s_buf = s_buf.to_string_mut();
        let typ = Self::signature();
        typ.to_str(s_buf);
    }
}

impl<S: Signature> Signature for &S {
    fn signature() -> crate::signature::Type {
        S::signature()
    }
    fn alignment() -> usize {
        S::alignment()
    }
}

impl<P: Marshal> Marshal for &P {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        (*self).marshal(ctx)
    }
}

impl<E: Signature> Signature for (E,) {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Struct(
            crate::signature::StructTypes::new(vec![E::signature()]).unwrap(),
        ))
    }
    fn alignment() -> usize {
        8
    }
}
impl<E: Marshal> Marshal for (E,) {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 8
        ctx.align_to(8);
        self.0.marshal(ctx)?;
        Ok(())
    }
}

impl<E1: Signature, E2: Signature> Signature for (E1, E2) {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Struct(
            crate::signature::StructTypes::new(vec![E1::signature(), E2::signature()]).unwrap(),
        ))
    }
    fn alignment() -> usize {
        8
    }
    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_str("(");
        E1::sig_str(s_buf);
        E2::sig_str(s_buf);
        s_buf.push_str(")");
    }
}
impl<E1: Marshal, E2: Marshal> Marshal for (E1, E2) {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 8
        ctx.align_to(8);
        self.0.marshal(ctx)?;
        self.1.marshal(ctx)?;
        Ok(())
    }
}

impl<E1: Signature, E2: Signature, E3: Signature> Signature for (E1, E2, E3) {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Struct(
            crate::signature::StructTypes::new(vec![
                E1::signature(),
                E2::signature(),
                E3::signature(),
            ])
            .unwrap(),
        ))
    }
    fn alignment() -> usize {
        8
    }

    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_str("(");
        E1::sig_str(s_buf);
        E2::sig_str(s_buf);
        E3::sig_str(s_buf);
        s_buf.push_str(")");
    }
}
impl<E1: Marshal, E2: Marshal, E3: Marshal> Marshal for (E1, E2, E3) {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 8
        ctx.align_to(8);
        self.0.marshal(ctx)?;
        self.1.marshal(ctx)?;
        self.2.marshal(ctx)?;
        Ok(())
    }
}

impl<E1: Signature, E2: Signature, E3: Signature, E4: Signature> Signature for (E1, E2, E3, E4) {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Struct(
            crate::signature::StructTypes::new(vec![
                E1::signature(),
                E2::signature(),
                E3::signature(),
                E4::signature(),
            ])
            .unwrap(),
        ))
    }
    fn alignment() -> usize {
        8
    }
    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_str("(");
        E1::sig_str(s_buf);
        E2::sig_str(s_buf);
        E3::sig_str(s_buf);
        E4::sig_str(s_buf);
        s_buf.push_str(")");
    }
}
impl<E1: Marshal, E2: Marshal, E3: Marshal, E4: Marshal> Marshal for (E1, E2, E3, E4) {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 8
        ctx.align_to(8);
        self.0.marshal(ctx)?;
        self.1.marshal(ctx)?;
        self.2.marshal(ctx)?;
        self.3.marshal(ctx)?;
        Ok(())
    }
}

impl<E1: Signature, E2: Signature, E3: Signature, E4: Signature, E5: Signature> Signature
    for (E1, E2, E3, E4, E5)
{
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Struct(
            crate::signature::StructTypes::new(vec![
                E1::signature(),
                E2::signature(),
                E3::signature(),
                E4::signature(),
                E5::signature(),
            ])
            .unwrap(),
        ))
    }
    fn alignment() -> usize {
        8
    }
    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_str("(");
        E1::sig_str(s_buf);
        E2::sig_str(s_buf);
        E3::sig_str(s_buf);
        E4::sig_str(s_buf);
        E5::sig_str(s_buf);
        s_buf.push_str(")");
    }
}
impl<E1: Marshal, E2: Marshal, E3: Marshal, E4: Marshal, E5: Marshal> Marshal
    for (E1, E2, E3, E4, E5)
{
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 8
        ctx.align_to(8);
        self.0.marshal(ctx)?;
        self.1.marshal(ctx)?;
        self.2.marshal(ctx)?;
        self.3.marshal(ctx)?;
        self.4.marshal(ctx)?;
        Ok(())
    }
}

impl<E: Marshal> Marshal for Vec<E> {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        self.as_slice().marshal(ctx)
    }
}

impl<E: Signature> Signature for [E] {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Array(Box::new(
            E::signature(),
        )))
    }
    #[inline]
    fn alignment() -> usize {
        4
    }
    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_str("a");
        E::sig_str(s_buf);
    }
}
impl<E: Marshal> Marshal for [E] {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        (&self).marshal(ctx)
    }
}

impl<E: Signature> Signature for &[E] {
    #[inline]
    fn signature() -> crate::signature::Type {
        <[E]>::signature()
    }
    #[inline]
    fn alignment() -> usize {
        <[E]>::alignment()
    }
    #[inline]
    fn sig_str(s_buf: &mut SignatureBuffer) {
        <[E]>::sig_str(s_buf)
    }
}
use crate::wire::util::write_u32;
impl<E: Marshal> Marshal for &[E] {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 4
        ctx.align_to(4);
        let alignment = E::alignment();
        unsafe {
            if E::valid_slice(ctx.byteorder) {
                debug_assert_eq!(alignment, std::mem::size_of::<E>());
                let len = alignment * self.len();
                assert!(len <= u32::MAX as usize);
                write_u32(len as u32, ctx.byteorder, ctx.buf);
                ctx.align_to(alignment);
                let ptr = *self as *const [E] as *const u8;
                let slice = std::slice::from_raw_parts(ptr, len);
                ctx.buf.extend_from_slice(slice);
                return Ok(());
            }
        }

        let size_pos = ctx.buf.len();
        ctx.buf.extend_from_slice(&[0; 4]);

        ctx.align_to(alignment);

        if self.is_empty() {
            return Ok(());
        }

        // In an array each entry, except the last  will take up at least its alignment in space.
        // The last may take less (like type '(yy)') but this is small and worth it.
        ctx.buf.reserve(self.len() * alignment);
        let size_before = ctx.buf.len();
        for p in self.iter() {
            p.marshal(ctx)?;
        }
        let size_of_content = ctx.buf.len() - size_before;
        crate::wire::util::insert_u32(
            ctx.byteorder,
            size_of_content as u32,
            &mut ctx.buf[size_pos..size_pos + 4],
        );

        Ok(())
    }
}

/// **_!!! This assumes that you are marshalling to the platforms byteorder !!!_**
///
/// It just memcpy's the content of the array into the message. This is fine for all integer types, but you cannot use it for structs,
/// even if they are copy!
/// They might have padding to be correctly aligned in the slice. I would recommend to only use this for marshalling
/// big integer arrays but I cannot express this in the type system cleanly so here is a comment.
pub struct OptimizedMarshal<'a, E: Copy + Marshal>(pub &'a [E]);
impl<'a, E: Copy + Marshal> Signature for OptimizedMarshal<'a, E> {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Container(crate::signature::Container::Array(Box::new(
            E::signature(),
        )))
    }

    fn alignment() -> usize {
        4
    }
}
impl<'a, E: Copy + Marshal> Marshal for OptimizedMarshal<'a, E> {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 4
        ctx.align_to(4);

        let size_pos = ctx.buf.len();
        ctx.buf.push(0);
        ctx.buf.push(0);
        ctx.buf.push(0);
        ctx.buf.push(0);

        ctx.align_to(E::alignment());

        if self.0.is_empty() {
            return Ok(());
        }

        let size_of_content = std::mem::size_of::<E>() * self.0.len();
        let len_before_resize = ctx.buf.len();
        ctx.buf.resize(ctx.buf.len() + size_of_content, 0);
        unsafe {
            let content_ptr = ctx.buf.as_mut_ptr().add(len_before_resize);
            std::ptr::copy_nonoverlapping(
                self.0.as_ptr() as *const u8,
                content_ptr,
                size_of_content,
            );
        }
        crate::wire::util::insert_u32(
            ctx.byteorder,
            size_of_content as u32,
            &mut ctx.buf[size_pos..size_pos + 4],
        );

        Ok(())
    }
}

#[test]
fn verify_optimized_arrays() {
    use crate::wire::marshal::container::marshal_container_param;
    use crate::ByteOrder;
    let mut fds = Vec::new();
    let mut buf = Vec::new();
    let mut ctx = MarshalContext {
        buf: &mut buf,
        fds: &mut fds,
        byteorder: ByteOrder::LittleEndian,
    };
    let ctx = &mut ctx;

    // marshal array of u64 optimized and non-optimized and compare
    let arru64: Vec<u64> = vec![1, 2, 3, 4, 5, 6, u64::MAX, u64::MAX / 2, u64::MAX / 1024];
    let mut buf_normal = Vec::new();
    ctx.buf = &mut buf_normal;
    arru64.as_slice().marshal(ctx).unwrap();

    let mut buf_optimized = Vec::new();
    ctx.buf = &mut buf_optimized;
    OptimizedMarshal(arru64.as_slice()).marshal(ctx).unwrap();
    assert_eq!(buf_normal, buf_optimized);

    let mut ctx = MarshalContext {
        buf: &mut buf,
        fds: &mut fds,
        byteorder: ByteOrder::LittleEndian,
    };
    let ctx = &mut ctx;

    // marshal array of u8 optimized and non-optimized and compare
    let mut buf_normal = Vec::new();
    ctx.buf = &mut buf_normal;
    let arru8: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 255, 128, 80, 180];
    arru8.as_slice().marshal(ctx).unwrap();

    let mut buf_optimized = Vec::new();
    ctx.buf = &mut buf_optimized;
    OptimizedMarshal(arru8.as_slice()).marshal(ctx).unwrap();
    assert_eq!(buf_normal, buf_optimized);

    let mut ctx = MarshalContext {
        buf: &mut buf,
        fds: &mut fds,
        byteorder: ByteOrder::LittleEndian,
    };
    let ctx = &mut ctx;

    // check that empty arrays work as expected
    let empty: Vec<u8> = Vec::new();
    let x = crate::params::Container::make_array("y", empty.clone().into_iter()).unwrap();

    let mut buf_normal = Vec::new();
    ctx.buf = &mut buf_normal;
    empty.as_slice().marshal(ctx).unwrap();

    let mut buf_optimized = Vec::new();
    ctx.buf = &mut buf_optimized;
    OptimizedMarshal(empty.as_slice()).marshal(ctx).unwrap();

    let mut buf_old = Vec::new();
    ctx.buf = &mut buf_old;
    marshal_container_param(&x, ctx).unwrap();
    assert_eq!(buf_normal, buf_optimized);
    assert_eq!(buf_normal, buf_old);
    assert_eq!(vec![0, 0, 0, 0], buf_old);
}

impl<K: Signature, V: Signature> Signature for std::collections::HashMap<K, V> {
    fn signature() -> crate::signature::Type {
        let ks = K::signature();
        let vs = V::signature();
        if let crate::signature::Type::Base(ks) = ks {
            crate::signature::Type::Container(crate::signature::Container::Dict(ks, Box::new(vs)))
        } else {
            panic!("Ivalid key sig")
        }
    }

    fn alignment() -> usize {
        4
    }
}

impl<K: Marshal, V: Marshal> Marshal for std::collections::HashMap<K, V> {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        // always align to 4
        ctx.align_to(4);

        let size_pos = ctx.buf.len();
        ctx.buf.push(0);
        ctx.buf.push(0);
        ctx.buf.push(0);
        ctx.buf.push(0);

        // always align to 8
        ctx.align_to(8);

        if self.is_empty() {
            return Ok(());
        }

        let size_before = ctx.buf.len();
        for p in self.iter() {
            // always align to 8
            ctx.align_to(8);
            p.0.marshal(ctx)?;
            p.1.marshal(ctx)?;
        }
        let size_of_content = ctx.buf.len() - size_before;
        crate::wire::util::insert_u32(
            ctx.byteorder,
            size_of_content as u32,
            &mut ctx.buf[size_pos..size_pos + 4],
        );

        Ok(())
    }
}

impl Signature for u64 {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Uint64)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("t");
    }
}
impl Marshal for u64 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        let b: params::Base = self.into();
        marshal_base_param(&b, ctx)
    }
}

impl Signature for i64 {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Int64)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("x");
    }
}
impl Marshal for i64 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        let b: params::Base = self.into();
        marshal_base_param(&b, ctx)
    }
}

impl Signature for u32 {
    #[inline]
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Uint32)
    }
    #[inline]
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("u");
    }
}
impl Marshal for u32 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        crate::wire::util::write_u32(*self, ctx.byteorder, ctx.buf);
        Ok(())
    }
}

impl Signature for i32 {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Int32)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("i");
    }
}
impl Marshal for i32 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        crate::wire::util::write_u32(*self as u32, ctx.byteorder, ctx.buf);
        Ok(())
    }
}

impl Signature for u16 {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Uint16)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("q");
    }
}
impl Marshal for u16 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        let b: params::Base = self.into();
        marshal_base_param(&b, ctx)
    }
}

impl Signature for i16 {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Int16)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(bo: crate::ByteOrder) -> bool {
        bo == crate::ByteOrder::NATIVE
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("n");
    }
}
impl Marshal for i16 {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        let b: params::Base = self.into();
        marshal_base_param(&b, ctx)
    }
}

impl Signature for u8 {
    #[inline]
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Byte)
    }
    #[inline]
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    unsafe fn valid_slice(_: crate::ByteOrder) -> bool {
        true
    }
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("y");
    }
}
impl Marshal for u8 {
    #[inline]
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.buf.push(*self);
        Ok(())
    }
}

impl Signature for bool {
    #[inline]
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Boolean)
    }
    #[inline]
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("b");
    }
}
impl Marshal for bool {
    #[inline]
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        (*self as u32).marshal(ctx)
    }
}

impl Signature for String {
    #[inline]
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::String)
    }
    #[inline]
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    fn sig_str(sig: &mut SignatureBuffer) {
        sig.push_static("s");
    }
}
impl Marshal for String {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        self.as_str().marshal(ctx)
    }
}

impl Signature for &str {
    #[inline]
    fn signature() -> crate::signature::Type {
        String::signature()
    }
    #[inline]
    fn alignment() -> usize {
        String::alignment()
    }
    #[inline]
    fn sig_str(sig: &mut SignatureBuffer) {
        String::sig_str(sig);
    }
}
impl Marshal for &str {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        ctx.align_to(Self::alignment());
        crate::wire::util::write_string(self, ctx.byteorder, ctx.buf);
        Ok(())
    }
}

#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
pub struct ObjectPath<S: AsRef<str>>(S);
impl<S: AsRef<str>> ObjectPath<S> {
    pub fn new(path: S) -> Result<Self, crate::params::validation::Error> {
        crate::params::validate_object_path(path.as_ref())?;
        Ok(ObjectPath(path))
    }
    pub fn to_owned(&self) -> ObjectPath<String> {
        ObjectPath(self.as_ref().to_owned())
    }
}
impl<S: AsRef<str>> AsRef<str> for ObjectPath<S> {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}
impl<S: AsRef<str>> Signature for ObjectPath<S> {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::ObjectPath)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
}
impl<S: AsRef<str>> Marshal for ObjectPath<S> {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        self.0.as_ref().marshal(ctx)
    }
}
#[derive(Debug, PartialEq)]
pub struct SignatureWrapper<'a>(&'a str);
impl<'a> SignatureWrapper<'a> {
    pub fn new(sig: &'a str) -> Result<Self, crate::params::validation::Error> {
        crate::params::validate_signature(sig)?;
        Ok(SignatureWrapper(sig))
    }
}
impl<'a> AsRef<str> for SignatureWrapper<'a> {
    fn as_ref(&self) -> &str {
        self.0
    }
}
impl Signature for SignatureWrapper<'_> {
    fn signature() -> crate::signature::Type {
        crate::signature::Type::Base(crate::signature::Base::Signature)
    }
    fn alignment() -> usize {
        Self::signature().get_alignment()
    }
    #[inline]
    fn sig_str(s_buf: &mut SignatureBuffer) {
        s_buf.push_static("g");
    }
}
impl Marshal for SignatureWrapper<'_> {
    fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
        crate::wire::util::write_signature(self.0, ctx.buf);
        Ok(())
    }
}

#[test]
fn test_trait_signature_creation() {
    let mut msg = crate::message_builder::MarshalledMessage::new();
    let body = &mut msg.body;

    body.push_param("a").unwrap();
    body.push_param(ObjectPath::new("/a/b").unwrap()).unwrap();
    body.push_param(SignatureWrapper::new("(a{su})").unwrap())
        .unwrap();

    let fd = crate::wire::UnixFd::new(nix::unistd::dup(1).unwrap());
    body.push_param(&fd).unwrap();
    body.push_param(true).unwrap();
    body.push_param(0u8).unwrap();
    body.push_param(0u16).unwrap();
    body.push_param(0u32).unwrap();
    body.push_param(0u64).unwrap();
    body.push_param(0i16).unwrap();
    body.push_param(0i32).unwrap();
    body.push_param(0i64).unwrap();
    body.push_param(&[0u8][..]).unwrap();

    let map: std::collections::HashMap<String, (u64, u32, u16, u8)> =
        std::collections::HashMap::new();
    body.push_param(&map).unwrap();

    assert_eq!("soghbyqutnixaya{s(tuqy)}", msg.get_sig());
}

#[test]
fn test_empty_array_padding() {
    use crate::wire::marshal::container::marshal_container_param;

    let mut msg = crate::message_builder::MarshalledMessage::new();
    let body = &mut msg.body;
    let empty = vec![0u64; 0];
    body.push_param(&empty[..]).unwrap();

    let empty = crate::params::Container::make_array_with_sig(
        crate::signature::Type::Base(crate::signature::Base::Uint64),
        empty.into_iter(),
    )
    .unwrap();

    let mut fds = Vec::new();
    let mut buf = Vec::new();
    let mut ctx = MarshalContext {
        fds: &mut fds,
        buf: &mut buf,
        byteorder: crate::ByteOrder::LittleEndian,
    };

    marshal_container_param(&empty, &mut ctx).unwrap();

    // 0 length and padded to 8 bytes even if there are no elements
    assert_eq!(msg.get_buf(), &[0, 0, 0, 0, 0, 0, 0, 0]);
    assert_eq!(buf.as_slice(), &[0, 0, 0, 0, 0, 0, 0, 0]);
}

#[test]
fn test_variant_marshalling() {
    let mut msg = crate::message_builder::MarshalledMessage::new();
    let body = &mut msg.body;

    let original = (100u64, "ABCD", true);
    body.push_variant(original).unwrap();

    assert_eq!(
        msg.get_buf(),
        // signature ++ padding ++ u64 ++ string ++ padding ++ boolean
        &[
            5, b'(', b't', b's', b'b', b')', b'\0', 0, 100, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, b'A',
            b'B', b'C', b'D', b'\0', 0, 0, 0, 1, 0, 0, 0
        ]
    )
}