griffin_core/pallas_codec/
utils.rs

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