Skip to content

Commit ed228e1

Browse files
feat: impl FromStr for integer types
1 parent f665ba3 commit ed228e1

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

benzina/src/error.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,27 @@ impl Display for TryFromIntError {
1414
}
1515

1616
impl Error for TryFromIntError {}
17+
18+
#[derive(Debug, Clone)]
19+
pub enum ParseIntError {
20+
Parse(std::num::ParseIntError),
21+
OutOfRange(TryFromIntError),
22+
}
23+
24+
impl Display for ParseIntError {
25+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26+
f.write_str(match self {
27+
Self::Parse(_err) => "could not parse integer",
28+
Self::OutOfRange(_err) => "integer is out of range",
29+
})
30+
}
31+
}
32+
33+
impl Error for ParseIntError {
34+
fn source(&self) -> Option<&(dyn Error + 'static)> {
35+
match self {
36+
Self::Parse(err) => Some(err),
37+
Self::OutOfRange(err) => Some(err),
38+
}
39+
}
40+
}

benzina/src/int.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::{
22
error::Error,
33
fmt::{self, Display},
44
ptr,
5+
str::FromStr,
56
};
67

78
use diesel::{
@@ -12,7 +13,7 @@ use diesel::{
1213
sql_types::{BigInt, Integer, SmallInt},
1314
};
1415

15-
use crate::error::TryFromIntError;
16+
use crate::error::{ParseIntError, TryFromIntError};
1617

1718
macro_rules! impl_numbers {
1819
($($type:ident => $inner:ident, $inner_signed:ident, $sql_type:ident),*) => {
@@ -135,6 +136,17 @@ macro_rules! impl_numbers {
135136
}
136137
}
137138

139+
impl FromStr for $type {
140+
type Err = ParseIntError;
141+
142+
fn from_str(value: &str) -> Result<Self, Self::Err> {
143+
value
144+
.parse::<$inner>()
145+
.map_err(ParseIntError::Parse)
146+
.and_then(|value| value.try_into().map_err(ParseIntError::OutOfRange))
147+
}
148+
}
149+
138150
impl Display for $type {
139151
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140152
Display::fmt(&self.get(), f)

0 commit comments

Comments
 (0)