Bläddra i källkod

Add optional serialization with `serde`

Patrick Walton 11 år sedan
förälder
incheckning
269af0e422
3 ändrade filer med 35 tillägg och 1 borttagningar
  1. 7 0
      Cargo.toml
  2. 2 1
      Makefile
  3. 26 0
      src/lib.rs

+ 7 - 0
Cargo.toml

@@ -14,12 +14,19 @@ license = "MIT/Apache-2.0"
 [features]
 
 query_encoding = ["encoding"]
+serde_serialization = ["serde"]
 
 [dependencies.encoding]
 
 version = "0.2"
 optional = true
 
+[dependencies.serde]
+
+version = "*"
+optional = true
+
 [dependencies]
 rustc-serialize = "0.3"
 matches = "0.1"
+

+ 2 - 1
Makefile

@@ -1,9 +1,10 @@
 test:
 	cargo test --features query_encoding
+	cargo test --features serde_serialization
 	cargo test
 
 doc:
-	cargo doc --features query_encoding
+	cargo doc --features "query_encoding serde_serialization"
 	@echo '<meta http-equiv=refresh content=0;url=url/index.html>' > target/doc/index.html
 	@cp github.png target/doc/
 

+ 26 - 0
src/lib.rs

@@ -123,10 +123,16 @@ extern crate rustc_serialize;
 #[macro_use]
 extern crate matches;
 
+#[cfg(feature="serde_serialization")]
+extern crate serde;
+
 use std::fmt::{self, Formatter};
 use std::str;
 use std::path::{Path, PathBuf};
 
+#[cfg(feature="serde_serialization")]
+use std::str::FromStr;
+
 pub use host::{Host, Ipv6Address};
 pub use parser::{ErrorHandler, ParseResult, ParseError};
 
@@ -768,6 +774,26 @@ impl rustc_serialize::Decodable for Url {
     }
 }
 
+/// Serializes this URL into a `serde` stream.
+///
+/// This implementation is only available if the `serde_serialization` Cargo feature is enabled.
+#[cfg(feature="serde_serialization")]
+impl serde::Serialize for Url {
+    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
+        format!("{}", self).serialize(serializer)
+    }
+}
+
+/// Deserializes this URL from a `serde` stream.
+///
+/// This implementation is only available if the `serde_serialization` Cargo feature is enabled.
+#[cfg(feature="serde_serialization")]
+impl serde::Deserialize for Url {
+    fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
+        let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
+        Ok(FromStr::from_str(&string_representation[..]).unwrap())
+    }
+}
 
 impl fmt::Display for Url {
     fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {