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
//! Implementation of the official tuple layer typecodes
//!
//! The official specification can be found [here](https://github.com/apple/foundationdb/blob/master/design/tuple.md).

mod element;
pub mod hca;
mod pack;
mod subspace;
mod versionstamp;

use std::borrow::Cow;
use std::fmt::{self, Display};
use std::io;
use std::ops::Deref;
use std::result;

#[cfg(feature = "uuid")]
pub use uuid::Uuid;

pub use element::Element;
pub use pack::{TuplePack, TupleUnpack, VersionstampOffset};
pub use subspace::Subspace;
pub use versionstamp::Versionstamp;

const NIL: u8 = 0x00;
const BYTES: u8 = 0x01;
const STRING: u8 = 0x02;
const NESTED: u8 = 0x05;
const NEGINTSTART: u8 = 0x0b;
const INTZERO: u8 = 0x14;
const POSINTEND: u8 = 0x1d;
const FLOAT: u8 = 0x20;
const DOUBLE: u8 = 0x21;
const FALSE: u8 = 0x26;
const TRUE: u8 = 0x27;
#[cfg(feature = "uuid")]
const UUID: u8 = 0x30;
// Not a single official binding is implementing 80 Bit versionstamp...
// const VERSIONSTAMP_88: u8 = 0x32;
const VERSIONSTAMP: u8 = 0x33;

const ESCAPE: u8 = 0xff;

/// Tracks the depth of a Tuple decoding chain
#[derive(Copy, Clone)]
pub struct TupleDepth(usize);

impl TupleDepth {
    fn new() -> Self {
        TupleDepth(0)
    }

    /// Increment the depth by one, this be called when calling into `Tuple::{encode, decode}` of tuple-like datastructures
    pub fn increment(self) -> Self {
        TupleDepth(self.0 + 1)
    }

    /// Returns the current depth in any recursive tuple processing, 0 representing there having been no recursion
    pub fn depth(self) -> usize {
        self.0
    }
}

/// A packing/unpacking error
#[derive(Debug)]
pub enum PackError {
    Message(Box<str>),
    IoError(io::Error),
    TrailingBytes,
    MissingBytes,
    BadStringFormat,
    BadCode {
        found: u8,
        expected: Option<u8>,
    },
    BadPrefix,
    #[cfg(feature = "uuid")]
    BadUuid,
    UnsupportedIntLength,
}

impl From<io::Error> for PackError {
    fn from(err: io::Error) -> Self {
        PackError::IoError(err)
    }
}

impl Display for PackError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PackError::Message(s) => s.fmt(f),
            PackError::IoError(err) => err.fmt(f),
            PackError::TrailingBytes => write!(f, "trailing bytes"),
            PackError::MissingBytes => write!(f, "missing bytes"),
            PackError::BadStringFormat => write!(f, "not an utf8 string"),
            PackError::BadCode { found, .. } => write!(f, "bad code, found {}", found),
            PackError::BadPrefix => write!(f, "bad prefix"),
            #[cfg(feature = "uuid")]
            PackError::BadUuid => write!(f, "bad uuid"),
            PackError::UnsupportedIntLength => write!(f, "integer length was to large"),
        }
    }
}

impl std::error::Error for PackError {}

/// Alias for `Result<..., tuple::Error>`
pub type PackResult<T> = result::Result<T, PackError>;

/// Represent a sequence of bytes (i.e. &[u8])
///
/// This sequence can be either owned or borrowed.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bytes<'a>(pub Cow<'a, [u8]>);

impl<'a> fmt::Debug for Bytes<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<'a> fmt::Display for Bytes<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "b\"")?;
        for &byte in self.0.iter() {
            if byte == b'\\' {
                write!(fmt, r"\\")?;
            } else if byte.is_ascii_alphanumeric() {
                write!(fmt, "{}", byte as char)?;
            } else {
                write!(fmt, "\\x{:02x}", byte)?;
            }
        }
        write!(fmt, "\"")
    }
}

