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

net improve interoperability of wrapper types #332

Closed
wants to merge 8 commits into from
Closed
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
10 changes: 2 additions & 8 deletions crates/net/src/eventsource/futures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use web_sys::MessageEvent;

/// Wrapper around browser's EventSource API. Dropping
/// this will close the underlying event source.
#[derive(Clone)]
#[derive(Clone, PartialEq, Eq)]
pub struct EventSource {
es: web_sys::EventSource,
}
Expand Down Expand Up @@ -178,13 +178,7 @@ impl EventSource {

/// The current state of the EventSource.
pub fn state(&self) -> State {
let ready_state = self.es.ready_state();
match ready_state {
0 => State::Connecting,
1 => State::Open,
2 => State::Closed,
_ => unreachable!(),
}
self.es.ready_state().into()
}
}

Expand Down
70 changes: 68 additions & 2 deletions crates/net/src/eventsource/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use std::fmt;
///
/// See [`EventSource.readyState` on MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/readyState)
/// to learn more.
#[derive(Copy, Clone, Debug)]
// This trait implements `Ord`, use caution when changing the order of the variants.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum State {
/// The connection has not yet been established.
Connecting,
Expand All @@ -21,8 +22,55 @@ pub enum State {
Closed,
}

impl State {
/// Returns the state as a &'static str.
///
/// # Example
///
/// ```
/// # use gloo_net::eventsource::State;
/// assert_eq!(State::Connecting.as_str(), "connecting");
/// assert_eq!(State::Open.as_str(), "open");
/// assert_eq!(State::Closed.as_str(), "closed");
/// ```
pub const fn as_str(&self) -> &'static str {
match self {
State::Connecting => "connecting",
State::Open => "open",
State::Closed => "closed",
}
}
}

impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}

impl From<u16> for State {
fn from(state: u16) -> Self {
match state {
0 => State::Connecting,
1 => State::Open,
2 => State::Closed,
_ => unreachable!("Invalid readyState"),
}
}
}

impl From<State> for u16 {
fn from(state: State) -> Self {
match state {
State::Connecting => 0,
State::Open => 1,
State::Closed => 2,
}
}
}

/// Error returned by the EventSource
#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[allow(missing_copy_implementations)]
pub enum EventSourceError {
Expand All @@ -37,3 +85,21 @@ impl fmt::Display for EventSourceError {
}
}
}

#[cfg(test)]
mod tests {
use crate::is_strictly_sorted;

use super::*;

#[test]
fn test_order() {
let expected_order = vec![State::Connecting, State::Open, State::Closed];

assert!(is_strictly_sorted(&expected_order));

// Check that the u16 conversion is also sorted
let order: Vec<_> = expected_order.iter().map(|s| u16::from(*s)).collect();
assert!(is_strictly_sorted(&order));
}
}
68 changes: 55 additions & 13 deletions crates/net/src/http/headers.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
use gloo_utils::iter::UncheckedIter;
use js_sys::{Array, Map};
use std::fmt;
use std::{fmt, iter::FromIterator};
use wasm_bindgen::{JsCast, UnwrapThrowExt};

// I experimented with using `js_sys::Object` for the headers, since this object is marked
// experimental in MDN. However it's in the fetch spec, and it's necessary for appending headers.
/// A wrapper around `web_sys::Headers`.
pub struct Headers {
raw: web_sys::Headers,
}

impl Default for Headers {
fn default() -> Self {
Self::new()
}
}

