darkfi_serial/types/
bigint.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::io::{Read, Result, Write};
20
21#[cfg(feature = "async")]
22use crate::{AsyncDecodable, AsyncEncodable};
23#[cfg(feature = "async")]
24use async_trait::async_trait;
25#[cfg(feature = "async")]
26use futures_lite::{AsyncRead, AsyncWrite};
27
28use crate::{Decodable, Encodable};
29
30impl Encodable for num_bigint::BigInt {
31    fn encode<S: Write>(&self, s: &mut S) -> Result<usize> {
32        self.to_signed_bytes_be().encode(s)
33    }
34}
35
36#[cfg(feature = "async")]
37#[async_trait]
38impl AsyncEncodable for num_bigint::BigInt {
39    async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
40        self.to_signed_bytes_be().encode_async(s).await
41    }
42}
43
44impl Decodable for num_bigint::BigInt {
45    fn decode<D: Read>(d: &mut D) -> Result<Self> {
46        let vec: Vec<u8> = Decodable::decode(d)?;
47        Ok(Self::from_signed_bytes_be(&vec))
48    }
49}
50
51#[cfg(feature = "async")]
52#[async_trait]
53impl AsyncDecodable for num_bigint::BigInt {
54    async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
55        let vec: Vec<u8> = AsyncDecodable::decode_async(d).await?;
56        Ok(Self::from_signed_bytes_be(&vec))
57    }
58}
59
60impl Encodable for num_bigint::BigUint {
61    fn encode<S: Write>(&self, s: &mut S) -> Result<usize> {
62        self.to_bytes_be().encode(s)
63    }
64}
65
66#[cfg(feature = "async")]
67#[async_trait]
68impl AsyncEncodable for num_bigint::BigUint {
69    async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
70        self.to_bytes_be().encode_async(s).await
71    }
72}
73
74impl Decodable for num_bigint::BigUint {
75    fn decode<D: Read>(d: &mut D) -> Result<Self> {
76        let vec: Vec<u8> = Decodable::decode(d)?;
77        Ok(Self::from_bytes_be(&vec))
78    }
79}
80
81#[cfg(feature = "async")]
82#[async_trait]
83impl AsyncDecodable for num_bigint::BigUint {
84    async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
85        let vec: Vec<u8> = AsyncDecodable::decode_async(d).await?;
86        Ok(Self::from_bytes_be(&vec))
87    }
88}