foundationdb_tuple/
lib.rs

1//! Implementation of the official tuple layer typecodes
2//!
3//! The official specification can be found [here](https://github.com/apple/foundationdb/blob/master/design/tuple.md).
4
5mod element;
6mod pack;
7mod subspace;
8mod versionstamp;
9
10use std::borrow::Cow;
11use std::fmt::{self, Display};
12use std::io;
13use std::ops::Deref;
14use std::result;
15
16#[cfg(feature = "uuid")]
17pub use uuid::Uuid;
18
19pub use element::Element;
20pub use pack::{TuplePack, TupleUnpack, VersionstampOffset};
21pub use subspace::Subspace;
22pub use versionstamp::Versionstamp;
23
24const NIL: u8 = 0x00;
25const BYTES: u8 = 0x01;
26const STRING: u8 = 0x02;
27const NESTED: u8 = 0x05;
28const NEGINTSTART: u8 = 0x0b;
29const INTZERO: u8 = 0x14;
30const POSINTEND: u8 = 0x1d;
31const FLOAT: u8 = 0x20;
32const DOUBLE: u8 = 0x21;
33const FALSE: u8 = 0x26;
34const TRUE: u8 = 0x27;
35#[cfg(feature = "uuid")]
36const UUID: u8 = 0x30;
37// Not a single official binding is implementing 80 Bit versionstamp...
38// const VERSIONSTAMP_88: u8 = 0x32;
39const VERSIONSTAMP: u8 = 0x33;
40
41const ESCAPE: u8 = 0xff;
42
43/// Tracks the depth of a Tuple decoding chain
44#[derive(Copy, Clone)]
45pub struct TupleDepth(usize);
46
47impl TupleDepth {
48    fn new() -> Self {
49        TupleDepth(0)
50    }
51
52    /// Increment the depth by one, this be called when calling into `Tuple::{encode, decode}` of tuple-like datastructures
53    pub fn increment(self) -> Self {
54        TupleDepth(self.0 + 1)
55    }
56
57    /// Returns the current depth in any recursive tuple processing, 0 representing there having been no recursion
58    pub fn depth(self) -> usize {
59        self.0
60    }
61}
62
63/// A packing/unpacking error
64#[derive(Debug)]
65pub enum PackError {
66    Message(Box<str>),
67    IoError(io::Error),
68    TrailingBytes,
69    MissingBytes,
70    BadStringFormat,
71    BadCode {
72        found: u8,
73        expected: Option<u8>,
74    },
75    BadPrefix,
76    #[cfg(feature = "uuid")]
77    BadUuid,
78    UnsupportedIntLength,
79}
80
81impl From<io::Error> for PackError {
82    fn from(err: io::Error) -> Self {
83        PackError::IoError(err)
84    }
85}
86
87impl Display for PackError {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        match self {
90            PackError::Message(s) => s.fmt(f),
91            PackError::IoError(err) => err.fmt(f),
92            PackError::TrailingBytes => write!(f, "trailing bytes"),
93            PackError::MissingBytes => write!(f, "missing bytes"),
94            PackError::BadStringFormat => write!(f, "not an utf8 string"),
95            PackError::BadCode { found, .. } => write!(f, "bad code, found {found}"),
96            PackError::BadPrefix => write!(f, "bad prefix"),
97            #[cfg(feature = "uuid")]
98            PackError::BadUuid => write!(f, "bad uuid"),
99            PackError::UnsupportedIntLength => write!(f, "integer length was to large"),
100        }
101    }
102}
103
104impl std::error::Error for PackError {}
105
106/// Alias for `Result<..., tuple::Error>`
107pub type PackResult<T> = result::Result<T, PackError>;
108
109/// Represent a sequence of bytes (i.e. &[u8])
110///
111/// This sequence can be either owned or borrowed.
112#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
113pub struct Bytes<'a>(pub Cow<'a, [u8]>);
114
115impl fmt::Debug for Bytes<'_> {
116    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117        fmt::Display::fmt(self, f)
118    }
119}
120
121impl fmt::Display for Bytes<'_> {
122    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
123        write!(fmt, "b\"")?;
124        for &byte in self.0.iter() {
125            if byte == b'\\' {
126                write!(fmt, r"\\")?;
127            } else if byte.is_ascii_alphanumeric() {
128                write!(fmt, "{}", byte as char)?;
129            } else {
130                write!(fmt, "\\x{byte:02x}")?;
131            }
132        }
133        write!(fmt, "\"")
134    }
135}
136
137impl Bytes<'_> {
138    pub fn into_owned(self) -> Vec<u8> {
139        self.0.into_owned()
140    }
141}
142
143impl Deref for Bytes<'_> {
144    type Target = [u8];
145    fn deref(&self) -> &Self::Target {
146        &self.0
147    }
148}
149impl AsRef<[u8]> for Bytes<'_> {
150    fn as_ref(&self) -> &[u8] {
151        &self.0
152    }
153}
154
155impl<'a> From<&'a [u8]> for Bytes<'a> {
156    fn from(bytes: &'a [u8]) -> Self {
157        Self(Cow::Borrowed(bytes))
158    }
159}
160impl From<Vec<u8>> for Bytes<'static> {
161    fn from(vec: Vec<u8>) -> Self {
162        Self(Cow::Owned(vec))
163    }
164}
165
166impl<'a> From<&'a str> for Bytes<'a> {
167    fn from(s: &'a str) -> Self {
168        s.as_bytes().into()
169    }
170}
171impl From<String> for Bytes<'static> {
172    fn from(vec: String) -> Self {
173        vec.into_bytes().into()
174    }
175}
176
177/// Pack value and returns the packed buffer
178///
179/// # Panics
180///
181/// Panics if the encoded data size doesn't fit in `u32`.
182pub fn pack<T: TuplePack>(v: &T) -> Vec<u8> {
183    v.pack_to_vec()
184}
185
186/// Pack a value using the versionstamp offset encoding for API 520 and later.
187///
188/// If the tuple contains an incomplete versionstamp, the result has a four-byte
189/// offset suffix. For keys under an earlier runtime API, use
190/// [`pack_with_versionstamp_for_key`]. Tuple values with incomplete stamps require
191/// API 520 or later; earlier APIs stamp at byte zero, overwriting the tuple's type
192/// code. Complete stamps are packed normally, without an offset suffix.
193///
194/// # Panics
195///
196/// Panics if there is multiple versionstamp present or if the encoded data size doesn't fit in `u32`.
197pub fn pack_with_versionstamp<T: TuplePack>(v: &T) -> Vec<u8> {
198    v.pack_to_vec_with_versionstamp()
199}
200
201/// Pack a tuple key for the explicitly selected runtime API version.
202///
203/// An incomplete versionstamp appends a two-byte little-endian offset before API
204/// 520, or a four-byte offset at API 520 and later. The version must match the
205/// runtime API selected by the application, which can differ from its headers or
206/// client library version. This function does not inspect client initialization.
207/// Tuples with no incomplete stamp are packed normally, without a suffix.
208///
209/// This is a key operand for `SetVersionstampedKey`, not a legacy
210/// `SetVersionstampedValue` operand: before API 520, values are stamped at byte
211/// zero and cannot preserve the tuple's type code.
212///
213/// # Panics
214///
215/// Panics if there are multiple incomplete stamps, the encoded size does not fit
216/// in `u32`, or a legacy key's stamp offset does not fit in `u16`.
217///
218/// ```
219/// use foundationdb_tuple::{pack_with_versionstamp_for_key, Versionstamp};
220/// let key = pack_with_versionstamp_for_key(&("event", Versionstamp::incomplete(0)), 510);
221/// assert_eq!(&key[key.len() - 2..], &8_u16.to_le_bytes());
222/// ```
223pub fn pack_with_versionstamp_for_key<T: TuplePack>(v: &T, api_version: i32) -> Vec<u8> {
224    let mut output = Vec::new();
225    let offset = pack_into(v, &mut output);
226    offset.append_key_offset(&mut output, api_version);
227    output
228}
229
230/// Pack value into the given buffer
231///
232/// # Panics
233///
234/// Panics if the encoded data size doesn't fit in `u32`.
235pub fn pack_into<T: TuplePack>(v: &T, output: &mut Vec<u8>) -> VersionstampOffset {
236    v.pack_into_vec(output)
237}
238
239/// Pack a value into the buffer with a four-byte versionstamp offset for API
240/// 520 and later. For legacy keys, use [`pack_with_versionstamp_for_key`] or
241/// [`Subspace::pack_with_versionstamp_for_key`] with the buffer as a prefix.
242///
243/// # Panics
244///
245/// Panics if there is multiple versionstamp present or if the encoded data size doesn't fit in `u32`.
246pub fn pack_into_with_versionstamp<T: TuplePack>(v: &T, output: &mut Vec<u8>) {
247    let offset = v.pack_into_vec_with_versionstamp(output);
248    if let VersionstampOffset::MultipleIncomplete = offset {
249        panic!("pack_into_with_versionstamp does not allow multiple versionstamps");
250    }
251}
252
253/// Unpack input
254pub fn unpack<'de, T: TupleUnpack<'de>>(input: &'de [u8]) -> PackResult<T> {
255    T::unpack_root(input)
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    const NIL_VAL: Option<()> = None;
263
264    fn test_serde<'de, T>(val: T, buf: &'de [u8])
265    where
266        T: TuplePack + TupleUnpack<'de> + fmt::Debug + PartialEq,
267    {
268        assert_eq!(Bytes::from(pack(&val)), Bytes::from(buf));
269        assert_eq!(unpack::<'de, T>(buf).unwrap(), val);
270    }
271
272    #[test]
273    fn test_spec() {
274        test_serde(NIL_VAL, &[NIL]);
275        test_serde((NIL_VAL,), &[NIL]);
276        test_serde(((NIL_VAL,),), &[NESTED, NIL, ESCAPE, NIL]);
277        // assert_eq!(to_bytes(b"foo\x00bar").unwrap(), b"\x01foo\x00\xffbar\x00");
278        test_serde("FÔO\x00bar".to_owned(), b"\x02F\xc3\x94O\x00\xffbar\x00");
279        test_serde(
280            (("foo\x00bar".to_owned(), NIL_VAL, ()),),
281            b"\x05\x02foo\x00\xffbar\x00\x00\xff\x05\x00\x00",
282        );
283        test_serde(-1, b"\x13\xfe");
284        test_serde(-5551212, b"\x11\xabK\x93");
285        test_serde(-42f32, b"\x20\x3d\xd7\xff\xff");
286    }
287
288    #[test]
289    fn test_simple() {
290        // bool
291        test_serde(false, &[FALSE]);
292        test_serde(true, &[TRUE]);
293
294        // int
295        test_serde(0i64, &[INTZERO]);
296        test_serde(1i64, &[0x15, 1]);
297        test_serde(-1i64, &[0x13, 254]);
298        test_serde(100i64, &[21, 100]);
299
300        test_serde(10000i32, &[22, 39, 16]);
301        test_serde(-100i16, &[19, 155]);
302        test_serde(-10000i64, &[18, 216, 239]);
303        test_serde(-1000000i64, &[17, 240, 189, 191]);
304
305        // boundary condition
306        test_serde(255u16, &[0x15, 255]);
307        test_serde(256i32, &[0x16, 1, 0]);
308        test_serde(-255i16, &[0x13, 0]);
309        test_serde(-256i64, &[0x12, 254, 255]);
310
311        // versionstamp
312        test_serde(
313            Versionstamp::complete(*b"\xaa\xbb\xcc\xdd\xee\xff\x00\x01\x02\x03", 0),
314            b"\x33\xaa\xbb\xcc\xdd\xee\xff\x00\x01\x02\x03\x00\x00",
315        );
316        test_serde(
317            Versionstamp::complete(*b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a", 657),
318            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
319        );
320
321        test_serde(0, b"\x14");
322        test_serde(1, b"\x15\x01");
323        test_serde(-1, b"\x13\xfe");
324        test_serde(255, b"\x15\xff");
325        test_serde(-255, b"\x13\x00");
326        test_serde(256, b"\x16\x01\x00");
327        test_serde(-256, b"\x12\xfe\xff");
328        test_serde(65536, b"\x17\x01\x00\x00");
329        test_serde(-65536, b"\x11\xfe\xff\xff");
330        test_serde(i64::MAX, b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff");
331        test_serde(i64::MAX as u64 + 1, b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00");
332        test_serde(u64::MAX, b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff");
333        test_serde(
334            u128::MAX,
335            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
336        );
337        test_serde(
338            u64::MAX as u128 + 1,
339            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
340        );
341        test_serde(
342            u64::MAX as i128 + 1,
343            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
344        );
345        test_serde(
346            i64::MIN as i128 + 1,
347            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
348        );
349        test_serde(
350            i64::MIN as i128 - 1,
351            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xfe",
352        );
353        test_serde(-(u64::MAX as i128), b"\x0C\x00\x00\x00\x00\x00\x00\x00\x00");
354        test_serde(
355            -(u64::MAX as i128) - 1,
356            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xff",
357        );
358        test_serde(
359            -(u64::MAX as i128) - 2,
360            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xfe",
361        );
362        test_serde(
363            (u64::MAX as i128) * -2,
364            b"\x0b\xf6\xfe\x00\x00\x00\x00\x00\x00\x00\x01",
365        );
366        test_serde(
367            (u64::MAX as i128) * 2,
368            b"\x1d\x09\x01\xff\xff\xff\xff\xff\xff\xff\xfe",
369        );
370        test_serde(-4294967295i64, b"\x10\x00\x00\x00\x00");
371        test_serde(i64::MIN + 2, b"\x0C\x80\x00\x00\x00\x00\x00\x00\x01");
372        test_serde(i64::MIN + 1, b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00");
373        test_serde(i64::MIN, b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xff");
374
375        test_serde(9252427359321063944i128, b"\x1c\x80g9\xa9np\x02\x08");
376        assert!(matches!(
377            unpack::<i64>(b"\x1c\x80g9\xa9np\x02\x08").unwrap_err(),
378            PackError::UnsupportedIntLength
379        ));
380
381        test_serde(
382            -9252427359321063944i128,
383            b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7",
384        );
385        assert!(matches!(
386            unpack::<i64>(b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7").unwrap_err(),
387            PackError::UnsupportedIntLength
388        ));
389
390        test_serde(u64::MAX as i128, b"\x1c\xff\xff\xff\xff\xff\xff\xff\xff");
391        assert!(matches!(
392            unpack::<i64>(b"\x1c\xff\xff\xff\xff\xff\xff\xff\xff").unwrap_err(),
393            PackError::UnsupportedIntLength
394        ));
395
396        test_serde(-(u64::MAX as i128), b"\x0c\x00\x00\x00\x00\x00\x00\x00\x00");
397        assert!(matches!(
398            unpack::<i64>(b"\x0c\x00\x00\x00\x00\x00\x00\x00\x00").unwrap_err(),
399            PackError::UnsupportedIntLength
400        ));
401
402        test_serde(
403            (i64::MAX as i128) + 1,
404            b"\x1c\x80\x00\x00\x00\x00\x00\x00\x00",
405        );
406        assert!(matches!(
407            unpack::<i64>(b"\x1c\x80\x00\x00\x00\x00\x00\x00\x00").unwrap_err(),
408            PackError::UnsupportedIntLength
409        ));
410
411        test_serde(
412            (i64::MIN as i128) - 1,
413            b"\x0c\x7f\xff\xff\xff\xff\xff\xff\xfe",
414        );
415        assert!(matches!(
416            unpack::<i64>(b"\x0c\x7f\xff\xff\xff\xff\xff\xff\xfe").unwrap_err(),
417            PackError::UnsupportedIntLength
418        ));
419    }
420
421    #[test]
422    fn test_typecode_band_ordering() {
423        // Order-preserving keys rely on packed tuples comparing byte-lexicographically
424        // (Rust's `Vec<u8>` ordering). This mirrors a subspace-prefix scheme where the
425        // prefix is a u32 discriminant, with a negative "header" band strictly before it
426        // and an f32 band strictly after it. The typecode band, not the value, decides:
427        //   negatives (0x0c..=0x13)  <  u32 (0x14..=0x18)  <  f32 (0x20 ...)
428        let hex = |b: &[u8]| {
429            b.iter()
430                .map(|x| format!("{x:02x}"))
431                .collect::<Vec<_>>()
432                .join(" ")
433        };
434
435        // "before" band: signed ints, min and max of the range we might use.
436        let neg_min = pack(&i64::MIN); // 0c 7f ff ff ff ff ff ff ff (most negative)
437        let neg_max = pack(&-1i64); //    13 fe                      (closest to u32 band)
438
439        // middle band: the u32 subspace prefix, min and max discriminant.
440        let u32_min = pack(&0u32); //     14                         (INTZERO)
441        let u32_max = pack(&u32::MAX); //  18 ff ff ff ff            (4-byte positive int)
442
443        // "after" band: f32 markers >= 1.0, min and max of the range we might use.
444        let f_min = pack(&1.0f32); //     20 bf 80 00 00             (closest to u32 band)
445        let f_max = pack(&f32::MAX); //    20 ff 7f ff ff
446
447        println!("i64::MIN = {}", hex(&neg_min));
448        println!("-1i64    = {}", hex(&neg_max));
449        println!("0u32     = {}", hex(&u32_min));
450        println!("u32::MAX = {}", hex(&u32_max));
451        println!("1.0f32   = {}", hex(&f_min));
452        println!("f32::MAX = {}", hex(&f_max));
453
454        // Within each band numeric order is preserved (nothing weird inside a band).
455        assert!(neg_min < neg_max); // 0c ..    < 13 fe
456        assert!(u32_min < u32_max); // 14       < 18 ..
457        assert!(f_min < f_max); //     20 bf .. < 20 ff ..
458
459        // Whole "before" band sorts under the u32 band; tightest pair is -1 vs 0.
460        assert!(neg_max < u32_min); // 13 fe < 14
461        assert!(neg_min < u32_min); // 0c .. < 14 (even the most negative stays below)
462
463        // Whole "after" band sorts over the u32 band; tightest pair is u32::MAX vs 1.0.
464        assert!(u32_max < f_min); //   18 ff ff ff ff < 20 bf 80 00 00
465        assert!(u32_max < f_max); //   18 ..          < 20 ff .. (magnitude irrelevant)
466    }
467
468    #[cfg(feature = "num-bigint")]
469    #[test]
470    fn test_bigint() {
471        use num_bigint::{BigInt, BigUint};
472        // int
473        test_serde(BigInt::from(0i64), &[INTZERO]);
474        test_serde(BigUint::from(0u64), &[INTZERO]);
475        test_serde(BigInt::from(1i64), &[0x15, 1]);
476        test_serde(BigUint::from(1u64), &[0x15, 1]);
477        test_serde(BigInt::from(-1i64), &[0x13, 254]);
478        test_serde(BigInt::from(100i64), &[0x15, 100]);
479        test_serde(BigUint::from(100u64), &[0x15, 100]);
480
481        test_serde(BigInt::from(10000i32), &[0x16, 39, 16]);
482        test_serde(BigUint::from(10000u32), &[0x16, 39, 16]);
483        test_serde(BigInt::from(-100i16), &[19, 155]);
484        test_serde(BigInt::from(-10000i64), &[18, 216, 239]);
485        test_serde(BigInt::from(-1000000i64), &[17, 240, 189, 191]);
486
487        // boundary condition
488        test_serde(BigInt::from(255u16), &[0x15, 255]);
489        test_serde(BigUint::from(255u16), &[0x15, 255]);
490        test_serde(BigInt::from(256i32), &[0x16, 1, 0]);
491        test_serde(BigInt::from(-255i16), &[0x13, 0]);
492        test_serde(BigInt::from(-256i64), &[0x12, 254, 255]);
493
494        test_serde(BigInt::from(0), b"\x14");
495        test_serde(BigUint::from(0u64), b"\x14");
496        test_serde(BigInt::from(1), b"\x15\x01");
497        test_serde(BigUint::from(1u64), b"\x15\x01");
498        test_serde(BigInt::from(-1), b"\x13\xfe");
499        test_serde(BigInt::from(255), b"\x15\xff");
500        test_serde(BigUint::from(255u64), b"\x15\xff");
501        test_serde(BigInt::from(-255), b"\x13\x00");
502        test_serde(BigInt::from(256), b"\x16\x01\x00");
503        test_serde(BigUint::from(256u64), b"\x16\x01\x00");
504        test_serde(BigInt::from(-256), b"\x12\xfe\xff");
505        test_serde(BigInt::from(65536), b"\x17\x01\x00\x00");
506        test_serde(BigUint::from(65536u64), b"\x17\x01\x00\x00");
507        test_serde(BigInt::from(-65536), b"\x11\xfe\xff\xff");
508        test_serde(
509            BigInt::from(i64::MAX),
510            b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff",
511        );
512        test_serde(
513            BigUint::from(i64::MAX as u64),
514            b"\x1C\x7f\xff\xff\xff\xff\xff\xff\xff",
515        );
516        test_serde(
517            BigInt::from(i64::MAX as u64 + 1),
518            b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00",
519        );
520        test_serde(
521            BigUint::from(i64::MAX as u64 + 1),
522            b"\x1C\x80\x00\x00\x00\x00\x00\x00\x00",
523        );
524        test_serde(
525            BigInt::from(u64::MAX),
526            b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff",
527        );
528        test_serde(
529            BigUint::from(u64::MAX),
530            b"\x1C\xff\xff\xff\xff\xff\xff\xff\xff",
531        );
532        test_serde(
533            BigInt::from(u128::MAX),
534            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
535        );
536        test_serde(
537            BigUint::from(u128::MAX),
538            b"\x1D\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
539        );
540        test_serde(
541            BigInt::from(u64::MAX as u128 + 1),
542            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
543        );
544        test_serde(
545            BigUint::from(u64::MAX as u128 + 1),
546            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
547        );
548        test_serde(
549            BigInt::from(u64::MAX as i128 + 1),
550            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
551        );
552        test_serde(
553            BigUint::from(u64::MAX as u128 + 1),
554            b"\x1D\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00",
555        );
556        test_serde(
557            BigInt::from(i64::MIN as i128 + 1),
558            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
559        );
560        test_serde(
561            BigInt::from(i64::MIN as i128 - 1),
562            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xfe",
563        );
564        test_serde(
565            BigInt::from(-(u64::MAX as i128)),
566            b"\x0C\x00\x00\x00\x00\x00\x00\x00\x00",
567        );
568        test_serde(
569            BigInt::from(-(u64::MAX as i128) - 1),
570            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xff",
571        );
572        test_serde(
573            BigInt::from(-(u64::MAX as i128) - 2),
574            b"\x0b\xf6\xfe\xff\xff\xff\xff\xff\xff\xff\xfe",
575        );
576        test_serde(
577            BigInt::from((u64::MAX as i128) * -2),
578            b"\x0b\xf6\xfe\x00\x00\x00\x00\x00\x00\x00\x01",
579        );
580        test_serde(
581            BigInt::from((u64::MAX as i128) * 2),
582            b"\x1d\x09\x01\xff\xff\xff\xff\xff\xff\xff\xfe",
583        );
584        test_serde(BigInt::from(-4294967295i64), b"\x10\x00\x00\x00\x00");
585        test_serde(
586            BigInt::from(i64::MIN + 2),
587            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x01",
588        );
589        test_serde(
590            BigInt::from(i64::MIN + 1),
591            b"\x0C\x80\x00\x00\x00\x00\x00\x00\x00",
592        );
593        test_serde(
594            BigInt::from(i64::MIN),
595            b"\x0C\x7f\xff\xff\xff\xff\xff\xff\xff",
596        );
597
598        test_serde(
599            Element::BigInt(9252427359321063944i128.into()),
600            b"\x1c\x80g9\xa9np\x02\x08",
601        );
602        test_serde(
603            Element::BigInt((-9252427359321063944i128).into()),
604            b"\x0c\x7f\x98\xc6V\x91\x8f\xfd\xf7",
605        );
606    }
607
608    #[cfg(feature = "uuid")]
609    #[test]
610    fn test_uuid() {
611        use uuid::Uuid;
612
613        test_serde(
614            Element::Uuid(
615                Uuid::from_slice(
616                    b"\xba\xff\xff\xff\xff\x5e\xba\x11\x00\x00\x00\x00\x5c\xa1\xab\x1e",
617                )
618                .unwrap(),
619            ),
620            b"\x30\xba\xff\xff\xff\xff\x5e\xba\x11\x00\x00\x00\x00\x5c\xa1\xab\x1e",
621        );
622    }
623
624    #[test]
625    fn test_bindingtester() {
626        test_serde("NEW_TRANSACTION".to_string(), b"\x02NEW_TRANSACTION\x00");
627        test_serde(
628            vec!["NEW_TRANSACTION".to_string()],
629            b"\x02NEW_TRANSACTION\x00",
630        );
631        test_serde(
632            vec![
633                Element::String(Cow::Borrowed("PUSH")),
634                Element::Bytes(Bytes::from(
635                    b"\x01tester_output\x00\x01results\x00\x14".as_ref(),
636                )),
637            ],
638            b"\x02PUSH\x00\x01\x01tester_output\x00\xff\x01results\x00\xff\x14\x00",
639        );
640        test_serde(
641            vec![Element::String(Cow::Borrowed("PUSH")), Element::Nil],
642            b"\x02PUSH\x00\x00",
643        );
644        test_serde(
645            vec![
646                Element::String(Cow::Borrowed("PUSH")),
647                Element::Tuple(vec![
648                    Element::Nil,
649                    Element::Float(3299069000000.0),
650                    Element::Float(-0.000000000000000000000000000000000000011883096),
651                ]),
652            ],
653            b"\x02PUSH\x00\x05\x00\xff \xd4@\x07\xf5 \x7f~\x9a\xc2\x00",
654        );
655        test_serde(
656            vec![
657                Element::String(Cow::Borrowed("PUSH")),
658                Element::Int(-133525682914243904),
659            ],
660            b"\x02PUSH\x00\x0c\xfe%\x9f\x19M\x81J\xbf",
661        );
662
663        test_serde(
664            Element::Tuple(vec![Element::Nil, Element::Nil]),
665            b"\x00\x00",
666        );
667        test_serde(
668            Element::Tuple(vec![
669                Element::String(Cow::Borrowed("PUSH")),
670                Element::Tuple(vec![Element::Double(-8.251343508909708e-15)]),
671            ]),
672            b"\x02PUSH\x00\x05!B\xfdkl\x9f\xcc\x8eK\x00",
673        );
674    }
675
676    #[test]
677    fn test_element() {
678        test_serde(Element::Bool(true), &[TRUE]);
679        test_serde(Element::Bool(false), &[FALSE]);
680        test_serde(Element::Int(-1), &[0x13, 254]);
681        test_serde(
682            Element::Versionstamp(Versionstamp::complete(
683                *b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a",
684                657,
685            )),
686            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
687        );
688        test_serde(
689            (Element::Versionstamp(Versionstamp::complete(
690                *b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a",
691                657,
692            )),),
693            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
694        );
695        test_serde(
696            (Element::Versionstamp(Versionstamp::complete(
697                *b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a",
698                657,
699            )),),
700            b"\x33\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x02\x91",
701        );
702        test_serde(
703            vec![Element::Bool(true), Element::Bool(false)],
704            &[TRUE, FALSE],
705        );
706        test_serde(
707            vec![Element::Tuple(vec![
708                Element::Bool(true),
709                Element::Bool(false),
710            ])],
711            &[NESTED, TRUE, FALSE, NIL],
712        );
713        test_serde(Vec::<Element>::new(), &[]);
714        test_serde(Element::Tuple(vec![]), &[]);
715    }
716
717    #[test]
718    fn test_verstionstamp() {
719        assert_eq!(
720            Bytes::from(pack(&("foo", Versionstamp::incomplete(0)))),
721            Bytes::from(&b"\x02foo\x00\x33\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00"[..])
722        );
723        assert_eq!(
724            Bytes::from(pack_with_versionstamp(&(
725                "foo",
726                Versionstamp::incomplete(0)
727            ))),
728            Bytes::from(
729                &b"\x02foo\x00\x33\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x06\x00\x00\x00"
730                    [..]
731            )
732        );
733    }
734
735    #[test]
736    fn versionstamp_key_encoding_matches_runtime_api() {
737        let tuple = ("foo", Versionstamp::incomplete(657));
738        let mut legacy = pack(&tuple);
739        legacy.extend_from_slice(&6_u16.to_le_bytes());
740        assert_eq!(pack_with_versionstamp_for_key(&tuple, 510), legacy);
741        for api_version in [520, 740] {
742            assert_eq!(
743                pack_with_versionstamp_for_key(&tuple, api_version),
744                pack_with_versionstamp(&tuple)
745            );
746        }
747        for api_version in [510, 520, 740] {
748            let complete = ("foo", Versionstamp::complete([7; 10], 657));
749            assert_eq!(
750                pack_with_versionstamp_for_key(&complete, api_version),
751                pack(&complete)
752            );
753            assert_eq!(
754                pack_with_versionstamp_for_key(&"foo", api_version),
755                pack(&"foo")
756            );
757            let multiple = (Versionstamp::incomplete(0), (Versionstamp::incomplete(1),));
758            assert!(
759                std::panic::catch_unwind(|| pack_with_versionstamp_for_key(&multiple, api_version))
760                    .is_err()
761            );
762        }
763    }
764}