Skip to content

Commit 2adcf00

Browse files
committed
impl FromPrimitive/ToPrimitive
1 parent db45e97 commit 2adcf00

File tree

1 file changed

+37
-7
lines changed

1 file changed

+37
-7
lines changed

src/types/decimal.rs

+37-7
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ impl Decimal {
5353
Some(Decimal::from(n))
5454
}
5555

56-
5756
///Return a new Decimal object equivalent to self,
5857
/// with internal scaling set to the number specified.
5958
/// If the new_scale is lower than the current value (indicating a larger power of 10),
@@ -144,7 +143,6 @@ impl From<i128> for Decimal {
144143
}
145144
}
146145

147-
148146
impl From<u128> for Decimal {
149147
fn from(arg: u128) -> Self {
150148
Self::from(BigDecimal::from(arg))
@@ -181,7 +179,7 @@ impl FromStr for Decimal {
181179
}
182180
}
183181

184-
impl ToPrimitive for Decimal{
182+
impl ToPrimitive for Decimal {
185183
fn to_i64(&self) -> Option<i64> {
186184
self.0.to_i64()
187185
}
@@ -200,6 +198,38 @@ impl ToPrimitive for Decimal{
200198
}
201199
}
202200

201+
impl FromPrimitive for Decimal {
202+
#[inline]
203+
fn from_i64(n: i64) -> Option<Self> {
204+
Some(Self::from(BigDecimal::from_i64(n)?))
205+
}
206+
207+
#[inline]
208+
fn from_u64(n: u64) -> Option<Self> {
209+
Some(Self::from(BigDecimal::from_u64(n)?))
210+
}
211+
212+
#[inline]
213+
fn from_i128(n: i128) -> Option<Self> {
214+
Some(Self::from(BigDecimal::from_i128(n)?))
215+
}
216+
217+
#[inline]
218+
fn from_u128(n: u128) -> Option<Self> {
219+
Some(Self::from(BigDecimal::from_u128(n)?))
220+
}
221+
222+
#[inline]
223+
fn from_f32(n: f32) -> Option<Self> {
224+
Some(Self::from(BigDecimal::from_f32(n)?))
225+
}
226+
227+
#[inline]
228+
fn from_f64(n: f64) -> Option<Self> {
229+
Some(Self::from(BigDecimal::from_f64(n)?))
230+
}
231+
}
232+
203233
impl Default for Decimal {
204234
fn default() -> Self {
205235
Decimal(BigDecimal::from(0))
@@ -373,11 +403,11 @@ mod test {
373403

374404
#[test]
375405
fn test_try_from_f64() {
376-
let f=1.1;
406+
let f = 1.1;
377407
let v = Decimal::from_f64(f);
378-
println!("{:?}",v);
379-
if let Some(v)=v{
380-
println!("{}",v.to_string());
408+
println!("{:?}", v);
409+
if let Some(v) = v {
410+
println!("{}", v.to_string());
381411
}
382412
}
383413
}

0 commit comments

Comments
 (0)