soroban_env_host_zephyr/host/
comparison.rs

1use core::cmp::{min, Ordering};
2
3use crate::{
4    budget::{AsBudget, Budget, DepthLimiter},
5    host_object::HostObject,
6    storage::Storage,
7    xdr::{
8        AccountId, ContractCostType, ContractDataDurability, ContractExecutable,
9        CreateContractArgs, Duration, Hash, Int128Parts, Int256Parts, LedgerKey, LedgerKeyAccount,
10        LedgerKeyContractCode, LedgerKeyContractData, LedgerKeyTrustLine, PublicKey, ScAddress,
11        ScContractInstance, ScError, ScErrorCode, ScErrorType, ScMap, ScMapEntry, ScNonceKey,
12        ScVal, ScVec, TimePoint, TrustLineAsset, UInt128Parts, UInt256Parts, Uint256,
13    },
14    Compare, Host, HostError, SymbolStr, I256, U256,
15};
16
17use super::declared_size::DeclaredSizeForMetering;
18
19// We can't use core::mem::discriminant here because it returns an opaque type
20// that only supports Eq, not Ord, to reduce the possibility of an API breakage
21// based on reordering enums: https://github.com/rust-lang/rust/issues/51561
22//
23// Note that these must have the same order as the impl
24// of Ord for ScVal, re https://github.com/stellar/rs-soroban-env/issues/743
25fn host_obj_discriminant(ho: &HostObject) -> usize {
26    match ho {
27        HostObject::U64(_) => 0,
28        HostObject::I64(_) => 1,
29        HostObject::TimePoint(_) => 2,
30        HostObject::Duration(_) => 3,
31        HostObject::U128(_) => 4,
32        HostObject::I128(_) => 5,
33        HostObject::U256(_) => 6,
34        HostObject::I256(_) => 7,
35        HostObject::Bytes(_) => 8,
36        HostObject::String(_) => 9,
37        HostObject::Symbol(_) => 10,
38        HostObject::Vec(_) => 11,
39        HostObject::Map(_) => 12,
40        HostObject::Address(_) => 13,
41    }
42}
43
44impl Compare<HostObject> for Host {
45    type Error = HostError;
46
47    fn compare(&self, a: &HostObject, b: &HostObject) -> Result<Ordering, Self::Error> {
48        use HostObject::*;
49        let _span = tracy_span!("Compare<HostObject>");
50        // This is the depth limit checkpoint for `Val` comparison.
51        self.budget_cloned().with_limited_depth(|_| {
52            match (a, b) {
53                (U64(a), U64(b)) => self.as_budget().compare(a, b),
54                (I64(a), I64(b)) => self.as_budget().compare(a, b),
55                (TimePoint(a), TimePoint(b)) => self.as_budget().compare(a, b),
56                (Duration(a), Duration(b)) => self.as_budget().compare(a, b),
57                (U128(a), U128(b)) => self.as_budget().compare(a, b),
58                (I128(a), I128(b)) => self.as_budget().compare(a, b),
59                (U256(a), U256(b)) => self.as_budget().compare(a, b),
60                (I256(a), I256(b)) => self.as_budget().compare(a, b),
61                (Vec(a), Vec(b)) => self.compare(a, b),
62                (Map(a), Map(b)) => self.compare(a, b),
63                (Bytes(a), Bytes(b)) => self.as_budget().compare(&a.as_slice(), &b.as_slice()),
64                (String(a), String(b)) => self.as_budget().compare(&a.as_slice(), &b.as_slice()),
65                (Symbol(a), Symbol(b)) => self.as_budget().compare(&a.as_slice(), &b.as_slice()),
66                (Address(a), Address(b)) => self.as_budget().compare(a, b),
67
68                // List out at least one side of all the remaining cases here so
69                // we don't accidentally forget to update this when/if a new
70                // HostObject type is added.
71                (U64(_), _)
72                | (TimePoint(_), _)
73                | (Duration(_), _)
74                | (I64(_), _)
75                | (U128(_), _)
76                | (I128(_), _)
77                | (U256(_), _)
78                | (I256(_), _)
79                | (Vec(_), _)
80                | (Map(_), _)
81                | (Bytes(_), _)
82                | (String(_), _)
83                | (Symbol(_), _)
84                | (Address(_), _) => {
85                    let a = host_obj_discriminant(a);
86                    let b = host_obj_discriminant(b);
87                    Ok(a.cmp(&b))
88                }
89            }
90        })
91    }
92}
93
94impl Compare<&[u8]> for Budget {
95    type Error = HostError;
96
97    fn compare(&self, a: &&[u8], b: &&[u8]) -> Result<Ordering, Self::Error> {
98        self.charge(ContractCostType::MemCmp, Some(min(a.len(), b.len()) as u64))?;
99        Ok(a.cmp(b))
100    }
101}
102
103impl<const N: usize> Compare<[u8; N]> for Budget {
104    type Error = HostError;
105
106    fn compare(&self, a: &[u8; N], b: &[u8; N]) -> Result<Ordering, Self::Error> {
107        self.charge(ContractCostType::MemCmp, Some(min(a.len(), b.len()) as u64))?;
108        Ok(a.cmp(b))
109    }
110}
111
112// Apparently we can't do a blanket T:Ord impl because there are Ord derivations
113// that also go through &T and Option<T> that conflict with our impls above
114// (patches welcome from someone who understands trait-system workarounds
115// better). But we can list out any concrete Ord instances we want to support
116// here.
117//
118// We only do this for declared-size types, because we want to charge them a constant
119// based on their size declared in accordance with their type layout.
120
121struct FixedSizeOrdType<'a, T: Ord + DeclaredSizeForMetering>(&'a T);
122impl<T: Ord + DeclaredSizeForMetering> Compare<FixedSizeOrdType<'_, T>> for Budget {
123    type Error = HostError;
124    fn compare(
125        &self,
126        a: &FixedSizeOrdType<'_, T>,
127        b: &FixedSizeOrdType<'_, T>,
128    ) -> Result<Ordering, Self::Error> {
129        // Here we make a runtime assertion that the type's size is below its promised element
130        // size for budget charging.
131        debug_assert!(
132            std::mem::size_of::<T>() as u64 <= <T as DeclaredSizeForMetering>::DECLARED_SIZE,
133            "mem size: {}, declared: {}",
134            std::mem::size_of::<T>(),
135            <T as DeclaredSizeForMetering>::DECLARED_SIZE
136        );
137        self.charge(
138            ContractCostType::MemCmp,
139            Some(<T as DeclaredSizeForMetering>::DECLARED_SIZE),
140        )?;
141        Ok(a.0.cmp(b.0))
142    }
143}
144
145macro_rules! impl_compare_fixed_size_ord_type {
146    ($t:ty) => {
147        impl Compare<$t> for Budget {
148            type Error = HostError;
149            fn compare(&self, a: &$t, b: &$t) -> Result<Ordering, Self::Error> {
150                self.compare(&FixedSizeOrdType(a), &FixedSizeOrdType(b))
151            }
152        }
153        impl Compare<$t> for Host {
154            type Error = HostError;
155            fn compare(&self, a: &$t, b: &$t) -> Result<Ordering, Self::Error> {
156                self.as_budget().compare(a, b)
157            }
158        }
159    };
160}
161
162impl_compare_fixed_size_ord_type!(bool);
163impl_compare_fixed_size_ord_type!(u32);
164impl_compare_fixed_size_ord_type!(i32);
165impl_compare_fixed_size_ord_type!(u64);
166impl_compare_fixed_size_ord_type!(i64);
167impl_compare_fixed_size_ord_type!(u128);
168impl_compare_fixed_size_ord_type!(i128);
169
170impl_compare_fixed_size_ord_type!(U256);
171impl_compare_fixed_size_ord_type!(I256);
172impl_compare_fixed_size_ord_type!(Int128Parts);
173impl_compare_fixed_size_ord_type!(UInt128Parts);
174impl_compare_fixed_size_ord_type!(Int256Parts);
175impl_compare_fixed_size_ord_type!(UInt256Parts);
176impl_compare_fixed_size_ord_type!(TimePoint);
177impl_compare_fixed_size_ord_type!(Duration);
178impl_compare_fixed_size_ord_type!(Hash);
179impl_compare_fixed_size_ord_type!(Uint256);
180impl_compare_fixed_size_ord_type!(ContractExecutable);
181impl_compare_fixed_size_ord_type!(AccountId);
182impl_compare_fixed_size_ord_type!(ScError);
183impl_compare_fixed_size_ord_type!(ScAddress);
184impl_compare_fixed_size_ord_type!(ScNonceKey);
185impl_compare_fixed_size_ord_type!(PublicKey);
186impl_compare_fixed_size_ord_type!(TrustLineAsset);
187impl_compare_fixed_size_ord_type!(ContractDataDurability);
188impl_compare_fixed_size_ord_type!(CreateContractArgs);
189
190impl_compare_fixed_size_ord_type!(LedgerKeyAccount);
191impl_compare_fixed_size_ord_type!(LedgerKeyTrustLine);
192// NB: LedgerKeyContractData is not here: it has a variable-size ScVal.
193impl_compare_fixed_size_ord_type!(LedgerKeyContractCode);
194
195impl Compare<SymbolStr> for Budget {
196    type Error = HostError;
197
198    fn compare(&self, a: &SymbolStr, b: &SymbolStr) -> Result<Ordering, Self::Error> {
199        self.compare(
200            &<SymbolStr as AsRef<[u8]>>::as_ref(a),
201            &<SymbolStr as AsRef<[u8]>>::as_ref(b),
202        )
203    }
204}
205
206impl Compare<ScVec> for Budget {
207    type Error = HostError;
208
209    fn compare(&self, a: &ScVec, b: &ScVec) -> Result<Ordering, Self::Error> {
210        let a: &Vec<ScVal> = a;
211        let b: &Vec<ScVal> = b;
212        self.compare(a, b)
213    }
214}
215
216impl Compare<ScMap> for Budget {
217    type Error = HostError;
218
219    fn compare(&self, a: &ScMap, b: &ScMap) -> Result<Ordering, Self::Error> {
220        let a: &Vec<ScMapEntry> = a;
221        let b: &Vec<ScMapEntry> = b;
222        self.compare(a, b)
223    }
224}
225
226impl Compare<ScMapEntry> for Budget {
227    type Error = HostError;
228
229    fn compare(&self, a: &ScMapEntry, b: &ScMapEntry) -> Result<Ordering, Self::Error> {
230        match self.compare(&a.key, &b.key)? {
231            Ordering::Equal => self.compare(&a.val, &b.val),
232            cmp => Ok(cmp),
233        }
234    }
235}
236
237impl Compare<ScVal> for Budget {
238    type Error = HostError;
239
240    fn compare(&self, a: &ScVal, b: &ScVal) -> Result<Ordering, Self::Error> {
241        use ScVal::*;
242        // This is the depth limit checkpoint for `ScVal` comparison.
243        self.clone().with_limited_depth(|_| match (a, b) {
244            (Vec(Some(a)), Vec(Some(b))) => self.compare(a, b),
245            (Map(Some(a)), Map(Some(b))) => self.compare(a, b),
246
247            (Vec(None), _) | (_, Vec(None)) | (Map(None), _) | (_, Map(None)) => {
248                Err((ScErrorType::Value, ScErrorCode::InvalidInput).into())
249            }
250
251            (Bytes(a), Bytes(b)) => {
252                <Self as Compare<&[u8]>>::compare(self, &a.as_slice(), &b.as_slice())
253            }
254
255            (String(a), String(b)) => {
256                <Self as Compare<&[u8]>>::compare(self, &a.as_slice(), &b.as_slice())
257            }
258
259            (Symbol(a), Symbol(b)) => {
260                <Self as Compare<&[u8]>>::compare(self, &a.as_slice(), &b.as_slice())
261            }
262
263            (ContractInstance(a), ContractInstance(b)) => self.compare(&a, &b),
264
265            // These two cases are content-free, besides their discriminant.
266            (Void, Void) => Ok(Ordering::Equal),
267            (LedgerKeyContractInstance, LedgerKeyContractInstance) => Ok(Ordering::Equal),
268
269            // Handle types with impl_compare_fixed_size_ord_type:
270            (Bool(a), Bool(b)) => self.compare(&a, &b),
271            (Error(a), Error(b)) => self.compare(&a, &b),
272            (U32(a), U32(b)) => self.compare(&a, &b),
273            (I32(a), I32(b)) => self.compare(&a, &b),
274            (U64(a), U64(b)) => self.compare(&a, &b),
275            (I64(a), I64(b)) => self.compare(&a, &b),
276            (Timepoint(a), Timepoint(b)) => self.compare(&a, &b),
277            (Duration(a), Duration(b)) => self.compare(&a, &b),
278            (U128(a), U128(b)) => self.compare(&a, &b),
279            (I128(a), I128(b)) => self.compare(&a, &b),
280            (U256(a), U256(b)) => self.compare(&a, &b),
281            (I256(a), I256(b)) => self.compare(&a, &b),
282            (Address(a), Address(b)) => self.compare(&a, &b),
283            (LedgerKeyNonce(a), LedgerKeyNonce(b)) => self.compare(&a, &b),
284
285            // List out at least one side of all the remaining cases here so
286            // we don't accidentally forget to update this when/if a new
287            // ScVal type is added.
288            (Vec(_), _)
289            | (Map(_), _)
290            | (Bytes(_), _)
291            | (String(_), _)
292            | (Symbol(_), _)
293            | (ContractInstance(_), _)
294            | (Bool(_), _)
295            | (Void, _)
296            | (Error(_), _)
297            | (U32(_), _)
298            | (I32(_), _)
299            | (U64(_), _)
300            | (I64(_), _)
301            | (Timepoint(_), _)
302            | (Duration(_), _)
303            | (U128(_), _)
304            | (I128(_), _)
305            | (U256(_), _)
306            | (I256(_), _)
307            | (Address(_), _)
308            | (LedgerKeyContractInstance, _)
309            | (LedgerKeyNonce(_), _) => Ok(a.discriminant().cmp(&b.discriminant())),
310        })
311    }
312}
313
314impl Compare<ScContractInstance> for Budget {
315    type Error = HostError;
316
317    fn compare(
318        &self,
319        a: &ScContractInstance,
320        b: &ScContractInstance,
321    ) -> Result<Ordering, Self::Error> {
322        self.compare(&(&a.executable, &a.storage), &(&b.executable, &b.storage))
323    }
324}
325
326impl Compare<LedgerKeyContractData> for Budget {
327    type Error = HostError;
328
329    fn compare(
330        &self,
331        a: &LedgerKeyContractData,
332        b: &LedgerKeyContractData,
333    ) -> Result<Ordering, Self::Error> {
334        self.compare(
335            &(&a.contract, &a.key, &a.durability),
336            &(&b.contract, &b.key, &b.durability),
337        )
338    }
339}
340
341impl Compare<LedgerKey> for Budget {
342    type Error = HostError;
343
344    fn compare(&self, a: &LedgerKey, b: &LedgerKey) -> Result<Ordering, Self::Error> {
345        Storage::check_supported_ledger_key_type(a)?;
346        Storage::check_supported_ledger_key_type(b)?;
347        use LedgerKey::*;
348        match (a, b) {
349            (Account(a), Account(b)) => self.compare(&a, &b),
350            (Trustline(a), Trustline(b)) => self.compare(&a, &b),
351            (ContractData(a), ContractData(b)) => self.compare(&a, &b),
352            (ContractCode(a), ContractCode(b)) => self.compare(&a, &b),
353
354            // All these cases should have been rejected above by check_supported_ledger_key_type.
355            (Offer(_), _)
356            | (Data(_), _)
357            | (ClaimableBalance(_), _)
358            | (LiquidityPool(_), _)
359            | (ConfigSetting(_), _)
360            | (Ttl(_), _)
361            | (_, Offer(_))
362            | (_, Data(_))
363            | (_, ClaimableBalance(_))
364            | (_, LiquidityPool(_))
365            | (_, ConfigSetting(_))
366            | (_, Ttl(_)) => Err((ScErrorType::Value, ScErrorCode::InternalError).into()),
367
368            // List out one side of each remaining unequal-discriminant case so
369            // we remember to update this code if LedgerKey changes. We don't
370            // charge for these since they're just 1-integer compares.
371            (Account(_), _) | (Trustline(_), _) | (ContractData(_), _) | (ContractCode(_), _) => {
372                Ok(a.discriminant().cmp(&b.discriminant()))
373            }
374        }
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use crate::xdr::ScVal;
382    use crate::{Compare, Host, Tag, TryFromVal, Val};
383    use itertools::Itertools;
384
385    #[test]
386    fn test_scvec_unequal_lengths() {
387        {
388            let v1 = ScVec::try_from((0, 1)).unwrap();
389            let v2 = ScVec::try_from((0, 1, 2)).unwrap();
390            let expected_cmp = Ordering::Less;
391            let budget = Budget::default();
392            let actual_cmp = budget.compare(&v1, &v2).unwrap();
393            assert_eq!(expected_cmp, actual_cmp);
394        }
395        {
396            let v1 = ScVec::try_from((0, 1, 2)).unwrap();
397            let v2 = ScVec::try_from((0, 1)).unwrap();
398            let expected_cmp = Ordering::Greater;
399            let budget = Budget::default();
400            let actual_cmp = budget.compare(&v1, &v2).unwrap();
401            assert_eq!(expected_cmp, actual_cmp);
402        }
403        {
404            let v1 = ScVec::try_from((0, 1)).unwrap();
405            let v2 = ScVec::try_from((0, 0, 2)).unwrap();
406            let expected_cmp = Ordering::Greater;
407            let budget = Budget::default();
408            let actual_cmp = budget.compare(&v1, &v2).unwrap();
409            assert_eq!(expected_cmp, actual_cmp);
410        }
411        {
412            let v1 = ScVec::try_from((0, 0, 2)).unwrap();
413            let v2 = ScVec::try_from((0, 1)).unwrap();
414            let expected_cmp = Ordering::Less;
415            let budget = Budget::default();
416            let actual_cmp = budget.compare(&v1, &v2).unwrap();
417            assert_eq!(expected_cmp, actual_cmp);
418        }
419    }
420
421    #[test]
422    fn test_scmap_unequal_lengths() {
423        {
424            let v1 = ScMap::sorted_from([
425                (ScVal::U32(0), ScVal::U32(0)),
426                (ScVal::U32(1), ScVal::U32(1)),
427            ])
428            .unwrap();
429            let v2 = ScMap::sorted_from([
430                (ScVal::U32(0), ScVal::U32(0)),
431                (ScVal::U32(1), ScVal::U32(1)),
432                (ScVal::U32(2), ScVal::U32(2)),
433            ])
434            .unwrap();
435            let expected_cmp = Ordering::Less;
436            let budget = Budget::default();
437            let actual_cmp = budget.compare(&v1, &v2).unwrap();
438            assert_eq!(expected_cmp, actual_cmp);
439        }
440        {
441            let v1 = ScMap::sorted_from([
442                (ScVal::U32(0), ScVal::U32(0)),
443                (ScVal::U32(1), ScVal::U32(1)),
444                (ScVal::U32(2), ScVal::U32(2)),
445            ])
446            .unwrap();
447            let v2 = ScMap::sorted_from([
448                (ScVal::U32(0), ScVal::U32(0)),
449                (ScVal::U32(1), ScVal::U32(1)),
450            ])
451            .unwrap();
452            let expected_cmp = Ordering::Greater;
453            let budget = Budget::default();
454            let actual_cmp = budget.compare(&v1, &v2).unwrap();
455            assert_eq!(expected_cmp, actual_cmp);
456        }
457        {
458            let v1 = ScMap::sorted_from([
459                (ScVal::U32(0), ScVal::U32(0)),
460                (ScVal::U32(1), ScVal::U32(1)),
461            ])
462            .unwrap();
463            let v2 = ScMap::sorted_from([
464                (ScVal::U32(0), ScVal::U32(0)),
465                (ScVal::U32(1), ScVal::U32(0)),
466                (ScVal::U32(2), ScVal::U32(2)),
467            ])
468            .unwrap();
469            let expected_cmp = Ordering::Greater;
470            let budget = Budget::default();
471            let actual_cmp = budget.compare(&v1, &v2).unwrap();
472            assert_eq!(expected_cmp, actual_cmp);
473        }
474        {
475            let v1 = ScMap::sorted_from([
476                (ScVal::U32(0), ScVal::U32(0)),
477                (ScVal::U32(1), ScVal::U32(0)),
478                (ScVal::U32(2), ScVal::U32(2)),
479            ])
480            .unwrap();
481            let v2 = ScMap::sorted_from([
482                (ScVal::U32(0), ScVal::U32(0)),
483                (ScVal::U32(1), ScVal::U32(1)),
484            ])
485            .unwrap();
486            let expected_cmp = Ordering::Less;
487            let budget = Budget::default();
488            let actual_cmp = budget.compare(&v1, &v2).unwrap();
489            assert_eq!(expected_cmp, actual_cmp);
490        }
491    }
492
493    #[test]
494    fn host_obj_discriminant_order() {
495        // The HostObject discriminants need to be ordered the same
496        // as the ScVal discriminants so that Compare<HostObject>
497        // produces the same results as `Ord for ScVal`,
498        // re https://github.com/stellar/rs-soroban-env/issues/743.
499        //
500        // This test creates pairs of corresponding ScVal/HostObjects,
501        // puts them all into a list, and sorts them 2 ways:
502        // comparing ScVals, and comparing the HostObject discriminants;
503        // then tests that the two lists are the same.
504
505        use crate::ScValObjRef;
506        use soroban_env_common::xdr;
507
508        let host = Host::default();
509
510        let xdr_vals = &[
511            ScVal::U64(u64::MAX),
512            ScVal::I64(i64::MAX),
513            ScVal::Timepoint(xdr::TimePoint(u64::MAX)),
514            ScVal::Duration(xdr::Duration(u64::MAX)),
515            ScVal::U128(xdr::UInt128Parts {
516                hi: u64::MAX,
517                lo: u64::MAX,
518            }),
519            ScVal::I128(xdr::Int128Parts {
520                hi: i64::MIN,
521                lo: u64::MAX,
522            }),
523            ScVal::U256(xdr::UInt256Parts {
524                hi_hi: u64::MAX,
525                hi_lo: u64::MAX,
526                lo_hi: u64::MAX,
527                lo_lo: u64::MAX,
528            }),
529            ScVal::I256(xdr::Int256Parts {
530                hi_hi: i64::MIN,
531                hi_lo: u64::MAX,
532                lo_hi: u64::MAX,
533                lo_lo: u64::MAX,
534            }),
535            ScVal::Bytes(xdr::ScBytes::try_from(vec![]).unwrap()),
536            ScVal::String(xdr::ScString::try_from(vec![]).unwrap()),
537            ScVal::Symbol(xdr::ScSymbol::try_from("very_big_symbol").unwrap()),
538            ScVal::Vec(Some(xdr::ScVec::try_from((0,)).unwrap())),
539            ScVal::Map(Some(xdr::ScMap::try_from(vec![]).unwrap())),
540            ScVal::Address(xdr::ScAddress::Contract(xdr::Hash([0; 32]))),
541        ];
542
543        let pairs: Vec<_> = xdr_vals
544            .into_iter()
545            .map(|xdr_val| {
546                let xdr_obj = ScValObjRef::classify(&xdr_val).unwrap();
547                let host_obj = host.to_host_obj(&xdr_obj).unwrap();
548                (xdr_obj, host_obj)
549            })
550            .collect();
551
552        let mut pairs_xdr_sorted = pairs.clone();
553        let mut pairs_host_sorted = pairs_xdr_sorted.clone();
554
555        pairs_xdr_sorted.sort_by(|&(v1, _), &(v2, _)| v1.cmp(&v2));
556
557        pairs_host_sorted.sort_by(|&(_, v1), &(_, v2)| {
558            host.visit_obj_untyped(v1, |v1| {
559                host.visit_obj_untyped(v2, |v2| {
560                    let v1d = host_obj_discriminant(v1);
561                    let v2d = host_obj_discriminant(v2);
562                    Ok(v1d.cmp(&v2d))
563                })
564            })
565            .unwrap()
566        });
567
568        let iter = pairs_xdr_sorted
569            .into_iter()
570            .zip(pairs_host_sorted.into_iter());
571
572        for ((xdr1, _), (xdr2, _)) in iter {
573            assert_eq!(xdr1, xdr2);
574        }
575    }
576
577    /// Test that comparison of an object of one type to a small value of another
578    /// type produces the same results as the equivalent ScVal comparison.
579    ///
580    /// This is a test of the Host::obj_cmp and Tag::get_scval_type methods.
581    ///
582    /// It works by generating an "example" Val for every possible tag,
583    /// with a match on Tag that ensures it will be updated as Tag changes.
584    ///
585    /// Those examples are then converted to an array of ScVal.
586    ///
587    /// For both arrays, every pairwise comparison is performed, and must be equal.
588    #[test]
589    fn compare_obj_to_small() {
590        let host = Host::default();
591        let vals: Vec<Val> = all_tags()
592            .into_iter()
593            .map(|t| example_for_tag(&host, t))
594            .collect();
595        let scvals: Vec<ScVal> = vals
596            .iter()
597            .map(|r| ScVal::try_from_val(&host, r).expect("scval"))
598            .collect();
599
600        let val_pairs = vals.iter().cartesian_product(&vals);
601        let scval_pairs = scvals.iter().cartesian_product(&scvals);
602
603        let pair_pairs = val_pairs.zip(scval_pairs);
604
605        for ((val1, val2), (scval1, scval2)) in pair_pairs {
606            let val_cmp = host.compare(val1, val2).expect("compare");
607            let scval_cmp = scval1.cmp(scval2);
608            assert_eq!(val_cmp, scval_cmp);
609        }
610    }
611
612    fn all_tags() -> Vec<Tag> {
613        (0_u8..=255)
614            .map(Tag::from_u8)
615            .filter(|t| {
616                // bad tags can't be converted to ScVal
617                !matches!(t, Tag::Bad)
618            })
619            .collect()
620    }
621
622    fn example_for_tag(host: &Host, tag: Tag) -> Val {
623        use crate::{xdr, Error};
624
625        let ex = match tag {
626            Tag::False => Val::from(false),
627            Tag::True => Val::from(true),
628            Tag::Void => Val::from(()),
629            Tag::Error => Val::from(Error::from_type_and_code(
630                ScErrorType::Context,
631                ScErrorCode::InternalError,
632            )),
633            Tag::U32Val => Val::from(u32::MAX),
634            Tag::I32Val => Val::from(i32::MAX),
635            Tag::U64Small => Val::try_from_val(host, &0_u64).unwrap(),
636            Tag::I64Small => Val::try_from_val(host, &0_i64).unwrap(),
637            Tag::TimepointSmall => {
638                Val::try_from_val(host, &ScVal::Timepoint(xdr::TimePoint(0))).unwrap()
639            }
640            Tag::DurationSmall => {
641                Val::try_from_val(host, &ScVal::Duration(xdr::Duration(0))).unwrap()
642            }
643            Tag::U128Small => Val::try_from_val(host, &0_u128).unwrap(),
644            Tag::I128Small => Val::try_from_val(host, &0_i128).unwrap(),
645            Tag::U256Small => Val::try_from_val(
646                host,
647                &ScVal::U256(xdr::UInt256Parts {
648                    hi_hi: 0,
649                    hi_lo: 0,
650                    lo_hi: 0,
651                    lo_lo: 0,
652                }),
653            )
654            .unwrap(),
655            Tag::I256Small => Val::try_from_val(
656                host,
657                &ScVal::I256(xdr::Int256Parts {
658                    hi_hi: 0,
659                    hi_lo: 0,
660                    lo_hi: 0,
661                    lo_lo: 0,
662                }),
663            )
664            .unwrap(),
665            Tag::SymbolSmall => {
666                Val::try_from_val(host, &ScVal::Symbol(xdr::ScSymbol::try_from("").unwrap()))
667                    .unwrap()
668            }
669            Tag::SmallCodeUpperBound => panic!(),
670            Tag::ObjectCodeLowerBound => panic!(),
671            Tag::U64Object => Val::try_from_val(host, &u64::MAX).unwrap(),
672            Tag::I64Object => Val::try_from_val(host, &i64::MAX).unwrap(),
673            Tag::TimepointObject => {
674                Val::try_from_val(host, &ScVal::Timepoint(xdr::TimePoint(u64::MAX))).unwrap()
675            }
676            Tag::DurationObject => {
677                Val::try_from_val(host, &ScVal::Duration(xdr::Duration(u64::MAX))).unwrap()
678            }
679            Tag::U128Object => Val::try_from_val(host, &u128::MAX).unwrap(),
680            Tag::I128Object => Val::try_from_val(host, &i128::MAX).unwrap(),
681            Tag::U256Object => Val::try_from_val(
682                host,
683                &ScVal::U256(xdr::UInt256Parts {
684                    hi_hi: u64::MAX,
685                    hi_lo: u64::MAX,
686                    lo_hi: u64::MAX,
687                    lo_lo: u64::MAX,
688                }),
689            )
690            .unwrap(),
691            Tag::I256Object => Val::try_from_val(
692                host,
693                &ScVal::I256(xdr::Int256Parts {
694                    hi_hi: i64::MIN,
695                    hi_lo: u64::MAX,
696                    lo_hi: u64::MAX,
697                    lo_lo: u64::MAX,
698                }),
699            )
700            .unwrap(),
701            Tag::BytesObject => Val::try_from_val(host, &vec![1]).unwrap(),
702            Tag::StringObject => Val::try_from_val(host, &"foo").unwrap(),
703            Tag::SymbolObject => Val::try_from_val(
704                host,
705                &ScVal::Symbol(xdr::ScSymbol::try_from("a_very_big_symbol").unwrap()),
706            )
707            .unwrap(),
708            Tag::VecObject => {
709                Val::try_from_val(host, &ScVal::Vec(Some(xdr::ScVec::try_from((0,)).unwrap())))
710                    .unwrap()
711            }
712            Tag::MapObject => Val::try_from_val(
713                host,
714                &ScVal::Map(Some(xdr::ScMap::try_from(vec![]).unwrap())),
715            )
716            .unwrap(),
717            Tag::AddressObject => Val::try_from_val(
718                host,
719                &ScVal::Address(xdr::ScAddress::Contract(xdr::Hash([0; 32]))),
720            )
721            .unwrap(),
722            Tag::ObjectCodeUpperBound => panic!(),
723            Tag::Bad => panic!(),
724            // NB: do not add a fallthrough case here if new Tag variants are added.
725            // this test depends on the match being exhaustive in order to ensure
726            // the correctness of Tag discriminants.
727        };
728
729        assert_eq!(ex.get_tag(), tag);
730
731        ex
732    }
733}