├── .github └── workflows │ └── main.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── rustfmt.toml ├── src └── lib.rs └── tests ├── supported.rs └── tokens.rs /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | workflow_dispatch: 8 | merge_group: 9 | types: [checks_requested] 10 | 11 | jobs: 12 | linux-ci: 13 | name: Linux 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | toolchain: ["stable", "beta", "nightly"] 18 | steps: 19 | - uses: actions/checkout@v2 20 | 21 | - name: Install toolchain 22 | uses: actions-rs/toolchain@v1 23 | with: 24 | profile: minimal 25 | toolchain: ${{ matrix.toolchain }} 26 | override: true 27 | 28 | - name: Cargo build 29 | run: cargo build --verbose 30 | 31 | - name: Cargo test 32 | run: cargo test --verbose 33 | 34 | build_result: 35 | name: Result 36 | runs-on: ubuntu-latest 37 | needs: 38 | - "linux-ci" 39 | 40 | steps: 41 | - name: Mark the job as successful 42 | run: exit 0 43 | if: success() 44 | - name: Mark the job as unsuccessful 45 | run: exit 1 46 | if: "!success()" 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hyper_serde" 3 | version = "0.13.2" 4 | edition = "2018" 5 | authors = ["Anthony Ramine "] 6 | description = "Serde support for hyper types." 7 | license = "MIT OR Apache-2.0" 8 | repository = "https://github.com/servo/hyper_serde" 9 | documentation = "https://docs.rs/hyper_serde" 10 | categories = ["encoding", "web-programming"] 11 | keywords = ["serde", "serialization", "hyper", "cookie", "mime"] 12 | 13 | [lib] 14 | doctest = false 15 | 16 | [dependencies] 17 | cookie = { version = "0.18", default-features = false } 18 | headers = "0.3" 19 | http = "0.2" 20 | hyper = "0.14" 21 | mime = "0.3" 22 | serde = "1.0" 23 | serde_bytes = "0.11" 24 | time = "0.1" 25 | 26 | [dev-dependencies] 27 | serde_test = "1.0" 28 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Anthony Ramine 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Serde support for Hyper types 2 | ============================= 3 | 4 | This crate provides wrappers and convenience functions to support [Serde] for 5 | some types defined in [cookie], [Hyper], [mime] and [time]. 6 | 7 | [cookie]: https://github.com/SergioBenitez/cookie-rs 8 | [Hyper]: https://github.com/hyperium/hyper 9 | [mime]: https://github.com/hyperium/mime 10 | [Serde]: https://github.com/serde-rs/serde 11 | [time]: https://github.com/time-rs/time 12 | 13 | The supported types are: 14 | 15 | * `cookie::Cookie` 16 | * `hyper::header::ContentType` 17 | * `hyper::header::Headers` 18 | * `hyper::http::RawStatus` 19 | * `hyper::method::Method` 20 | * `hyper::Uri` 21 | * `mime::Mime` 22 | * `time::Tm` 23 | 24 | For more details, see the crate documentation. 25 | 26 | ## License 27 | 28 | hyper_serde is licensed under either of 29 | 30 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 31 | https://www.apache.org/licenses/LICENSE-2.0) 32 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 33 | https://opensource.org/licenses/MIT) 34 | 35 | at your option. 36 | 37 | ### Contribution 38 | 39 | Unless you explicitly state otherwise, any contribution intentionally submitted 40 | for inclusion in hyper_serde by you, as defined in the Apache-2.0 license, 41 | shall be dual licensed as above, without any additional terms or conditions. 42 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | match_block_trailing_comma = true 2 | max_width = 80 3 | newline_style = "Unix" 4 | normalize_comments = true 5 | reorder_imported_names = true 6 | reorder_imports = true 7 | use_try_shorthand = true 8 | where_trailing_comma = true 9 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate provides wrappers and convenience functions to make Hyper and 2 | //! Serde work hand in hand. 3 | //! 4 | //! The supported types are: 5 | //! 6 | //! * `cookie::Cookie` 7 | //! * `headers_ext::ContentType` 8 | //! * `hyper::header::Headers` 9 | //! * `hyper::StatusCode` 10 | //! * `hyper::Method` 11 | //! * `hyper::Uri` 12 | //! * `mime::Mime` 13 | //! * `time::Tm` 14 | //! 15 | //! # How do I use a data type with a `HeaderMap` member with Serde? 16 | //! 17 | //! Use the serde attributes `deserialize_with` and `serialize_with`. 18 | //! 19 | //! ``` 20 | //! struct MyStruct { 21 | //! #[serde(deserialize_with = "hyper_serde::deserialize", 22 | //! serialize_with = "hyper_serde::serialize")] 23 | //! headers: HeaderMap, 24 | //! } 25 | //! ``` 26 | //! 27 | //! # How do I encode a `HeaderMap` value with `serde_json::to_string`? 28 | //! 29 | //! Use the `Ser` wrapper. 30 | //! 31 | //! ``` 32 | //! serde_json::to_string(&Ser::new(&headers)) 33 | //! ``` 34 | //! 35 | //! # How do I decode a `Method` value with `serde_json::parse`? 36 | //! 37 | //! Use the `De` wrapper. 38 | //! 39 | //! ``` 40 | //! serde_json::parse::>("\"PUT\"").map(De::into_inner) 41 | //! ``` 42 | //! 43 | //! # How do I send `Cookie` values as part of an IPC channel? 44 | //! 45 | //! Use the `Serde` wrapper. It implements `Deref` and `DerefMut` for 46 | //! convenience. 47 | //! 48 | //! ``` 49 | //! ipc::channel::>() 50 | //! ``` 51 | //! 52 | //! 53 | 54 | #![deny(missing_docs)] 55 | #![deny(unsafe_code)] 56 | 57 | use cookie::Cookie; 58 | use headers::ContentType; 59 | use hyper::StatusCode; 60 | use hyper::header::{HeaderName, HeaderValue}; 61 | use http::HeaderMap; 62 | use hyper::Method; 63 | use mime::Mime; 64 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 65 | use serde_bytes::{ByteBuf, Bytes}; 66 | use serde::de::{self, MapAccess, SeqAccess, Visitor, Error}; 67 | use serde::ser::{SerializeMap, SerializeSeq}; 68 | use std::cmp; 69 | use std::fmt; 70 | use std::ops::{Deref, DerefMut}; 71 | use std::str; 72 | use std::str::FromStr; 73 | use time::{Tm, strptime}; 74 | use hyper::Uri; 75 | 76 | /// Deserialises a `T` value with a given deserializer. 77 | /// 78 | /// This is useful to deserialize Hyper types used in structure fields or 79 | /// tuple members with `#[serde(deserialize_with = "hyper_serde::deserialize")]`. 80 | #[inline(always)] 81 | pub fn deserialize<'de, T, D>(deserializer: D) -> Result 82 | where D: Deserializer<'de>, 83 | De: Deserialize<'de>, 84 | { 85 | De::deserialize(deserializer).map(De::into_inner) 86 | } 87 | 88 | /// Serialises `value` with a given serializer. 89 | /// 90 | /// This is useful to serialize Hyper types used in structure fields or 91 | /// tuple members with `#[serde(serialize_with = "hyper_serde::serialize")]`. 92 | #[inline(always)] 93 | pub fn serialize(value: &T, serializer: S) -> Result 94 | where S: Serializer, 95 | for<'a> Ser<'a, T>: Serialize, 96 | { 97 | Ser::new(value).serialize(serializer) 98 | } 99 | 100 | /// Serialises `value` with a given serializer in a pretty way. 101 | /// 102 | /// This does the same job as `serialize` but with a prettier format 103 | /// for some combinations of types and serialisers. 104 | /// 105 | /// For now, the only change from `serialize` is when serialising `Headers`, 106 | /// where the items in the header values get serialised as strings instead 107 | /// of sequences of bytes, if they represent UTF-8 text. 108 | #[inline(always)] 109 | pub fn serialize_pretty(value: &T, 110 | serializer: S) 111 | -> Result 112 | where S: Serializer, 113 | for<'a> Ser<'a, T>: Serialize, 114 | { 115 | Ser::new_pretty(value).serialize(serializer) 116 | } 117 | 118 | /// A wrapper to deserialize Hyper types. 119 | /// 120 | /// This is useful with functions such as `serde_json::from_str`. 121 | /// 122 | /// Values of this type can only be obtained through 123 | /// the `serde::Deserialize` trait. 124 | #[derive(Debug, PartialEq)] 125 | pub struct De { 126 | v: T, 127 | } 128 | 129 | impl De { 130 | /// Returns a new `De` wrapper 131 | #[inline(always)] 132 | pub fn new(v: T) -> Self { 133 | De { v: v } 134 | } 135 | } 136 | 137 | impl<'de, T> De 138 | where De: Deserialize<'de>, 139 | { 140 | /// Consumes this wrapper, returning the deserialized value. 141 | #[inline(always)] 142 | pub fn into_inner(self) -> T { 143 | self.v 144 | } 145 | } 146 | 147 | /// A wrapper to serialize Hyper types. 148 | /// 149 | /// This is useful with functions such as `serde_json::to_string`. 150 | /// 151 | /// Values of this type can only be passed to the `serde::Serialize` trait. 152 | #[derive(Debug)] 153 | pub struct Ser<'a, T: 'a> { 154 | v: &'a T, 155 | pretty: bool, 156 | } 157 | 158 | impl<'a, T> Ser<'a, T> 159 | where Ser<'a, T>: serde::Serialize, 160 | { 161 | /// Returns a new `Ser` wrapper. 162 | #[inline(always)] 163 | pub fn new(value: &'a T) -> Self { 164 | Ser { 165 | v: value, 166 | pretty: false, 167 | } 168 | } 169 | 170 | /// Returns a new `Ser` wrapper, in pretty mode. 171 | /// 172 | /// See `serialize_pretty`. 173 | #[inline(always)] 174 | pub fn new_pretty(value: &'a T) -> Self { 175 | Ser { 176 | v: value, 177 | pretty: true, 178 | } 179 | } 180 | } 181 | 182 | /// A convenience wrapper to be used as a type parameter, for example when 183 | /// a `Vec` need to be passed to serde. 184 | #[derive(Clone, PartialEq)] 185 | pub struct Serde(pub T) 186 | where for<'de> De: Deserialize<'de>, 187 | for<'a> Ser<'a, T>: Serialize; 188 | 189 | impl Serde 190 | where for<'de> De: Deserialize<'de>, 191 | for<'a> Ser<'a, T>: Serialize, 192 | { 193 | /// Consumes this wrapper, returning the inner value. 194 | #[inline(always)] 195 | pub fn into_inner(self) -> T { 196 | self.0 197 | } 198 | } 199 | 200 | impl fmt::Debug for Serde 201 | where T: fmt::Debug, 202 | for<'de> De: Deserialize<'de>, 203 | for<'a> Ser<'a, T>: Serialize, 204 | { 205 | fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { 206 | self.0.fmt(formatter) 207 | } 208 | } 209 | 210 | impl Deref for Serde 211 | where for<'de> De: Deserialize<'de>, 212 | for<'a> Ser<'a, T>: Serialize, 213 | { 214 | type Target = T; 215 | 216 | fn deref(&self) -> &T { 217 | &self.0 218 | } 219 | } 220 | 221 | impl DerefMut for Serde 222 | where for<'de> De: Deserialize<'de>, 223 | for<'a> Ser<'a, T>: Serialize, 224 | { 225 | fn deref_mut(&mut self) -> &mut T { 226 | &mut self.0 227 | } 228 | } 229 | 230 | impl PartialEq for Serde 231 | where for<'de> De: Deserialize<'de>, 232 | for<'a> Ser<'a, T>: Serialize, 233 | { 234 | fn eq(&self, other: &T) -> bool { 235 | self.0 == *other 236 | } 237 | } 238 | 239 | impl<'b, T> Deserialize<'b> for Serde 240 | where for<'de> De: Deserialize<'de>, 241 | for<'a> Ser<'a, T>: Serialize, 242 | { 243 | fn deserialize(deserializer: D) -> Result 244 | where D: Deserializer<'b>, 245 | { 246 | De::deserialize(deserializer).map(De::into_inner).map(Serde) 247 | } 248 | } 249 | 250 | impl Serialize for Serde 251 | where for<'de> De: Deserialize<'de>, 252 | for<'a> Ser<'a, T>: Serialize, 253 | { 254 | fn serialize(&self, serializer: S) -> Result 255 | where S: Serializer, 256 | { 257 | Ser::new(&self.0).serialize(serializer) 258 | } 259 | } 260 | 261 | impl<'de> Deserialize<'de> for De { 262 | fn deserialize(deserializer: D) -> Result 263 | where D: Deserializer<'de>, 264 | { 265 | deserialize(deserializer).map(|v: mime::Mime| ContentType::from(v)).map(De::new) 266 | } 267 | } 268 | 269 | impl<'a> Serialize for Ser<'a, ContentType> { 270 | fn serialize(&self, serializer: S) -> Result 271 | where S: Serializer, 272 | { 273 | serialize(&mime::Mime::from(self.v.clone()), serializer) 274 | } 275 | } 276 | 277 | impl<'de> Deserialize<'de> for De> { 278 | fn deserialize(deserializer: D) -> Result 279 | where D: Deserializer<'de>, 280 | { 281 | struct CookieVisitor; 282 | 283 | impl<'de> Visitor<'de> for CookieVisitor { 284 | type Value = De>; 285 | 286 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 287 | write!(formatter, "an HTTP cookie header value") 288 | } 289 | 290 | fn visit_str(self, v: &str) -> Result 291 | where E: de::Error, 292 | { 293 | Cookie::parse(v) 294 | .map(Cookie::into_owned) 295 | .map(De::new) 296 | .map_err(|e| E::custom(format!("{:?}", e))) 297 | } 298 | } 299 | 300 | deserializer.deserialize_string(CookieVisitor) 301 | } 302 | } 303 | 304 | impl<'a, 'cookie> Serialize for Ser<'a, Cookie<'cookie>> { 305 | fn serialize(&self, serializer: S) -> Result 306 | where S: Serializer, 307 | { 308 | serializer.serialize_str(&self.v.to_string()) 309 | } 310 | } 311 | 312 | 313 | impl<'de> Deserialize<'de> for De { 314 | fn deserialize(deserializer: D) -> Result 315 | where D: Deserializer<'de>, 316 | { 317 | struct HeadersVisitor; 318 | 319 | impl<'de> Visitor<'de> for HeadersVisitor { 320 | type Value = De; 321 | 322 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 323 | write!(formatter, "a map from header names to header values") 324 | } 325 | 326 | fn visit_unit(self) -> Result 327 | where E: de::Error, 328 | { 329 | Ok(De::new(HeaderMap::new())) 330 | } 331 | 332 | fn visit_map(self, 333 | mut visitor: V) 334 | -> Result 335 | where V: MapAccess<'de>, 336 | { 337 | let mut headers = HeaderMap::new(); 338 | while let Some((k, values)) = visitor.next_entry::()? { 339 | for v in values.0.iter() { 340 | headers.append(HeaderName::from_str(&k).map_err(V::Error::custom)?, HeaderValue::from_bytes(&v).map_err(V::Error::custom)?); 341 | } 342 | } 343 | Ok(De::new(headers)) 344 | } 345 | } 346 | 347 | struct Value(Vec>); 348 | 349 | impl<'de> Deserialize<'de> for Value { 350 | fn deserialize(deserializer: D) -> Result 351 | where D: Deserializer<'de>, 352 | { 353 | deserializer.deserialize_seq(ValueVisitor) 354 | } 355 | } 356 | 357 | struct ValueVisitor; 358 | 359 | impl<'de> Visitor<'de> for ValueVisitor { 360 | type Value = Value; 361 | 362 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 363 | write!(formatter, "an array of strings and sequences of bytes") 364 | } 365 | 366 | fn visit_unit(self) -> Result 367 | where E: de::Error, 368 | { 369 | Ok(Value(vec![])) 370 | } 371 | 372 | fn visit_seq(self, mut visitor: V) -> Result 373 | where V: SeqAccess<'de>, 374 | { 375 | // Clamp to not OOM on rogue values. 376 | let capacity = cmp::min(visitor.size_hint().unwrap_or(0), 64); 377 | let mut values = Vec::with_capacity(capacity); 378 | while let Some(v) = visitor.next_element::()? { 379 | values.push(v.into_vec()); 380 | } 381 | Ok(Value(values)) 382 | } 383 | } 384 | 385 | deserializer.deserialize_map(HeadersVisitor) 386 | } 387 | } 388 | 389 | impl<'a> Serialize for Ser<'a, HeaderMap> { 390 | fn serialize(&self, serializer: S) -> Result 391 | where S: Serializer, 392 | { 393 | struct Value<'headers>(&'headers [Vec], bool); 394 | 395 | impl<'headers> Serialize for Value<'headers> { 396 | fn serialize(&self, serializer: S) -> Result 397 | where S: Serializer, 398 | { 399 | let mut serializer = 400 | serializer.serialize_seq(Some(self.0.len()))?; 401 | for v in self.0 { 402 | if self.1 { 403 | if let Ok(v) = str::from_utf8(v) { 404 | serializer.serialize_element(v)?; 405 | continue; 406 | } 407 | } 408 | serializer.serialize_element(&Bytes::new(v))?; 409 | } 410 | serializer.end() 411 | } 412 | } 413 | 414 | let mut serializer = serializer.serialize_map(Some(self.v.keys_len()))?; 415 | for name in self.v.keys() { 416 | let values = self.v.get_all(name); 417 | serializer.serialize_entry(name.as_str(), &Value(&values.iter().map(|v| v.as_bytes().iter().cloned().collect()).collect::>>(), self.pretty))?; 418 | } 419 | serializer.end() 420 | } 421 | } 422 | 423 | impl<'de> Deserialize<'de> for De { 424 | fn deserialize(deserializer: D) -> Result 425 | where D: Deserializer<'de>, 426 | { 427 | struct MethodVisitor; 428 | 429 | impl<'de> Visitor<'de> for MethodVisitor { 430 | type Value = De; 431 | 432 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 433 | write!(formatter, "an HTTP method") 434 | } 435 | 436 | fn visit_str(self, v: &str) -> Result 437 | where E: de::Error, 438 | { 439 | v.parse::().map(De::new).map_err(E::custom) 440 | } 441 | } 442 | 443 | deserializer.deserialize_string(MethodVisitor) 444 | } 445 | } 446 | 447 | impl<'a> Serialize for Ser<'a, Method> { 448 | fn serialize(&self, serializer: S) -> Result 449 | where S: Serializer, 450 | { 451 | Serialize::serialize(self.v.as_ref(), serializer) 452 | } 453 | } 454 | 455 | impl<'de> Deserialize<'de> for De { 456 | fn deserialize(deserializer: D) -> Result 457 | where D: Deserializer<'de>, 458 | { 459 | struct MimeVisitor; 460 | 461 | impl<'de> Visitor<'de> for MimeVisitor { 462 | type Value = De; 463 | 464 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 465 | write!(formatter, "a mime type") 466 | } 467 | 468 | fn visit_str(self, v: &str) -> Result 469 | where E: de::Error, 470 | { 471 | v.parse::().map(De::new).map_err(|_| { 472 | E::custom("could not parse mime type") 473 | }) 474 | } 475 | } 476 | 477 | deserializer.deserialize_string(MimeVisitor) 478 | } 479 | } 480 | 481 | impl<'a> Serialize for Ser<'a, Mime> { 482 | fn serialize(&self, serializer: S) -> Result 483 | where S: Serializer, 484 | { 485 | serializer.serialize_str(&self.v.to_string()) 486 | } 487 | } 488 | 489 | impl<'de> Deserialize<'de> for De { 490 | fn deserialize(deserializer: D) -> Result 491 | where D: Deserializer<'de>, 492 | { 493 | let code = Deserialize::deserialize(deserializer)?; 494 | Ok(De::new(StatusCode::from_u16(code).map_err(D::Error::custom)?)) 495 | } 496 | } 497 | 498 | impl<'a> Serialize for Ser<'a, StatusCode> { 499 | fn serialize(&self, serializer: S) -> Result 500 | where S: Serializer, 501 | { 502 | self.v.as_u16().serialize(serializer) 503 | } 504 | } 505 | 506 | impl<'a> Serialize for Ser<'a, (StatusCode, String)> { 507 | fn serialize(&self, serializer: S) -> Result 508 | where S: Serializer, 509 | { 510 | let mut serializer = serializer.serialize_seq(Some(2))?; 511 | serializer.serialize_element(&Ser::new(&self.v.0))?; 512 | serializer.serialize_element(&self.v.1)?; 513 | serializer.end() 514 | } 515 | } 516 | 517 | impl<'de> Deserialize<'de> for De<(StatusCode, String)> { 518 | fn deserialize(deserializer: D) -> Result 519 | where D: Deserializer<'de>, 520 | { 521 | Ok(De::new(deserializer.deserialize_seq(StatusVisitor)?)) 522 | } 523 | } 524 | 525 | struct StatusVisitor; 526 | 527 | impl<'de> Visitor<'de> for StatusVisitor { 528 | type Value = (StatusCode, String); 529 | 530 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 531 | write!(formatter, "an array containing a status code and a reason string") 532 | } 533 | 534 | fn visit_seq(self, mut visitor: V) -> Result 535 | where V: SeqAccess<'de>, 536 | { 537 | 538 | let code = visitor.next_element::()?.ok_or_else(|| 539 | V::Error::custom("Can't find the status code") 540 | )?; 541 | let code = StatusCode::from_u16(code).map_err(V::Error::custom)?; 542 | let reason = visitor.next_element::()?.ok_or_else(|| 543 | V::Error::custom("Can't find the reason string") 544 | )?; 545 | Ok((code, reason)) 546 | } 547 | } 548 | 549 | impl<'de> Deserialize<'de> for De { 550 | fn deserialize(deserializer: D) -> Result 551 | where D: Deserializer<'de>, 552 | { 553 | struct TmVisitor; 554 | 555 | impl<'de> Visitor<'de> for TmVisitor { 556 | type Value = De; 557 | 558 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 559 | write!(formatter, "a date and time according to RFC 3339") 560 | } 561 | 562 | fn visit_str(self, v: &str) -> Result 563 | where E: de::Error, 564 | { 565 | strptime(v, "%Y-%m-%dT%H:%M:%SZ").map(De::new).map_err(|e| { 566 | E::custom(e.to_string()) 567 | }) 568 | } 569 | } 570 | 571 | deserializer.deserialize_string(TmVisitor) 572 | } 573 | } 574 | 575 | impl<'a> Serialize for Ser<'a, Tm> { 576 | fn serialize(&self, serializer: S) -> Result 577 | where S: Serializer, 578 | { 579 | serializer.serialize_str(&self.v.rfc3339().to_string()) 580 | } 581 | } 582 | 583 | impl<'de> Deserialize<'de> for De { 584 | fn deserialize(deserializer: D) -> Result 585 | where D: Deserializer<'de>, 586 | { 587 | struct UriVisitor; 588 | 589 | impl<'de> Visitor<'de> for UriVisitor { 590 | type Value = De; 591 | 592 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 593 | write!(formatter, "an HTTP Uri value") 594 | } 595 | 596 | fn visit_str(self, v: &str) -> Result 597 | where E: de::Error, 598 | { 599 | Uri::from_str(v) 600 | .map(De::new) 601 | .map_err(|e| E::custom(format!("{}", e))) 602 | } 603 | } 604 | 605 | deserializer.deserialize_string(UriVisitor) 606 | } 607 | } 608 | 609 | impl<'a> Serialize for Ser<'a, Uri> { 610 | fn serialize(&self, serializer: S) -> Result 611 | where S: Serializer, 612 | { 613 | // As of hyper 0.12, hyper::Uri (re-exported http::Uri) 614 | // does not implement as_ref due to underlying implementation 615 | // so we must construct a string to serialize it 616 | serializer.serialize_str(&self.v.to_string()) 617 | } 618 | } 619 | -------------------------------------------------------------------------------- /tests/supported.rs: -------------------------------------------------------------------------------- 1 | extern crate cookie; 2 | extern crate headers; 3 | extern crate http; 4 | extern crate hyper; 5 | extern crate hyper_serde; 6 | extern crate mime; 7 | extern crate serde; 8 | extern crate time; 9 | 10 | use cookie::Cookie; 11 | use http::header::HeaderMap; 12 | use headers::ContentType; 13 | use hyper::{Method, StatusCode, Uri}; 14 | use hyper_serde::{De, Ser, Serde}; 15 | use mime::Mime; 16 | use serde::{Deserialize, Serialize}; 17 | use time::Tm; 18 | 19 | fn is_supported() 20 | where for<'de> De: Deserialize<'de>, 21 | for<'a> Ser<'a, T>: Serialize, 22 | for <'de> Serde: Deserialize<'de> + Serialize 23 | { 24 | } 25 | 26 | #[test] 27 | fn supported() { 28 | is_supported::(); 29 | is_supported::(); 30 | is_supported::(); 31 | is_supported::(); 32 | is_supported::(); 33 | is_supported::(); 34 | is_supported::(); 35 | is_supported::(); 36 | } 37 | -------------------------------------------------------------------------------- /tests/tokens.rs: -------------------------------------------------------------------------------- 1 | extern crate cookie; 2 | extern crate headers; 3 | extern crate http; 4 | extern crate hyper; 5 | extern crate hyper_serde; 6 | extern crate mime; 7 | extern crate serde; 8 | extern crate serde_test; 9 | extern crate time; 10 | 11 | use cookie::{time::Duration, Cookie}; 12 | use headers::ContentType; 13 | use http::header::{self, HeaderMap, HeaderValue}; 14 | use http::StatusCode; 15 | use hyper::{Method, Uri}; 16 | use hyper_serde::{De, Ser}; 17 | use serde_test::{assert_de_tokens, assert_ser_tokens, Token}; 18 | 19 | #[test] 20 | fn test_content_type() { 21 | let content_type = ContentType::from("Application/Json".parse::().unwrap()); 22 | let tokens = &[Token::Str("application/json")]; 23 | 24 | assert_ser_tokens(&Ser::new(&content_type), tokens); 25 | assert_de_tokens(&De::new(content_type), tokens); 26 | } 27 | 28 | #[test] 29 | fn test_cookie() { 30 | // Unfortunately we have to do the to_string().parse() dance here to avoid the object being a 31 | // string with a bunch of indices in it which apparently is different from the exact same 32 | // cookie but parsed as a bunch of strings. 33 | let cookie: Cookie = Cookie::build(("Hello", "World!")) 34 | .max_age(Duration::seconds(42)) 35 | .domain("servo.org") 36 | .path("/") 37 | .secure(true) 38 | .http_only(false) 39 | .to_string().parse().unwrap(); 40 | 41 | let tokens = &[Token::Str("Hello=World!; Secure; Path=/; Domain=servo.org; Max-Age=42")]; 42 | 43 | assert_ser_tokens(&Ser::new(&cookie), tokens); 44 | assert_de_tokens(&De::new(cookie), tokens); 45 | } 46 | 47 | #[test] 48 | fn test_headers_empty() { 49 | let headers = HeaderMap::new(); 50 | 51 | let tokens = &[Token::Map { len: Some(0) }, Token::MapEnd]; 52 | 53 | assert_ser_tokens(&Ser::new(&headers), tokens); 54 | assert_de_tokens(&De::new(headers), tokens); 55 | } 56 | 57 | #[test] 58 | fn test_headers_not_empty() { 59 | let mut headers = HeaderMap::new(); 60 | headers.insert(header::HOST, HeaderValue::from_static("baguette")); 61 | 62 | // In http, HeaderMap is internally a HashMap and thus testing this 63 | // with multiple headers is non-deterministic. 64 | 65 | let tokens = &[Token::Map{ len: Some(1) }, 66 | Token::Str("host"), 67 | Token::Seq{ len: Some(1) }, 68 | Token::Bytes(b"baguette"), 69 | Token::SeqEnd, 70 | Token::MapEnd]; 71 | 72 | assert_ser_tokens(&Ser::new(&headers), tokens); 73 | assert_de_tokens(&De::new(headers.clone()), tokens); 74 | 75 | let pretty = &[Token::Map{ len: Some(1) }, 76 | Token::Str("host"), 77 | Token::Seq{ len: Some(1) }, 78 | Token::Str("baguette"), 79 | Token::SeqEnd, 80 | Token::MapEnd]; 81 | 82 | assert_ser_tokens(&Ser::new_pretty(&headers), pretty); 83 | assert_de_tokens(&De::new(headers), pretty); 84 | } 85 | 86 | #[test] 87 | fn test_method() { 88 | let method = Method::PUT; 89 | let tokens = &[Token::Str("PUT")]; 90 | 91 | assert_ser_tokens(&Ser::new(&method), tokens); 92 | assert_de_tokens(&De::new(method), tokens); 93 | } 94 | 95 | #[test] 96 | fn test_raw_status() { 97 | let raw_status = StatusCode::from_u16(200).unwrap(); 98 | let tokens = &[Token::U16(200)]; 99 | 100 | assert_ser_tokens(&Ser::new(&raw_status), tokens); 101 | assert_de_tokens(&De::new(raw_status), tokens); 102 | } 103 | 104 | #[test] 105 | fn test_tm() { 106 | use time::strptime; 107 | 108 | let time = strptime("2017-02-22T12:03:31Z", "%Y-%m-%dT%H:%M:%SZ").unwrap(); 109 | let tokens = &[Token::Str("2017-02-22T12:03:31Z")]; 110 | 111 | assert_ser_tokens(&Ser::new(&time), tokens); 112 | assert_de_tokens(&De::new(time), tokens); 113 | } 114 | 115 | #[test] 116 | fn test_uri() { 117 | use std::str::FromStr; 118 | 119 | // Note that fragment is not serialized / deserialized 120 | let uri_string = "abc://username:password@example.com:123/path/data?key=value&key2=value2"; 121 | let uri = Uri::from_str(uri_string).unwrap(); 122 | let tokens = &[Token::Str(uri_string)]; 123 | 124 | assert_ser_tokens(&Ser::new(&uri), tokens); 125 | assert_de_tokens(&De::new(uri), tokens); 126 | } 127 | --------------------------------------------------------------------------------