pallas_codec/
utils.rs

1use minicbor::{
2    data::{IanaTag, Tag, Type},
3    decode::Error,
4    Decode, Encode,
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() {
802            None
803        } else {
804            Some(Self(x))
805        }
806    }
807}
808
809impl<T> Deref for NonEmptySet<T> {
810    type Target = Vec<T>;
811
812    fn deref(&self) -> &Self::Target {
813        &self.0
814    }
815}
816
817impl<T> TryFrom<Vec<T>> for NonEmptySet<T> {
818    type Error = Vec<T>;
819
820    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
821        if value.is_empty() {
822            Err(value)
823        } else {
824            Ok(NonEmptySet(value))
825        }
826    }
827}
828
829impl<T> From<NonEmptySet<KeepRaw<'_, T>>> for NonEmptySet<T> {
830    fn from(value: NonEmptySet<KeepRaw<'_, T>>) -> Self {
831        let inner = value.0.into_iter().map(|x| x.unwrap()).collect();
832        Self(inner)
833    }
834}
835
836impl<'a, T> IntoIterator for &'a NonEmptySet<T> {
837    type Item = &'a T;
838    type IntoIter = std::slice::Iter<'a, T>;
839
840    fn into_iter(self) -> Self::IntoIter {
841        self.0.iter()
842    }
843}
844
845impl<'b, C, T> minicbor::decode::Decode<'b, C> for NonEmptySet<T>
846where
847    T: Decode<'b, C>,
848{
849    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
850        // decode optional set tag (this will be required in era following Conway)
851        if d.datatype()? == Type::Tag {
852            let found_tag = d.tag()?;
853
854            if found_tag != Tag::new(TAG_SET) {
855                return Err(Error::message(format!("Unrecognised tag: {found_tag:?}")));
856            }
857        }
858
859        let inner: Vec<T> = d.decode_with(ctx)?;
860
861        // if inner.is_empty() {
862        //     return Err(Error::message("decoding empty set as NonEmptySet"));
863        // }
864
865        Ok(Self(inner))
866    }
867}
868
869impl<C, T> minicbor::encode::Encode<C> for NonEmptySet<T>
870where
871    T: Encode<C>,
872{
873    fn encode<W: minicbor::encode::Write>(
874        &self,
875        e: &mut minicbor::Encoder<W>,
876        ctx: &mut C,
877    ) -> Result<(), minicbor::encode::Error<W::Error>> {
878        e.tag(Tag::new(TAG_SET))?;
879        e.encode_with(&self.0, ctx)?;
880
881        Ok(())
882    }
883}
884
885/// A uint structure that preserves original int length
886#[derive(Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash)]
887pub enum AnyUInt {
888    MajorByte(u8),
889    U8(u8),
890    U16(u16),
891    U32(u32),
892    U64(u64),
893}
894
895impl<'b, C> minicbor::decode::Decode<'b, C> for AnyUInt {
896    fn decode(
897        d: &mut minicbor::Decoder<'b>,
898        _ctx: &mut C,
899    ) -> Result<Self, minicbor::decode::Error> {
900        let data_type = d.datatype()?;
901
902        use minicbor::data::Type::*;
903        match data_type {
904            U8 => match d.u8()? {
905                x @ 0..=0x17 => Ok(AnyUInt::MajorByte(x)),
906                x @ 0x18..=0xff => Ok(AnyUInt::U8(x)),
907            },
908            U16 => Ok(AnyUInt::U16(d.u16()?)),
909            U32 => Ok(AnyUInt::U32(d.u32()?)),
910            U64 => Ok(AnyUInt::U64(d.u64()?)),
911            _ => Err(minicbor::decode::Error::message(format!(
912                "invalid data type for AnyUInt at position {}: {}",
913                d.position(),
914                data_type
915            ))),
916        }
917    }
918}
919
920impl<C> minicbor::encode::Encode<C> for AnyUInt {
921    fn encode<W: minicbor::encode::Write>(
922        &self,
923        e: &mut minicbor::Encoder<W>,
924        _ctx: &mut C,
925    ) -> Result<(), minicbor::encode::Error<W::Error>> {
926        match self {
927            AnyUInt::MajorByte(x) => {
928                let b = &x.to_be_bytes()[..];
929
930                e.writer_mut()
931                    .write_all(b)
932                    .map_err(minicbor::encode::Error::write)?;
933
934                Ok(())
935            }
936            AnyUInt::U8(x) => {
937                let x = x.to_be_bytes();
938                let b = &[[24u8], x].concat()[..];
939
940                e.writer_mut()
941                    .write_all(b)
942                    .map_err(minicbor::encode::Error::write)?;
943
944                Ok(())
945            }
946            AnyUInt::U16(x) => {
947                let x = &x.to_be_bytes()[..];
948                let b = &[&[25u8], x].concat()[..];
949
950                e.writer_mut()
951                    .write_all(b)
952                    .map_err(minicbor::encode::Error::write)?;
953
954                Ok(())
955            }
956            AnyUInt::U32(x) => {
957                let x = &x.to_be_bytes()[..];
958                let b = &[&[26u8], x].concat()[..];
959
960                e.writer_mut()
961                    .write_all(b)
962                    .map_err(minicbor::encode::Error::write)?;
963
964                Ok(())
965            }
966            AnyUInt::U64(x) => {
967                let x = &x.to_be_bytes()[..];
968                let b = &[&[27u8], x].concat()[..];
969
970                e.writer_mut()
971                    .write_all(b)
972                    .map_err(minicbor::encode::Error::write)?;
973
974                Ok(())
975            }
976        }
977    }
978}
979
980impl From<AnyUInt> for u64 {
981    fn from(x: AnyUInt) -> Self {
982        match x {
983            AnyUInt::MajorByte(x) => x as u64,
984            AnyUInt::U8(x) => x as u64,
985            AnyUInt::U16(x) => x as u64,
986            AnyUInt::U32(x) => x as u64,
987            AnyUInt::U64(x) => x,
988        }
989    }
990}
991
992impl From<&AnyUInt> for u64 {
993    fn from(x: &AnyUInt) -> Self {
994        u64::from(*x)
995    }
996}
997
998/// Introduced in Conway
999/// positive_coin = 1 .. 18446744073709551615
1000#[derive(
1001    Encode, Decode, Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize,
1002)]
1003#[serde(transparent)]
1004#[cbor(transparent)]
1005pub struct PositiveCoin(u64);
1006
1007impl TryFrom<u64> for PositiveCoin {
1008    type Error = u64;
1009
1010    fn try_from(value: u64) -> Result<Self, Self::Error> {
1011        if value == 0 {
1012            return Err(value);
1013        }
1014
1015        Ok(Self(value))
1016    }
1017}
1018
1019impl From<PositiveCoin> for u64 {
1020    fn from(value: PositiveCoin) -> Self {
1021        value.0
1022    }
1023}
1024
1025impl From<&PositiveCoin> for u64 {
1026    fn from(x: &PositiveCoin) -> Self {
1027        u64::from(*x)
1028    }
1029}
1030
1031/// Introduced in Conway
1032/// negInt64 = -9223372036854775808 .. -1
1033/// posInt64 = 1 .. 9223372036854775807
1034/// nonZeroInt64 = negInt64 / posInt64 ; this is the same as the current int64
1035/// definition but without zero
1036#[derive(Debug, PartialEq, Copy, Clone, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
1037#[serde(transparent)]
1038pub struct NonZeroInt(i64);
1039
1040impl TryFrom<i64> for NonZeroInt {
1041    type Error = i64;
1042
1043    fn try_from(value: i64) -> Result<Self, Self::Error> {
1044        if value == 0 {
1045            return Err(value);
1046        }
1047
1048        Ok(Self(value))
1049    }
1050}
1051
1052impl From<NonZeroInt> for i64 {
1053    fn from(value: NonZeroInt) -> Self {
1054        value.0
1055    }
1056}
1057
1058impl From<&NonZeroInt> for i64 {
1059    fn from(x: &NonZeroInt) -> Self {
1060        i64::from(*x)
1061    }
1062}
1063
1064impl<'b, C> minicbor::decode::Decode<'b, C> for NonZeroInt {
1065    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1066        let n = d.decode_with(ctx)?;
1067
1068        if n == 0 {
1069            return Err(Error::message("decoding 0 as NonZeroInt"));
1070        }
1071
1072        Ok(Self(n))
1073    }
1074}
1075
1076impl<C> minicbor::encode::Encode<C> for NonZeroInt {
1077    fn encode<W: minicbor::encode::Write>(
1078        &self,
1079        e: &mut minicbor::Encoder<W>,
1080        _ctx: &mut C,
1081    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1082        e.encode(self.0)?;
1083
1084        Ok(())
1085    }
1086}
1087
1088/// Decodes a struct while preserving original CBOR
1089///
1090/// # Examples
1091///
1092/// ```
1093/// use pallas_codec::utils::KeepRaw;
1094///
1095/// let a = (123u16, (456u16, 789u16), 123u16);
1096/// let data = minicbor::to_vec(a).unwrap();
1097///
1098/// let (_, keeper, _): (u16, KeepRaw<(u16, u16)>, u16) = minicbor::decode(&data).unwrap();
1099/// let confirm: (u16, u16) = minicbor::decode(keeper.raw_cbor()).unwrap();
1100/// assert_eq!(confirm, (456u16, 789u16));
1101/// ```
1102#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
1103pub struct KeepRaw<'b, T> {
1104    raw: Cow<'b, [u8]>,
1105    inner: T,
1106}
1107
1108impl<T> KeepRaw<'_, T> {
1109    pub fn raw_cbor(&self) -> &[u8] {
1110        &self.raw
1111    }
1112
1113    pub fn unwrap(self) -> T {
1114        self.inner
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        &mut self.inner
1136    }
1137}
1138
1139impl<T> From<T> for KeepRaw<'static, T> {
1140    /// Note that the `KeepRaw` value obtained from this implementation does
1141    /// **not** include a valid CBOR representation.
1142    fn from(val: T) -> Self {
1143        Self {
1144            raw: Cow::from(vec![]),
1145            inner: val,
1146        }
1147    }
1148}
1149
1150impl<'b, T, C> minicbor::Decode<'b, C> for KeepRaw<'b, T>
1151where
1152    T: minicbor::Decode<'b, C>,
1153{
1154    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1155        let all = d.input();
1156        let start = d.position();
1157        let inner: T = d.decode_with(ctx)?;
1158        let end = d.position();
1159
1160        Ok(Self {
1161            inner,
1162            raw: Cow::Borrowed(&all[start..end]),
1163        })
1164    }
1165}
1166
1167impl<C, T> minicbor::Encode<C> for KeepRaw<'_, T> {
1168    fn encode<W: minicbor::encode::Write>(
1169        &self,
1170        e: &mut minicbor::Encoder<W>,
1171        _ctx: &mut C,
1172    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1173        e.writer_mut()
1174            .write_all(self.raw_cbor())
1175            .map_err(minicbor::encode::Error::write)
1176    }
1177}
1178
1179impl<T: Serialize> Serialize for KeepRaw<'_, T> {
1180    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1181    where
1182        S: serde::Serializer,
1183    {
1184        self.deref().serialize(serializer)
1185    }
1186}
1187
1188impl<'de, T: Deserialize<'de>> Deserialize<'de> for KeepRaw<'_, T> {
1189    /// Note that the `KeepRaw` value obtained from this implementation does
1190    /// **not** include a valid CBOR representation.
1191    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1192    where
1193        D: serde::Deserializer<'de>,
1194    {
1195        let inner: T = T::deserialize(deserializer)?;
1196
1197        Ok(Self {
1198            inner,
1199            raw: Cow::from(vec![]),
1200        })
1201    }
1202}
1203
1204/// Struct to hold arbitrary CBOR to be processed independently
1205///
1206/// # Examples
1207///
1208/// ```
1209/// use pallas_codec::utils::AnyCbor;
1210///
1211/// let a = (123u16, (456u16, 789u16), 123u16);
1212/// let data = minicbor::to_vec(a).unwrap();
1213///
1214/// let (_, any, _): (u16, AnyCbor, u16) = minicbor::decode(&data).unwrap();
1215/// let confirm: (u16, u16) = any.into_decode().unwrap();
1216/// assert_eq!(confirm, (456u16, 789u16));
1217/// ```
1218#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
1219pub struct AnyCbor {
1220    inner: Vec<u8>,
1221}
1222
1223impl AnyCbor {
1224    pub fn raw_bytes(&self) -> &[u8] {
1225        &self.inner
1226    }
1227
1228    pub fn unwrap(self) -> Vec<u8> {
1229        self.inner
1230    }
1231
1232    pub fn from_encode<T>(other: T) -> Self
1233    where
1234        T: Encode<()>,
1235    {
1236        let inner = minicbor::to_vec(other).unwrap();
1237        Self { inner }
1238    }
1239
1240    pub fn into_decode<T>(self) -> Result<T, minicbor::decode::Error>
1241    where
1242        for<'b> T: Decode<'b, ()>,
1243    {
1244        minicbor::decode(&self.inner)
1245    }
1246}
1247
1248impl Deref for AnyCbor {
1249    type Target = Vec<u8>;
1250
1251    fn deref(&self) -> &Self::Target {
1252        &self.inner
1253    }
1254}
1255
1256impl<'b, C> minicbor::Decode<'b, C> for AnyCbor {
1257    fn decode(
1258        d: &mut minicbor::Decoder<'b>,
1259        _ctx: &mut C,
1260    ) -> Result<Self, minicbor::decode::Error> {
1261        let all = d.input();
1262        let start = d.position();
1263        d.skip()?;
1264        let end = d.position();
1265
1266        Ok(Self {
1267            inner: Vec::from(&all[start..end]),
1268        })
1269    }
1270}
1271
1272impl<C> minicbor::Encode<C> for AnyCbor {
1273    fn encode<W: minicbor::encode::Write>(
1274        &self,
1275        e: &mut minicbor::Encoder<W>,
1276        _ctx: &mut C,
1277    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1278        e.writer_mut()
1279            .write_all(self.raw_bytes())
1280            .map_err(minicbor::encode::Error::write)
1281    }
1282}
1283
1284#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
1285#[serde(from = "Option::<T>", into = "Option::<T>")]
1286pub enum Nullable<T>
1287where
1288    T: std::clone::Clone,
1289{
1290    Some(T),
1291    Null,
1292    Undefined,
1293}
1294
1295impl<T> Nullable<T>
1296where
1297    T: std::clone::Clone,
1298{
1299    pub fn map<F, O>(self, f: F) -> Nullable<O>
1300    where
1301        O: std::clone::Clone,
1302        F: Fn(T) -> O,
1303    {
1304        match self {
1305            Nullable::Some(x) => Nullable::Some(f(x)),
1306            Nullable::Null => Nullable::Null,
1307            Nullable::Undefined => Nullable::Undefined,
1308        }
1309    }
1310
1311    pub fn as_ref(&self) -> Nullable<&T> {
1312        match self {
1313            Nullable::Some(x) => Nullable::Some(x),
1314            Nullable::Null => Nullable::Null,
1315            Nullable::Undefined => Nullable::Undefined,
1316        }
1317    }
1318}
1319
1320impl<'b, C, T> minicbor::Decode<'b, C> for Nullable<T>
1321where
1322    T: minicbor::Decode<'b, C> + std::clone::Clone,
1323{
1324    fn decode(d: &mut minicbor::Decoder<'b>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
1325        match d.datatype()? {
1326            minicbor::data::Type::Null => {
1327                d.null()?;
1328                Ok(Self::Null)
1329            }
1330            minicbor::data::Type::Undefined => {
1331                d.undefined()?;
1332                Ok(Self::Undefined)
1333            }
1334            _ => {
1335                let x = d.decode_with(ctx)?;
1336                Ok(Self::Some(x))
1337            }
1338        }
1339    }
1340}
1341
1342impl<C, T> minicbor::Encode<C> for Nullable<T>
1343where
1344    T: minicbor::Encode<C> + std::clone::Clone,
1345{
1346    fn encode<W: minicbor::encode::Write>(
1347        &self,
1348        e: &mut minicbor::Encoder<W>,
1349        ctx: &mut C,
1350    ) -> Result<(), minicbor::encode::Error<W::Error>> {
1351        match self {
1352            Nullable::Some(x) => {
1353                e.encode_with(x, ctx)?;
1354                Ok(())
1355            }
1356            Nullable::Null => {
1357                e.null()?;
1358                Ok(())
1359            }
1360            Nullable::Undefined => {
1361                e.undefined()?;
1362                Ok(())
1363            }
1364        }
1365    }
1366}
1367
1368impl<T> From<Option<T>> for Nullable<T>
1369where
1370    T: std::clone::Clone,
1371{
1372    fn from(x: Option<T>) -> Self {
1373        match x {
1374            Some(x) => Nullable::Some(x),
1375            None => Nullable::Null,
1376        }
1377    }
1378}
1379
1380impl<T> From<Nullable<T>> for Option<T>
1381where
1382    T: std::clone::Clone,
1383{
1384    fn from(other: Nullable<T>) -> Self {
1385        match other {
1386            Nullable::Some(x) => Some(x),
1387            _ => None,
1388        }
1389    }
1390}
1391
1392#[derive(
1393    Serialize, Deserialize, Clone, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1394)]
1395#[cbor(transparent)]
1396#[serde(into = "String")]
1397#[serde(try_from = "String")]
1398pub struct Bytes(#[n(0)] minicbor::bytes::ByteVec);
1399
1400impl From<Vec<u8>> for Bytes {
1401    fn from(xs: Vec<u8>) -> Self {
1402        Bytes(minicbor::bytes::ByteVec::from(xs))
1403    }
1404}
1405
1406impl From<Bytes> for Vec<u8> {
1407    fn from(b: Bytes) -> Self {
1408        b.0.into()
1409    }
1410}
1411
1412impl Deref for Bytes {
1413    type Target = Vec<u8>;
1414
1415    fn deref(&self) -> &Self::Target {
1416        self.0.deref()
1417    }
1418}
1419
1420impl<const N: usize> TryFrom<&Bytes> for [u8; N] {
1421    type Error = core::array::TryFromSliceError;
1422
1423    fn try_from(value: &Bytes) -> Result<Self, Self::Error> {
1424        value.0.as_slice().try_into()
1425    }
1426}
1427
1428impl TryFrom<String> for Bytes {
1429    type Error = hex::FromHexError;
1430
1431    fn try_from(value: String) -> Result<Self, Self::Error> {
1432        let v = hex::decode(value)?;
1433        Ok(Bytes(minicbor::bytes::ByteVec::from(v)))
1434    }
1435}
1436
1437impl FromStr for Bytes {
1438    type Err = hex::FromHexError;
1439
1440    fn from_str(s: &str) -> Result<Self, Self::Err> {
1441        let v = hex::decode(s)?;
1442        Ok(Bytes(minicbor::bytes::ByteVec::from(v)))
1443    }
1444}
1445
1446impl From<Bytes> for String {
1447    fn from(b: Bytes) -> Self {
1448        hex::encode(b.deref())
1449    }
1450}
1451
1452impl fmt::Display for Bytes {
1453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454        let bytes: Vec<u8> = self.clone().into();
1455
1456        f.write_str(&hex::encode(bytes))
1457    }
1458}
1459
1460#[derive(
1461    Serialize, Deserialize, Clone, Copy, Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1462)]
1463#[cbor(transparent)]
1464#[serde(into = "i128")]
1465#[serde(try_from = "i128")]
1466pub struct Int(#[n(0)] pub minicbor::data::Int);
1467
1468impl Deref for Int {
1469    type Target = minicbor::data::Int;
1470
1471    fn deref(&self) -> &Self::Target {
1472        &self.0
1473    }
1474}
1475
1476impl From<Int> for i128 {
1477    fn from(value: Int) -> Self {
1478        i128::from(value.0)
1479    }
1480}
1481
1482impl From<i64> for Int {
1483    fn from(x: i64) -> Self {
1484        let inner = minicbor::data::Int::from(x);
1485        Self(inner)
1486    }
1487}
1488
1489impl TryFrom<i128> for Int {
1490    type Error = minicbor::data::TryFromIntError;
1491
1492    fn try_from(value: i128) -> Result<Self, Self::Error> {
1493        let inner = minicbor::data::Int::try_from(value)?;
1494        Ok(Self(inner))
1495    }
1496}