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