Skip to main content

pallas_codec/
utils.rs

1use minicbor::{
2    Decode, Encode,
3    data::{IanaTag, Tag, Type},
4    decode::Error,
5};
6use serde::{Deserialize, Serialize};
7use std::{borrow::Cow, str::FromStr};
8use std::{
9    collections::HashMap,
10    fmt,
11    hash::Hash as StdHash,
12    ops::{Deref, DerefMut},
13};
14
15static TAG_SET: u64 = 258;
16
17/// Utility for skipping parts of the CBOR payload, use only for debugging
18#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]
19pub struct SkipCbor<const N: usize> {}
20
21impl<'b, C, const N: usize> minicbor::Decode<'b, C> for SkipCbor<N> {
22    fn decode(
23        d: &mut minicbor::Decoder<'b>,
24        _ctx: &mut C,
25    ) -> Result<Self, minicbor::decode::Error> {
26        {
27            let probe = d.probe();
28            println!("skipped cbor value {N}: {:?}", probe.datatype()?);
29        }
30
31        d.skip()?;
32        Ok(SkipCbor {})
33    }
34}
35
36impl<C, const N: usize> minicbor::Encode<C> for SkipCbor<N> {
37    fn encode<W: minicbor::encode::Write>(
38        &self,
39        _e: &mut minicbor::Encoder<W>,
40        _ctx: &mut C,
41    ) -> Result<(), minicbor::encode::Error<W::Error>> {
42        todo!()
43    }
44}
45
46/// Custom collection to ensure ordered pairs of values
47///
48/// Since the ordering of the entries requires a particular order to maintain
49/// canonicalization for isomorphic decoding / encoding operators, we use a Vec
50/// as the underlaying struct for storage of the items (as opposed to a BTreeMap
51/// or HashMap).
52#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
53#[serde(from = "Vec::<(K, V)>", into = "Vec::<(K, V)>")]
54pub enum KeyValuePairs<K, V>
55where
56    K: Clone,
57    V: Clone,
58{
59    Def(Vec<(K, V)>),
60    Indef(Vec<(K, V)>),
61}
62
63impl<K, V> KeyValuePairs<K, V>
64where
65    K: Clone,
66    V: Clone,
67{
68    pub fn to_vec(self) -> Vec<(K, V)> {
69        self.into()
70    }
71}
72
73impl<K, V> FromIterator<(K, V)> for KeyValuePairs<K, V>
74where
75    K: Clone,
76    V: Clone,
77{
78    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
79        KeyValuePairs::Def(Vec::from_iter(iter))
80    }
81}
82
83impl<K, V> From<KeyValuePairs<K, V>> for Vec<(K, V)>
84where
85    K: Clone,
86    V: Clone,
87{
88    fn from(other: KeyValuePairs<K, V>) -> Self {
89        match other {
90            KeyValuePairs::Def(x) => x,
91            KeyValuePairs::Indef(x) => x,
92        }
93    }
94}
95
96impl<K, V> From<Vec<(K, V)>> for KeyValuePairs<K, V>
97where
98    K: Clone,
99    V: Clone,
100{
101    fn from(other: Vec<(K, V)>) -> Self {
102        KeyValuePairs::Def(other)
103    }
104}
105
106impl<K, V> From<KeyValuePairs<K, V>> for HashMap<K, V>
107where
108    K: Clone + Eq + std::hash::Hash,
109    V: Clone,
110{
111    fn from(other: KeyValuePairs<K, V>) -> Self {
112        match other {
113            KeyValuePairs::Def(x) => x.into_iter().collect(),
114            KeyValuePairs::Indef(x) => x.into_iter().collect(),
115        }
116    }
117}
118impl<K, V> From<HashMap<K, V>> for KeyValuePairs<K, V>
119where
120    K: Clone,
121    V: Clone,
122{
123    fn from(other: HashMap<K, V>) -> Self {
124        KeyValuePairs::Def(other.into_iter().collect())
125    }
126}
127
128impl<K, V> Deref for KeyValuePairs<K, V>
129where
130    K: Clone,
131    V: Clone,
132{
133    type Target = Vec<(K, V)>;
134
135    fn deref(&self) -> &Self::Target {
136        match self {
137            KeyValuePairs::Def(x) => x,
138            KeyValuePairs::Indef(x) => x,
139        }
140    }
141}
142
143impl<'b, C, K, V> minicbor::decode::Decode<'b, C> for KeyValuePairs<K, V>
144where
145    K: Decode<'b, C> + Clone,
146    V: Decode<'b, C> + Clone,
147{
148    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
149        let datatype = d.datatype()?;
150
151        let items: Result<Vec<_>, _> = d.map_iter_with::<C, K, V>(ctx)?.collect();
152        let items = items?;
153
154        match datatype {
155            minicbor::data::Type::Map => Ok(KeyValuePairs::Def(items)),
156            minicbor::data::Type::MapIndef => Ok(KeyValuePairs::Indef(items)),
157            _ => Err(minicbor::decode::Error::message(
158                "invalid data type for keyvaluepairs",
159            )),
160        }
161    }
162}
163
164impl<C, K, V> minicbor::encode::Encode<C> for KeyValuePairs<K, V>
165where
166    K: Encode<C> + Clone,
167    V: Encode<C> + Clone,
168{
169    fn encode<W: minicbor::encode::Write>(
170        &self,
171        e: &mut minicbor::Encoder<W>,
172        ctx: &mut C,
173    ) -> Result<(), minicbor::encode::Error<W::Error>> {
174        match self {
175            KeyValuePairs::Def(x) => {
176                e.map(x.len() as u64)?;
177
178                for (k, v) in x.iter() {
179                    k.encode(e, ctx)?;
180                    v.encode(e, ctx)?;
181                }
182            }
183            KeyValuePairs::Indef(x) => {
184                e.begin_map()?;
185
186                for (k, v) in x.iter() {
187                    k.encode(e, ctx)?;
188                    v.encode(e, ctx)?;
189                }
190
191                e.end()?;
192            }
193        }
194
195        Ok(())
196    }
197}
198
199/// Custom collection to ensure ordered pairs of values (non-empty)
200///
201/// Since the ordering of the entries requires a particular order to maintain
202/// canonicalization for isomorphic decoding / encoding operators, we use a Vec
203/// as the underlaying struct for storage of the items (as opposed to a BTreeMap
204/// or HashMap).
205#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
206#[serde(try_from = "Vec::<(K, V)>", into = "Vec::<(K, V)>")]
207pub enum NonEmptyKeyValuePairs<K, V>
208where
209    K: Clone,
210    V: Clone,
211{
212    Def(Vec<(K, V)>),
213    Indef(Vec<(K, V)>),
214}
215
216impl<K, V> IntoIterator for NonEmptyKeyValuePairs<K, V>
217where
218    K: Clone,
219    V: Clone,
220{
221    type Item = (K, V);
222    type IntoIter = std::vec::IntoIter<Self::Item>;
223
224    fn into_iter(self) -> Self::IntoIter {
225        match self {
226            NonEmptyKeyValuePairs::Def(pairs) => pairs.into_iter(),
227            NonEmptyKeyValuePairs::Indef(pairs) => pairs.into_iter(),
228        }
229    }
230}
231
232impl<K, V> NonEmptyKeyValuePairs<K, V>
233where
234    K: Clone,
235    V: Clone,
236{
237    pub fn to_vec(self) -> Vec<(K, V)> {
238        self.into()
239    }
240
241    pub fn from_vec(x: Vec<(K, V)>) -> Option<Self> {
242        if x.is_empty() {
243            None
244        } else {
245            Some(NonEmptyKeyValuePairs::Def(x))
246        }
247    }
248}
249
250impl<K, V> From<NonEmptyKeyValuePairs<K, V>> for Vec<(K, V)>
251where
252    K: Clone,
253    V: Clone,
254{
255    fn from(other: NonEmptyKeyValuePairs<K, V>) -> Self {
256        match other {
257            NonEmptyKeyValuePairs::Def(x) => x,
258            NonEmptyKeyValuePairs::Indef(x) => x,
259        }
260    }
261}
262
263impl<K, V> TryFrom<Vec<(K, V)>> for NonEmptyKeyValuePairs<K, V>
264where
265    K: Clone,
266    V: Clone,
267{
268    type Error = String;
269
270    fn try_from(value: Vec<(K, V)>) -> Result<Self, Self::Error> {
271        if value.is_empty() {
272            Err("NonEmptyKeyValuePairs must contain at least one element".into())
273        } else {
274            Ok(NonEmptyKeyValuePairs::Def(value))
275        }
276    }
277}
278
279impl<K, V> TryFrom<KeyValuePairs<K, V>> for NonEmptyKeyValuePairs<K, V>
280where
281    K: Clone,
282    V: Clone,
283{
284    type Error = String;
285
286    fn try_from(value: KeyValuePairs<K, V>) -> Result<Self, Self::Error> {
287        match value {
288            KeyValuePairs::Def(x) => {
289                if x.is_empty() {
290                    Err("NonEmptyKeyValuePairs must contain at least one element".into())
291                } else {
292                    Ok(NonEmptyKeyValuePairs::Def(x))
293                }
294            }
295            KeyValuePairs::Indef(x) => {
296                if x.is_empty() {
297                    Err("NonEmptyKeyValuePairs must contain at least one element".into())
298                } else {
299                    Ok(NonEmptyKeyValuePairs::Indef(x))
300                }
301            }
302        }
303    }
304}
305
306impl<K, V> Deref for NonEmptyKeyValuePairs<K, V>
307where
308    K: Clone,
309    V: Clone,
310{
311    type Target = Vec<(K, V)>;
312
313    fn deref(&self) -> &Self::Target {
314        match self {
315            NonEmptyKeyValuePairs::Def(x) => x,
316            NonEmptyKeyValuePairs::Indef(x) => x,
317        }
318    }
319}
320
321impl<'b, C, K, V> minicbor::decode::Decode<'b, C> for NonEmptyKeyValuePairs<K, V>
322where
323    K: Decode<'b, C> + Clone,
324    V: Decode<'b, C> + Clone,
325{
326    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
327        let datatype = d.datatype()?;
328
329        let items: Result<Vec<_>, _> = d.map_iter_with::<C, K, V>(ctx)?.collect();
330        let items = items?;
331
332        // if items.is_empty() {
333        //     return Err(Error::message(
334        //         "decoding empty map as NonEmptyKeyValuePairs",
335        //     ));
336        // }
337
338        match datatype {
339            minicbor::data::Type::Map => Ok(NonEmptyKeyValuePairs::Def(items)),
340            minicbor::data::Type::MapIndef => Ok(NonEmptyKeyValuePairs::Indef(items)),
341            _ => Err(minicbor::decode::Error::message(
342                "invalid data type for nonemptykeyvaluepairs",
343            )),
344        }
345    }
346}
347
348impl<C, K, V> minicbor::encode::Encode<C> for NonEmptyKeyValuePairs<K, V>
349where
350    K: Encode<C> + Clone,
351    V: Encode<C> + Clone,
352{
353    fn encode<W: minicbor::encode::Write>(
354        &self,
355        e: &mut minicbor::Encoder<W>,
356        ctx: &mut C,
357    ) -> Result<(), minicbor::encode::Error<W::Error>> {
358        match self {
359            NonEmptyKeyValuePairs::Def(x) => {
360                e.map(x.len() as u64)?;
361
362                for (k, v) in x.iter() {
363                    k.encode(e, ctx)?;
364                    v.encode(e, ctx)?;
365                }
366            }
367            NonEmptyKeyValuePairs::Indef(x) => {
368                e.begin_map()?;
369
370                for (k, v) in x.iter() {
371                    k.encode(e, ctx)?;
372                    v.encode(e, ctx)?;
373                }
374
375                e.end()?;
376            }
377        }
378
379        Ok(())
380    }
381}
382
383/// A struct that maintains a reference to whether a cbor array was indef or not
384#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
385pub enum MaybeIndefArray<A> {
386    Def(Vec<A>),
387    Indef(Vec<A>),
388}
389
390impl<A> MaybeIndefArray<A> {
391    pub fn to_vec(self) -> Vec<A> {
392        self.into()
393    }
394}
395
396impl<A> Deref for MaybeIndefArray<A> {
397    type Target = Vec<A>;
398
399    fn deref(&self) -> &Self::Target {
400        match self {
401            MaybeIndefArray::Def(x) => x,
402            MaybeIndefArray::Indef(x) => x,
403        }
404    }
405}
406
407impl<A> From<MaybeIndefArray<A>> for Vec<A> {
408    fn from(other: MaybeIndefArray<A>) -> Self {
409        match other {
410            MaybeIndefArray::Def(x) => x,
411            MaybeIndefArray::Indef(x) => x,
412        }
413    }
414}
415
416impl<'b, C, A> minicbor::decode::Decode<'b, C> for MaybeIndefArray<A>
417where
418    A: minicbor::decode::Decode<'b, C>,
419{
420    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
421        let datatype = d.datatype()?;
422
423        match datatype {
424            minicbor::data::Type::Array => Ok(Self::Def(d.decode_with(ctx)?)),
425            minicbor::data::Type::ArrayIndef => Ok(Self::Indef(d.decode_with(ctx)?)),
426            _ => Err(minicbor::decode::Error::message(
427                "unknown data type of maybe indef array",
428            )),
429        }
430    }
431}
432
433impl<C, A> minicbor::encode::Encode<C> for MaybeIndefArray<A>
434where
435    A: minicbor::encode::Encode<C>,
436{
437    fn encode<W: minicbor::encode::Write>(
438        &self,
439        e: &mut minicbor::Encoder<W>,
440        ctx: &mut C,
441    ) -> Result<(), minicbor::encode::Error<W::Error>> {
442        match self {
443            MaybeIndefArray::Def(x) => {
444                e.encode_with(x, ctx)?;
445            }
446            // TODO: this seemed necesary on alonzo, but breaks on byron. We need to double check.
447            //MaybeIndefArray::Indef(x) if x.is_empty() => {
448            //    e.encode(x)?;
449            //}
450            MaybeIndefArray::Indef(x) => {
451                e.begin_array()?;
452
453                for v in x.iter() {
454                    e.encode_with(v, ctx)?;
455                }
456
457                e.end()?;
458            }
459        };
460
461        Ok(())
462    }
463}
464
465/// Order-preserving set of attributes
466///
467/// There's no guarantee that the entries on a Cardano cbor entity that uses
468/// maps for its representation will follow the canonical order specified by the
469/// standard. To implement an isomorphic codec, we need a way of preserving the
470/// original order in which the entries were encoded. To acomplish this, we
471/// transform key-value structures into an orderer vec of `properties`, where
472/// each entry represents a a cbor-encodable variant of an attribute of the
473/// struct.
474#[derive(Debug, PartialEq, Eq, Clone, PartialOrd)]
475pub struct OrderPreservingProperties<P>(Vec<P>);
476
477impl<P> Deref for OrderPreservingProperties<P> {
478    type Target = Vec<P>;
479
480    fn deref(&self) -> &Self::Target {
481        &self.0
482    }
483}
484
485impl<P> From<Vec<P>> for OrderPreservingProperties<P> {
486    fn from(value: Vec<P>) -> Self {
487        OrderPreservingProperties(value)
488    }
489}
490
491impl<'b, C, P> minicbor::decode::Decode<'b, C> for OrderPreservingProperties<P>
492where
493    P: Decode<'b, C>,
494{
495    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
496        let len = d.map()?.unwrap_or_default();
497
498        let components: Result<_, _> = (0..len).map(|_| d.decode_with(ctx)).collect();
499
500        Ok(Self(components?))
501    }
502}
503
504impl<C, P> minicbor::encode::Encode<C> for OrderPreservingProperties<P>
505where
506    P: Encode<C>,
507{
508    fn encode<W: minicbor::encode::Write>(
509        &self,
510        e: &mut minicbor::Encoder<W>,
511        ctx: &mut C,
512    ) -> Result<(), minicbor::encode::Error<W::Error>> {
513        e.map(self.0.len() as u64)?;
514        for component in &self.0 {
515            e.encode_with(component, ctx)?;
516        }
517
518        Ok(())
519    }
520}
521
522/// Wraps a struct so that it is encoded/decoded as a cbor bytes
523#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, StdHash)]
524#[serde(transparent)]
525pub struct CborWrap<T>(pub T);
526
527impl<T> CborWrap<T> {
528    pub fn unwrap(self) -> T {
529        self.0
530    }
531}
532
533impl<'b, C, T> minicbor::Decode<'b, C> for CborWrap<T>
534where
535    T: minicbor::Decode<'b, C>,
536{
537    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
538        d.tag()?;
539        let cbor = d.bytes()?;
540        let wrapped = minicbor::decode_with(cbor, ctx)?;
541
542        Ok(CborWrap(wrapped))
543    }
544}
545
546impl<C, T> minicbor::Encode<C> for CborWrap<T>
547where
548    T: minicbor::Encode<C>,
549{
550    fn encode<W: minicbor::encode::Write>(
551        &self,
552        e: &mut minicbor::Encoder<W>,
553        ctx: &mut C,
554    ) -> Result<(), minicbor::encode::Error<W::Error>> {
555        let buf = minicbor::to_vec_with(&self.0, ctx).map_err(|_| {
556            minicbor::encode::Error::message("error encoding cbor-wrapped structure")
557        })?;
558
559        e.tag(IanaTag::Cbor)?;
560        e.bytes(&buf)?;
561
562        Ok(())
563    }
564}
565
566impl<T> Deref for CborWrap<T> {
567    type Target = T;
568
569    fn deref(&self) -> &Self::Target {
570        &self.0
571    }
572}
573
574#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
575pub struct TagWrap<I, const T: u64>(pub I);
576
577impl<I, const T: u64> TagWrap<I, T> {
578    pub fn new(inner: I) -> Self {
579        TagWrap(inner)
580    }
581}
582
583impl<I, const T: u64> From<I> for TagWrap<I, T> {
584    fn from(inner: I) -> Self {
585        TagWrap(inner)
586    }
587}
588
589impl<'b, C, I, const T: u64> minicbor::Decode<'b, C> for TagWrap<I, T>
590where
591    I: minicbor::Decode<'b, C>,
592{
593    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
594        d.tag()?;
595
596        Ok(TagWrap(d.decode_with(ctx)?))
597    }
598}
599
600impl<C, I, const T: u64> minicbor::Encode<C> for TagWrap<I, T>
601where
602    I: minicbor::Encode<C>,
603{
604    fn encode<W: minicbor::encode::Write>(
605        &self,
606        e: &mut minicbor::Encoder<W>,
607        ctx: &mut C,
608    ) -> Result<(), minicbor::encode::Error<W::Error>> {
609        e.tag(Tag::new(T))?;
610        e.encode_with(&self.0, ctx)?;
611
612        Ok(())
613    }
614}
615
616impl<I, const T: u64> Deref for TagWrap<I, T> {
617    type Target = I;
618
619    fn deref(&self) -> &Self::Target {
620        &self.0
621    }
622}
623
624/// An empty map
625///
626/// don't ask me why, that's what the CDDL asks for.
627#[derive(Debug, Clone, PartialEq, Eq)]
628pub struct EmptyMap;
629
630impl<'b, C> minicbor::decode::Decode<'b, C> for EmptyMap {
631    fn decode(
632        d: &mut minicbor::Decoder<'b>,
633        _ctx: &mut C,
634    ) -> Result<Self, minicbor::decode::Error> {
635        d.skip()?;
636        Ok(EmptyMap)
637    }
638}
639
640impl<C> minicbor::encode::Encode<C> for EmptyMap {
641    fn encode<W: minicbor::encode::Write>(
642        &self,
643        e: &mut minicbor::Encoder<W>,
644        _ctx: &mut C,
645    ) -> Result<(), minicbor::encode::Error<W::Error>> {
646        e.map(0)?;
647
648        Ok(())
649    }
650}
651
652/// An array with zero or one elements
653///
654/// A common pattern seen in the CDDL is to represent optional values as an
655/// array containing zero or more items. This structure reflects that pattern
656/// while providing semantic meaning.
657#[derive(Debug, Clone)]
658pub struct ZeroOrOneArray<T>(Option<T>);
659
660impl<T> Deref for ZeroOrOneArray<T> {
661    type Target = Option<T>;
662
663    fn deref(&self) -> &Self::Target {
664        &self.0
665    }
666}
667
668impl<'b, C, T> minicbor::decode::Decode<'b, C> for ZeroOrOneArray<T>
669where
670    T: Decode<'b, C>,
671{
672    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
673        let len = d.array()?;
674
675        match len {
676            Some(0) => Ok(ZeroOrOneArray(None)),
677            Some(1) => Ok(ZeroOrOneArray(Some(d.decode_with(ctx)?))),
678            Some(_) => Err(minicbor::decode::Error::message(
679                "found invalid len for zero-or-one pattern",
680            )),
681            None => Err(minicbor::decode::Error::message(
682                "found invalid indefinite len array for zero-or-one pattern",
683            )),
684        }
685    }
686}
687
688impl<C, T> minicbor::encode::Encode<C> for ZeroOrOneArray<T>
689where
690    T: minicbor::Encode<C>,
691{
692    fn encode<W: minicbor::encode::Write>(
693        &self,
694        e: &mut minicbor::Encoder<W>,
695        ctx: &mut C,
696    ) -> Result<(), minicbor::encode::Error<W::Error>> {
697        match &self.0 {
698            Some(x) => {
699                e.array(1)?;
700                e.encode_with(x, ctx)?;
701            }
702            None => {
703                e.array(0)?;
704            }
705        }
706
707        Ok(())
708    }
709}
710
711/// Set
712///
713/// Optional 258 tag (until era after Conway, at which point is it required)
714/// with a vec of items which should contain no duplicates
715#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Serialize, Deserialize)]
716pub struct Set<T>(Vec<T>);
717
718impl<T> Set<T> {
719    pub fn to_vec(self) -> Vec<T> {
720        self.0
721    }
722}
723
724impl<T> Deref for Set<T> {
725    type Target = Vec<T>;
726
727    fn deref(&self) -> &Self::Target {
728        &self.0
729    }
730}
731
732impl<T> From<Vec<T>> for Set<T> {
733    fn from(value: Vec<T>) -> Self {
734        Set(value)
735    }
736}
737
738impl<T> From<Set<KeepRaw<'_, T>>> for Set<T> {
739    fn from(value: Set<KeepRaw<'_, T>>) -> Self {
740        let inner = value.0.into_iter().map(|x| x.unwrap()).collect();
741        Self(inner)
742    }
743}
744
745impl<'a, T> IntoIterator for &'a Set<T> {
746    type Item = &'a T;
747    type IntoIter = std::slice::Iter<'a, T>;
748
749    fn into_iter(self) -> Self::IntoIter {
750        self.0.iter()
751    }
752}
753
754impl<'b, C, T> minicbor::decode::Decode<'b, C> for Set<T>
755where
756    T: Decode<'b, C>,
757{
758    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
759        // decode optional set tag (this will be required in era following Conway)
760        if d.datatype()? == Type::Tag {
761            let found_tag = d.tag()?;
762
763            if found_tag != Tag::new(TAG_SET) {
764                return Err(Error::message(format!("Unrecognised tag: {found_tag:?}")));
765            }
766        }
767
768        Ok(Self(d.decode_with(ctx)?))
769    }
770}
771
772impl<C, T> minicbor::encode::Encode<C> for Set<T>
773where
774    T: Encode<C>,
775{
776    fn encode<W: minicbor::encode::Write>(
777        &self,
778        e: &mut minicbor::Encoder<W>,
779        ctx: &mut C,
780    ) -> Result<(), minicbor::encode::Error<W::Error>> {
781        e.tag(Tag::new(TAG_SET))?;
782        e.encode_with(&self.0, ctx)?;
783
784        Ok(())
785    }
786}
787
788/// Non-empty Set
789///
790/// Optional 258 tag (until era after Conway, at which point is it required)
791/// with a vec of items which should contain no duplicates
792#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Serialize, Deserialize)]
793pub struct NonEmptySet<T>(Vec<T>);
794
795impl<T> NonEmptySet<T> {
796    pub fn to_vec(self) -> Vec<T> {
797        self.0
798    }
799
800    pub fn from_vec(x: Vec<T>) -> Option<Self> {
801        if x.is_empty() { None } else { Some(Self(x)) }
802    }
803}
804
805impl<T> Deref for NonEmptySet<T> {
806    type Target = Vec<T>;
807
808    fn deref(&self) -> &Self::Target {
809        &self.0
810    }
811}
812
813impl<T> TryFrom<Vec<T>> for NonEmptySet<T> {
814    type Error = Vec<T>;
815
816    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
817        if value.is_empty() {
818            Err(value)
819        } else {
820            Ok(NonEmptySet(value))
821        }
822    }
823}
824
825impl<T> From<NonEmptySet<KeepRaw<'_, T>>> for NonEmptySet<T> {
826    fn from(value: NonEmptySet<KeepRaw<'_, T>>) -> Self {
827        let inner = value.0.into_iter().map(|x| x.unwrap()).collect();
828        Self(inner)
829    }
830}
831
832impl<'a, T> IntoIterator for &'a NonEmptySet<T> {
833    type Item = &'a T;
834    type IntoIter = std::slice::Iter<'a, T>;
835
836    fn into_iter(self) -> Self::IntoIter {
837        self.0.iter()
838    }
839}
840
841impl<'b, C, T> minicbor::decode::Decode<'b, C> for NonEmptySet<T>
842where
843    T: Decode<'b, C>,
844{
845    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
846        // decode optional set tag (this will be required in era following Conway)
847        if d.datatype()? == Type::Tag {
848            let found_tag = d.tag()?;
849
850            if found_tag != Tag::new(TAG_SET) {
851                return Err(Error::message(format!("Unrecognised tag: {found_tag:?}")));
852            }
853        }
854
855        let inner: Vec<T> = d.decode_with(ctx)?;
856
857        // if inner.is_empty() {
858        //     return Err(Error::message("decoding empty set as NonEmptySet"));
859        // }
860
861        Ok(Self(inner))
862    }
863}
864
865impl<C, T> minicbor::encode::Encode<C> for NonEmptySet<T>
866where
867    T: Encode<C>,
868{
869    fn encode<W: minicbor::encode::Write>(
870        &self,
871        e: &mut minicbor::Encoder<W>,
872        ctx: &mut C,
873    ) -> Result<(), minicbor::encode::Error<W::Error>> {
874        e.tag(Tag::new(TAG_SET))?;
875        e.encode_with(&self.0, ctx)?;
876
877        Ok(())
878    }
879}
880
881/// A uint structure that preserves original int length
882#[derive(Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash)]
883pub enum AnyUInt {
884    MajorByte(u8),
885    U8(u8),
886    U16(u16),
887    U32(u32),
888    U64(u64),
889}
890
891impl<'b, C> minicbor::decode::Decode<'b, C> for AnyUInt {
892    fn decode(
893        d: &mut minicbor::Decoder<'b>,
894        _ctx: &mut C,
895    ) -> Result<Self, minicbor::decode::Error> {
896        let data_type = d.datatype()?;
897
898        use minicbor::data::Type::*;
899        match data_type {
900            U8 => match d.u8()? {
901                x @ 0..=0x17 => Ok(AnyUInt::MajorByte(x)),
902                x @ 0x18..=0xff => Ok(AnyUInt::U8(x)),
903            },
904            U16 => Ok(AnyUInt::U16(d.u16()?)),
905            U32 => Ok(AnyUInt::U32(d.u32()?)),
906            U64 => Ok(AnyUInt::U64(d.u64()?)),
907            _ => Err(minicbor::decode::Error::message(format!(
908                "invalid data type for AnyUInt at position {}: {}",
909                d.position(),
910                data_type
911            ))),
912        }
913    }
914}
915
916impl<C> minicbor::encode::Encode<C> for AnyUInt {
917    fn encode<W: minicbor::encode::Write>(
918        &self,
919        e: &mut minicbor::Encoder<W>,
920        _ctx: &mut C,
921    ) -> Result<(), minicbor::encode::Error<W::Error>> {
922        match self {
923            AnyUInt::MajorByte(x) => {
924                let b = &x.to_be_bytes()[..];
925
926                e.writer_mut()
927                    .write_all(b)
928                    .map_err(minicbor::encode::Error::write)?;
929
930                Ok(())
931            }
932            AnyUInt::U8(x) => {
933                let x = x.to_be_bytes();
934                let b = &[[24u8], x].concat()[..];
935
936                e.writer_mut()
937                    .write_all(b)
938                    .map_err(minicbor::encode::Error::write)?;
939
940                Ok(())
941            }
942            AnyUInt::U16(x) => {
943                let x = &x.to_be_bytes()[..];
944                let b = &[&[25u8], x].concat()[..];
945
946                e.writer_mut()
947                    .write_all(b)
948                    .map_err(minicbor::encode::Error::write)?;
949
950                Ok(())
951            }
952            AnyUInt::U32(x) => {
953                let x = &x.to_be_bytes()[..];
954                let b = &[&[26u8], x].concat()[..];
955
956                e.writer_mut()
957                    .write_all(b)
958                    .map_err(minicbor::encode::Error::write)?;
959
960                Ok(())
961            }
962            AnyUInt::U64(x) => {
963                let x = &x.to_be_bytes()[..];
964                let b = &[&[27u8], x].concat()[..];
965
966                e.writer_mut()
967                    .write_all(b)
968                    .map_err(minicbor::encode::Error::write)?;
969
970                Ok(())
971            }
972        }
973    }
974}
975
976impl From<AnyUInt> for u64 {
977    fn from(x: AnyUInt) -> Self {
978        match x {
979            AnyUInt::MajorByte(x) => x as u64,
980            AnyUInt::U8(x) => x as u64,
981            AnyUInt::U16(x) => x as u64,
982            AnyUInt::U32(x) => x as u64,
983            AnyUInt::U64(x) => x,
984        }
985    }
986}
987
988impl From<&AnyUInt> for u64 {
989    fn from(x: &AnyUInt) -> Self {
990        u64::from(*x)
991    }
992}
993
994/// Introduced in Conway
995/// positive_coin = 1 .. 18446744073709551615
996#[derive(
997    Encode, Decode, Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize,
998)]
999#[serde(transparent)]
1000#[cbor(transparent)]
1001pub struct PositiveCoin(u64);
1002
1003impl TryFrom<u64> for PositiveCoin {
1004    type Error = u64;
1005
1006    fn try_from(value: u64) -> Result<Self, Self::Error> {
1007        if value == 0 {
1008            return Err(value);
1009        }
1010
1011        Ok(Self(value))
1012    }
1013}
1014
1015impl From<PositiveCoin> for u64 {
1016    fn from(value: PositiveCoin) -> Self {
1017        value.0
1018    }
1019}
1020
1021impl From<&PositiveCoin> for u64 {
1022    fn from(x: &PositiveCoin) -> Self {
1023        u64::from(*x)
1024    }
1025}
1026
1027/// Introduced in Conway
1028/// negInt64 = -9223372036854775808 .. -1
1029/// posInt64 = 1 .. 9223372036854775807
1030/// nonZeroInt64 = negInt64 / posInt64 ; this is the same as the current int64
1031/// definition but without zero
1032#[derive(Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
1033#[serde(transparent)]
1034pub struct NonZeroInt(i64);
1035
1036impl TryFrom<i64> for NonZeroInt {
1037    type Error = i64;
1038
1039    fn try_from(value: i64) -> Result<Self, Self::Error> {
1040        if value == 0 {
1041            return Err(value);
1042        }
1043
1044        Ok(Self(value))
1045    }
1046}
1047
1048impl From<NonZeroInt> for i64 {
1049    fn from(value: NonZeroInt) -> Self {
1050        value.0
1051    }
1052}
1053
1054impl From<&NonZeroInt> for i64 {
1055    fn from(x: &NonZeroInt) -> Self {
1056        i64::from(*x)
1057    }
1058}
1059
1060impl<'b, C> minicbor::decode::Decode<'b, C> for NonZeroInt {
1061    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1062        let n = d.decode_with(ctx)?;
1063
1064        if n == 0 {
1065            return Err(Error::message("decoding 0 as NonZeroInt"));
1066        }
1067
1068        Ok(Self(n))
1069    }
1070}
1071
1072impl<C> minicbor::encode::Encode<C> for NonZeroInt {
1073    fn encode<W: minicbor::encode::Write>(
1074        &self,
1075        e: &mut minicbor::Encoder<W>,
1076        _ctx: &mut C,
1077    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1078        e.encode(self.0)?;
1079
1080        Ok(())
1081    }
1082}
1083
1084/// Decodes a struct while preserving original CBOR
1085///
1086/// # Examples
1087///
1088/// ```
1089/// use pallas_codec::utils::KeepRaw;
1090///
1091/// let a = (123u16, (456u16, 789u16), 123u16);
1092/// let data = minicbor::to_vec(a).unwrap();
1093///
1094/// let (_, keeper, _): (u16, KeepRaw<(u16, u16)>, u16) = minicbor::decode(&data).unwrap();
1095/// let confirm: (u16, u16) = minicbor::decode(keeper.raw_cbor()).unwrap();
1096/// assert_eq!(confirm, (456u16, 789u16));
1097/// ```
1098#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
1099pub struct KeepRaw<'b, T> {
1100    raw: Cow<'b, [u8]>,
1101    inner: T,
1102}
1103
1104impl<T> KeepRaw<'_, T> {
1105    pub fn raw_cbor(&self) -> &[u8] {
1106        &self.raw
1107    }
1108
1109    pub fn unwrap(self) -> T {
1110        self.inner
1111    }
1112
1113    pub fn clear_raw(&mut self) {
1114        self.raw = Cow::from(vec![]);
1115    }
1116
1117    pub fn to_owned(self) -> KeepRaw<'static, T> {
1118        KeepRaw {
1119            raw: Cow::Owned(self.raw.into_owned()),
1120            inner: self.inner,
1121        }
1122    }
1123}
1124
1125impl<T> Deref for KeepRaw<'_, T> {
1126    type Target = T;
1127
1128    fn deref(&self) -> &Self::Target {
1129        &self.inner
1130    }
1131}
1132
1133impl<T> DerefMut for KeepRaw<'_, T> {
1134    fn deref_mut(&mut self) -> &mut Self::Target {
1135        // If the inner value is mutated, we need to clear the raw bytes to
1136        // avoid returning stale data.
1137        self.clear_raw();
1138
1139        &mut self.inner
1140    }
1141}
1142
1143impl<T> From<T> for KeepRaw<'static, T> {
1144    /// Note that the `KeepRaw` value obtained from this implementation does
1145    /// **not** include a valid CBOR representation.
1146    fn from(val: T) -> Self {
1147        Self {
1148            raw: Cow::from(vec![]),
1149            inner: val,
1150        }
1151    }
1152}
1153
1154impl<'b, T, C> minicbor::Decode<'b, C> for KeepRaw<'b, T>
1155where
1156    T: minicbor::Decode<'b, C>,
1157{
1158    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1159        let all = d.input();
1160        let start = d.position();
1161        let inner: T = d.decode_with(ctx)?;
1162        let end = d.position();
1163
1164        Ok(Self {
1165            inner,
1166            raw: Cow::Borrowed(&all[start..end]),
1167        })
1168    }
1169}
1170
1171impl<C, T> minicbor::Encode<C> for KeepRaw<'_, T>
1172where
1173    T: minicbor::Encode<C>,
1174{
1175    fn encode<W: minicbor::encode::Write>(
1176        &self,
1177        e: &mut minicbor::Encoder<W>,
1178        ctx: &mut C,
1179    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1180        if self.raw_cbor().is_empty() {
1181            e.encode_with(&self.inner, ctx)?;
1182            Ok(())
1183        } else {
1184            e.writer_mut()
1185                .write_all(self.raw_cbor())
1186                .map_err(minicbor::encode::Error::write)
1187        }
1188    }
1189}
1190
1191impl<T: Serialize> Serialize for KeepRaw<'_, T> {
1192    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1193    where
1194        S: serde::Serializer,
1195    {
1196        self.deref().serialize(serializer)
1197    }
1198}
1199
1200impl<'de, T: Deserialize<'de>> Deserialize<'de> for KeepRaw<'_, T> {
1201    /// Note that the `KeepRaw` value obtained from this implementation does
1202    /// **not** include a valid CBOR representation.
1203    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1204    where
1205        D: serde::Deserializer<'de>,
1206    {
1207        let inner: T = T::deserialize(deserializer)?;
1208
1209        Ok(Self {
1210            inner,
1211            raw: Cow::from(vec![]),
1212        })
1213    }
1214}
1215
1216/// Struct to hold arbitrary CBOR to be processed independently
1217///
1218/// # Examples
1219///
1220/// ```
1221/// use pallas_codec::utils::AnyCbor;
1222///
1223/// let a = (123u16, (456u16, 789u16), 123u16);
1224/// let data = minicbor::to_vec(a).unwrap();
1225///
1226/// let (_, any, _): (u16, AnyCbor, u16) = minicbor::decode(&data).unwrap();
1227/// let confirm: (u16, u16) = any.into_decode().unwrap();
1228/// assert_eq!(confirm, (456u16, 789u16));
1229/// ```
1230#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
1231pub struct AnyCbor {
1232    inner: Vec<u8>,
1233}
1234
1235impl AnyCbor {
1236    pub fn raw_bytes(&self) -> &[u8] {
1237        &self.inner
1238    }
1239
1240    pub fn unwrap(self) -> Vec<u8> {
1241        self.inner
1242    }
1243
1244    pub fn from_encode<T>(other: T) -> Self
1245    where
1246        T: Encode<()>,
1247    {
1248        let inner = minicbor::to_vec(other).unwrap();
1249        Self { inner }
1250    }
1251
1252    pub fn into_decode<T>(self) -> Result<T, minicbor::decode::Error>
1253    where
1254        for<'b> T: Decode<'b, ()>,
1255    {
1256        minicbor::decode(&self.inner)
1257    }
1258}
1259
1260impl Deref for AnyCbor {
1261    type Target = Vec<u8>;
1262
1263    fn deref(&self) -> &Self::Target {
1264        &self.inner
1265    }
1266}
1267
1268impl<'b, C> minicbor::Decode<'b, C> for AnyCbor {
1269    fn decode(
1270        d: &mut minicbor::Decoder<'b>,
1271        _ctx: &mut C,
1272    ) -> Result<Self, minicbor::decode::Error> {
1273        let all = d.input();
1274        let start = d.position();
1275        d.skip()?;
1276        let end = d.position();
1277
1278        Ok(Self {
1279            inner: Vec::from(&all[start..end]),
1280        })
1281    }
1282}
1283
1284impl<C> minicbor::Encode<C> for AnyCbor {
1285    fn encode<W: minicbor::encode::Write>(
1286        &self,
1287        e: &mut minicbor::Encoder<W>,
1288        _ctx: &mut C,
1289    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1290        e.writer_mut()
1291            .write_all(self.raw_bytes())
1292            .map_err(minicbor::encode::Error::write)
1293    }
1294}
1295
1296#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
1297#[serde(from = "Option::<T>", into = "Option::<T>")]
1298pub enum Nullable<T>
1299where
1300    T: std::clone::Clone,
1301{
1302    Some(T),
1303    Null,
1304    Undefined,
1305}
1306
1307impl<T> Nullable<T>
1308where
1309    T: std::clone::Clone,
1310{
1311    pub fn map<F, O>(self, f: F) -> Nullable<O>
1312    where
1313        O: std::clone::Clone,
1314        F: Fn(T) -> O,
1315    {
1316        match self {
1317            Nullable::Some(x) => Nullable::Some(f(x)),
1318            Nullable::Null => Nullable::Null,
1319            Nullable::Undefined => Nullable::Undefined,
1320        }
1321    }
1322
1323    pub fn as_ref(&self) -> Nullable<&T> {
1324        match self {
1325            Nullable::Some(x) => Nullable::Some(x),
1326            Nullable::Null => Nullable::Null,
1327            Nullable::Undefined => Nullable::Undefined,
1328        }
1329    }
1330}
1331
1332impl<'b, C, T> minicbor::Decode<'b, C> for Nullable<T>
1333where
1334    T: minicbor::Decode<'b, C> + std::clone::Clone,
1335{
1336    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1337        match d.datatype()? {
1338            minicbor::data::Type::Null => {
1339                d.null()?;
1340                Ok(Self::Null)
1341            }
1342            minicbor::data::Type::Undefined => {
1343                d.undefined()?;
1344                Ok(Self::Undefined)
1345            }
1346            _ => {
1347                let x = d.decode_with(ctx)?;
1348                Ok(Self::Some(x))
1349            }
1350        }
1351    }
1352}
1353
1354impl<C, T> minicbor::Encode<C> for Nullable<T>
1355where
1356    T: minicbor::Encode<C> + std::clone::Clone,
1357{
1358    fn encode<W: minicbor::encode::Write>(
1359        &self,
1360        e: &mut minicbor::Encoder<W>,
1361        ctx: &mut C,
1362    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1363        match self {
1364            Nullable::Some(x) => {
1365                e.encode_with(x, ctx)?;
1366                Ok(())
1367            }
1368            Nullable::Null => {
1369                e.null()?;
1370                Ok(())
1371            }
1372            Nullable::Undefined => {
1373                e.undefined()?;
1374                Ok(())
1375            }
1376        }
1377    }
1378}
1379
1380impl<T> From<Option<T>> for Nullable<T>
1381where
1382    T: std::clone::Clone,
1383{
1384    fn from(x: Option<T>) -> Self {
1385        match x {
1386            Some(x) => Nullable::Some(x),
1387            None => Nullable::Null,
1388        }
1389    }
1390}
1391
1392impl<T> From<Nullable<T>> for Option<T>
1393where
1394    T: std::clone::Clone,
1395{
1396    fn from(other: Nullable<T>) -> Self {
1397        match other {
1398            Nullable::Some(x) => Some(x),
1399            _ => None,
1400        }
1401    }
1402}
1403
1404#[derive(
1405    Serialize, Deserialize, Clone, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1406)]
1407#[cbor(transparent)]
1408#[serde(into = "String")]
1409#[serde(try_from = "String")]
1410pub struct Bytes(#[n(0)] minicbor::bytes::ByteVec);
1411
1412impl From<Vec<u8>> for Bytes {
1413    fn from(xs: Vec<u8>) -> Self {
1414        Bytes(minicbor::bytes::ByteVec::from(xs))
1415    }
1416}
1417
1418impl From<Bytes> for Vec<u8> {
1419    fn from(b: Bytes) -> Self {
1420        b.0.into()
1421    }
1422}
1423
1424impl Deref for Bytes {
1425    type Target = Vec<u8>;
1426
1427    fn deref(&self) -> &Self::Target {
1428        self.0.deref()
1429    }
1430}
1431
1432impl<const N: usize> TryFrom<&Bytes> for [u8; N] {
1433    type Error = core::array::TryFromSliceError;
1434
1435    fn try_from(value: &Bytes) -> Result<Self, Self::Error> {
1436        value.0.as_slice().try_into()
1437    }
1438}
1439
1440impl TryFrom<String> for Bytes {
1441    type Error = hex::FromHexError;
1442
1443    fn try_from(value: String) -> Result<Self, Self::Error> {
1444        let v = hex::decode(value)?;
1445        Ok(Bytes(minicbor::bytes::ByteVec::from(v)))
1446    }
1447}
1448
1449impl FromStr for Bytes {
1450    type Err = hex::FromHexError;
1451
1452    fn from_str(s: &str) -> Result<Self, Self::Err> {
1453        let v = hex::decode(s)?;
1454        Ok(Bytes(minicbor::bytes::ByteVec::from(v)))
1455    }
1456}
1457
1458impl From<Bytes> for String {
1459    fn from(b: Bytes) -> Self {
1460        hex::encode(b.deref())
1461    }
1462}
1463
1464impl fmt::Display for Bytes {
1465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466        let bytes: Vec<u8> = self.clone().into();
1467
1468        f.write_str(&hex::encode(bytes))
1469    }
1470}
1471
1472#[derive(
1473    Serialize, Deserialize, Clone, Copy, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1474)]
1475#[cbor(transparent)]
1476#[serde(into = "i128")]
1477#[serde(try_from = "i128")]
1478pub struct Int(#[n(0)] pub minicbor::data::Int);
1479
1480impl Deref for Int {
1481    type Target = minicbor::data::Int;
1482
1483    fn deref(&self) -> &Self::Target {
1484        &self.0
1485    }
1486}
1487
1488impl From<Int> for i128 {
1489    fn from(value: Int) -> Self {
1490        i128::from(value.0)
1491    }
1492}
1493
1494impl From<i32> for Int {
1495    fn from(x: i32) -> Self {
1496        let inner = minicbor::data::Int::from(x);
1497        Self(inner)
1498    }
1499}
1500
1501impl From<i64> for Int {
1502    fn from(x: i64) -> Self {
1503        let inner = minicbor::data::Int::from(x);
1504        Self(inner)
1505    }
1506}
1507
1508impl TryFrom<i128> for Int {
1509    type Error = minicbor::data::TryFromIntError;
1510
1511    fn try_from(value: i128) -> Result<Self, Self::Error> {
1512        let inner = minicbor::data::Int::try_from(value)?;
1513        Ok(Self(inner))
1514    }
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519    use super::*;
1520
1521    #[test]
1522    fn keep_raw_retains_original() {
1523        // Indef array info is lost when decoded. By using KeepRaw, we can retain the
1524        // original bytes. This test makes sure KeepRaw is working by making use of this
1525        // well-known CBOR nuance.
1526
1527        let raw = hex::decode("9F0102FF").unwrap();
1528        let subject: KeepRaw<'_, Vec<u32>> = minicbor::decode(&raw).unwrap();
1529        assert_eq!(subject.inner, vec![1, 2]);
1530        assert_eq!(subject.raw_cbor(), raw);
1531    }
1532
1533    #[test]
1534    fn keep_raw_fallbacks_to_encode() {
1535        // By using the From trait we can encode the inner value directly without any
1536        // information about the original cbor bytes. By attempting to encode this
1537        // structure we ensure that KeepRaw is falling back to the expected encode
1538        // behavior.
1539
1540        let subject = KeepRaw::from(vec![1, 2]);
1541        let encoded = minicbor::to_vec(&subject).unwrap();
1542
1543        assert_eq!(encoded, hex::decode("820102").unwrap());
1544    }
1545
1546    #[test]
1547    fn keep_raw_clears_original_when_mutated() {
1548        // If the inner value is mutated, we need to clear the raw bytes to
1549        // avoid returning stale data. This test starts from raw bytes, mutates the
1550        // value and then asserts that the returned cbor matches the updates.
1551
1552        let raw = hex::decode("9F0102FF").unwrap();
1553        let mut subject: KeepRaw<'_, Vec<u32>> = minicbor::decode(&raw).unwrap();
1554
1555        let inner = subject.deref_mut();
1556        inner.push(3);
1557
1558        let encoded = minicbor::to_vec(&subject).unwrap();
1559
1560        assert_eq!(subject.inner, vec![1, 2, 3]);
1561        assert_eq!(encoded, hex::decode("83010203").unwrap());
1562    }
1563}