Skip to content

Commit

Permalink
start of derive(Header), split into multiple crates
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmonstar committed Sep 12, 2018
1 parent 6b859a8 commit 593d118
Show file tree
Hide file tree
Showing 71 changed files with 509 additions and 311 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/target
/Cargo.lock
target
Cargo.lock
14 changes: 11 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
[package]

name = "headers"
version = "0.12.5" # don't forget to update html_root_url
description = "A fast and correct HTTP library."
version = "0.0.0" # don't forget to update html_root_url
description = "typed HTTP headers"
readme = "README.md"
homepage = "https://hyper.rs"
license = "MIT"
Expand All @@ -18,9 +17,18 @@ include = [
"src/**/*"
]

[workspace]
members = [
"./",
"headers-core",
"headers-derive",
"headers-ext",
]

[dependencies]
base64 = "0.9"
bytes = "0.4.4"
headers-derive = { path = "./headers-derive" }
http = "0.1.7"
httparse = "1.3"
language-tags = "0.2"
Expand Down
9 changes: 9 additions & 0 deletions headers-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "headers-core"
version = "0.0.0" # don't forget to update html_root_url
description = "typed HTTP headers"
authors = ["Sean McArthur <[email protected]>"]
license = "MIT"

[dependencies]
http = "0.1.7"
40 changes: 40 additions & 0 deletions headers-core/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#[derive(Debug)]
pub struct Error {
kind: Kind,
}

#[derive(Debug)]
enum Kind {
Invalid,
Empty,
TooMany,
}

pub type Result<T> = ::std::result::Result<T, Error>;

impl Error {
fn new(kind: Kind) -> Self {
Error {
kind,
}
}

pub fn invalid() -> Self {
Error::new(Kind::Invalid)
}

pub fn empty() -> Self {
Error::new(Kind::Empty)
}

pub fn too_many_values() -> Self {
Error::new(Kind::TooMany)
}
}

impl From<::http::header::ToStrError> for Error {
fn from(_: ::http::header::ToStrError) -> Error {
Error::invalid()
}
}

101 changes: 101 additions & 0 deletions headers-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
extern crate http;

pub use http::header::{self, HeaderName, HeaderValue};

mod error;
pub mod parsing;

pub use self::error::{Error, Result};

/// A trait for any object that will represent a header field and value.
///
/// This trait represents the construction and identification of headers,
/// and contains trait-object unsafe methods.
pub trait Header {
/// The name of this header.
const NAME: &'static HeaderName;

/// Decode this type from a `HeaderValue`.
fn decode(values: &mut Values) -> Result<Self>
where
Self: Sized;

/// Encode this type to a `HeaderMap`.
///
/// This function should be infallible. Any errors converting to a
/// `HeaderValue` should have been caught when parsing or constructing
/// this value.
fn encode(&self, values: &mut ToValues);
}

#[derive(Debug)]
pub struct Values<'a> {
inner: http::header::ValueIter<'a, http::header::HeaderValue>,
}

impl<'a> Iterator for Values<'a> {
type Item = &'a HeaderValue;

#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}

fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}

pub struct ToValues<'a> {
state: State<'a>,
}

