Ver Fonte

Implement Encodable and Decodable for Url. See #27.

Simon Sapin há 12 anos atrás
pai
commit
bfdf809365
1 ficheiros alterados com 16 adições e 2 exclusões
  1. 16 2
      src/lib.rs

+ 16 - 2
src/lib.rs

@@ -120,8 +120,6 @@ assert!(css_url.serialize() == "http://servo.github.io/rust-url/main.css".to_str
 #![feature(macro_rules, default_type_params)]
 
 extern crate encoding;
-
-#[cfg(test)]
 extern crate serialize;
 
 use std::fmt::{Formatter, FormatError, Show};
@@ -754,6 +752,22 @@ impl Url {
 }
 
 
+impl<E, S: serialize::Encoder<E>> serialize::Encodable<S, E> for Url {
+    fn encode(&self, encoder: &mut S) -> Result<(), E> {
+        encoder.emit_str(self.to_string().as_slice())
+    }
+}
+
+
+impl<E, D: serialize::Decoder<E>> serialize::Decodable<D, E> for Url {
+    fn decode(decoder: &mut D) -> Result<Url, E> {
+        Url::parse(try!(decoder.read_str()).as_slice()).map_err(|error| {
+            decoder.error(format!("URL parsing error: {}", error).as_slice())
+        })
+    }
+}
+
+
 impl Show for Url {
     fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
         try!(UrlNoFragmentFormatter{ url: self }.fmt(formatter));