impl<'a> Bytes<'a> {
    pub fn into_owned(self) -> Vec<u8> {
        self.0.into_owned()
    }
}

impl<'a> Deref for Bytes<'a> {
    type Target = [u8];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'a> AsRef<[u8]> for Bytes<'a> {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl<'a> From<&'a [u8]> for Bytes<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self(Cow::Borrowed(bytes))
    }
}
impl From<Vec<u8>> for Bytes<'static> {
    fn from(vec: Vec<u8>) -> Self {
        Self(Cow::Owned(vec))
    }
}

impl<'a> From<&'a str> for Bytes<'a> {
    fn from(s: &'a str) -> Self {
        s.as_bytes().into()
    }
}
impl From<String> for Bytes<'static> {
    fn from(vec: String) -> Self {
        vec.into_bytes().into()
    }
}

/// Pack value and returns the packed buffer
///
/// # Panics
///
/// Panics if the encoded data size doesn't fit in `u32`.
pub fn pack<T: TuplePack>(v: &T) -> Vec<u8> {
    v.pack_to_vec()
}

/// Pack value and returns the packed buffer
///
/// # Panics
///
/// Panics if there is multiple versionstamp present or if the encoded data size doesn't fit in `u32`.
pub fn pack_with_versionstamp<T: TuplePack>(v: &T) -> Vec<u8> {
    v.pack_to_vec_with_versionstamp()
}

/// Pack value into the given buffer
///
/// # Panics
///
/// Panics if the encoded data size doesn't fit in `u32`.
pub fn pack_into<T: TuplePack>(v: &T, output: &mut Vec<u8>) {
    v.pack_into_vec(output)
}

/// Pack value into the given buffer
///
/// # Panics
///
/// Panics if there is multiple versionstamp present or if the encoded data size doesn't fit in `u32`.
pub fn pack_into_with_versionstamp<T: TuplePack>(v: &T, output: &mut Vec<u8>) {
    let offset = v.pack_into_vec_with_versionstamp(output);
    if let VersionstampOffset::MultipleIncomplete = offset {
        panic!("pack_into_with_versionstamp does not allow multiple versionstamps");
    }
}

/// Unpack input
pub fn unpack<'de, T: TupleUnpack<'de>>(input: &'de [u8]) -> PackResult<T> {
    T::unpack_root(input)
}

#[cfg(test)]
mod tests {
    use super::*;

    const NIL_VAL: Option<()> = None;

    fn test_serde<'de, T>(val: T, buf: &'de [u8])
    where
        T: TuplePack + TupleUnpack<'de> + fmt::Debug + PartialEq,
    {
        assert_eq!(Bytes::from(pack(&val)), Bytes::from(buf));
        assert_eq!(unpack::<'de, T>(buf).unwrap(), val);
    }

    #[test]
    fn test_spec() {
        test_serde(NIL_VAL, &[NIL]);
        test_serde((NIL_VAL,), &[NIL]);
        test_serde(((NIL_VAL,),), &[NESTED, NIL, ESCAPE, NIL]);
        // assert_eq!(to_bytes(b"foo\x00bar").unwrap(), b"\x01foo\x00\xffbar\x00");
        test_serde("FÔO\x00bar".to_owned(), b"\x02F\xc3\x94O\x00\xffbar\x00");
        test_serde(
            (("foo\x00bar".to_owned(), NIL_VAL, ()),),
            b"\x05\x02foo\x00\xffbar\x00\x00\xff\x05\x00\x00",
        );
        test_serde(-1, b"\x13\xfe");
        test_serde(-5551212, b"\x11\xabK\x93");
        test_serde(-42f32, b"\x20\x3d\xd7\xff\xff");
    }

    #[test]
    fn test_simple() {
        // bool
        test_serde(false, &[FALSE]);
        test_serde(true, &[TRUE]);

        // int
        test_serde(0i64, &[INTZERO]);
        test_serde(1i64, &[0x15, 1]);
        test_serde(-1i64, &[0x13, 254]);
        test_serde(100i64, &[21, 100]);

        test_serde(10000i32, &[22, 39, 16]);
        test_serde(-100i16, &[19, 155]);
        test_serde(-10000i64, &[18, 216, 239]);
        test_serde(-1000000i64, &[17, 240, 189, 191]);

        // boundary condition
        test_serde(255u16, &[0x15, 255]);
        test_serde(256i32, &[0x16, 1, 0]);
        test_serde(-255i16, &[0x13, 0]);
        test_serde(-256i64, &[0x12, 254, 255]);

        // versionstamp
        test_serde(
            Versionstamp::complete(b"\xaa\xbb\xcc\xdd\xee\xff\x00\x01\x02\x03".clone(), 0),
            b"\x33\xaa\xbb\xcc\xdd\xee\xff\x00\x01\x02\x03\x00\x00",
        );
        test_serde(
            Versionstamp::complete(b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a".clone(), 657),
            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
        );

        test_serde(0, b"\x14");
        test_serde(1, b"\x15\x01");
        test_serde(-1, b"\x13\xfe");
        test_serde(255, b"\x15\xff");
        test_serde(-255, b"\x13\x00");
        test_serde(256, b"\x16\x01\x00");
        test_serde(-256, b"\x12\xfe\xff");
        test_serde(65536, b"\x17\x01\x00\x00");
        test_serde(-65536, b"\x11\xfe\xff\xff");
        test_serde(i64::max_value(), b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff");
        test_serde(
            i64::max_value() as u64 + 1,
            b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(u64::max_value(), b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff");
        test_serde(
            u128::max_value(),
            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            u64::max_value() as u128 + 1,
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            u64::max_value() as i128 + 1,
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            i64::min_value() as i128 + 1,
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            i64::min_value() as i128 - 1,
            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(
            -(u64::max_value() as i128),
            b"\x0C\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            -(u64::max_value() as i128) - 1,
            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            -(u64::max_value() as i128) - 2,
            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(
            (u64::max_value() as i128) * -2,
            b"\x0b\xf6\xfe\x00\x00\x00\x00\x00\x00\x00\x01",
        );
        test_serde(
            (u64::max_value() as i128) * 2,
            b"\x1d\x09\x01\xff\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(-4294967295i64, b"\x10\x00\x00\x00\x00");
        test_serde(
            i64::min_value() + 2,
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x01",
        );
        test_serde(
            i64::min_value() + 1,
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(i64::min_value(), b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xff");

        test_serde(9252427359321063944i128, b"\x1c\x80g9\xa9np\x02\x08");
        assert!(
            match unpack::<i64>(b"\x1c\x80g9\xa9np\x02\x08").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );

        test_serde(
            -9252427359321063944i128,
            b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7",
        );
        assert!(
            match unpack::<i64>(b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );

        test_serde(
            u64::max_value() as i128,
            b"\x1c\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        assert!(
            match unpack::<i64>(b"\x1c\xff\xff\xff\xff\xff\xff\xff\xff").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );

        test_serde(
            -(u64::max_value() as i128),
            b"\x0c\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        assert!(
            match unpack::<i64>(b"\x0c\x00\x00\x00\x00\x00\x00\x00\x00").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );

        test_serde(
            (i64::max_value() as i128) + 1,
            b"\x1c\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        assert!(
            match unpack::<i64>(b"\x1c\x80\x00\x00\x00\x00\x00\x00\x00").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );

        test_serde(
            (i64::min_value() as i128) - 1,
            b"\x0c\x7f\xff\xff\xff\xff\xff\xff\xfe",
        );
        assert!(
            match unpack::<i64>(b"\x0c\x7f\xff\xff\xff\xff\xff\xff\xfe").unwrap_err() {
                PackError::UnsupportedIntLength => true,
                _ => false,
            }
        );
    }

    #[cfg(feature = "num-bigint")]
    #[test]
    fn test_bigint() {
        use num_bigint::{BigInt, BigUint};
        // int
        test_serde(BigInt::from(0i64), &[INTZERO]);
        test_serde(BigUint::from(0u64), &[INTZERO]);
        test_serde(BigInt::from(1i64), &[0x15, 1]);
        test_serde(BigUint::from(1u64), &[0x15, 1]);
        test_serde(BigInt::from(-1i64), &[0x13, 254]);
        test_serde(BigInt::from(100i64), &[0x15, 100]);
        test_serde(BigUint::from(100u64), &[0x15, 100]);

        test_serde(BigInt::from(10000i32), &[0x16, 39, 16]);
        test_serde(BigUint::from(10000u32), &[0x16, 39, 16]);
        test_serde(BigInt::from(-100i16), &[19, 155]);
        test_serde(BigInt::from(-10000i64), &[18, 216, 239]);
        test_serde(BigInt::from(-1000000i64), &[17, 240, 189, 191]);

        // boundary condition
        test_serde(BigInt::from(255u16), &[0x15, 255]);
        test_serde(BigUint::from(255u16), &[0x15, 255]);
        test_serde(BigInt::from(256i32), &[0x16, 1, 0]);
        test_serde(BigInt::from(-255i16), &[0x13, 0]);
        test_serde(BigInt::from(-256i64), &[0x12, 254, 255]);

        test_serde(BigInt::from(0), b"\x14");
        test_serde(BigUint::from(0u64), b"\x14");
        test_serde(BigInt::from(1), b"\x15\x01");
        test_serde(BigUint::from(1u64), b"\x15\x01");
        test_serde(BigInt::from(-1), b"\x13\xfe");
        test_serde(BigInt::from(255), b"\x15\xff");
        test_serde(BigUint::from(255u64), b"\x15\xff");
        test_serde(BigInt::from(-255), b"\x13\x00");
        test_serde(BigInt::from(256), b"\x16\x01\x00");
        test_serde(BigUint::from(256u64), b"\x16\x01\x00");
        test_serde(BigInt::from(-256), b"\x12\xfe\xff");
        test_serde(BigInt::from(65536), b"\x17\x01\x00\x00");
        test_serde(BigUint::from(65536u64), b"\x17\x01\x00\x00");
        test_serde(BigInt::from(-65536), b"\x11\xfe\xff\xff");
        test_serde(
            BigInt::from(i64::max_value()),
            b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigUint::from(i64::max_value() as u64),
            b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigInt::from(i64::max_value() as u64 + 1),
            b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigUint::from(i64::max_value() as u64 + 1),
            b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(u64::max_value()),
            b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigUint::from(u64::max_value()),
            b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigInt::from(u128::max_value()),
            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigUint::from(u128::max_value()),
            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigInt::from(u64::max_value() as u128 + 1),
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigUint::from(u64::max_value() as u128 + 1),
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(u64::max_value() as i128 + 1),
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigUint::from(u64::max_value() as u128 + 1),
            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(i64::min_value() as i128 + 1),
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(i64::min_value() as i128 - 1),
            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(
            BigInt::from(-(u64::max_value() as i128)),
            b"\x0C\x00\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(-(u64::max_value() as i128) - 1),
            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xff",
        );
        test_serde(
            BigInt::from(-(u64::max_value() as i128) - 2),
            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(
            BigInt::from((u64::max_value() as i128) * -2),
            b"\x0b\xf6\xfe\x00\x00\x00\x00\x00\x00\x00\x01",
        );
        test_serde(
            BigInt::from((u64::max_value() as i128) * 2),
            b"\x1d\x09\x01\xff\xff\xff\xff\xff\xff\xff\xfe",
        );
        test_serde(BigInt::from(-4294967295i64), b"\x10\x00\x00\x00\x00");
        test_serde(
            BigInt::from(i64::min_value() + 2),
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x01",
        );
        test_serde(
            BigInt::from(i64::min_value() + 1),
            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
        );
        test_serde(
            BigInt::from(i64::min_value()),
            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xff",
        );

        test_serde(
            Element::BigInt(9252427359321063944i128.into()),
            b"\x1c\x80g9\xa9np\x02\x08",
        );
        test_serde(
            Element::BigInt((-9252427359321063944i128).into()),
            b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7",
        );
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn test_uuid() {
        use uuid::Uuid;

        test_serde(
            Element::Uuid(
                Uuid::from_slice(
                    b"\xba\xff\xff\xff\xff\x5e\xba\x11\x00\x00\x00\x00\x5c\xa1\xab\x1e",
                )
                .unwrap(),
            ),
            b"\x30\xba\xff\xff\xff\xff\x5e\xba\x11\x00\x00\x00\x00\x5c\xa1\xab\x1e",
        );
    }

    #[test]
    fn test_bindingtester() {
        test_serde("NEW_TRANSACTION".to_string(), b"\x02NEW_TRANSACTION\x00");
        test_serde(
            vec!["NEW_TRANSACTION".to_string()],
            b"\x02NEW_TRANSACTION\x00",
        );
        test_serde(
            vec![
                Element::String(Cow::Borrowed("PUSH")),
                Element::Bytes(Bytes::from(
                    b"\x01tester_output\x00\x01results\x00\x14".as_ref(),
                )),
            ],
            b"\x02PUSH\x00\x01\x01tester_output\x00\xff\x01results\x00\xff\x14\x00",
        );
        test_serde(
            vec![Element::String(Cow::Borrowed("PUSH")), Element::Nil],
            b"\x02PUSH\x00\x00",
        );
        test_serde(
            vec![
                Element::String(Cow::Borrowed("PUSH")),
                Element::Tuple(vec![
                    Element::Nil,
                    Element::Float(3299069000000.0),
                    Element::Float(-0.000000000000000000000000000000000000011883096),
                ]),
            ],
            b"\x02PUSH\x00\x05\x00\xff \xd4@\x07\xf5 \x7f~\x9a\xc2\x00",
        );
        test_serde(
            vec![
                Element::String(Cow::Borrowed("PUSH")),
                Element::Int(-133525682914243904),
            ],
            b"\x02PUSH\x00\x0c\xfe%\x9f\x19M\x81J\xbf",
        );

        test_serde(
            Element::Tuple(vec![Element::Nil, Element::Nil]),
            b"\x00\x00",
        );
        test_serde(
            Element::Tuple(vec![
                Element::String(Cow::Borrowed("PUSH")),
                Element::Tuple(vec![Element::Double(-8.251343508909708e-15)]),
            ]),
            b"\x02PUSH\x00\x05!B\xfdkl\x9f\xcc\x8eK\x00",
        );
    }

    #[test]
    fn test_element() {
        test_serde(Element::Bool(true), &[TRUE]);
        test_serde(Element::Bool(false), &[FALSE]);
        test_serde(Element::Int(-1), &[0x13, 254]);
        test_serde(
            Element::Versionstamp(Versionstamp::complete(
                b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a".clone(),
                657,
            )),
            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
        );
        test_serde(
            (Element::Versionstamp(Versionstamp::complete(
                b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a".clone(),
                657,
            )),),
            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
        );
        test_serde(
            (Element::Versionstamp(Versionstamp::complete(
                b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a".clone(),
                657,
            )),),
            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
        );
        test_serde(
            vec![Element::Bool(true), Element::Bool(false)],
            &[TRUE, FALSE],
        );
        test_serde(
            vec![Element::Tuple(vec![
                Element::Bool(true),
                Element::Bool(false),
            ])],
            &[NESTED, TRUE, FALSE, NIL],
        );
        test_serde(Vec::<Element>::new(), &[]);
        test_serde(Element::Tuple(vec![]), &[]);
    }

    #[test]
    fn test_verstionstamp() {
        assert_eq!(
            Bytes::from(pack(&("foo", Versionstamp::incomplete(0)))),
            Bytes::from(&b"\x02foo\x00\x33\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00"[..])
        );
        assert_eq!(
            Bytes::from(pack_with_versionstamp(&(
                "foo",
                Versionstamp::incomplete(0)
            ))),
            Bytes::from(
                &b"\x02foo\x00\x33\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x06\x00\x00\x00"
                    [..]
            )
        );
    }
}