enum State<'a> {
First(http::header::Entry<'a, HeaderValue>),
Latter(http::header::OccupiedEntry<'a, HeaderValue>),
Tmp,
}

impl<'a> ToValues<'a> {
pub fn append(&mut self, value: HeaderValue) {
let entry = match ::std::mem::replace(&mut self.state, State::Tmp) {
State::First(http::header::Entry::Occupied(mut e)) => {
e.insert(value);
e
},
State::First(http::header::Entry::Vacant(e)) => e.insert_entry(value),
State::Latter(mut e) => {
e.append(value);
e
},
State::Tmp => unreachable!("ToValues State::Tmp"),
};
self.state = State::Latter(entry);
}
}

pub trait HeaderMapExt: self::sealed::Sealed {
fn typed_insert<H>(&mut self, header: H)
where
H: Header;
}

impl HeaderMapExt for http::HeaderMap {
fn typed_insert<H>(&mut self, header: H)
where
H: Header,
{
let entry = self
.entry(H::NAME)
.expect("HeaderName is always valid");
let mut values = ToValues {
state: State::First(entry),
};
header.encode(&mut values);
}
}

mod sealed {
pub trait Sealed {}
impl Sealed for ::http::HeaderMap {}
}
32 changes: 15 additions & 17 deletions src/parsing.rs → headers-core/src/parsing.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,26 @@
//! Utility functions for Header implementations.
use language_tags::LanguageTag;
use std::str;
use std::str::FromStr;
use std::fmt::{self, Display};

//use language_tags::LanguageTag;
use http::HttpTryFrom;
use http::header::HeaderValue;
use percent_encoding;
//use percent_encoding;

use shared::Charset;
//use shared::Charset;


/// Reads a single raw string when parsing a header.
pub fn from_one_raw_str<T: str::FromStr>(_raw: &HeaderValue) -> ::Result<T> {
unimplemented!("from_one_raw_str");
/*
if let Some(line) = raw.one() {
if !line.is_empty() {
return from_raw_str(line)
}
pub fn from_one_value<'a, T: HttpTryFrom<&'a HeaderValue>>(values: &mut ::Values<'a>) -> ::Result<T> {
if let Some(value) = values.next() {
HttpTryFrom::try_from(value)
.map_err(|_| ::Error::invalid())
} else {
Err(::Error::empty())
}
Err(::Error::Header)
*/
}

/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(_raw: &HeaderValue) -> ::Result<Vec<T>> {
pub fn from_comma_delimited<T: ::std::str::FromStr, E: ::std::iter::FromIterator<T>>(_values: &mut ::Values) -> ::Result<E> {
unimplemented!("from_comma_delimited");
/*
let mut result = Vec::new();
Expand All @@ -43,6 +37,7 @@ pub fn from_comma_delimited<T: str::FromStr>(_raw: &HeaderValue) -> ::Result<Vec
*/
}

/*
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
let mut iter = parts.iter();
Expand All @@ -55,7 +50,9 @@ pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> f
}
Ok(())
}
*/

/*
/// An extended header parameter value (i.e., tagged with a character set and optionally,
/// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
#[derive(Clone, Debug, PartialEq)]
Expand Down Expand Up @@ -248,3 +245,4 @@ mod tests {
format!("{}", extended_value));
}
}
*/
15 changes: 15 additions & 0 deletions headers-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]

name = "headers-derive"
version = "0.0.0" # don't forget to update html_root_url
description = "derive(Header)"
authors = ["Sean McArthur <[email protected]>"]

[lib]
name = "headers_derive"
proc-macro = true

[dependencies]
proc-macro2 = "0.4"
quote = "0.6"
syn = "0.14"
113 changes: 113 additions & 0 deletions headers-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;

use proc_macro::TokenStream;
use proc_macro2::Span;
use syn::{Data, Fields, Ident};

#[proc_macro_derive(Header, attributes(header))]
pub fn derive_header(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
impl_header(&ast).into()
}

fn impl_header(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
let fns = match impl_fns(ast) {
Ok(fns) => fns,
Err(msg) => {
return quote! {
compile_error!(#msg);
}.into();
}
};

let decode = fns.decode;
let encode = fns.encode;

let ty = &ast.ident;
let dummy_const = Ident::new(&format!("_IMPL_HEADER_FOR_{}", ty), Span::call_site());
let impl_block = quote! {
impl __hc::Header for #ty {
const NAME: &'static __hc::HeaderName = &__hc::header::HOST;
fn decode(values: &mut __hc::Values) -> __hc::Result<Self> {
#decode
}

fn encode(&self, values: &mut __hc::ToValues) {
#encode
}
}
};

quote! {
const #dummy_const: () = {
extern crate headers_core as __hc;
#impl_block
};
}
}

struct Fns {
encode: proc_macro2::TokenStream,
decode: proc_macro2::TokenStream,
}

fn impl_fns(ast: &syn::DeriveInput) -> Result<Fns, String> {
let ty = &ast.ident;
let st = match ast.data {
Data::Struct(ref st) => st,
_ => {
return Err("derive(Header) only works on structs".into())
}
};

match st.fields {
Fields::Named(ref fields) => {
if fields.named.len() != 1 {
return Err("derive(Header) doesn't support multiple fields".into());
}

let _field = fields
.named
.iter()
.next()
.expect("just checked for len() == 1");

let decode = quote! {
unimplemented!()
};
let encode = quote! {

};

Ok(Fns {
decode,
encode,
})
},
Fields::Unnamed(ref fields) => {
if fields.unnamed.len() != 1 {
return Err("derive(Header) doesn't support multiple fields".into());
}

let decode = quote! {
__hc::parsing::from_one_value(values)
.map(#ty)
};
let encode = quote! {

};

Ok(Fns {
decode,
encode,
})
},
Fields::Unit => {
Err("ah".into())
}
}
}
12 changes: 12 additions & 0 deletions headers-ext/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]

name = "headers-ext"
version = "0.0.0" # don't forget to update html_root_url
description = "typed HTTP headers"
authors = ["Sean McArthur <[email protected]>"]
license = "MIT"

[dependencies]
headers-core = { path = "../headers-core" }
headers-derive = { path = "../headers-derive" }
http = "0.1.7"
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 593d118

Please sign in to comment.