├── rustfmt.toml ├── .gitignore ├── Cargo.toml ├── src ├── lib.rs ├── error.rs ├── ser.rs └── de.rs ├── README.md ├── LICENSE-MIT ├── .github └── workflows │ └── ci.yml └── LICENSE-APACHE /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 80 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde-example" 3 | version = "0.1.0" 4 | authors = ["David Tolnay "] 5 | categories = ["encoding"] 6 | description = "An example Serializer and Deserializer data format for Serde" 7 | documentation = "https://serde.rs/data-format.html" 8 | edition = "2021" 9 | keywords = ["serde"] 10 | license = "MIT OR Apache-2.0" 11 | publish = false 12 | repository = "https://github.com/serde-rs/example-format" 13 | rust-version = "1.68" 14 | 15 | [dependencies] 16 | serde_core = "1" 17 | 18 | [dev-dependencies] 19 | serde = "1" 20 | serde_derive = "1" 21 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Serde Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | extern crate serde_core as serde; 10 | 11 | mod de; 12 | mod error; 13 | mod ser; 14 | 15 | pub use crate::de::{from_str, Deserializer}; 16 | pub use crate::error::{Error, Result}; 17 | pub use crate::ser::{to_string, Serializer}; 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Please refer to the Serde website under [**Writing a data format**] for a 2 | discussion of this example code. 3 | 4 | [**Writing a data format**]: https://serde.rs/data-format.html 5 | 6 |
7 | 8 | #### License 9 | 10 | 11 | Licensed under either of Apache License, Version 12 | 2.0 or MIT license at your option. 13 | 14 | 15 |
16 | 17 | 18 | Unless you explicitly state otherwise, any contribution intentionally submitted 19 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 20 | be dual licensed as above, without any additional terms or conditions. 21 | 22 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | test: 17 | name: Rust ${{matrix.rust}} 18 | runs-on: ubuntu-latest 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | rust: [nightly, beta, stable, 1.68.0] 23 | timeout-minutes: 45 24 | steps: 25 | - uses: actions/checkout@v6 26 | - uses: dtolnay/rust-toolchain@master 27 | with: 28 | toolchain: ${{matrix.rust}} 29 | - run: cargo test 30 | - uses: actions/upload-artifact@v6 31 | if: matrix.rust == 'nightly' && always() 32 | with: 33 | name: Cargo.lock 34 | path: Cargo.lock 35 | continue-on-error: true 36 | 37 | doc: 38 | name: Documentation 39 | runs-on: ubuntu-latest 40 | timeout-minutes: 45 41 | env: 42 | RUSTDOCFLAGS: -Dwarnings 43 | steps: 44 | - uses: actions/checkout@v6 45 | - uses: dtolnay/rust-toolchain@nightly 46 | - uses: dtolnay/install@cargo-docs-rs 47 | - run: cargo docs-rs 48 | 49 | clippy: 50 | name: Clippy 51 | runs-on: ubuntu-latest 52 | timeout-minutes: 45 53 | steps: 54 | - uses: actions/checkout@v6 55 | - uses: dtolnay/rust-toolchain@clippy 56 | - run: cargo clippy -- -Dclippy::all 57 | 58 | outdated: 59 | name: Outdated 60 | runs-on: ubuntu-latest 61 | if: github.event_name != 'pull_request' 62 | timeout-minutes: 45 63 | steps: 64 | - uses: actions/checkout@v6 65 | - uses: dtolnay/rust-toolchain@stable 66 | - uses: dtolnay/install@cargo-outdated 67 | - run: cargo outdated --workspace --exit-code 1 68 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Serde Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use serde::{de, ser}; 10 | use std::fmt::{self, Display}; 11 | 12 | pub type Result = std::result::Result; 13 | 14 | // This is a bare-bones implementation. A real library would provide additional 15 | // information in its error type, for example the line and column at which the 16 | // error occurred, the byte offset into the input, or the current key being 17 | // processed. 18 | #[derive(Debug)] 19 | pub enum Error { 20 | // One or more variants that can be created by data structures through the 21 | // `ser::Error` and `de::Error` traits. For example the Serialize impl for 22 | // Mutex might return an error because the mutex is poisoned, or the 23 | // Deserialize impl for a struct may return an error because a required 24 | // field is missing. 25 | Message(String), 26 | 27 | // Zero or more variants that can be created directly by the Serializer and 28 | // Deserializer without going through `ser::Error` and `de::Error`. These 29 | // are specific to the format, in this case JSON. 30 | Eof, 31 | Syntax, 32 | ExpectedBoolean, 33 | ExpectedInteger, 34 | ExpectedString, 35 | ExpectedNull, 36 | ExpectedArray, 37 | ExpectedArrayComma, 38 | ExpectedArrayEnd, 39 | ExpectedMap, 40 | ExpectedMapColon, 41 | ExpectedMapComma, 42 | ExpectedMapEnd, 43 | ExpectedEnum, 44 | TrailingCharacters, 45 | } 46 | 47 | impl ser::Error for Error { 48 | fn custom(msg: T) -> Self { 49 | Error::Message(msg.to_string()) 50 | } 51 | } 52 | 53 | impl de::Error for Error { 54 | fn custom(msg: T) -> Self { 55 | Error::Message(msg.to_string()) 56 | } 57 | } 58 | 59 | impl Display for Error { 60 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 61 | match self { 62 | Error::Message(msg) => write!(f, "{}", msg), 63 | Error::Eof => f.write_str("unexpected end of input"), 64 | /* and so forth */ 65 | _ => unimplemented!(), 66 | } 67 | } 68 | } 69 | 70 | impl std::error::Error for Error {} 71 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/ser.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Serde Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use crate::error::{Error, Result}; 10 | use serde::ser::{self, Serialize}; 11 | 12 | pub struct Serializer { 13 | // This string starts empty and JSON is appended as values are serialized. 14 | output: String, 15 | } 16 | 17 | // By convention, the public API of a Serde serializer is one or more `to_abc` 18 | // functions such as `to_string`, `to_bytes`, or `to_writer` depending on what 19 | // Rust types the serializer is able to produce as output. 20 | // 21 | // This basic serializer supports only `to_string`. 22 | pub fn to_string(value: &T) -> Result 23 | where 24 | T: Serialize, 25 | { 26 | let mut serializer = Serializer { 27 | output: String::new(), 28 | }; 29 | value.serialize(&mut serializer)?; 30 | Ok(serializer.output) 31 | } 32 | 33 | impl ser::Serializer for &mut Serializer { 34 | // The output type produced by this `Serializer` during successful 35 | // serialization. Most serializers that produce text or binary output should 36 | // set `Ok = ()` and serialize into an `io::Write` or buffer contained 37 | // within the `Serializer` instance, as happens here. Serializers that build 38 | // in-memory data structures may be simplified by using `Ok` to propagate 39 | // the data structure around. 40 | type Ok = (); 41 | 42 | // The error type when some error occurs during serialization. 43 | type Error = Error; 44 | 45 | // Associated types for keeping track of additional state while serializing 46 | // compound data structures like sequences and maps. In this case no 47 | // additional state is required beyond what is already stored in the 48 | // Serializer struct. 49 | type SerializeSeq = Self; 50 | type SerializeTuple = Self; 51 | type SerializeTupleStruct = Self; 52 | type SerializeTupleVariant = Self; 53 | type SerializeMap = Self; 54 | type SerializeStruct = Self; 55 | type SerializeStructVariant = Self; 56 | 57 | // Here we go with the simple methods. The following 12 methods receive one 58 | // of the primitive types of the data model and map it to JSON by appending 59 | // into the output string. 60 | fn serialize_bool(self, v: bool) -> Result<()> { 61 | self.output += if v { "true" } else { "false" }; 62 | Ok(()) 63 | } 64 | 65 | // JSON does not distinguish between different sizes of integers, so all 66 | // signed integers will be serialized the same and all unsigned integers 67 | // will be serialized the same. Other formats, especially compact binary 68 | // formats, may need independent logic for the different sizes. 69 | fn serialize_i8(self, v: i8) -> Result<()> { 70 | self.serialize_i64(i64::from(v)) 71 | } 72 | 73 | fn serialize_i16(self, v: i16) -> Result<()> { 74 | self.serialize_i64(i64::from(v)) 75 | } 76 | 77 | fn serialize_i32(self, v: i32) -> Result<()> { 78 | self.serialize_i64(i64::from(v)) 79 | } 80 | 81 | // Not particularly efficient but this is example code anyway. A more 82 | // performant approach would be to use the `itoa` crate. 83 | fn serialize_i64(self, v: i64) -> Result<()> { 84 | self.output += &v.to_string(); 85 | Ok(()) 86 | } 87 | 88 | fn serialize_u8(self, v: u8) -> Result<()> { 89 | self.serialize_u64(u64::from(v)) 90 | } 91 | 92 | fn serialize_u16(self, v: u16) -> Result<()> { 93 | self.serialize_u64(u64::from(v)) 94 | } 95 | 96 | fn serialize_u32(self, v: u32) -> Result<()> { 97 | self.serialize_u64(u64::from(v)) 98 | } 99 | 100 | fn serialize_u64(self, v: u64) -> Result<()> { 101 | self.output += &v.to_string(); 102 | Ok(()) 103 | } 104 | 105 | fn serialize_f32(self, v: f32) -> Result<()> { 106 | self.serialize_f64(f64::from(v)) 107 | } 108 | 109 | fn serialize_f64(self, v: f64) -> Result<()> { 110 | self.output += &v.to_string(); 111 | Ok(()) 112 | } 113 | 114 | // Serialize a char as a single-character string. Other formats may 115 | // represent this differently. 116 | fn serialize_char(self, v: char) -> Result<()> { 117 | self.serialize_str(&v.to_string()) 118 | } 119 | 120 | // This only works for strings that don't require escape sequences but you 121 | // get the idea. For example it would emit invalid JSON if the input string 122 | // contains a '"' character. 123 | fn serialize_str(self, v: &str) -> Result<()> { 124 | self.output += "\""; 125 | self.output += v; 126 | self.output += "\""; 127 | Ok(()) 128 | } 129 | 130 | // Serialize a byte array as an array of bytes. Could also use a base64 131 | // string here. Binary formats will typically represent byte arrays more 132 | // compactly. 133 | fn serialize_bytes(self, v: &[u8]) -> Result<()> { 134 | use serde::ser::SerializeSeq; 135 | let mut seq = self.serialize_seq(Some(v.len()))?; 136 | for byte in v { 137 | seq.serialize_element(byte)?; 138 | } 139 | seq.end() 140 | } 141 | 142 | // An absent optional is represented as the JSON `null`. 143 | fn serialize_none(self) -> Result<()> { 144 | self.serialize_unit() 145 | } 146 | 147 | // A present optional is represented as just the contained value. Note that 148 | // this is a lossy representation. For example the values `Some(())` and 149 | // `None` both serialize as just `null`. Unfortunately this is typically 150 | // what people expect when working with JSON. Other formats are encouraged 151 | // to behave more intelligently if possible. 152 | fn serialize_some(self, value: &T) -> Result<()> 153 | where 154 | T: ?Sized + Serialize, 155 | { 156 | value.serialize(self) 157 | } 158 | 159 | // In Serde, unit means an anonymous value containing no data. Map this to 160 | // JSON as `null`. 161 | fn serialize_unit(self) -> Result<()> { 162 | self.output += "null"; 163 | Ok(()) 164 | } 165 | 166 | // Unit struct means a named value containing no data. Again, since there is 167 | // no data, map this to JSON as `null`. There is no need to serialize the 168 | // name in most formats. 169 | fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { 170 | self.serialize_unit() 171 | } 172 | 173 | // When serializing a unit variant (or any other kind of variant), formats 174 | // can choose whether to keep track of it by index or by name. Binary 175 | // formats typically use the index of the variant and human-readable formats 176 | // typically use the name. 177 | fn serialize_unit_variant( 178 | self, 179 | _name: &'static str, 180 | _variant_index: u32, 181 | variant: &'static str, 182 | ) -> Result<()> { 183 | self.serialize_str(variant) 184 | } 185 | 186 | // As is done here, serializers are encouraged to treat newtype structs as 187 | // insignificant wrappers around the data they contain. 188 | fn serialize_newtype_struct( 189 | self, 190 | _name: &'static str, 191 | value: &T, 192 | ) -> Result<()> 193 | where 194 | T: ?Sized + Serialize, 195 | { 196 | value.serialize(self) 197 | } 198 | 199 | // Note that newtype variant (and all of the other variant serialization 200 | // methods) refer exclusively to the "externally tagged" enum 201 | // representation. 202 | // 203 | // Serialize this to JSON in externally tagged form as `{ NAME: VALUE }`. 204 | fn serialize_newtype_variant( 205 | self, 206 | _name: &'static str, 207 | _variant_index: u32, 208 | variant: &'static str, 209 | value: &T, 210 | ) -> Result<()> 211 | where 212 | T: ?Sized + Serialize, 213 | { 214 | self.output += "{"; 215 | variant.serialize(&mut *self)?; 216 | self.output += ":"; 217 | value.serialize(&mut *self)?; 218 | self.output += "}"; 219 | Ok(()) 220 | } 221 | 222 | // Now we get to the serialization of compound types. 223 | // 224 | // The start of the sequence, each value, and the end are three separate 225 | // method calls. This one is responsible only for serializing the start, 226 | // which in JSON is `[`. 227 | // 228 | // The length of the sequence may or may not be known ahead of time. This 229 | // doesn't make a difference in JSON because the length is not represented 230 | // explicitly in the serialized form. Some serializers may only be able to 231 | // support sequences for which the length is known up front. 232 | fn serialize_seq(self, _len: Option) -> Result { 233 | self.output += "["; 234 | Ok(self) 235 | } 236 | 237 | // Tuples look just like sequences in JSON. Some formats may be able to 238 | // represent tuples more efficiently by omitting the length, since tuple 239 | // means that the corresponding `Deserialize implementation will know the 240 | // length without needing to look at the serialized data. 241 | fn serialize_tuple(self, len: usize) -> Result { 242 | self.serialize_seq(Some(len)) 243 | } 244 | 245 | // Tuple structs look just like sequences in JSON. 246 | fn serialize_tuple_struct( 247 | self, 248 | _name: &'static str, 249 | len: usize, 250 | ) -> Result { 251 | self.serialize_seq(Some(len)) 252 | } 253 | 254 | // Tuple variants are represented in JSON as `{ NAME: [DATA...] }`. Again 255 | // this method is only responsible for the externally tagged representation. 256 | fn serialize_tuple_variant( 257 | self, 258 | _name: &'static str, 259 | _variant_index: u32, 260 | variant: &'static str, 261 | _len: usize, 262 | ) -> Result { 263 | self.output += "{"; 264 | variant.serialize(&mut *self)?; 265 | self.output += ":["; 266 | Ok(self) 267 | } 268 | 269 | // Maps are represented in JSON as `{ K: V, K: V, ... }`. 270 | fn serialize_map(self, _len: Option) -> Result { 271 | self.output += "{"; 272 | Ok(self) 273 | } 274 | 275 | // Structs look just like maps in JSON. In particular, JSON requires that we 276 | // serialize the field names of the struct. Other formats may be able to 277 | // omit the field names when serializing structs because the corresponding 278 | // Deserialize implementation is required to know what the keys are without 279 | // looking at the serialized data. 280 | fn serialize_struct( 281 | self, 282 | _name: &'static str, 283 | len: usize, 284 | ) -> Result { 285 | self.serialize_map(Some(len)) 286 | } 287 | 288 | // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }`. 289 | // This is the externally tagged representation. 290 | fn serialize_struct_variant( 291 | self, 292 | _name: &'static str, 293 | _variant_index: u32, 294 | variant: &'static str, 295 | _len: usize, 296 | ) -> Result { 297 | self.output += "{"; 298 | variant.serialize(&mut *self)?; 299 | self.output += ":{"; 300 | Ok(self) 301 | } 302 | } 303 | 304 | // The following 7 impls deal with the serialization of compound types like 305 | // sequences and maps. Serialization of such types is begun by a Serializer 306 | // method and followed by zero or more calls to serialize individual elements of 307 | // the compound type and one call to end the compound type. 308 | // 309 | // This impl is SerializeSeq so these methods are called after `serialize_seq` 310 | // is called on the Serializer. 311 | impl ser::SerializeSeq for &mut Serializer { 312 | // Must match the `Ok` type of the serializer. 313 | type Ok = (); 314 | // Must match the `Error` type of the serializer. 315 | type Error = Error; 316 | 317 | // Serialize a single element of the sequence. 318 | fn serialize_element(&mut self, value: &T) -> Result<()> 319 | where 320 | T: ?Sized + Serialize, 321 | { 322 | if !self.output.ends_with('[') { 323 | self.output += ","; 324 | } 325 | value.serialize(&mut **self) 326 | } 327 | 328 | // Close the sequence. 329 | fn end(self) -> Result<()> { 330 | self.output += "]"; 331 | Ok(()) 332 | } 333 | } 334 | 335 | // Same thing but for tuples. 336 | impl ser::SerializeTuple for &mut Serializer { 337 | type Ok = (); 338 | type Error = Error; 339 | 340 | fn serialize_element(&mut self, value: &T) -> Result<()> 341 | where 342 | T: ?Sized + Serialize, 343 | { 344 | if !self.output.ends_with('[') { 345 | self.output += ","; 346 | } 347 | value.serialize(&mut **self) 348 | } 349 | 350 | fn end(self) -> Result<()> { 351 | self.output += "]"; 352 | Ok(()) 353 | } 354 | } 355 | 356 | // Same thing but for tuple structs. 357 | impl ser::SerializeTupleStruct for &mut Serializer { 358 | type Ok = (); 359 | type Error = Error; 360 | 361 | fn serialize_field(&mut self, value: &T) -> Result<()> 362 | where 363 | T: ?Sized + Serialize, 364 | { 365 | if !self.output.ends_with('[') { 366 | self.output += ","; 367 | } 368 | value.serialize(&mut **self) 369 | } 370 | 371 | fn end(self) -> Result<()> { 372 | self.output += "]"; 373 | Ok(()) 374 | } 375 | } 376 | 377 | // Tuple variants are a little different. Refer back to the 378 | // `serialize_tuple_variant` method above: 379 | // 380 | // self.output += "{"; 381 | // variant.serialize(&mut *self)?; 382 | // self.output += ":["; 383 | // 384 | // So the `end` method in this impl is responsible for closing both the `]` and 385 | // the `}`. 386 | impl ser::SerializeTupleVariant for &mut Serializer { 387 | type Ok = (); 388 | type Error = Error; 389 | 390 | fn serialize_field(&mut self, value: &T) -> Result<()> 391 | where 392 | T: ?Sized + Serialize, 393 | { 394 | if !self.output.ends_with('[') { 395 | self.output += ","; 396 | } 397 | value.serialize(&mut **self) 398 | } 399 | 400 | fn end(self) -> Result<()> { 401 | self.output += "]}"; 402 | Ok(()) 403 | } 404 | } 405 | 406 | // Some `Serialize` types are not able to hold a key and value in memory at the 407 | // same time so `SerializeMap` implementations are required to support 408 | // `serialize_key` and `serialize_value` individually. 409 | // 410 | // There is a third optional method on the `SerializeMap` trait. The 411 | // `serialize_entry` method allows serializers to optimize for the case where 412 | // key and value are both available simultaneously. In JSON it doesn't make a 413 | // difference so the default behavior for `serialize_entry` is fine. 414 | impl ser::SerializeMap for &mut Serializer { 415 | type Ok = (); 416 | type Error = Error; 417 | 418 | // The Serde data model allows map keys to be any serializable type. JSON 419 | // only allows string keys so the implementation below will produce invalid 420 | // JSON if the key serializes as something other than a string. 421 | // 422 | // A real JSON serializer would need to validate that map keys are strings. 423 | // This can be done by using a different Serializer to serialize the key 424 | // (instead of `&mut **self`) and having that other serializer only 425 | // implement `serialize_str` and return an error on any other data type. 426 | fn serialize_key(&mut self, key: &T) -> Result<()> 427 | where 428 | T: ?Sized + Serialize, 429 | { 430 | if !self.output.ends_with('{') { 431 | self.output += ","; 432 | } 433 | key.serialize(&mut **self) 434 | } 435 | 436 | // It doesn't make a difference whether the colon is printed at the end of 437 | // `serialize_key` or at the beginning of `serialize_value`. In this case 438 | // the code is a bit simpler having it here. 439 | fn serialize_value(&mut self, value: &T) -> Result<()> 440 | where 441 | T: ?Sized + Serialize, 442 | { 443 | self.output += ":"; 444 | value.serialize(&mut **self) 445 | } 446 | 447 | fn end(self) -> Result<()> { 448 | self.output += "}"; 449 | Ok(()) 450 | } 451 | } 452 | 453 | // Structs are like maps in which the keys are constrained to be compile-time 454 | // constant strings. 455 | impl ser::SerializeStruct for &mut Serializer { 456 | type Ok = (); 457 | type Error = Error; 458 | 459 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> 460 | where 461 | T: ?Sized + Serialize, 462 | { 463 | if !self.output.ends_with('{') { 464 | self.output += ","; 465 | } 466 | key.serialize(&mut **self)?; 467 | self.output += ":"; 468 | value.serialize(&mut **self) 469 | } 470 | 471 | fn end(self) -> Result<()> { 472 | self.output += "}"; 473 | Ok(()) 474 | } 475 | } 476 | 477 | // Similar to `SerializeTupleVariant`, here the `end` method is responsible for 478 | // closing both of the curly braces opened by `serialize_struct_variant`. 479 | impl ser::SerializeStructVariant for &mut Serializer { 480 | type Ok = (); 481 | type Error = Error; 482 | 483 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> 484 | where 485 | T: ?Sized + Serialize, 486 | { 487 | if !self.output.ends_with('{') { 488 | self.output += ","; 489 | } 490 | key.serialize(&mut **self)?; 491 | self.output += ":"; 492 | value.serialize(&mut **self) 493 | } 494 | 495 | fn end(self) -> Result<()> { 496 | self.output += "}}"; 497 | Ok(()) 498 | } 499 | } 500 | 501 | //////////////////////////////////////////////////////////////////////////////// 502 | 503 | #[cfg(test)] 504 | mod tests { 505 | use super::to_string; 506 | use serde_derive::Serialize; 507 | 508 | #[test] 509 | fn test_struct() { 510 | #[derive(Serialize)] 511 | struct Test { 512 | int: u32, 513 | seq: Vec<&'static str>, 514 | } 515 | 516 | let test = Test { 517 | int: 1, 518 | seq: vec!["a", "b"], 519 | }; 520 | let expected = r#"{"int":1,"seq":["a","b"]}"#; 521 | assert_eq!(to_string(&test).unwrap(), expected); 522 | } 523 | 524 | #[test] 525 | fn test_enum() { 526 | #[derive(Serialize)] 527 | enum E { 528 | Unit, 529 | Newtype(u32), 530 | Tuple(u32, u32), 531 | Struct { a: u32 }, 532 | } 533 | 534 | let u = E::Unit; 535 | let expected = r#""Unit""#; 536 | assert_eq!(to_string(&u).unwrap(), expected); 537 | 538 | let n = E::Newtype(1); 539 | let expected = r#"{"Newtype":1}"#; 540 | assert_eq!(to_string(&n).unwrap(), expected); 541 | 542 | let t = E::Tuple(1, 2); 543 | let expected = r#"{"Tuple":[1,2]}"#; 544 | assert_eq!(to_string(&t).unwrap(), expected); 545 | 546 | let s = E::Struct { a: 1 }; 547 | let expected = r#"{"Struct":{"a":1}}"#; 548 | assert_eq!(to_string(&s).unwrap(), expected); 549 | } 550 | } 551 | -------------------------------------------------------------------------------- /src/de.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Serde Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use crate::error::{Error, Result}; 10 | use serde::de::{ 11 | self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, 12 | MapAccess, SeqAccess, VariantAccess, Visitor, 13 | }; 14 | use std::ops::{AddAssign, MulAssign, Neg}; 15 | 16 | pub struct Deserializer<'de> { 17 | // This string starts with the input data and characters are truncated off 18 | // the beginning as data is parsed. 19 | input: &'de str, 20 | } 21 | 22 | impl<'de> Deserializer<'de> { 23 | // By convention, `Deserializer` constructors are named like `from_xyz`. 24 | // That way basic use cases are satisfied by something like 25 | // `serde_json::from_str(...)` while advanced use cases that require a 26 | // deserializer can make one with `serde_json::Deserializer::from_str(...)`. 27 | #[allow(clippy::should_implement_trait)] 28 | pub fn from_str(input: &'de str) -> Self { 29 | Deserializer { input } 30 | } 31 | } 32 | 33 | // By convention, the public API of a Serde deserializer is one or more 34 | // `from_xyz` methods such as `from_str`, `from_bytes`, or `from_reader` 35 | // depending on what Rust types the deserializer is able to consume as input. 36 | // 37 | // This basic deserializer supports only `from_str`. 38 | pub fn from_str<'a, T>(s: &'a str) -> Result 39 | where 40 | T: Deserialize<'a>, 41 | { 42 | let mut deserializer = Deserializer::from_str(s); 43 | let t = T::deserialize(&mut deserializer)?; 44 | if deserializer.input.is_empty() { 45 | Ok(t) 46 | } else { 47 | Err(Error::TrailingCharacters) 48 | } 49 | } 50 | 51 | // SERDE IS NOT A PARSING LIBRARY. This impl block defines a few basic parsing 52 | // functions from scratch. More complicated formats may wish to use a dedicated 53 | // parsing library to help implement their Serde deserializer. 54 | impl<'de> Deserializer<'de> { 55 | // Look at the first character in the input without consuming it. 56 | fn peek_char(&mut self) -> Result { 57 | self.input.chars().next().ok_or(Error::Eof) 58 | } 59 | 60 | // Consume the first character in the input. 61 | fn next_char(&mut self) -> Result { 62 | let ch = self.peek_char()?; 63 | self.input = &self.input[ch.len_utf8()..]; 64 | Ok(ch) 65 | } 66 | 67 | // Parse the JSON identifier `true` or `false`. 68 | fn parse_bool(&mut self) -> Result { 69 | if self.input.starts_with("true") { 70 | self.input = &self.input["true".len()..]; 71 | Ok(true) 72 | } else if self.input.starts_with("false") { 73 | self.input = &self.input["false".len()..]; 74 | Ok(false) 75 | } else { 76 | Err(Error::ExpectedBoolean) 77 | } 78 | } 79 | 80 | // Parse a group of decimal digits as an unsigned integer of type T. 81 | // 82 | // This implementation is a bit too lenient, for example `001` is not 83 | // allowed in JSON. Also the various arithmetic operations can overflow and 84 | // panic or return bogus data. But it is good enough for example code! 85 | fn parse_unsigned(&mut self) -> Result 86 | where 87 | T: AddAssign + MulAssign + From, 88 | { 89 | let mut int = match self.next_char()? { 90 | ch @ '0'..='9' => T::from(ch as u8 - b'0'), 91 | _ => { 92 | return Err(Error::ExpectedInteger); 93 | } 94 | }; 95 | loop { 96 | match self.input.chars().next() { 97 | Some(ch @ '0'..='9') => { 98 | self.input = &self.input[1..]; 99 | int *= T::from(10); 100 | int += T::from(ch as u8 - b'0'); 101 | } 102 | _ => { 103 | return Ok(int); 104 | } 105 | } 106 | } 107 | } 108 | 109 | // Parse a possible minus sign followed by a group of decimal digits as a 110 | // signed integer of type T. 111 | fn parse_signed(&mut self) -> Result 112 | where 113 | T: Neg + AddAssign + MulAssign + From, 114 | { 115 | // Optional minus sign, delegate to `parse_unsigned`, negate if negative. 116 | unimplemented!() 117 | } 118 | 119 | // Parse a string until the next '"' character. 120 | // 121 | // Makes no attempt to handle escape sequences. What did you expect? This is 122 | // example code! 123 | fn parse_string(&mut self) -> Result<&'de str> { 124 | if self.next_char()? != '"' { 125 | return Err(Error::ExpectedString); 126 | } 127 | match self.input.find('"') { 128 | Some(len) => { 129 | let s = &self.input[..len]; 130 | self.input = &self.input[len + 1..]; 131 | Ok(s) 132 | } 133 | None => Err(Error::Eof), 134 | } 135 | } 136 | } 137 | 138 | impl<'de> de::Deserializer<'de> for &mut Deserializer<'de> { 139 | type Error = Error; 140 | 141 | // Look at the input data to decide what Serde data model type to 142 | // deserialize as. Not all data formats are able to support this operation. 143 | // Formats that support `deserialize_any` are known as self-describing. 144 | fn deserialize_any(self, visitor: V) -> Result 145 | where 146 | V: Visitor<'de>, 147 | { 148 | match self.peek_char()? { 149 | 'n' => self.deserialize_unit(visitor), 150 | 't' | 'f' => self.deserialize_bool(visitor), 151 | '"' => self.deserialize_str(visitor), 152 | '0'..='9' => self.deserialize_u64(visitor), 153 | '-' => self.deserialize_i64(visitor), 154 | '[' => self.deserialize_seq(visitor), 155 | '{' => self.deserialize_map(visitor), 156 | _ => Err(Error::Syntax), 157 | } 158 | } 159 | 160 | // Uses the `parse_bool` parsing function defined above to read the JSON 161 | // identifier `true` or `false` from the input. 162 | // 163 | // Parsing refers to looking at the input and deciding that it contains the 164 | // JSON value `true` or `false`. 165 | // 166 | // Deserialization refers to mapping that JSON value into Serde's data 167 | // model by invoking one of the `Visitor` methods. In the case of JSON and 168 | // bool that mapping is straightforward so the distinction may seem silly, 169 | // but in other cases Deserializers sometimes perform non-obvious mappings. 170 | // For example the TOML format has a Datetime type and Serde's data model 171 | // does not. In the `toml` crate, a Datetime in the input is deserialized by 172 | // mapping it to a Serde data model "struct" type with a special name and a 173 | // single field containing the Datetime represented as a string. 174 | fn deserialize_bool(self, visitor: V) -> Result 175 | where 176 | V: Visitor<'de>, 177 | { 178 | visitor.visit_bool(self.parse_bool()?) 179 | } 180 | 181 | // The `parse_signed` function is generic over the integer type `T` so here 182 | // it is invoked with `T=i8`. The next 8 methods are similar. 183 | fn deserialize_i8(self, visitor: V) -> Result 184 | where 185 | V: Visitor<'de>, 186 | { 187 | visitor.visit_i8(self.parse_signed()?) 188 | } 189 | 190 | fn deserialize_i16(self, visitor: V) -> Result 191 | where 192 | V: Visitor<'de>, 193 | { 194 | visitor.visit_i16(self.parse_signed()?) 195 | } 196 | 197 | fn deserialize_i32(self, visitor: V) -> Result 198 | where 199 | V: Visitor<'de>, 200 | { 201 | visitor.visit_i32(self.parse_signed()?) 202 | } 203 | 204 | fn deserialize_i64(self, visitor: V) -> Result 205 | where 206 | V: Visitor<'de>, 207 | { 208 | visitor.visit_i64(self.parse_signed()?) 209 | } 210 | 211 | fn deserialize_u8(self, visitor: V) -> Result 212 | where 213 | V: Visitor<'de>, 214 | { 215 | visitor.visit_u8(self.parse_unsigned()?) 216 | } 217 | 218 | fn deserialize_u16(self, visitor: V) -> Result 219 | where 220 | V: Visitor<'de>, 221 | { 222 | visitor.visit_u16(self.parse_unsigned()?) 223 | } 224 | 225 | fn deserialize_u32(self, visitor: V) -> Result 226 | where 227 | V: Visitor<'de>, 228 | { 229 | visitor.visit_u32(self.parse_unsigned()?) 230 | } 231 | 232 | fn deserialize_u64(self, visitor: V) -> Result 233 | where 234 | V: Visitor<'de>, 235 | { 236 | visitor.visit_u64(self.parse_unsigned()?) 237 | } 238 | 239 | // Float parsing is stupidly hard. 240 | fn deserialize_f32(self, _visitor: V) -> Result 241 | where 242 | V: Visitor<'de>, 243 | { 244 | unimplemented!() 245 | } 246 | 247 | // Float parsing is stupidly hard. 248 | fn deserialize_f64(self, _visitor: V) -> Result 249 | where 250 | V: Visitor<'de>, 251 | { 252 | unimplemented!() 253 | } 254 | 255 | // The `Serializer` implementation on the previous page serialized chars as 256 | // single-character strings so handle that representation here. 257 | fn deserialize_char(self, _visitor: V) -> Result 258 | where 259 | V: Visitor<'de>, 260 | { 261 | // Parse a string, check that it is one character, call `visit_char`. 262 | unimplemented!() 263 | } 264 | 265 | // Refer to the "Understanding deserializer lifetimes" page for information 266 | // about the three deserialization flavors of strings in Serde. 267 | fn deserialize_str(self, visitor: V) -> Result 268 | where 269 | V: Visitor<'de>, 270 | { 271 | visitor.visit_borrowed_str(self.parse_string()?) 272 | } 273 | 274 | fn deserialize_string(self, visitor: V) -> Result 275 | where 276 | V: Visitor<'de>, 277 | { 278 | self.deserialize_str(visitor) 279 | } 280 | 281 | // The `Serializer` implementation on the previous page serialized byte 282 | // arrays as JSON arrays of bytes. Handle that representation here. 283 | fn deserialize_bytes(self, _visitor: V) -> Result 284 | where 285 | V: Visitor<'de>, 286 | { 287 | unimplemented!() 288 | } 289 | 290 | fn deserialize_byte_buf(self, _visitor: V) -> Result 291 | where 292 | V: Visitor<'de>, 293 | { 294 | unimplemented!() 295 | } 296 | 297 | // An absent optional is represented as the JSON `null` and a present 298 | // optional is represented as just the contained value. 299 | // 300 | // As commented in `Serializer` implementation, this is a lossy 301 | // representation. For example the values `Some(())` and `None` both 302 | // serialize as just `null`. Unfortunately this is typically what people 303 | // expect when working with JSON. Other formats are encouraged to behave 304 | // more intelligently if possible. 305 | fn deserialize_option(self, visitor: V) -> Result 306 | where 307 | V: Visitor<'de>, 308 | { 309 | if self.input.starts_with("null") { 310 | self.input = &self.input["null".len()..]; 311 | visitor.visit_none() 312 | } else { 313 | visitor.visit_some(self) 314 | } 315 | } 316 | 317 | // In Serde, unit means an anonymous value containing no data. 318 | fn deserialize_unit(self, visitor: V) -> Result 319 | where 320 | V: Visitor<'de>, 321 | { 322 | if self.input.starts_with("null") { 323 | self.input = &self.input["null".len()..]; 324 | visitor.visit_unit() 325 | } else { 326 | Err(Error::ExpectedNull) 327 | } 328 | } 329 | 330 | // Unit struct means a named value containing no data. 331 | fn deserialize_unit_struct( 332 | self, 333 | _name: &'static str, 334 | visitor: V, 335 | ) -> Result 336 | where 337 | V: Visitor<'de>, 338 | { 339 | self.deserialize_unit(visitor) 340 | } 341 | 342 | // As is done here, serializers are encouraged to treat newtype structs as 343 | // insignificant wrappers around the data they contain. That means not 344 | // parsing anything other than the contained value. 345 | fn deserialize_newtype_struct( 346 | self, 347 | _name: &'static str, 348 | visitor: V, 349 | ) -> Result 350 | where 351 | V: Visitor<'de>, 352 | { 353 | visitor.visit_newtype_struct(self) 354 | } 355 | 356 | // Deserialization of compound types like sequences and maps happens by 357 | // passing the visitor an "Access" object that gives it the ability to 358 | // iterate through the data contained in the sequence. 359 | fn deserialize_seq(self, visitor: V) -> Result 360 | where 361 | V: Visitor<'de>, 362 | { 363 | // Parse the opening bracket of the sequence. 364 | if self.next_char()? == '[' { 365 | // Give the visitor access to each element of the sequence. 366 | let value = visitor.visit_seq(CommaSeparated::new(self))?; 367 | // Parse the closing bracket of the sequence. 368 | if self.next_char()? == ']' { 369 | Ok(value) 370 | } else { 371 | Err(Error::ExpectedArrayEnd) 372 | } 373 | } else { 374 | Err(Error::ExpectedArray) 375 | } 376 | } 377 | 378 | // Tuples look just like sequences in JSON. Some formats may be able to 379 | // represent tuples more efficiently. 380 | // 381 | // As indicated by the length parameter, the `Deserialize` implementation 382 | // for a tuple in the Serde data model is required to know the length of the 383 | // tuple before even looking at the input data. 384 | fn deserialize_tuple(self, _len: usize, visitor: V) -> Result 385 | where 386 | V: Visitor<'de>, 387 | { 388 | self.deserialize_seq(visitor) 389 | } 390 | 391 | // Tuple structs look just like sequences in JSON. 392 | fn deserialize_tuple_struct( 393 | self, 394 | _name: &'static str, 395 | _len: usize, 396 | visitor: V, 397 | ) -> Result 398 | where 399 | V: Visitor<'de>, 400 | { 401 | self.deserialize_seq(visitor) 402 | } 403 | 404 | // Much like `deserialize_seq` but calls the visitors `visit_map` method 405 | // with a `MapAccess` implementation, rather than the visitor's `visit_seq` 406 | // method with a `SeqAccess` implementation. 407 | fn deserialize_map(self, visitor: V) -> Result 408 | where 409 | V: Visitor<'de>, 410 | { 411 | // Parse the opening brace of the map. 412 | if self.next_char()? == '{' { 413 | // Give the visitor access to each entry of the map. 414 | let value = visitor.visit_map(CommaSeparated::new(self))?; 415 | // Parse the closing brace of the map. 416 | if self.next_char()? == '}' { 417 | Ok(value) 418 | } else { 419 | Err(Error::ExpectedMapEnd) 420 | } 421 | } else { 422 | Err(Error::ExpectedMap) 423 | } 424 | } 425 | 426 | // Structs look just like maps in JSON. 427 | // 428 | // Notice the `fields` parameter - a "struct" in the Serde data model means 429 | // that the `Deserialize` implementation is required to know what the fields 430 | // are before even looking at the input data. Any key-value pairing in which 431 | // the fields cannot be known ahead of time is probably a map. 432 | fn deserialize_struct( 433 | self, 434 | _name: &'static str, 435 | _fields: &'static [&'static str], 436 | visitor: V, 437 | ) -> Result 438 | where 439 | V: Visitor<'de>, 440 | { 441 | self.deserialize_map(visitor) 442 | } 443 | 444 | fn deserialize_enum( 445 | self, 446 | _name: &'static str, 447 | _variants: &'static [&'static str], 448 | visitor: V, 449 | ) -> Result 450 | where 451 | V: Visitor<'de>, 452 | { 453 | if self.peek_char()? == '"' { 454 | // Visit a unit variant. 455 | visitor.visit_enum(self.parse_string()?.into_deserializer()) 456 | } else if self.next_char()? == '{' { 457 | // Visit a newtype variant, tuple variant, or struct variant. 458 | let value = visitor.visit_enum(Enum::new(self))?; 459 | // Parse the matching close brace. 460 | if self.next_char()? == '}' { 461 | Ok(value) 462 | } else { 463 | Err(Error::ExpectedMapEnd) 464 | } 465 | } else { 466 | Err(Error::ExpectedEnum) 467 | } 468 | } 469 | 470 | // An identifier in Serde is the type that identifies a field of a struct or 471 | // the variant of an enum. In JSON, struct fields and enum variants are 472 | // represented as strings. In other formats they may be represented as 473 | // numeric indices. 474 | fn deserialize_identifier(self, visitor: V) -> Result 475 | where 476 | V: Visitor<'de>, 477 | { 478 | self.deserialize_str(visitor) 479 | } 480 | 481 | // Like `deserialize_any` but indicates to the `Deserializer` that it makes 482 | // no difference which `Visitor` method is called because the data is 483 | // ignored. 484 | // 485 | // Some deserializers are able to implement this more efficiently than 486 | // `deserialize_any`, for example by rapidly skipping over matched 487 | // delimiters without paying close attention to the data in between. 488 | // 489 | // Some formats are not able to implement this at all. Formats that can 490 | // implement `deserialize_any` and `deserialize_ignored_any` are known as 491 | // self-describing. 492 | fn deserialize_ignored_any(self, visitor: V) -> Result 493 | where 494 | V: Visitor<'de>, 495 | { 496 | self.deserialize_any(visitor) 497 | } 498 | } 499 | 500 | // In order to handle commas correctly when deserializing a JSON array or map, 501 | // we need to track whether we are on the first element or past the first 502 | // element. 503 | struct CommaSeparated<'a, 'de: 'a> { 504 | de: &'a mut Deserializer<'de>, 505 | first: bool, 506 | } 507 | 508 | impl<'a, 'de> CommaSeparated<'a, 'de> { 509 | fn new(de: &'a mut Deserializer<'de>) -> Self { 510 | CommaSeparated { de, first: true } 511 | } 512 | } 513 | 514 | // `SeqAccess` is provided to the `Visitor` to give it the ability to iterate 515 | // through elements of the sequence. 516 | impl<'de> SeqAccess<'de> for CommaSeparated<'_, 'de> { 517 | type Error = Error; 518 | 519 | fn next_element_seed(&mut self, seed: T) -> Result> 520 | where 521 | T: DeserializeSeed<'de>, 522 | { 523 | // Check if there are no more elements. 524 | if self.de.peek_char()? == ']' { 525 | return Ok(None); 526 | } 527 | // Comma is required before every element except the first. 528 | if !self.first && self.de.next_char()? != ',' { 529 | return Err(Error::ExpectedArrayComma); 530 | } 531 | self.first = false; 532 | // Deserialize an array element. 533 | seed.deserialize(&mut *self.de).map(Some) 534 | } 535 | } 536 | 537 | // `MapAccess` is provided to the `Visitor` to give it the ability to iterate 538 | // through entries of the map. 539 | impl<'de> MapAccess<'de> for CommaSeparated<'_, 'de> { 540 | type Error = Error; 541 | 542 | fn next_key_seed(&mut self, seed: K) -> Result> 543 | where 544 | K: DeserializeSeed<'de>, 545 | { 546 | // Check if there are no more entries. 547 | if self.de.peek_char()? == '}' { 548 | return Ok(None); 549 | } 550 | // Comma is required before every entry except the first. 551 | if !self.first && self.de.next_char()? != ',' { 552 | return Err(Error::ExpectedMapComma); 553 | } 554 | self.first = false; 555 | // Deserialize a map key. 556 | seed.deserialize(&mut *self.de).map(Some) 557 | } 558 | 559 | fn next_value_seed(&mut self, seed: V) -> Result 560 | where 561 | V: DeserializeSeed<'de>, 562 | { 563 | // It doesn't make a difference whether the colon is parsed at the end 564 | // of `next_key_seed` or at the beginning of `next_value_seed`. In this 565 | // case the code is a bit simpler having it here. 566 | if self.de.next_char()? != ':' { 567 | return Err(Error::ExpectedMapColon); 568 | } 569 | // Deserialize a map value. 570 | seed.deserialize(&mut *self.de) 571 | } 572 | } 573 | 574 | struct Enum<'a, 'de: 'a> { 575 | de: &'a mut Deserializer<'de>, 576 | } 577 | 578 | impl<'a, 'de> Enum<'a, 'de> { 579 | fn new(de: &'a mut Deserializer<'de>) -> Self { 580 | Enum { de } 581 | } 582 | } 583 | 584 | // `EnumAccess` is provided to the `Visitor` to give it the ability to determine 585 | // which variant of the enum is supposed to be deserialized. 586 | // 587 | // Note that all enum deserialization methods in Serde refer exclusively to the 588 | // "externally tagged" enum representation. 589 | impl<'de> EnumAccess<'de> for Enum<'_, 'de> { 590 | type Error = Error; 591 | type Variant = Self; 592 | 593 | fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant)> 594 | where 595 | V: DeserializeSeed<'de>, 596 | { 597 | // The `deserialize_enum` method parsed a `{` character so we are 598 | // currently inside of a map. The seed will be deserializing itself from 599 | // the key of the map. 600 | let val = seed.deserialize(&mut *self.de)?; 601 | // Parse the colon separating map key from value. 602 | if self.de.next_char()? == ':' { 603 | Ok((val, self)) 604 | } else { 605 | Err(Error::ExpectedMapColon) 606 | } 607 | } 608 | } 609 | 610 | // `VariantAccess` is provided to the `Visitor` to give it the ability to see 611 | // the content of the single variant that it decided to deserialize. 612 | impl<'de> VariantAccess<'de> for Enum<'_, 'de> { 613 | type Error = Error; 614 | 615 | // If the `Visitor` expected this variant to be a unit variant, the input 616 | // should have been the plain string case handled in `deserialize_enum`. 617 | fn unit_variant(self) -> Result<()> { 618 | Err(Error::ExpectedString) 619 | } 620 | 621 | // Newtype variants are represented in JSON as `{ NAME: VALUE }` so 622 | // deserialize the value here. 623 | fn newtype_variant_seed(self, seed: T) -> Result 624 | where 625 | T: DeserializeSeed<'de>, 626 | { 627 | seed.deserialize(self.de) 628 | } 629 | 630 | // Tuple variants are represented in JSON as `{ NAME: [DATA...] }` so 631 | // deserialize the sequence of data here. 632 | fn tuple_variant(self, _len: usize, visitor: V) -> Result 633 | where 634 | V: Visitor<'de>, 635 | { 636 | de::Deserializer::deserialize_seq(self.de, visitor) 637 | } 638 | 639 | // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so 640 | // deserialize the inner map here. 641 | fn struct_variant( 642 | self, 643 | _fields: &'static [&'static str], 644 | visitor: V, 645 | ) -> Result 646 | where 647 | V: Visitor<'de>, 648 | { 649 | de::Deserializer::deserialize_map(self.de, visitor) 650 | } 651 | } 652 | 653 | //////////////////////////////////////////////////////////////////////////////// 654 | 655 | #[cfg(test)] 656 | mod tests { 657 | use super::from_str; 658 | use serde_derive::Deserialize; 659 | 660 | #[test] 661 | fn test_struct() { 662 | #[derive(Deserialize, PartialEq, Debug)] 663 | struct Test { 664 | int: u32, 665 | seq: Vec, 666 | } 667 | 668 | let j = r#"{"int":1,"seq":["a","b"]}"#; 669 | let expected = Test { 670 | int: 1, 671 | seq: vec!["a".to_owned(), "b".to_owned()], 672 | }; 673 | assert_eq!(expected, from_str(j).unwrap()); 674 | } 675 | 676 | #[test] 677 | fn test_enum() { 678 | #[derive(Deserialize, PartialEq, Debug)] 679 | enum E { 680 | Unit, 681 | Newtype(u32), 682 | Tuple(u32, u32), 683 | Struct { a: u32 }, 684 | } 685 | 686 | let j = r#""Unit""#; 687 | let expected = E::Unit; 688 | assert_eq!(expected, from_str(j).unwrap()); 689 | 690 | let j = r#"{"Newtype":1}"#; 691 | let expected = E::Newtype(1); 692 | assert_eq!(expected, from_str(j).unwrap()); 693 | 694 | let j = r#"{"Tuple":[1,2]}"#; 695 | let expected = E::Tuple(1, 2); 696 | assert_eq!(expected, from_str(j).unwrap()); 697 | 698 | let j = r#"{"Struct":{"a":1}}"#; 699 | let expected = E::Struct { a: 1 }; 700 | assert_eq!(expected, from_str(j).unwrap()); 701 | } 702 | } 703 | --------------------------------------------------------------------------------