Skip to content

Commit 4dd18a8

Browse files
committed
feat(client): Implement TryFrom for Destination
Add TryFrom<Uri> impl for Destination, for compiler version >= 1.34. Add basic unit tests for TryFrom impl Ref Issue: Implement TryFrom for Destination hyperium#1808
1 parent b342c38 commit 4dd18a8

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

build.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ extern crate rustc_version;
33
use rustc_version::{version, Version};
44

55
fn main() {
6-
if version().unwrap() >= Version::parse("1.30.0").unwrap() {
6+
let version = version().unwrap();
7+
if version >= Version::parse("1.30.0").unwrap() {
78
println!("cargo:rustc-cfg=error_source");
89
}
10+
if version >= Version::parse("1.34.0").unwrap() {
11+
println!("cargo:rustc-cfg=try_from");
12+
}
913
}

src/client/connect/mod.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//! - The [`Connect`](Connect) trait and related types to build custom connectors.
88
use std::error::Error as StdError;
99
use std::{fmt, mem};
10+
use std::convert::TryFrom;
1011

1112
use bytes::{BufMut, Bytes, BytesMut};
1213
use futures::Future;
@@ -251,6 +252,17 @@ impl Destination {
251252
*/
252253
}
253254

255+
#[cfg(try_from)]
256+
impl TryFrom<Uri> for Destination {
257+
type Error = ::error::Error;
258+
259+
fn try_from(uri: Uri) -> Result<Self, Self::Error> {
260+
uri.authority_part().ok_or(::error::Parse::Uri)?;
261+
uri.scheme_part().ok_or(::error::Parse::Uri)?;
262+
Ok(Destination { uri })
263+
}
264+
}
265+
254266
impl Connected {
255267
/// Create new `Connected` type with empty metadata.
256268
pub fn new() -> Connected {
@@ -381,7 +393,7 @@ where
381393

382394
#[cfg(test)]
383395
mod tests {
384-
use super::{Connected, Destination};
396+
use super::{Connected, Destination, TryFrom};
385397

386398
#[test]
387399
fn test_destination_set_scheme() {
@@ -527,6 +539,22 @@ mod tests {
527539
assert_eq!(dst.port(), None);
528540
}
529541

542+
#[cfg(try_from)]
543+
#[test]
544+
fn test_try_from_destination() {
545+
let uri: http::Uri = "http://hyper.rs".parse().expect("initial parse");
546+
let result = Destination::try_from(uri);
547+
assert_eq!(result.is_ok(), true);
548+
}
549+
550+
#[cfg(try_from)]
551+
#[test]
552+
fn test_try_from_no_scheme() {
553+
let uri: http::Uri = "hyper.rs".parse().expect("initial parse error");
554+
let result = Destination::try_from(uri);
555+
assert_eq!(result.is_err(), true);
556+
}
557+
530558
#[derive(Clone, Debug, PartialEq)]
531559
struct Ex1(usize);
532560

0 commit comments

Comments
 (0)