plutus_ledger_api/csl/
csl_to_pla.rs

1use std::{ops::Neg, str::FromStr};
2
3use cardano_serialization_lib as csl;
4use num_bigint::{BigInt, ParseBigIntError};
5
6#[derive(Debug, Clone, thiserror::Error)]
7pub enum TryFromCSLError {
8    #[error("Unable to parse BigInt: {0}")]
9    InvalidBigInt(ParseBigIntError),
10
11    #[error("Unable to represent CSL value in PLA: {0}")]
12    ImpossibleConversion(String),
13}
14
15/// Convert a cardano-serialization-lib type to its plutus-ledger-api counterpart
16pub trait FromCSL<T> {
17    fn from_csl(value: &T) -> Self
18    where
19        Self: Sized;
20}
21
22pub trait ToPLA<T> {
23    fn to_pla(&self) -> T;
24}
25
26impl<T, U> ToPLA<U> for T
27where
28    U: FromCSL<T>,
29{
30    fn to_pla(&self) -> U {
31        FromCSL::from_csl(self)
32    }
33}
34
35/// Convert a cardano-serialization-lib type to its plutus-ledger-api counterpart
36pub trait TryFromCSL<T> {
37    fn try_from_csl(value: &T) -> Result<Self, TryFromCSLError>
38    where
39        Self: Sized;
40}
41
42pub trait TryToPLA<T> {
43    fn try_to_pla(&self) -> Result<T, TryFromCSLError>;
44}
45
46impl<T, U> TryToPLA<U> for T
47where
48    U: TryFromCSL<T>,
49{
50    fn try_to_pla(&self) -> Result<U, TryFromCSLError> {
51        TryFromCSL::try_from_csl(self)
52    }
53}
54
55impl FromCSL<csl::BigNum> for BigInt {
56    fn from_csl(value: &csl::BigNum) -> Self {
57        let x: u64 = From::from(*value);
58        BigInt::from(x)
59    }
60}
61
62impl FromCSL<u32> for BigInt {
63    fn from_csl(value: &u32) -> Self {
64        BigInt::from(*value)
65    }
66}
67
68impl TryFromCSL<csl::BigInt> for BigInt {
69    fn try_from_csl(value: &csl::BigInt) -> Result<Self, TryFromCSLError> {
70        BigInt::from_str(&value.to_str()).map_err(TryFromCSLError::InvalidBigInt)
71    }
72}
73
74impl FromCSL<csl::Int> for BigInt {
75    fn from_csl(value: &csl::Int) -> Self {
76        if value.is_positive() {
77            BigInt::from_csl(&value.as_positive().unwrap())
78        } else {
79            BigInt::from_csl(&value.as_negative().unwrap()).neg()
80        }
81    }
82}