Skip to content

Commit f7beeff

Browse files
committed
response fallible start
Signed-off-by: Yoshua Wuyts <[email protected]>
1 parent 00852fb commit f7beeff

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/response.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use async_std::io::{self, BufRead, Read};
22

33
use std::borrow::Borrow;
4+
use std::convert::TryInto;
45
use std::fmt::{self, Debug};
56
use std::pin::Pin;
67
use std::task::{Context, Poll};
@@ -12,6 +13,16 @@ type BodyReader = dyn BufRead + Unpin + Send + 'static;
1213

1314
pin_project_lite::pin_project! {
1415
/// An HTTP response.
16+
///
17+
/// ```
18+
/// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
19+
/// #
20+
/// use http_types::{Response, StatusCode};
21+
///
22+
/// let mut req = Response::new(200)?;
23+
/// #
24+
/// # Ok(()) }
25+
/// ```
1526
pub struct Response {
1627
#[pin]
1728
body_reader: Box<BodyReader>,
@@ -23,13 +34,17 @@ pin_project_lite::pin_project! {
2334

2435
impl Response {
2536
/// Create a new response.
26-
pub fn new(status: StatusCode) -> Self {
27-
Self {
28-
status,
37+
pub fn new<S>(status: S) -> Result<Self, Box<dyn std::error::Error + Send + Sync + 'static>>
38+
where
39+
S: TryInto<StatusCode>,
40+
<S as TryInto<StatusCode>>::Error: Sync + Send + std::error::Error + 'static,
41+
{
42+
Ok(Self {
43+
status: status.try_into()?,
2944
headers: Headers::new(),
3045
body_reader: Box::new(io::empty()),
3146
length: Some(0),
32-
}
47+
})
3348
}
3449

3550
/// Get the status

src/status_code.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,14 @@ impl Into<u16> for StatusCode {
466466
}
467467
}
468468

469+
impl std::convert::TryFrom<i32> for StatusCode {
470+
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
471+
472+
fn try_from(value: i32) -> Result<Self, Self::Error> {
473+
Self::try_from(value as u16)
474+
}
475+
}
476+
469477
impl std::convert::TryFrom<u16> for StatusCode {
470478
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
471479

0 commit comments

Comments
 (0)