├── .github └── workflows │ └── CI.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bors.toml ├── rustfmt.toml ├── src ├── de.rs ├── lib.rs └── ser │ ├── key.rs │ ├── mod.rs │ ├── pair.rs │ ├── part.rs │ └── value.rs └── tests ├── test_deserialize.rs └── test_serialize.rs /.github/workflows/CI.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | 8 | env: 9 | RUST_BACKTRACE: 1 10 | 11 | jobs: 12 | style: 13 | name: Check Style 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v1 18 | 19 | - name: Install Rust 20 | uses: actions-rs/toolchain@v1 21 | with: 22 | profile: minimal 23 | toolchain: stable 24 | override: true 25 | components: rustfmt 26 | 27 | - name: cargo fmt --check 28 | uses: actions-rs/cargo@v1 29 | with: 30 | command: fmt 31 | args: --all -- --check 32 | 33 | test: 34 | name: Test ${{ matrix.rust }} on ${{ matrix.os }} 35 | needs: [style] 36 | strategy: 37 | matrix: 38 | rust: 39 | - stable 40 | - beta 41 | - nightly 42 | 43 | os: 44 | - ubuntu-latest 45 | - windows-latest 46 | - macOS-latest 47 | 48 | runs-on: ${{ matrix.os }} 49 | 50 | steps: 51 | - name: Checkout 52 | uses: actions/checkout@v1 53 | 54 | - name: Install Rust (${{ matrix.rust }}) 55 | uses: actions-rs/toolchain@v1 56 | with: 57 | profile: minimal 58 | toolchain: ${{ matrix.rust }} 59 | override: true 60 | 61 | - name: Test 62 | uses: actions-rs/cargo@v1 63 | with: 64 | command: test 65 | args: ${{ matrix.features }} 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde_urlencoded" 3 | version = "0.7.1" # bump in documentation link and in README on update 4 | authors = ["Anthony Ramine "] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/nox/serde_urlencoded" 7 | documentation = "https://docs.rs/serde_urlencoded/0.7.1/serde_urlencoded/" 8 | description = "`x-www-form-urlencoded` meets Serde" 9 | categories = ["encoding", "web-programming"] 10 | keywords = ["serde", "serialization", "urlencoded"] 11 | exclude = ["/.travis.yml", "/bors.toml"] 12 | edition = "2018" 13 | 14 | [badges] 15 | travis-ci = {repository = "nox/serde_urlencoded"} 16 | 17 | [lib] 18 | test = false 19 | 20 | [dependencies] 21 | form_urlencoded = "1" 22 | itoa = "1" 23 | ryu = "1" 24 | serde = "1.0.69" 25 | 26 | [dev-dependencies] 27 | serde_derive = "1" 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 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | `x-www-form-urlencoded` meets Serde 2 | =================================== 3 | 4 | This crate is a Rust library for serialising to and deserialising from 5 | the [`application/x-www-form-urlencoded`][urlencoded] format. It is built 6 | upon [Serde], a high performance generic serialization framework and [rust-url], 7 | a URL parser for Rust. 8 | 9 | [rust-url]: https://github.com/servo/rust-url 10 | [Serde]: https://github.com/serde-rs/serde 11 | [urlencoded]: https://url.spec.whatwg.org/#application/x-www-form-urlencoded 12 | 13 | Installation 14 | ============ 15 | 16 | This crate works with Cargo and can be found on 17 | [crates.io] with a `Cargo.toml` like: 18 | 19 | ```toml 20 | [dependencies] 21 | serde_urlencoded = "0.7" 22 | ``` 23 | 24 | The documentation is available on [docs.rs]. 25 | 26 | [crates.io]: https://crates.io/crates/serde_urlencoded 27 | [docs.rs]: https://docs.rs/serde_urlencoded/0.7.1/serde_urlencoded/ 28 | 29 | ## Getting help 30 | 31 | Serde developers live in the #serde channel on 32 | [`irc.mozilla.org`](https://wiki.mozilla.org/IRC) and most rust-url developers 33 | live in the #servo one. The #rust channel is also a good resource with generally 34 | faster response time but less specific knowledge about Serde, rust-url or this 35 | crate. If IRC is not your thing, we are happy to respond to [GitHub 36 | issues](https://github.com/nox/serde_urlencoded/issues/new) as well. 37 | 38 | ## License 39 | 40 | serde_urlencoded is licensed under either of 41 | 42 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 43 | http://www.apache.org/licenses/LICENSE-2.0) 44 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 45 | http://opensource.org/licenses/MIT) 46 | 47 | at your option. 48 | 49 | ### Contribution 50 | 51 | Unless you explicitly state otherwise, any contribution intentionally submitted 52 | for inclusion in serde_urlencoded by you, as defined in the Apache-2.0 license, 53 | shall be dual licensed as above, without any additional terms or conditions. 54 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = ["continuous-integration/travis-ci/push"] 2 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | match_block_trailing_comma = false 2 | max_width = 80 3 | newline_style = "Unix" 4 | reorder_imports = true 5 | use_try_shorthand = true 6 | -------------------------------------------------------------------------------- /src/de.rs: -------------------------------------------------------------------------------- 1 | //! Deserialization support for the `application/x-www-form-urlencoded` format. 2 | 3 | use form_urlencoded::parse; 4 | use form_urlencoded::Parse as UrlEncodedParse; 5 | use serde::de::value::MapDeserializer; 6 | use serde::de::Error as de_Error; 7 | use serde::de::{self, IntoDeserializer}; 8 | use serde::forward_to_deserialize_any; 9 | use std::borrow::Cow; 10 | use std::io::Read; 11 | 12 | #[doc(inline)] 13 | pub use serde::de::value::Error; 14 | 15 | /// Deserializes a `application/x-www-form-urlencoded` value from a `&[u8]`. 16 | /// 17 | /// ``` 18 | /// let meal = vec![ 19 | /// ("bread".to_owned(), "baguette".to_owned()), 20 | /// ("cheese".to_owned(), "comté".to_owned()), 21 | /// ("meat".to_owned(), "ham".to_owned()), 22 | /// ("fat".to_owned(), "butter".to_owned()), 23 | /// ]; 24 | /// 25 | /// assert_eq!( 26 | /// serde_urlencoded::from_bytes::>( 27 | /// b"bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"), 28 | /// Ok(meal)); 29 | /// ``` 30 | pub fn from_bytes<'de, T>(input: &'de [u8]) -> Result 31 | where 32 | T: de::Deserialize<'de>, 33 | { 34 | T::deserialize(Deserializer::new(parse(input))) 35 | } 36 | 37 | /// Deserializes a `application/x-www-form-urlencoded` value from a `&str`. 38 | /// 39 | /// ``` 40 | /// let meal = vec![ 41 | /// ("bread".to_owned(), "baguette".to_owned()), 42 | /// ("cheese".to_owned(), "comté".to_owned()), 43 | /// ("meat".to_owned(), "ham".to_owned()), 44 | /// ("fat".to_owned(), "butter".to_owned()), 45 | /// ]; 46 | /// 47 | /// assert_eq!( 48 | /// serde_urlencoded::from_str::>( 49 | /// "bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"), 50 | /// Ok(meal)); 51 | /// ``` 52 | pub fn from_str<'de, T>(input: &'de str) -> Result 53 | where 54 | T: de::Deserialize<'de>, 55 | { 56 | from_bytes(input.as_bytes()) 57 | } 58 | 59 | /// Convenience function that reads all bytes from `reader` and deserializes 60 | /// them with `from_bytes`. 61 | pub fn from_reader(mut reader: R) -> Result 62 | where 63 | T: de::DeserializeOwned, 64 | R: Read, 65 | { 66 | let mut buf = vec![]; 67 | reader.read_to_end(&mut buf).map_err(|e| { 68 | de::Error::custom(format_args!("could not read input: {}", e)) 69 | })?; 70 | from_bytes(&buf) 71 | } 72 | 73 | /// A deserializer for the `application/x-www-form-urlencoded` format. 74 | /// 75 | /// * Supported top-level outputs are structs, maps and sequences of pairs, 76 | /// with or without a given length. 77 | /// 78 | /// * Main `deserialize` methods defers to `deserialize_map`. 79 | /// 80 | /// * Everything else but `deserialize_seq` and `deserialize_seq_fixed_size` 81 | /// defers to `deserialize`. 82 | pub struct Deserializer<'de> { 83 | inner: MapDeserializer<'de, PartIterator<'de>, Error>, 84 | } 85 | 86 | impl<'de> Deserializer<'de> { 87 | /// Returns a new `Deserializer`. 88 | pub fn new(parser: UrlEncodedParse<'de>) -> Self { 89 | Deserializer { 90 | inner: MapDeserializer::new(PartIterator(parser)), 91 | } 92 | } 93 | } 94 | 95 | impl<'de> de::Deserializer<'de> for Deserializer<'de> { 96 | type Error = Error; 97 | 98 | fn deserialize_any(self, visitor: V) -> Result 99 | where 100 | V: de::Visitor<'de>, 101 | { 102 | self.deserialize_map(visitor) 103 | } 104 | 105 | fn deserialize_map(self, visitor: V) -> Result 106 | where 107 | V: de::Visitor<'de>, 108 | { 109 | visitor.visit_map(self.inner) 110 | } 111 | 112 | fn deserialize_seq(self, visitor: V) -> Result 113 | where 114 | V: de::Visitor<'de>, 115 | { 116 | visitor.visit_seq(self.inner) 117 | } 118 | 119 | fn deserialize_unit(self, visitor: V) -> Result 120 | where 121 | V: de::Visitor<'de>, 122 | { 123 | self.inner.end()?; 124 | visitor.visit_unit() 125 | } 126 | 127 | forward_to_deserialize_any! { 128 | bool 129 | u8 130 | u16 131 | u32 132 | u64 133 | u128 134 | i8 135 | i16 136 | i32 137 | i64 138 | i128 139 | f32 140 | f64 141 | char 142 | str 143 | string 144 | option 145 | bytes 146 | byte_buf 147 | unit_struct 148 | newtype_struct 149 | tuple_struct 150 | struct 151 | identifier 152 | tuple 153 | enum 154 | ignored_any 155 | } 156 | } 157 | 158 | struct PartIterator<'de>(UrlEncodedParse<'de>); 159 | 160 | impl<'de> Iterator for PartIterator<'de> { 161 | type Item = (Part<'de>, Part<'de>); 162 | 163 | fn next(&mut self) -> Option { 164 | self.0.next().map(|(k, v)| (Part(k), Part(v))) 165 | } 166 | } 167 | 168 | struct Part<'de>(Cow<'de, str>); 169 | 170 | impl<'de> IntoDeserializer<'de> for Part<'de> { 171 | type Deserializer = Self; 172 | 173 | fn into_deserializer(self) -> Self::Deserializer { 174 | self 175 | } 176 | } 177 | 178 | macro_rules! forward_parsed_value { 179 | ($($ty:ident => $method:ident,)*) => { 180 | $( 181 | fn $method(self, visitor: V) -> Result 182 | where V: de::Visitor<'de> 183 | { 184 | match self.0.parse::<$ty>() { 185 | Ok(val) => val.into_deserializer().$method(visitor), 186 | Err(e) => Err(de::Error::custom(e)) 187 | } 188 | } 189 | )* 190 | } 191 | } 192 | 193 | impl<'de> de::Deserializer<'de> for Part<'de> { 194 | type Error = Error; 195 | 196 | fn deserialize_any(self, visitor: V) -> Result 197 | where 198 | V: de::Visitor<'de>, 199 | { 200 | match self.0 { 201 | Cow::Borrowed(value) => visitor.visit_borrowed_str(value), 202 | Cow::Owned(value) => visitor.visit_string(value), 203 | } 204 | } 205 | 206 | fn deserialize_option(self, visitor: V) -> Result 207 | where 208 | V: de::Visitor<'de>, 209 | { 210 | visitor.visit_some(self) 211 | } 212 | 213 | fn deserialize_enum( 214 | self, 215 | _name: &'static str, 216 | _variants: &'static [&'static str], 217 | visitor: V, 218 | ) -> Result 219 | where 220 | V: de::Visitor<'de>, 221 | { 222 | visitor.visit_enum(ValueEnumAccess(self.0)) 223 | } 224 | 225 | fn deserialize_newtype_struct( 226 | self, 227 | _name: &'static str, 228 | visitor: V, 229 | ) -> Result 230 | where 231 | V: de::Visitor<'de>, 232 | { 233 | visitor.visit_newtype_struct(self) 234 | } 235 | 236 | forward_to_deserialize_any! { 237 | char 238 | str 239 | string 240 | unit 241 | bytes 242 | byte_buf 243 | unit_struct 244 | tuple_struct 245 | struct 246 | identifier 247 | tuple 248 | ignored_any 249 | seq 250 | map 251 | } 252 | 253 | forward_parsed_value! { 254 | bool => deserialize_bool, 255 | u8 => deserialize_u8, 256 | u16 => deserialize_u16, 257 | u32 => deserialize_u32, 258 | u64 => deserialize_u64, 259 | u128 => deserialize_u128, 260 | i8 => deserialize_i8, 261 | i16 => deserialize_i16, 262 | i32 => deserialize_i32, 263 | i64 => deserialize_i64, 264 | i128 => deserialize_i128, 265 | f32 => deserialize_f32, 266 | f64 => deserialize_f64, 267 | } 268 | } 269 | 270 | struct ValueEnumAccess<'de>(Cow<'de, str>); 271 | 272 | impl<'de> de::EnumAccess<'de> for ValueEnumAccess<'de> { 273 | type Error = Error; 274 | type Variant = UnitOnlyVariantAccess; 275 | 276 | fn variant_seed( 277 | self, 278 | seed: V, 279 | ) -> Result<(V::Value, Self::Variant), Self::Error> 280 | where 281 | V: de::DeserializeSeed<'de>, 282 | { 283 | let variant = seed.deserialize(self.0.into_deserializer())?; 284 | Ok((variant, UnitOnlyVariantAccess)) 285 | } 286 | } 287 | 288 | struct UnitOnlyVariantAccess; 289 | 290 | impl<'de> de::VariantAccess<'de> for UnitOnlyVariantAccess { 291 | type Error = Error; 292 | 293 | fn unit_variant(self) -> Result<(), Self::Error> { 294 | Ok(()) 295 | } 296 | 297 | fn newtype_variant_seed(self, _seed: T) -> Result 298 | where 299 | T: de::DeserializeSeed<'de>, 300 | { 301 | Err(Error::custom("expected unit variant")) 302 | } 303 | 304 | fn tuple_variant( 305 | self, 306 | _len: usize, 307 | _visitor: V, 308 | ) -> Result 309 | where 310 | V: de::Visitor<'de>, 311 | { 312 | Err(Error::custom("expected unit variant")) 313 | } 314 | 315 | fn struct_variant( 316 | self, 317 | _fields: &'static [&'static str], 318 | _visitor: V, 319 | ) -> Result 320 | where 321 | V: de::Visitor<'de>, 322 | { 323 | Err(Error::custom("expected unit variant")) 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! `x-www-form-urlencoded` meets Serde 2 | 3 | #![warn(unused_extern_crates)] 4 | #![forbid(unsafe_code)] 5 | 6 | pub mod de; 7 | pub mod ser; 8 | 9 | #[doc(inline)] 10 | pub use crate::de::{from_bytes, from_reader, from_str, Deserializer}; 11 | #[doc(inline)] 12 | pub use crate::ser::{to_string, Serializer}; 13 | -------------------------------------------------------------------------------- /src/ser/key.rs: -------------------------------------------------------------------------------- 1 | use crate::ser::part::Sink; 2 | use crate::ser::Error; 3 | use serde::Serialize; 4 | use std::borrow::Cow; 5 | use std::ops::Deref; 6 | 7 | pub enum Key<'key> { 8 | Static(&'static str), 9 | Dynamic(Cow<'key, str>), 10 | } 11 | 12 | impl<'key> Deref for Key<'key> { 13 | type Target = str; 14 | 15 | fn deref(&self) -> &str { 16 | match *self { 17 | Key::Static(key) => key, 18 | Key::Dynamic(ref key) => key, 19 | } 20 | } 21 | } 22 | 23 | impl<'key> From> for Cow<'static, str> { 24 | fn from(key: Key<'key>) -> Self { 25 | match key { 26 | Key::Static(key) => key.into(), 27 | Key::Dynamic(key) => key.into_owned().into(), 28 | } 29 | } 30 | } 31 | 32 | pub struct KeySink { 33 | end: End, 34 | } 35 | 36 | impl KeySink 37 | where 38 | End: for<'key> FnOnce(Key<'key>) -> Result, 39 | { 40 | pub fn new(end: End) -> Self { 41 | KeySink { end } 42 | } 43 | } 44 | 45 | impl Sink for KeySink 46 | where 47 | End: for<'key> FnOnce(Key<'key>) -> Result, 48 | { 49 | type Ok = Ok; 50 | 51 | fn serialize_static_str(self, value: &'static str) -> Result { 52 | (self.end)(Key::Static(value)) 53 | } 54 | 55 | fn serialize_str(self, value: &str) -> Result { 56 | (self.end)(Key::Dynamic(value.into())) 57 | } 58 | 59 | fn serialize_string(self, value: String) -> Result { 60 | (self.end)(Key::Dynamic(value.into())) 61 | } 62 | 63 | fn serialize_none(self) -> Result { 64 | Err(self.unsupported("none")) 65 | } 66 | 67 | fn serialize_some( 68 | self, 69 | _value: &T, 70 | ) -> Result { 71 | Err(self.unsupported("some")) 72 | } 73 | 74 | fn unsupported(self, type_str: &'static str) -> Error { 75 | Error::Custom(format!("unsupported key type: {type_str}").into()) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/ser/mod.rs: -------------------------------------------------------------------------------- 1 | //! Serialization support for the `application/x-www-form-urlencoded` format. 2 | 3 | mod key; 4 | mod pair; 5 | mod part; 6 | mod value; 7 | 8 | use form_urlencoded::Serializer as UrlEncodedSerializer; 9 | use form_urlencoded::Target as UrlEncodedTarget; 10 | use serde::ser; 11 | use std::borrow::Cow; 12 | use std::error; 13 | use std::fmt; 14 | use std::str; 15 | 16 | /// Serializes a value into a `application/x-www-form-urlencoded` `String` buffer. 17 | /// 18 | /// ``` 19 | /// let meal = &[ 20 | /// ("bread", "baguette"), 21 | /// ("cheese", "comté"), 22 | /// ("meat", "ham"), 23 | /// ("fat", "butter"), 24 | /// ]; 25 | /// 26 | /// assert_eq!( 27 | /// serde_urlencoded::to_string(meal), 28 | /// Ok("bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter".to_owned())); 29 | /// ``` 30 | pub fn to_string(input: T) -> Result { 31 | let mut urlencoder = UrlEncodedSerializer::new("".to_owned()); 32 | input.serialize(Serializer::new(&mut urlencoder))?; 33 | Ok(urlencoder.finish()) 34 | } 35 | 36 | /// A serializer for the `application/x-www-form-urlencoded` format. 37 | /// 38 | /// * Supported top-level inputs are structs, maps and sequences of pairs, 39 | /// with or without a given length. 40 | /// 41 | /// * Supported keys and values are integers, bytes (if convertible to strings), 42 | /// unit structs and unit variants. 43 | /// 44 | /// * Newtype structs defer to their inner values. 45 | pub struct Serializer<'input, 'output, Target: UrlEncodedTarget> { 46 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 47 | } 48 | 49 | impl<'input, 'output, Target: 'output + UrlEncodedTarget> 50 | Serializer<'input, 'output, Target> 51 | { 52 | /// Returns a new `Serializer`. 53 | pub fn new( 54 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 55 | ) -> Self { 56 | Serializer { urlencoder } 57 | } 58 | } 59 | 60 | /// Errors returned during serializing to `application/x-www-form-urlencoded`. 61 | #[derive(Clone, Debug, PartialEq, Eq)] 62 | pub enum Error { 63 | Custom(Cow<'static, str>), 64 | Utf8(str::Utf8Error), 65 | } 66 | 67 | impl fmt::Display for Error { 68 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 69 | match *self { 70 | Error::Custom(ref msg) => msg.fmt(f), 71 | Error::Utf8(ref err) => write!(f, "invalid UTF-8: {}", err), 72 | } 73 | } 74 | } 75 | 76 | impl error::Error for Error { 77 | fn description(&self) -> &str { 78 | match *self { 79 | Error::Custom(ref msg) => msg, 80 | Error::Utf8(ref err) => error::Error::description(err), 81 | } 82 | } 83 | 84 | /// The lower-level cause of this error, in the case of a `Utf8` error. 85 | fn cause(&self) -> Option<&dyn error::Error> { 86 | match *self { 87 | Error::Custom(_) => None, 88 | Error::Utf8(ref err) => Some(err), 89 | } 90 | } 91 | 92 | /// The lower-level source of this error, in the case of a `Utf8` error. 93 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { 94 | match *self { 95 | Error::Custom(_) => None, 96 | Error::Utf8(ref err) => Some(err), 97 | } 98 | } 99 | } 100 | 101 | impl ser::Error for Error { 102 | fn custom(msg: T) -> Self { 103 | Error::Custom(format!("{}", msg).into()) 104 | } 105 | } 106 | 107 | /// Sequence serializer. 108 | pub struct SeqSerializer<'input, 'output, Target: UrlEncodedTarget> { 109 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 110 | } 111 | 112 | /// Tuple serializer. 113 | /// 114 | /// Mostly used for arrays. 115 | pub struct TupleSerializer<'input, 'output, Target: UrlEncodedTarget> { 116 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 117 | } 118 | 119 | /// Tuple struct serializer. 120 | /// 121 | /// Never instantiated, tuple structs are not supported. 122 | pub struct TupleStructSerializer<'input, 'output, T: UrlEncodedTarget> { 123 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, 124 | } 125 | 126 | /// Tuple variant serializer. 127 | /// 128 | /// Never instantiated, tuple variants are not supported. 129 | pub struct TupleVariantSerializer<'input, 'output, T: UrlEncodedTarget> { 130 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, 131 | } 132 | 133 | /// Map serializer. 134 | pub struct MapSerializer<'input, 'output, Target: UrlEncodedTarget> { 135 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 136 | key: Option>, 137 | } 138 | 139 | /// Struct serializer. 140 | pub struct StructSerializer<'input, 'output, Target: UrlEncodedTarget> { 141 | urlencoder: &'output mut UrlEncodedSerializer<'input, Target>, 142 | } 143 | 144 | /// Struct variant serializer. 145 | /// 146 | /// Never instantiated, struct variants are not supported. 147 | pub struct StructVariantSerializer<'input, 'output, T: UrlEncodedTarget> { 148 | inner: ser::Impossible<&'output mut UrlEncodedSerializer<'input, T>, Error>, 149 | } 150 | 151 | impl<'input, 'output, Target> ser::Serializer 152 | for Serializer<'input, 'output, Target> 153 | where 154 | Target: 'output + UrlEncodedTarget, 155 | { 156 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 157 | type Error = Error; 158 | type SerializeSeq = SeqSerializer<'input, 'output, Target>; 159 | type SerializeTuple = TupleSerializer<'input, 'output, Target>; 160 | type SerializeTupleStruct = TupleStructSerializer<'input, 'output, Target>; 161 | type SerializeTupleVariant = 162 | TupleVariantSerializer<'input, 'output, Target>; 163 | type SerializeMap = MapSerializer<'input, 'output, Target>; 164 | type SerializeStruct = StructSerializer<'input, 'output, Target>; 165 | type SerializeStructVariant = 166 | StructVariantSerializer<'input, 'output, Target>; 167 | 168 | /// Returns an error. 169 | fn serialize_bool(self, _v: bool) -> Result { 170 | Err(Error::top_level()) 171 | } 172 | 173 | /// Returns an error. 174 | fn serialize_i8(self, _v: i8) -> Result { 175 | Err(Error::top_level()) 176 | } 177 | 178 | /// Returns an error. 179 | fn serialize_i16(self, _v: i16) -> Result { 180 | Err(Error::top_level()) 181 | } 182 | 183 | /// Returns an error. 184 | fn serialize_i32(self, _v: i32) -> Result { 185 | Err(Error::top_level()) 186 | } 187 | 188 | /// Returns an error. 189 | fn serialize_i64(self, _v: i64) -> Result { 190 | Err(Error::top_level()) 191 | } 192 | 193 | /// Returns an error. 194 | fn serialize_u8(self, _v: u8) -> Result { 195 | Err(Error::top_level()) 196 | } 197 | 198 | /// Returns an error. 199 | fn serialize_u16(self, _v: u16) -> Result { 200 | Err(Error::top_level()) 201 | } 202 | 203 | /// Returns an error. 204 | fn serialize_u32(self, _v: u32) -> Result { 205 | Err(Error::top_level()) 206 | } 207 | 208 | /// Returns an error. 209 | fn serialize_u64(self, _v: u64) -> Result { 210 | Err(Error::top_level()) 211 | } 212 | 213 | /// Returns an error. 214 | fn serialize_f32(self, _v: f32) -> Result { 215 | Err(Error::top_level()) 216 | } 217 | 218 | /// Returns an error. 219 | fn serialize_f64(self, _v: f64) -> Result { 220 | Err(Error::top_level()) 221 | } 222 | 223 | /// Returns an error. 224 | fn serialize_char(self, _v: char) -> Result { 225 | Err(Error::top_level()) 226 | } 227 | 228 | /// Returns an error. 229 | fn serialize_str(self, _value: &str) -> Result { 230 | Err(Error::top_level()) 231 | } 232 | 233 | /// Returns an error. 234 | fn serialize_bytes(self, _value: &[u8]) -> Result { 235 | Err(Error::top_level()) 236 | } 237 | 238 | /// Returns `Ok`. 239 | fn serialize_unit(self) -> Result { 240 | Ok(self.urlencoder) 241 | } 242 | 243 | /// Returns `Ok`. 244 | fn serialize_unit_struct( 245 | self, 246 | _name: &'static str, 247 | ) -> Result { 248 | Ok(self.urlencoder) 249 | } 250 | 251 | /// Returns an error. 252 | fn serialize_unit_variant( 253 | self, 254 | _name: &'static str, 255 | _variant_index: u32, 256 | _variant: &'static str, 257 | ) -> Result { 258 | Err(Error::top_level()) 259 | } 260 | 261 | /// Serializes the inner value, ignoring the newtype name. 262 | fn serialize_newtype_struct( 263 | self, 264 | _name: &'static str, 265 | value: &T, 266 | ) -> Result { 267 | value.serialize(self) 268 | } 269 | 270 | /// Returns an error. 271 | fn serialize_newtype_variant( 272 | self, 273 | _name: &'static str, 274 | _variant_index: u32, 275 | _variant: &'static str, 276 | _value: &T, 277 | ) -> Result { 278 | Err(Error::top_level()) 279 | } 280 | 281 | /// Returns `Ok`. 282 | fn serialize_none(self) -> Result { 283 | Ok(self.urlencoder) 284 | } 285 | 286 | /// Serializes the given value. 287 | fn serialize_some( 288 | self, 289 | value: &T, 290 | ) -> Result { 291 | value.serialize(self) 292 | } 293 | 294 | /// Serialize a sequence, given length (if any) is ignored. 295 | fn serialize_seq( 296 | self, 297 | _len: Option, 298 | ) -> Result { 299 | Ok(SeqSerializer { 300 | urlencoder: self.urlencoder, 301 | }) 302 | } 303 | 304 | /// Returns an error. 305 | fn serialize_tuple( 306 | self, 307 | _len: usize, 308 | ) -> Result { 309 | Ok(TupleSerializer { 310 | urlencoder: self.urlencoder, 311 | }) 312 | } 313 | 314 | /// Returns an error. 315 | fn serialize_tuple_struct( 316 | self, 317 | _name: &'static str, 318 | _len: usize, 319 | ) -> Result { 320 | Err(Error::top_level()) 321 | } 322 | 323 | /// Returns an error. 324 | fn serialize_tuple_variant( 325 | self, 326 | _name: &'static str, 327 | _variant_index: u32, 328 | _variant: &'static str, 329 | _len: usize, 330 | ) -> Result { 331 | Err(Error::top_level()) 332 | } 333 | 334 | /// Serializes a map, given length is ignored. 335 | fn serialize_map( 336 | self, 337 | _len: Option, 338 | ) -> Result { 339 | Ok(MapSerializer { 340 | urlencoder: self.urlencoder, 341 | key: None, 342 | }) 343 | } 344 | 345 | /// Serializes a struct, given length is ignored. 346 | fn serialize_struct( 347 | self, 348 | _name: &'static str, 349 | _len: usize, 350 | ) -> Result { 351 | Ok(StructSerializer { 352 | urlencoder: self.urlencoder, 353 | }) 354 | } 355 | 356 | /// Returns an error. 357 | fn serialize_struct_variant( 358 | self, 359 | _name: &'static str, 360 | _variant_index: u32, 361 | _variant: &'static str, 362 | _len: usize, 363 | ) -> Result { 364 | Err(Error::top_level()) 365 | } 366 | } 367 | 368 | impl<'input, 'output, Target> ser::SerializeSeq 369 | for SeqSerializer<'input, 'output, Target> 370 | where 371 | Target: 'output + UrlEncodedTarget, 372 | { 373 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 374 | type Error = Error; 375 | 376 | fn serialize_element( 377 | &mut self, 378 | value: &T, 379 | ) -> Result<(), Error> { 380 | value.serialize(pair::PairSerializer::new(self.urlencoder)) 381 | } 382 | 383 | fn end(self) -> Result { 384 | Ok(self.urlencoder) 385 | } 386 | } 387 | 388 | impl<'input, 'output, Target> ser::SerializeTuple 389 | for TupleSerializer<'input, 'output, Target> 390 | where 391 | Target: 'output + UrlEncodedTarget, 392 | { 393 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 394 | type Error = Error; 395 | 396 | fn serialize_element( 397 | &mut self, 398 | value: &T, 399 | ) -> Result<(), Error> { 400 | value.serialize(pair::PairSerializer::new(self.urlencoder)) 401 | } 402 | 403 | fn end(self) -> Result { 404 | Ok(self.urlencoder) 405 | } 406 | } 407 | 408 | impl<'input, 'output, Target> ser::SerializeTupleStruct 409 | for TupleStructSerializer<'input, 'output, Target> 410 | where 411 | Target: 'output + UrlEncodedTarget, 412 | { 413 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 414 | type Error = Error; 415 | 416 | fn serialize_field( 417 | &mut self, 418 | value: &T, 419 | ) -> Result<(), Error> { 420 | self.inner.serialize_field(value) 421 | } 422 | 423 | fn end(self) -> Result { 424 | self.inner.end() 425 | } 426 | } 427 | 428 | impl<'input, 'output, Target> ser::SerializeTupleVariant 429 | for TupleVariantSerializer<'input, 'output, Target> 430 | where 431 | Target: 'output + UrlEncodedTarget, 432 | { 433 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 434 | type Error = Error; 435 | 436 | fn serialize_field( 437 | &mut self, 438 | value: &T, 439 | ) -> Result<(), Error> { 440 | self.inner.serialize_field(value) 441 | } 442 | 443 | fn end(self) -> Result { 444 | self.inner.end() 445 | } 446 | } 447 | 448 | impl<'input, 'output, Target> ser::SerializeMap 449 | for MapSerializer<'input, 'output, Target> 450 | where 451 | Target: 'output + UrlEncodedTarget, 452 | { 453 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 454 | type Error = Error; 455 | 456 | fn serialize_entry< 457 | K: ?Sized + ser::Serialize, 458 | V: ?Sized + ser::Serialize, 459 | >( 460 | &mut self, 461 | key: &K, 462 | value: &V, 463 | ) -> Result<(), Error> { 464 | let key_sink = key::KeySink::new(|key| { 465 | let value_sink = value::ValueSink::new(self.urlencoder, &key); 466 | value.serialize(part::PartSerializer::new(value_sink))?; 467 | self.key = None; 468 | Ok(()) 469 | }); 470 | let entry_serializer = part::PartSerializer::new(key_sink); 471 | key.serialize(entry_serializer) 472 | } 473 | 474 | fn serialize_key( 475 | &mut self, 476 | key: &T, 477 | ) -> Result<(), Error> { 478 | let key_sink = key::KeySink::new(|key| Ok(key.into())); 479 | let key_serializer = part::PartSerializer::new(key_sink); 480 | self.key = Some(key.serialize(key_serializer)?); 481 | Ok(()) 482 | } 483 | 484 | fn serialize_value( 485 | &mut self, 486 | value: &T, 487 | ) -> Result<(), Error> { 488 | { 489 | let key = self.key.as_ref().ok_or_else(Error::no_key)?; 490 | let value_sink = value::ValueSink::new(self.urlencoder, &key); 491 | value.serialize(part::PartSerializer::new(value_sink))?; 492 | } 493 | self.key = None; 494 | Ok(()) 495 | } 496 | 497 | fn end(self) -> Result { 498 | Ok(self.urlencoder) 499 | } 500 | } 501 | 502 | impl<'input, 'output, Target> ser::SerializeStruct 503 | for StructSerializer<'input, 'output, Target> 504 | where 505 | Target: 'output + UrlEncodedTarget, 506 | { 507 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 508 | type Error = Error; 509 | 510 | fn serialize_field( 511 | &mut self, 512 | key: &'static str, 513 | value: &T, 514 | ) -> Result<(), Error> { 515 | let value_sink = value::ValueSink::new(self.urlencoder, key); 516 | value.serialize(part::PartSerializer::new(value_sink)) 517 | } 518 | 519 | fn end(self) -> Result { 520 | Ok(self.urlencoder) 521 | } 522 | } 523 | 524 | impl<'input, 'output, Target> ser::SerializeStructVariant 525 | for StructVariantSerializer<'input, 'output, Target> 526 | where 527 | Target: 'output + UrlEncodedTarget, 528 | { 529 | type Ok = &'output mut UrlEncodedSerializer<'input, Target>; 530 | type Error = Error; 531 | 532 | fn serialize_field( 533 | &mut self, 534 | key: &'static str, 535 | value: &T, 536 | ) -> Result<(), Error> { 537 | self.inner.serialize_field(key, value) 538 | } 539 | 540 | fn end(self) -> Result { 541 | self.inner.end() 542 | } 543 | } 544 | 545 | impl Error { 546 | fn top_level() -> Self { 547 | let msg = "top-level serializer supports only maps and structs"; 548 | Error::Custom(msg.into()) 549 | } 550 | 551 | fn no_key() -> Self { 552 | let msg = "tried to serialize a value before serializing key"; 553 | Error::Custom(msg.into()) 554 | } 555 | } 556 | -------------------------------------------------------------------------------- /src/ser/pair.rs: -------------------------------------------------------------------------------- 1 | use crate::ser::key::KeySink; 2 | use crate::ser::part::PartSerializer; 3 | use crate::ser::value::ValueSink; 4 | use crate::ser::Error; 5 | use form_urlencoded::Serializer as UrlEncodedSerializer; 6 | use form_urlencoded::Target as UrlEncodedTarget; 7 | use serde::ser; 8 | use std::borrow::Cow; 9 | use std::mem; 10 | 11 | pub struct PairSerializer<'input, 'target, Target: UrlEncodedTarget> { 12 | urlencoder: &'target mut UrlEncodedSerializer<'input, Target>, 13 | state: PairState, 14 | } 15 | 16 | impl<'input, 'target, Target> PairSerializer<'input, 'target, Target> 17 | where 18 | Target: 'target + UrlEncodedTarget, 19 | { 20 | pub fn new( 21 | urlencoder: &'target mut UrlEncodedSerializer<'input, Target>, 22 | ) -> Self { 23 | PairSerializer { 24 | urlencoder, 25 | state: PairState::WaitingForKey, 26 | } 27 | } 28 | } 29 | 30 | impl<'input, 'target, Target> ser::Serializer 31 | for PairSerializer<'input, 'target, Target> 32 | where 33 | Target: 'target + UrlEncodedTarget, 34 | { 35 | type Ok = (); 36 | type Error = Error; 37 | type SerializeSeq = ser::Impossible<(), Error>; 38 | type SerializeTuple = Self; 39 | type SerializeTupleStruct = ser::Impossible<(), Error>; 40 | type SerializeTupleVariant = ser::Impossible<(), Error>; 41 | type SerializeMap = ser::Impossible<(), Error>; 42 | type SerializeStruct = ser::Impossible<(), Error>; 43 | type SerializeStructVariant = ser::Impossible<(), Error>; 44 | 45 | fn serialize_bool(self, _v: bool) -> Result<(), Error> { 46 | Err(Error::unsupported_pair()) 47 | } 48 | 49 | fn serialize_i8(self, _v: i8) -> Result<(), Error> { 50 | Err(Error::unsupported_pair()) 51 | } 52 | 53 | fn serialize_i16(self, _v: i16) -> Result<(), Error> { 54 | Err(Error::unsupported_pair()) 55 | } 56 | 57 | fn serialize_i32(self, _v: i32) -> Result<(), Error> { 58 | Err(Error::unsupported_pair()) 59 | } 60 | 61 | fn serialize_i64(self, _v: i64) -> Result<(), Error> { 62 | Err(Error::unsupported_pair()) 63 | } 64 | 65 | fn serialize_u8(self, _v: u8) -> Result<(), Error> { 66 | Err(Error::unsupported_pair()) 67 | } 68 | 69 | fn serialize_u16(self, _v: u16) -> Result<(), Error> { 70 | Err(Error::unsupported_pair()) 71 | } 72 | 73 | fn serialize_u32(self, _v: u32) -> Result<(), Error> { 74 | Err(Error::unsupported_pair()) 75 | } 76 | 77 | fn serialize_u64(self, _v: u64) -> Result<(), Error> { 78 | Err(Error::unsupported_pair()) 79 | } 80 | 81 | fn serialize_f32(self, _v: f32) -> Result<(), Error> { 82 | Err(Error::unsupported_pair()) 83 | } 84 | 85 | fn serialize_f64(self, _v: f64) -> Result<(), Error> { 86 | Err(Error::unsupported_pair()) 87 | } 88 | 89 | fn serialize_char(self, _v: char) -> Result<(), Error> { 90 | Err(Error::unsupported_pair()) 91 | } 92 | 93 | fn serialize_str(self, _value: &str) -> Result<(), Error> { 94 | Err(Error::unsupported_pair()) 95 | } 96 | 97 | fn serialize_bytes(self, _value: &[u8]) -> Result<(), Error> { 98 | Err(Error::unsupported_pair()) 99 | } 100 | 101 | fn serialize_unit(self) -> Result<(), Error> { 102 | Err(Error::unsupported_pair()) 103 | } 104 | 105 | fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Error> { 106 | Err(Error::unsupported_pair()) 107 | } 108 | 109 | fn serialize_unit_variant( 110 | self, 111 | _name: &'static str, 112 | _variant_index: u32, 113 | _variant: &'static str, 114 | ) -> Result<(), Error> { 115 | Err(Error::unsupported_pair()) 116 | } 117 | 118 | fn serialize_newtype_struct( 119 | self, 120 | _name: &'static str, 121 | value: &T, 122 | ) -> Result<(), Error> { 123 | value.serialize(self) 124 | } 125 | 126 | fn serialize_newtype_variant( 127 | self, 128 | _name: &'static str, 129 | _variant_index: u32, 130 | _variant: &'static str, 131 | _value: &T, 132 | ) -> Result<(), Error> { 133 | Err(Error::unsupported_pair()) 134 | } 135 | 136 | fn serialize_none(self) -> Result<(), Error> { 137 | Ok(()) 138 | } 139 | 140 | fn serialize_some( 141 | self, 142 | value: &T, 143 | ) -> Result<(), Error> { 144 | value.serialize(self) 145 | } 146 | 147 | fn serialize_seq( 148 | self, 149 | _len: Option, 150 | ) -> Result { 151 | Err(Error::unsupported_pair()) 152 | } 153 | 154 | fn serialize_tuple(self, len: usize) -> Result { 155 | if len == 2 { 156 | Ok(self) 157 | } else { 158 | Err(Error::unsupported_pair()) 159 | } 160 | } 161 | 162 | fn serialize_tuple_struct( 163 | self, 164 | _name: &'static str, 165 | _len: usize, 166 | ) -> Result { 167 | Err(Error::unsupported_pair()) 168 | } 169 | 170 | fn serialize_tuple_variant( 171 | self, 172 | _name: &'static str, 173 | _variant_index: u32, 174 | _variant: &'static str, 175 | _len: usize, 176 | ) -> Result { 177 | Err(Error::unsupported_pair()) 178 | } 179 | 180 | fn serialize_map( 181 | self, 182 | _len: Option, 183 | ) -> Result { 184 | Err(Error::unsupported_pair()) 185 | } 186 | 187 | fn serialize_struct( 188 | self, 189 | _name: &'static str, 190 | _len: usize, 191 | ) -> Result { 192 | Err(Error::unsupported_pair()) 193 | } 194 | 195 | fn serialize_struct_variant( 196 | self, 197 | _name: &'static str, 198 | _variant_index: u32, 199 | _variant: &'static str, 200 | _len: usize, 201 | ) -> Result { 202 | Err(Error::unsupported_pair()) 203 | } 204 | } 205 | 206 | impl<'input, 'target, Target> ser::SerializeTuple 207 | for PairSerializer<'input, 'target, Target> 208 | where 209 | Target: 'target + UrlEncodedTarget, 210 | { 211 | type Ok = (); 212 | type Error = Error; 213 | 214 | fn serialize_element( 215 | &mut self, 216 | value: &T, 217 | ) -> Result<(), Error> { 218 | match mem::replace(&mut self.state, PairState::Done) { 219 | PairState::WaitingForKey => { 220 | let key_sink = KeySink::new(|key| Ok(key.into())); 221 | let key_serializer = PartSerializer::new(key_sink); 222 | self.state = PairState::WaitingForValue { 223 | key: value.serialize(key_serializer)?, 224 | }; 225 | Ok(()) 226 | } 227 | PairState::WaitingForValue { key } => { 228 | let result = { 229 | let value_sink = ValueSink::new(self.urlencoder, &key); 230 | let value_serializer = PartSerializer::new(value_sink); 231 | value.serialize(value_serializer) 232 | }; 233 | if result.is_ok() { 234 | self.state = PairState::Done; 235 | } else { 236 | self.state = PairState::WaitingForValue { key }; 237 | } 238 | result 239 | } 240 | PairState::Done => Err(Error::done()), 241 | } 242 | } 243 | 244 | fn end(self) -> Result<(), Error> { 245 | if let PairState::Done = self.state { 246 | Ok(()) 247 | } else { 248 | Err(Error::not_done()) 249 | } 250 | } 251 | } 252 | 253 | enum PairState { 254 | WaitingForKey, 255 | WaitingForValue { key: Cow<'static, str> }, 256 | Done, 257 | } 258 | 259 | impl Error { 260 | fn done() -> Self { 261 | Error::Custom("this pair has already been serialized".into()) 262 | } 263 | 264 | fn not_done() -> Self { 265 | Error::Custom("this pair has not yet been serialized".into()) 266 | } 267 | 268 | fn unsupported_pair() -> Self { 269 | Error::Custom("unsupported pair".into()) 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/ser/part.rs: -------------------------------------------------------------------------------- 1 | use crate::ser::Error; 2 | use serde::ser; 3 | use std::str; 4 | 5 | pub struct PartSerializer { 6 | sink: S, 7 | } 8 | 9 | impl PartSerializer { 10 | pub fn new(sink: S) -> Self { 11 | PartSerializer { sink } 12 | } 13 | } 14 | 15 | pub trait Sink: Sized { 16 | type Ok; 17 | 18 | fn serialize_static_str( 19 | self, 20 | value: &'static str, 21 | ) -> Result; 22 | 23 | fn serialize_str(self, value: &str) -> Result; 24 | fn serialize_string(self, value: String) -> Result; 25 | fn serialize_none(self) -> Result; 26 | 27 | fn serialize_some( 28 | self, 29 | value: &T, 30 | ) -> Result; 31 | 32 | fn unsupported(self, type_str: &'static str) -> Error; 33 | } 34 | 35 | impl ser::Serializer for PartSerializer { 36 | type Ok = S::Ok; 37 | type Error = Error; 38 | type SerializeSeq = ser::Impossible; 39 | type SerializeTuple = ser::Impossible; 40 | type SerializeTupleStruct = ser::Impossible; 41 | type SerializeTupleVariant = ser::Impossible; 42 | type SerializeMap = ser::Impossible; 43 | type SerializeStruct = ser::Impossible; 44 | type SerializeStructVariant = ser::Impossible; 45 | 46 | fn serialize_bool(self, v: bool) -> Result { 47 | self.sink 48 | .serialize_static_str(if v { "true" } else { "false" }) 49 | } 50 | 51 | fn serialize_i8(self, v: i8) -> Result { 52 | self.serialize_integer(v) 53 | } 54 | 55 | fn serialize_i16(self, v: i16) -> Result { 56 | self.serialize_integer(v) 57 | } 58 | 59 | fn serialize_i32(self, v: i32) -> Result { 60 | self.serialize_integer(v) 61 | } 62 | 63 | fn serialize_i64(self, v: i64) -> Result { 64 | self.serialize_integer(v) 65 | } 66 | 67 | fn serialize_u8(self, v: u8) -> Result { 68 | self.serialize_integer(v) 69 | } 70 | 71 | fn serialize_u16(self, v: u16) -> Result { 72 | self.serialize_integer(v) 73 | } 74 | 75 | fn serialize_u32(self, v: u32) -> Result { 76 | self.serialize_integer(v) 77 | } 78 | 79 | fn serialize_u64(self, v: u64) -> Result { 80 | self.serialize_integer(v) 81 | } 82 | 83 | fn serialize_u128(self, v: u128) -> Result { 84 | self.serialize_integer(v) 85 | } 86 | 87 | fn serialize_i128(self, v: i128) -> Result { 88 | self.serialize_integer(v) 89 | } 90 | 91 | fn serialize_f32(self, v: f32) -> Result { 92 | self.serialize_floating(v) 93 | } 94 | 95 | fn serialize_f64(self, v: f64) -> Result { 96 | self.serialize_floating(v) 97 | } 98 | 99 | fn serialize_char(self, v: char) -> Result { 100 | self.sink.serialize_string(v.to_string()) 101 | } 102 | 103 | fn serialize_str(self, value: &str) -> Result { 104 | self.sink.serialize_str(value) 105 | } 106 | 107 | fn serialize_bytes(self, value: &[u8]) -> Result { 108 | match str::from_utf8(value) { 109 | Ok(value) => self.sink.serialize_str(value), 110 | Err(err) => Err(Error::Utf8(err)), 111 | } 112 | } 113 | 114 | fn serialize_unit(self) -> Result { 115 | Err(self.sink.unsupported("unit")) 116 | } 117 | 118 | fn serialize_unit_struct(self, name: &'static str) -> Result { 119 | self.sink.serialize_static_str(name) 120 | } 121 | 122 | fn serialize_unit_variant( 123 | self, 124 | _name: &'static str, 125 | _variant_index: u32, 126 | variant: &'static str, 127 | ) -> Result { 128 | self.sink.serialize_static_str(variant) 129 | } 130 | 131 | fn serialize_newtype_struct( 132 | self, 133 | _name: &'static str, 134 | value: &T, 135 | ) -> Result { 136 | value.serialize(self) 137 | } 138 | 139 | fn serialize_newtype_variant( 140 | self, 141 | _name: &'static str, 142 | _variant_index: u32, 143 | _variant: &'static str, 144 | _value: &T, 145 | ) -> Result { 146 | Err(self.sink.unsupported("newtype variant")) 147 | } 148 | 149 | fn serialize_none(self) -> Result { 150 | self.sink.serialize_none() 151 | } 152 | 153 | fn serialize_some( 154 | self, 155 | value: &T, 156 | ) -> Result { 157 | self.sink.serialize_some(value) 158 | } 159 | 160 | fn serialize_seq( 161 | self, 162 | _len: Option, 163 | ) -> Result { 164 | Err(self.sink.unsupported("sequence")) 165 | } 166 | 167 | fn serialize_tuple( 168 | self, 169 | _len: usize, 170 | ) -> Result { 171 | Err(self.sink.unsupported("tuple")) 172 | } 173 | 174 | fn serialize_tuple_struct( 175 | self, 176 | _name: &'static str, 177 | _len: usize, 178 | ) -> Result { 179 | Err(self.sink.unsupported("tuple struct")) 180 | } 181 | 182 | fn serialize_tuple_variant( 183 | self, 184 | _name: &'static str, 185 | _variant_index: u32, 186 | _variant: &'static str, 187 | _len: usize, 188 | ) -> Result { 189 | Err(self.sink.unsupported("tuple variant")) 190 | } 191 | 192 | fn serialize_map( 193 | self, 194 | _len: Option, 195 | ) -> Result { 196 | Err(self.sink.unsupported("map")) 197 | } 198 | 199 | fn serialize_struct( 200 | self, 201 | _name: &'static str, 202 | _len: usize, 203 | ) -> Result { 204 | Err(self.sink.unsupported("struct")) 205 | } 206 | 207 | fn serialize_struct_variant( 208 | self, 209 | _name: &'static str, 210 | _variant_index: u32, 211 | _variant: &'static str, 212 | _len: usize, 213 | ) -> Result { 214 | Err(self.sink.unsupported("struct variant")) 215 | } 216 | } 217 | 218 | impl PartSerializer { 219 | fn serialize_integer(self, value: I) -> Result 220 | where 221 | I: itoa::Integer, 222 | { 223 | let mut buf = itoa::Buffer::new(); 224 | let part = buf.format(value); 225 | ser::Serializer::serialize_str(self, part) 226 | } 227 | 228 | fn serialize_floating(self, value: F) -> Result 229 | where 230 | F: ryu::Float, 231 | { 232 | let mut buf = ryu::Buffer::new(); 233 | let part = buf.format(value); 234 | ser::Serializer::serialize_str(self, part) 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /src/ser/value.rs: -------------------------------------------------------------------------------- 1 | use crate::ser::part::{PartSerializer, Sink}; 2 | use crate::ser::Error; 3 | use form_urlencoded::Serializer as UrlEncodedSerializer; 4 | use form_urlencoded::Target as UrlEncodedTarget; 5 | use serde::ser::Serialize; 6 | use std::str; 7 | 8 | pub struct ValueSink<'input, 'key, 'target, Target> 9 | where 10 | Target: UrlEncodedTarget, 11 | { 12 | urlencoder: &'target mut UrlEncodedSerializer<'input, Target>, 13 | key: &'key str, 14 | } 15 | 16 | impl<'input, 'key, 'target, Target> ValueSink<'input, 'key, 'target, Target> 17 | where 18 | Target: 'target + UrlEncodedTarget, 19 | { 20 | pub fn new( 21 | urlencoder: &'target mut UrlEncodedSerializer<'input, Target>, 22 | key: &'key str, 23 | ) -> Self { 24 | ValueSink { urlencoder, key } 25 | } 26 | } 27 | 28 | impl<'input, 'key, 'target, Target> Sink 29 | for ValueSink<'input, 'key, 'target, Target> 30 | where 31 | Target: 'target + UrlEncodedTarget, 32 | { 33 | type Ok = (); 34 | 35 | fn serialize_str(self, value: &str) -> Result<(), Error> { 36 | self.urlencoder.append_pair(self.key, value); 37 | Ok(()) 38 | } 39 | 40 | fn serialize_static_str(self, value: &'static str) -> Result<(), Error> { 41 | self.serialize_str(value) 42 | } 43 | 44 | fn serialize_string(self, value: String) -> Result<(), Error> { 45 | self.serialize_str(&value) 46 | } 47 | 48 | fn serialize_none(self) -> Result { 49 | Ok(()) 50 | } 51 | 52 | fn serialize_some( 53 | self, 54 | value: &T, 55 | ) -> Result { 56 | value.serialize(PartSerializer::new(self)) 57 | } 58 | 59 | fn unsupported(self, type_str: &'static str) -> Error { 60 | Error::Custom(format!("unsupported value type: {type_str}").into()) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/test_deserialize.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Deserialize; 2 | 3 | #[derive(Deserialize, Debug, PartialEq)] 4 | struct NewType(T); 5 | 6 | #[test] 7 | fn deserialize_newtype_i32() { 8 | let result = vec![("field".to_owned(), NewType(11))]; 9 | 10 | assert_eq!(serde_urlencoded::from_str("field=11"), Ok(result)); 11 | } 12 | 13 | #[test] 14 | fn deserialize_bytes() { 15 | let result = vec![("first".to_owned(), 23), ("last".to_owned(), 42)]; 16 | 17 | assert_eq!( 18 | serde_urlencoded::from_bytes(b"first=23&last=42"), 19 | Ok(result) 20 | ); 21 | } 22 | 23 | #[test] 24 | fn deserialize_str() { 25 | let result = vec![("first".to_owned(), 23), ("last".to_owned(), 42)]; 26 | 27 | assert_eq!(serde_urlencoded::from_str("first=23&last=42"), Ok(result)); 28 | } 29 | 30 | #[test] 31 | fn deserialize_borrowed_str() { 32 | let result = vec![("first", 23), ("last", 42)]; 33 | 34 | assert_eq!(serde_urlencoded::from_str("first=23&last=42"), Ok(result)); 35 | } 36 | 37 | #[test] 38 | fn deserialize_reader() { 39 | let result = vec![("first".to_owned(), 23), ("last".to_owned(), 42)]; 40 | 41 | assert_eq!( 42 | serde_urlencoded::from_reader(b"first=23&last=42" as &[_]), 43 | Ok(result) 44 | ); 45 | } 46 | 47 | #[test] 48 | fn deserialize_option() { 49 | let result = vec![ 50 | ("first".to_owned(), Some(23)), 51 | ("last".to_owned(), Some(42)), 52 | ]; 53 | assert_eq!(serde_urlencoded::from_str("first=23&last=42"), Ok(result)); 54 | } 55 | 56 | #[test] 57 | fn deserialize_unit() { 58 | assert_eq!(serde_urlencoded::from_str(""), Ok(())); 59 | assert_eq!(serde_urlencoded::from_str("&"), Ok(())); 60 | assert_eq!(serde_urlencoded::from_str("&&"), Ok(())); 61 | assert!(serde_urlencoded::from_str::<()>("first=23").is_err()); 62 | } 63 | 64 | #[derive(Deserialize, Debug, PartialEq, Eq)] 65 | enum X { 66 | A, 67 | B, 68 | C, 69 | } 70 | 71 | #[test] 72 | fn deserialize_unit_enum() { 73 | let result = vec![ 74 | ("one".to_owned(), X::A), 75 | ("two".to_owned(), X::B), 76 | ("three".to_owned(), X::C), 77 | ]; 78 | 79 | assert_eq!( 80 | serde_urlencoded::from_str("one=A&two=B&three=C"), 81 | Ok(result) 82 | ); 83 | } 84 | 85 | #[test] 86 | fn deserialize_unit_type() { 87 | assert_eq!(serde_urlencoded::from_str(""), Ok(())); 88 | } 89 | 90 | #[test] 91 | fn deserialize_128bit() { 92 | let result = vec![("max", u128::MAX)]; 93 | let q = format!("max={}", u128::MAX); 94 | assert_eq!(serde_urlencoded::from_str(&q), Ok(result)); 95 | 96 | let result = vec![("min", i128::MIN)]; 97 | let q = format!("min={}", i128::MIN); 98 | assert_eq!(serde_urlencoded::from_str(&q), Ok(result)); 99 | } 100 | -------------------------------------------------------------------------------- /tests/test_serialize.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Serialize; 2 | 3 | #[derive(Serialize)] 4 | struct NewType(T); 5 | 6 | #[test] 7 | fn serialize_newtype_i32() { 8 | let params = &[("field", Some(NewType(11)))]; 9 | assert_eq!( 10 | serde_urlencoded::to_string(params), 11 | Ok("field=11".to_owned()) 12 | ); 13 | } 14 | 15 | #[test] 16 | fn serialize_newtype_u128() { 17 | let params = &[("field", Some(NewType(u128::MAX)))]; 18 | assert_eq!( 19 | serde_urlencoded::to_string(params), 20 | Ok(format!("field={}", u128::MAX)) 21 | ); 22 | } 23 | 24 | #[test] 25 | fn serialize_newtype_i128() { 26 | let params = &[("field", Some(NewType(i128::MIN)))]; 27 | assert_eq!( 28 | serde_urlencoded::to_string(params), 29 | Ok(format!("field={}", i128::MIN)) 30 | ); 31 | } 32 | 33 | #[test] 34 | fn serialize_option_map_int() { 35 | let params = &[("first", Some(23)), ("middle", None), ("last", Some(42))]; 36 | 37 | assert_eq!( 38 | serde_urlencoded::to_string(params), 39 | Ok("first=23&last=42".to_owned()) 40 | ); 41 | } 42 | 43 | #[test] 44 | fn serialize_option_map_string() { 45 | let params = &[ 46 | ("first", Some("hello")), 47 | ("middle", None), 48 | ("last", Some("world")), 49 | ]; 50 | 51 | assert_eq!( 52 | serde_urlencoded::to_string(params), 53 | Ok("first=hello&last=world".to_owned()) 54 | ); 55 | } 56 | 57 | #[test] 58 | fn serialize_option_map_bool() { 59 | let params = &[("one", Some(true)), ("two", Some(false))]; 60 | 61 | assert_eq!( 62 | serde_urlencoded::to_string(params), 63 | Ok("one=true&two=false".to_owned()) 64 | ); 65 | } 66 | 67 | #[test] 68 | fn serialize_map_bool() { 69 | let params = &[("one", true), ("two", false)]; 70 | 71 | assert_eq!( 72 | serde_urlencoded::to_string(params), 73 | Ok("one=true&two=false".to_owned()) 74 | ); 75 | } 76 | 77 | #[derive(Serialize)] 78 | enum X { 79 | A, 80 | B, 81 | C, 82 | } 83 | 84 | #[test] 85 | fn serialize_unit_enum() { 86 | let params = &[("one", X::A), ("two", X::B), ("three", X::C)]; 87 | assert_eq!( 88 | serde_urlencoded::to_string(params), 89 | Ok("one=A&two=B&three=C".to_owned()) 90 | ); 91 | } 92 | 93 | #[derive(Serialize)] 94 | struct Unit; 95 | 96 | #[test] 97 | fn serialize_unit_struct() { 98 | assert_eq!(serde_urlencoded::to_string(Unit), Ok("".to_owned())); 99 | } 100 | 101 | #[test] 102 | fn serialize_unit_type() { 103 | assert_eq!(serde_urlencoded::to_string(()), Ok("".to_owned())); 104 | } 105 | 106 | #[derive(Serialize)] 107 | struct ListStruct { 108 | x: Vec, 109 | y: Vec, 110 | } 111 | 112 | #[test] 113 | #[should_panic( 114 | expected = r#"called `Result::unwrap()` on an `Err` value: Custom("unsupported value type: sequence")"# 115 | )] 116 | fn value_type_error_msg() { 117 | let list_struct = ListStruct { 118 | x: vec![1, 2, 3], 119 | y: vec![4, 5, 6], 120 | }; 121 | let _ = serde_urlencoded::to_string(list_struct).unwrap(); 122 | } 123 | 124 | #[test] 125 | #[should_panic( 126 | expected = r#"called `Result::unwrap()` on an `Err` value: Custom("unsupported key type: sequence")"# 127 | )] 128 | fn key_type_error_msg() { 129 | use std::collections::HashMap; 130 | 131 | let mut map = HashMap::from([(vec![1, 2, 3], "value")]); 132 | let _ = serde_urlencoded::to_string(map).unwrap(); 133 | } 134 | --------------------------------------------------------------------------------