Skip to content

Commit

Permalink
defi asset pair as slice
Browse files Browse the repository at this point in the history
Signed-off-by: dzmitry-lahoda <dzmitry@lahoda.pro>
  • Loading branch information
dzmitry-lahoda committed Jan 3, 2022
1 parent ad3b85d commit fd2686d
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions frame/composable-traits/src/defi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ impl<AssetId: PartialEq, Balance: PartialOrd + Zero + SafeArithmetic> Sell<Asset

/// given `base`, how much `quote` needed for unit
/// see [currency pair](https://www.investopedia.com/terms/c/currencypair.asp)
/// Pair with base and quote considered valid as it allows to have mixer(money laundering) like
/// behavior.
/// Pair with same base and quote is considered valid as it allows to have mixer, money laundering
/// like behavior.
#[repr(C)]
#[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq)]
pub struct CurrencyPair<AssetId> {
Expand All @@ -77,10 +77,23 @@ impl<AssetId: PartialEq> CurrencyPair<AssetId> {
Self { base, quote }
}

pub fn as_array(&self) -> &[AssetId; 2] {
// adding lifetimes explicitly considered by rust as not needed, so lifetime is proper for
// return array
unsafe { sp_std::mem::transmute(self) }
///```rust
/// let pair = composable_traits::defi::CurrencyPair::<u128>::new(13, 42);
/// let slice = pair.as_slice();
/// assert_eq!(slice[0], pair.base);
/// assert_eq!(slice[1], pair.quote);
/// drop(pair);
/// // next line will fail to compile
/// // let _ = slice[0];
/// ```
pub fn as_slice(&self) -> &[AssetId] {
unsafe { sp_std::slice::from_raw_parts(self as *const Self as *const AssetId, 2) }
}
}

impl<AssetId: PartialEq> AsRef<[AssetId]> for CurrencyPair<AssetId> {
fn as_ref(&self) -> &[AssetId] {
self.as_slice()
}
}

Expand Down

0 comments on commit fd2686d

Please sign in to comment.