impl Headers {
/// Create a new empty headers object.
pub fn new() -> Self {
Expand All @@ -37,19 +29,33 @@ impl Headers {

/// This method appends a new value onto an existing header, or adds the header if it does not
/// already exist.
pub fn append(&self, name: &str, value: &str) {
///
/// # Examples
///
/// ```
/// # use gloo_net::http::Headers;
/// # fn no_run() {
/// let headers = Headers::new();
/// headers.append("Content-Type", "text/plain");
/// assert_eq!(headers.get("Content-Type"), Some("text/plain".to_string()));
///
/// headers.append("Content-Type", "text/html");
/// assert_eq!(headers.get("Content-Type"), Some("text/plain, text/html".to_string()));
/// # }
/// ```
pub fn append(&mut self, name: &str, value: &str) {
Copy link
Author

@Alextopher Alextopher May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know web_sys::Headers (and all? web_sys types) allow inner mutability through a &T but I'm not sure if it's idiomatic to do the same on our wrapper types.

For example, if someday we choose to change the implementation of Header wrap a HashSet<&str, String> this method would need to be &mut or we're committing to using a something like RefCell<_> forever

// XXX Can this throw? WEBIDL says yes, my experiments with forbidden headers and MDN say
// no.
self.raw.append(name, value).unwrap_throw()
}

/// Deletes a header if it is present.
pub fn delete(&self, name: &str) {
pub fn delete(&mut self, name: &str) {
self.raw.delete(name).unwrap_throw()
}

/// Gets a header if it is present.
pub fn get(&self, name: &str) -> Option<String> {
pub fn get(&mut self, name: &str) -> Option<String> {
self.raw.get(name).unwrap_throw()
}

Expand All @@ -59,7 +65,7 @@ impl Headers {
}

/// Overwrites a header with the given name.
pub fn set(&self, name: &str, value: &str) {
pub fn set(&mut self, name: &str, value: &str) {
self.raw.set(name, value).unwrap_throw()
}

Expand Down Expand Up @@ -93,6 +99,42 @@ impl Headers {
}
}

impl Clone for Headers {
fn clone(&self) -> Self {
self.entries().collect()
}
}

impl Default for Headers {
fn default() -> Self {
Self::new()
}
}

impl<K, V> Extend<(K, V)> for Headers
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where
K: AsRef<str>,
V: AsRef<str>,
{
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
for (key, value) in iter {
self.append(key.as_ref(), value.as_ref());
}
}
}

impl<K, V> FromIterator<(K, V)> for Headers
where
K: AsRef<str>,
V: AsRef<str>,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut headers = Self::new();
headers.extend(iter);
headers
}
}

impl fmt::Debug for Headers {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut dbg = f.debug_struct("Headers");
Expand Down
41 changes: 38 additions & 3 deletions crates/net/src/http/query.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use gloo_utils::iter::UncheckedIter;
use js_sys::{Array, Map};
use std::fmt;
use std::{fmt, iter::FromIterator};
use wasm_bindgen::{JsCast, UnwrapThrowExt};

/// A sequence of URL query parameters, wrapping [`web_sys::UrlSearchParams`].
Expand Down Expand Up @@ -29,8 +29,13 @@ impl QueryParams {
Self { raw }
}

/// Create [`web_sys::UrlSearchParams`] from [`QueryParams`] object.
pub fn into_raw(self) -> web_sys::UrlSearchParams {
self.raw
}

/// Append a parameter to the query string.
pub fn append(&self, name: &str, value: &str) {
pub fn append(&mut self, name: &str, value: &str) {
self.raw.append(name, value)
}

Expand All @@ -50,7 +55,7 @@ impl QueryParams {
}

/// Remove all occurrences of a parameter from the query string.
pub fn delete(&self, name: &str) {
pub fn delete(&mut self, name: &str) {
self.raw.delete(name)
}

Expand All @@ -72,6 +77,36 @@ impl QueryParams {
}
}

impl Clone for QueryParams {
fn clone(&self) -> Self {
self.iter().collect()
}
}

impl<K, V> Extend<(K, V)> for QueryParams
where
K: AsRef<str>,
V: AsRef<str>,
{
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (key, value) in iter {
self.append(key.as_ref(), value.as_ref());
}
}
}

impl<K, V> FromIterator<(K, V)> for QueryParams
where
K: AsRef<str>,
V: AsRef<str>,
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut params = Self::new();
params.extend(iter);
params
}
}

/// The formatted query parameters ready to be used in a URL query string.
///
/// # Examples
Expand Down
Loading