Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add serde serialize/deserialize support #21

Merged
merged 5 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,25 @@ harness = false
[features]
# pass `cpp_set_stdlib("c++")` to `cc`
libcpp = []
# enables serde serialization/deserialization support
serde = ["dep:serde"]

[dependencies]
thiserror = "1"
serde = { version = "1.0", optional = true, features = ["derive"] }

[dev-dependencies]
criterion = "0.5"
url = "2" # Used by benchmarks
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[build-dependencies]
cc = { version = "1.0", features = ["parallel"] }
link_args = "0.6"

[package.metadata.docs.rs]
features = ["serde"]

[package.metadata.playground]
features = ["serde"]
83 changes: 78 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@
//! servo url ▏ 664 ns/URL ███████████▎
//! CURL ▏ 1471 ns/URL █████████████████████████
//! ```
//!
//! # Feature: `serde`
//!
//! If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
//! [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
//! [`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
//! See [serde documentation](https://serde.rs) for more information.
//!
//! ```toml
//! ada-url = { version = "1", features = ["serde"] }
//! ```

pub mod ffi;
mod idna;
Expand All @@ -27,21 +38,24 @@ pub use idna::Idna;
use std::{borrow, fmt, hash, ops};
use thiserror::Error;

#[cfg(feature = "serde")]
extern crate serde;

#[derive(Error, Debug)]
pub enum Error {
#[error("Invalid url: \"{0}\"")]
ParseUrl(String),
}

/// A parsed URL struct according to WHATWG URL specification.
#[derive(Eq)]
pub struct Url {
url: *mut ffi::ada_url,
}

impl Drop for Url {
fn drop(&mut self) {
unsafe {
ffi::ada_free(self.url);
}
unsafe { ffi::ada_free(self.url) }
}
}

Expand Down Expand Up @@ -354,15 +368,61 @@ impl Url {
}
}

/// Serializes this URL into a `serde` stream.
///
/// This implementation is only available if the `serde` Cargo feature is enabled.
#[cfg(feature = "serde")]
impl serde::Serialize for Url {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}

/// Deserializes this URL from a `serde` stream.
///
/// This implementation is only available if the `serde` Cargo feature is enabled.
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Url {
fn deserialize<D>(deserializer: D) -> Result<Url, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{Error, Unexpected, Visitor};

struct UrlVisitor;

impl<'de> Visitor<'de> for UrlVisitor {
type Value = Url;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string representing an URL")
}

fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
Url::parse(s, None).map_err(|err| {
let err_s = format!("{}", err);
Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
})
}
}

deserializer.deserialize_str(UrlVisitor)
}
}

/// URLs compare like their stringification.
impl PartialEq for Url {
fn eq(&self, other: &Self) -> bool {
self.href() == other.href()
}
}

impl Eq for Url {}

impl PartialOrd for Url {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.href().partial_cmp(other.href())
Expand Down Expand Up @@ -476,6 +536,7 @@ impl ops::Deref for Url {
self.href()
}
}

impl AsRef<str> for Url {
fn as_ref(&self) -> &str {
self.href()
Expand Down Expand Up @@ -614,4 +675,16 @@ mod test {
assert!(Url::can_parse("https://google.com", None));
assert!(Url::can_parse("/helo", Some("https://www.google.com")));
}

#[cfg(feature = "serde")]
#[test]
fn test_serde_serialize_deserialize() {
let input = "https://www.google.com";
let output = "\"https://www.google.com/\"";
let url = Url::parse(&input, None).unwrap();
assert_eq!(serde_json::to_string(&url).unwrap(), output.to_string());

let deserialized: Url = serde_json::from_str(&output).unwrap();
assert_eq!(deserialized.href(), input.to_string() + "/");
}
}