├── .github └── workflows │ └── test.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── macro ├── Cargo.toml └── src │ └── lib.rs ├── rust-toolchain.toml └── src ├── alloc.rs ├── filter.rs ├── lib.rs ├── map.rs ├── std.rs └── struct.rs /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | jobs: 3 | test: 4 | runs-on: ubuntu-latest 5 | steps: 6 | - uses: actions/checkout@v3 7 | - run: cargo fmt --all -- --check && cargo clippy --workspace -- -D warnings 8 | - run: cargo test 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde-partial" 3 | version = "0.3.1" 4 | edition = "2021" 5 | rust-version = "1.56.0" 6 | authors = ["Raphaël Thériault "] 7 | license = "MIT OR Apache-2.0" 8 | description = "Serde partial serialization made easy" 9 | repository = "https://github.com/raftario/serde-partial" 10 | keywords = ["serde", "partial", "filter", "serialization"] 11 | categories = ["encoding", "rust-patterns", "no-std"] 12 | 13 | [features] 14 | default = ["alloc", "std"] 15 | alloc = ["serde/alloc"] 16 | std = ["serde/std"] 17 | 18 | [dependencies] 19 | serde = { version = "1", default-features = false } 20 | serde-partial-macro = { path = "macro", version = "0.3.0" } 21 | 22 | [dev-dependencies] 23 | serde = { version = "1", features = ["derive"] } 24 | serde_json = "1" 25 | 26 | [workspace] 27 | members = ["macro"] 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 | 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serde-partial 2 | 3 | One of the few things that still require boilerplate when using Serde is partial serialization. 4 | 5 | Let's say we have an API route which returns product information. We want to return the stock only to admins and not to visitors. There are a few options here; have a second struct with a subset of the fields which also derives `Serialize`, make the stock field an `Option` with `#[serde(skip_serializing_if = "Option::is_none")]` and set to `None` for visitors, or use something like the `serde_json::json!` macro and do manual serialization. 6 | 7 | None of these options are particularly attractive. Having to maintain a struct and handle conversion for each subset of fields is a lot of boilerplate. Making a field that's always present optional just for serialization is a hack at best. Manual serialization kind of defeats the purpose of serde derives. 8 | 9 | `serde-partial` aims to make partial serialization (almost) as clean an concise as complete serialization while also being `no_std` compatible. Using this crate this problem could be solved in a single line. 10 | 11 | ```rust 12 | use serde::Serialize; 13 | use serde_partial::SerializePartial; 14 | 15 | #[derive(Serialize, SerializePartial)] 16 | pub struct Product { 17 | name: String, 18 | price: u32, 19 | stock: u32, 20 | } 21 | 22 | fn get_product(id: i32) -> Product { 23 | todo!() 24 | } 25 | 26 | fn product_api(id: i32, is_manager: bool) -> String { 27 | let product = get_product(id); 28 | if is_manager { 29 | serde_json::to_string(&product).unwrap() 30 | } else { 31 | serde_json::to_string(&product.without_fields(|p| [p.stock])).unwrap() 32 | } 33 | } 34 | ``` 35 | 36 | Check out the [`with_fields`](SerializePartial::with_fields) [documentation](https://docs.rs/serde-partial) for more details and examples. 37 | -------------------------------------------------------------------------------- /macro/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde-partial-macro" 3 | version = "0.3.1" 4 | edition = "2021" 5 | rust-version = "1.56.0" 6 | authors = ["Raphaël Thériault "] 7 | license = "MIT OR Apache-2.0" 8 | description = "proc-macro for serde-partial" 9 | repository = "https://github.com/raftario/serde-partial" 10 | 11 | [lib] 12 | proc-macro = true 13 | 14 | [dependencies] 15 | quote = { version = "1", default-features = false, features = ["proc-macro"] } 16 | serde_derive_internals = "~0.26.0" 17 | syn = { version = "1", default-features = false, features = [ 18 | "proc-macro", 19 | "derive", 20 | ] } 21 | -------------------------------------------------------------------------------- /macro/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::{Span, TokenStream}; 2 | use quote::ToTokens; 3 | use serde_derive_internals::{ 4 | ast::{Container, Data, Style}, 5 | Ctxt, Derive, 6 | }; 7 | use syn::{DeriveInput, Error}; 8 | 9 | #[proc_macro_derive(SerializePartial, attributes(serde))] 10 | pub fn serialize_partial(input: TokenStream) -> TokenStream { 11 | let cx = Ctxt::new(); 12 | let item = syn::parse_macro_input!(input as DeriveInput); 13 | let Container { 14 | data, 15 | attrs, 16 | ident, 17 | original, 18 | .. 19 | } = match Container::from_ast(&cx, &item, Derive::Serialize) { 20 | Some(c) => c, 21 | None => return item.to_token_stream().into(), 22 | }; 23 | let ident = &ident; 24 | let vis = &original.vis; 25 | 26 | if cx.check().is_err() { 27 | return item.to_token_stream().into(); 28 | } 29 | 30 | let mut fields = match data { 31 | Data::Struct(Style::Struct, f) => f, 32 | _ => { 33 | return Error::new( 34 | Span::call_site().into(), 35 | "SerializePartial only supports structs", 36 | ) 37 | .to_compile_error() 38 | .into() 39 | } 40 | }; 41 | for f in fields.iter_mut() { 42 | f.attrs.rename_by_rules(attrs.rename_all_rules()); 43 | } 44 | fields.retain(|f| !f.attrs.skip_serializing()); 45 | 46 | let field_idents = fields 47 | .iter() 48 | .map(|f| f.original.ident.as_ref().unwrap()) 49 | .collect::>(); 50 | let field_idents = &field_idents; 51 | 52 | let field_names = fields 53 | .iter() 54 | .map(|f| f.attrs.name().serialize_name()) 55 | .collect::>(); 56 | let field_names = &field_names; 57 | 58 | let fields_len = fields.len(); 59 | 60 | let fields_struct_ident = "e::format_ident!("{}Fields", ident); 61 | let filter_struct_ident = "e::format_ident!("{}Filter", ident); 62 | 63 | let fields_struct = quote::quote! { 64 | #[derive(Debug, Clone, Copy)] 65 | #vis struct #fields_struct_ident { 66 | #( 67 | pub #field_idents: ::serde_partial::Field<'static, #ident>, 68 | )* 69 | } 70 | 71 | impl #fields_struct_ident { 72 | pub const FIELDS: Self = Self { 73 | #( 74 | #field_idents: ::serde_partial::Field::new(#field_names), 75 | )* 76 | }; 77 | } 78 | 79 | impl ::core::iter::IntoIterator for #fields_struct_ident { 80 | type Item = ::serde_partial::Field<'static, #ident>; 81 | type IntoIter = ::core::array::IntoIter; 82 | 83 | fn into_iter(self) -> Self::IntoIter { 84 | #[allow(deprecated)] 85 | ::core::array::IntoIter::new([ 86 | #( 87 | self.#field_idents, 88 | )* 89 | ]) 90 | } 91 | } 92 | }; 93 | 94 | let filter_struct = quote::quote! { 95 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] 96 | #vis struct #filter_struct_ident { 97 | #( 98 | #field_idents: bool, 99 | )* 100 | } 101 | 102 | impl ::serde_partial::SerializeFilter<#ident> for #filter_struct_ident { 103 | fn skip(&self, field: ::serde_partial::Field<'_, #ident>) -> bool { 104 | match field.name() { 105 | #( 106 | #field_names => !self.#field_idents, 107 | )* 108 | _ => panic!("unknown field"), 109 | } 110 | } 111 | 112 | fn filtered_len(&self, _len: Option) -> Option { 113 | let mut len = 0; 114 | #( 115 | if self.#field_idents { 116 | len += 1; 117 | } 118 | )* 119 | Some(len) 120 | } 121 | } 122 | }; 123 | 124 | let trait_impl = quote::quote! { 125 | impl<'a> ::serde_partial::SerializePartial<'a> for #ident { 126 | type Fields = #fields_struct_ident; 127 | type Filter = #filter_struct_ident; 128 | 129 | fn with_fields(&'a self, select: F) -> ::serde_partial::Partial<'a, Self> 130 | where 131 | F: ::core::ops::FnOnce(Self::Fields) -> I, 132 | I: ::core::iter::IntoIterator>, 133 | { 134 | let fields = Self::Fields::FIELDS; 135 | let mut filter = ::default(); 136 | 137 | for filtered in select(fields) { 138 | match filtered.name() { 139 | #( 140 | #field_names => { filter.#field_idents = true } 141 | )* 142 | _ => panic!("unknown field"), 143 | } 144 | } 145 | 146 | ::serde_partial::Partial { 147 | value: self, 148 | filter, 149 | } 150 | } 151 | } 152 | }; 153 | 154 | let derive = quote::quote! { 155 | #[doc(hidden)] 156 | #[allow(non_upper_case_globals, non_camel_case_types)] 157 | const _: () = { 158 | #fields_struct 159 | #filter_struct 160 | #trait_impl 161 | }; 162 | }; 163 | derive.into() 164 | } 165 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.56.0" 3 | profile = "minimal" 4 | components = ["rustfmt", "clippy"] 5 | -------------------------------------------------------------------------------- /src/alloc.rs: -------------------------------------------------------------------------------- 1 | use alloc::collections::{ 2 | btree_map::{BTreeMap, Keys}, 3 | BTreeSet, 4 | }; 5 | use core::iter::Map; 6 | 7 | use serde::Serialize; 8 | 9 | use crate::{Field, Partial, SerializeFilter, SerializePartial}; 10 | 11 | impl<'a, K, V> SerializePartial<'a> for BTreeMap 12 | where 13 | K: Ord + AsRef + Serialize + 'a, 14 | V: Serialize + 'a, 15 | { 16 | #[allow(clippy::type_complexity)] 17 | type Fields = Map, fn(&'a K) -> Field<'a, Self>>; 18 | type Filter = BTreeSet>; 19 | 20 | fn with_fields(&'a self, select: F) -> Partial<'a, Self> 21 | where 22 | F: FnOnce(Self::Fields) -> I, 23 | I: IntoIterator>, 24 | { 25 | let fields: Self::Fields = self.keys().map(|k| Field::new(k.as_ref())); 26 | let filter = select(fields).into_iter().collect(); 27 | Partial { 28 | value: self, 29 | filter, 30 | } 31 | } 32 | } 33 | 34 | impl<'a, K, V> SerializeFilter> for BTreeSet>> { 35 | fn skip(&self, field: Field<'_, BTreeMap>) -> bool { 36 | !self.contains(&field) 37 | } 38 | 39 | fn filtered_len(&self, _len: Option) -> Option { 40 | Some(self.len()) 41 | } 42 | } 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use crate::{Field, SerializePartial}; 47 | 48 | use alloc::collections::BTreeMap; 49 | 50 | #[test] 51 | fn b_tree_map() { 52 | let map = BTreeMap::from([("a", "b"), ("c", "d")]); 53 | let filtered = map.with_fields(|_| [Field::new("a")]); 54 | assert_eq!( 55 | serde_json::to_value(&filtered).unwrap(), 56 | serde_json::json!({ "a": "b" }) 57 | ) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/filter.rs: -------------------------------------------------------------------------------- 1 | //! Field filtering 2 | 3 | use core::{fmt, marker::PhantomData}; 4 | 5 | use crate::{Field, SerializePartial}; 6 | 7 | /// Trait implemented by types which can be used to filter the serializable fields of another type. 8 | pub trait SerializeFilter { 9 | /// Returns whether the specified field should be skipped. 10 | fn skip(&self, field: Field<'_, T>) -> bool; 11 | 12 | /// Returns the number of fields which will be serialized given the total field count. 13 | fn filtered_len(&self, len: Option) -> Option; 14 | } 15 | 16 | /// A [`SerializeFilter`] which inverts the behavior of the filter it wraps. 17 | pub struct InverseFilter<'a, T, F = >::Filter> 18 | where 19 | T: ?Sized + SerializePartial<'a>, 20 | { 21 | filter: F, 22 | _ty: PhantomData<&'a T>, 23 | } 24 | 25 | impl<'a, T, F> SerializeFilter for InverseFilter<'a, T, F> 26 | where 27 | T: ?Sized + SerializePartial<'a>, 28 | F: SerializeFilter, 29 | { 30 | fn skip(&self, field: Field<'_, T>) -> bool { 31 | !self.filter.skip(field) 32 | } 33 | 34 | fn filtered_len(&self, len: Option) -> Option { 35 | match (len, self.filter.filtered_len(len)) { 36 | (Some(len), Some(filtered_len)) => Some(len - filtered_len), 37 | _ => None, 38 | } 39 | } 40 | } 41 | 42 | impl<'a, T, F> InverseFilter<'a, T, F> 43 | where 44 | T: ?Sized + SerializePartial<'a>, 45 | F: SerializeFilter, 46 | { 47 | /// Creates a filter which inverts the behavior of the provided one. 48 | pub fn new(filter: F) -> Self { 49 | Self { 50 | filter, 51 | _ty: PhantomData, 52 | } 53 | } 54 | } 55 | 56 | impl<'a, T, F> Clone for InverseFilter<'a, T, F> 57 | where 58 | T: ?Sized + SerializePartial<'a>, 59 | F: Clone, 60 | { 61 | fn clone(&self) -> Self { 62 | Self { 63 | filter: self.filter.clone(), 64 | _ty: PhantomData, 65 | } 66 | } 67 | } 68 | impl<'a, T, F> Copy for InverseFilter<'a, T, F> 69 | where 70 | T: ?Sized + SerializePartial<'a>, 71 | F: Copy, 72 | { 73 | } 74 | 75 | impl<'a, T, F> fmt::Debug for InverseFilter<'a, T, F> 76 | where 77 | T: ?Sized + SerializePartial<'a>, 78 | F: fmt::Debug, 79 | { 80 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 81 | f.debug_tuple("InverseFilter").field(&self.filter).finish() 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![doc = include_str!("../README.md")] 3 | #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] 4 | 5 | #[cfg(feature = "alloc")] 6 | extern crate alloc; 7 | #[cfg(feature = "std")] 8 | extern crate std; 9 | 10 | use core::{cmp, fmt, hash, marker::PhantomData}; 11 | 12 | use serde::ser::{Serialize, Serializer}; 13 | 14 | #[cfg(feature = "alloc")] 15 | #[cfg_attr(feature = "alloc", path = "alloc.rs")] 16 | mod feature_alloc; 17 | #[cfg(feature = "std")] 18 | #[cfg_attr(feature = "std", path = "std.rs")] 19 | mod feature_std; 20 | #[path = "map.rs"] 21 | mod serde_map; 22 | #[path = "struct.rs"] 23 | mod serde_struct; 24 | 25 | pub mod filter; 26 | pub use filter::SerializeFilter; 27 | 28 | /// Derive macro for the [`SerializePartial`] trait. 29 | pub use serde_partial_macro::SerializePartial; 30 | 31 | /// Trait implemented by types which can be partially serialized. 32 | pub trait SerializePartial<'a>: Serialize { 33 | /// Type which provides the list of serializable fields. 34 | /// 35 | /// When using the derive macro, this type is a struct with the same fields as the original struct. 36 | /// It will implement [`IntoIterator`] to make it possible to iterate over the available fields, and [`Copy`] and [`Clone`] for convenience. 37 | /// It will also have a `FIELDS: Self` associated constant. 38 | type Fields: 'a; 39 | /// Type which can be used to check whether a serializable field should be skipped. 40 | type Filter: SerializeFilter + 'a; 41 | 42 | /// Returns a value which forwards the [`Serialize`] implementation but only serializes the selected fields. 43 | /// 44 | /// The `select` closure receives an instance of [`Fields`][SerializePartial::Fields] which can than be used to select which fields should be serialized. 45 | /// The closure can return any type which implements [`IntoIterator`]. This could be an array, but could also be a `Vec` or an [`Iterator`] with fields selected at runtime. 46 | /// 47 | /// ## Example 48 | /// 49 | /// ``` 50 | /// use serde::Serialize; 51 | /// use serde_partial::SerializePartial; 52 | /// 53 | /// #[derive(Serialize, SerializePartial)] 54 | /// #[serde(rename_all = "camelCase")] 55 | /// struct User { 56 | /// full_name: &'static str, 57 | /// age: u8, 58 | /// #[serde(rename = "contact")] 59 | /// email: &'static str, 60 | /// } 61 | /// 62 | /// const USER: User = User { 63 | /// full_name: "John Doe", 64 | /// age: 42, 65 | /// email: "john.doe@example.com", 66 | /// }; 67 | /// 68 | /// // serialize only the `full_name` field 69 | /// let filtered = USER.with_fields(|u| [u.full_name]); 70 | /// let json = serde_json::to_value(&filtered).unwrap(); 71 | /// assert_eq!( 72 | /// json, 73 | /// serde_json::json!({ 74 | /// "fullName": USER.full_name, 75 | /// }) 76 | /// ); 77 | /// 78 | /// // the field list doesn't have to be an array 79 | /// // serialize every field with a name longer than 4 characters 80 | /// let filtered = USER.with_fields(|u| u.into_iter().filter(|f| f.name().len() > 4)); 81 | /// let json = serde_json::to_value(&filtered).unwrap(); 82 | /// assert_eq!( 83 | /// json, 84 | /// serde_json::json!({ 85 | /// "fullName": USER.full_name, 86 | /// "contact": USER.email, 87 | /// }) 88 | /// ); 89 | /// 90 | /// // field names respect serde attributes 91 | /// assert_eq!(::Fields::FIELDS.full_name.name(), "fullName"); 92 | /// assert_eq!(::Fields::FIELDS.age.name(), "age"); 93 | /// assert_eq!(::Fields::FIELDS.email.name(), "contact"); 94 | /// ``` 95 | fn with_fields(&'a self, select: F) -> Partial<'a, Self> 96 | where 97 | F: FnOnce(Self::Fields) -> I, 98 | I: IntoIterator>; 99 | 100 | /// Same as [`with_fields`][SerializePartial::with_fields] but fields are opt-out instead of opt-in. 101 | /// 102 | /// ## Example 103 | /// 104 | /// ``` 105 | /// # use serde::Serialize; 106 | /// # use serde_partial::SerializePartial; 107 | /// # 108 | /// # #[derive(Serialize, SerializePartial)] 109 | /// # #[serde(rename_all = "camelCase")] 110 | /// # struct User { 111 | /// # full_name: &'static str, 112 | /// # age: u8, 113 | /// # #[serde(rename = "contact")] 114 | /// # email: &'static str, 115 | /// # } 116 | /// # 117 | /// # const USER: User = User { 118 | /// # full_name: "John Doe", 119 | /// # age: 42, 120 | /// # email: "john.doe@example.com", 121 | /// # }; 122 | /// # 123 | /// let filtered = USER.without_fields(|u| [u.email]); 124 | /// let json = serde_json::to_value(&filtered).unwrap(); 125 | /// assert_eq!( 126 | /// json, 127 | /// serde_json::json!({ 128 | /// "fullName": USER.full_name, 129 | /// "age": USER.age, 130 | /// }) 131 | /// ); 132 | /// ``` 133 | fn without_fields( 134 | &'a self, 135 | select: F, 136 | ) -> Partial<'a, Self, filter::InverseFilter<'a, Self>> 137 | where 138 | F: FnOnce(Self::Fields) -> I, 139 | I: IntoIterator>, 140 | { 141 | let Partial { value, filter } = self.with_fields(select); 142 | Partial { 143 | value, 144 | filter: filter::InverseFilter::new(filter), 145 | } 146 | } 147 | } 148 | 149 | /// A type which implements [`Serialize`] by forwarding the implementation to the value it references while skipping fields according to its filter. 150 | #[derive(Debug)] 151 | pub struct Partial<'a, T, F = >::Filter> 152 | where 153 | T: ?Sized + SerializePartial<'a>, 154 | { 155 | /// The value to serialize. 156 | pub value: &'a T, 157 | /// The field filter to use. 158 | pub filter: F, 159 | } 160 | 161 | /// Newtype around a field name for the specified type. 162 | #[repr(transparent)] 163 | pub struct Field<'a, T: ?Sized> { 164 | name: &'a str, 165 | _ty: PhantomData, 166 | } 167 | 168 | impl<'a, T, F> Clone for Partial<'a, T, F> 169 | where 170 | T: ?Sized + SerializePartial<'a>, 171 | F: Clone, 172 | { 173 | fn clone(&self) -> Self { 174 | Self { 175 | value: self.value, 176 | filter: self.filter.clone(), 177 | } 178 | } 179 | } 180 | impl<'a, T, F> Copy for Partial<'a, T, F> 181 | where 182 | T: ?Sized + SerializePartial<'a>, 183 | F: Copy, 184 | { 185 | } 186 | 187 | impl<'a, T: ?Sized> Field<'a, T> { 188 | /// Creates a new field. 189 | /// 190 | /// The name should be the serde field name and not the Rust field name. 191 | pub const fn new(name: &'a str) -> Self { 192 | Self { 193 | name, 194 | _ty: PhantomData, 195 | } 196 | } 197 | 198 | /// Returns the field name. 199 | pub const fn name(&self) -> &'a str { 200 | self.name 201 | } 202 | } 203 | 204 | impl Clone for Field<'_, T> { 205 | fn clone(&self) -> Self { 206 | Self { 207 | name: self.name, 208 | _ty: PhantomData, 209 | } 210 | } 211 | } 212 | impl Copy for Field<'_, T> {} 213 | 214 | impl fmt::Debug for Field<'_, T> { 215 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 216 | f.debug_struct("Field") 217 | .field("name", &self.name) 218 | .field("container", &core::any::type_name::()) 219 | .finish() 220 | } 221 | } 222 | 223 | impl PartialEq for Field<'_, T> { 224 | fn eq(&self, other: &Self) -> bool { 225 | self.name == other.name 226 | } 227 | } 228 | impl Eq for Field<'_, T> {} 229 | impl hash::Hash for Field<'_, T> { 230 | fn hash(&self, state: &mut H) { 231 | self.name.hash(state); 232 | } 233 | } 234 | impl PartialOrd for Field<'_, T> { 235 | fn partial_cmp(&self, other: &Self) -> Option { 236 | self.name.partial_cmp(other.name) 237 | } 238 | } 239 | impl Ord for Field<'_, T> { 240 | fn cmp(&self, other: &Self) -> cmp::Ordering { 241 | self.name.cmp(other.name) 242 | } 243 | } 244 | 245 | impl Serialize for Partial<'_, T, F> 246 | where 247 | T: ?Sized + for<'a> SerializePartial<'a>, 248 | F: SerializeFilter, 249 | { 250 | fn serialize(&self, serializer: S) -> Result 251 | where 252 | S: Serializer, 253 | { 254 | let serializer = PartialSerializer { 255 | s: serializer, 256 | filter: &self.filter, 257 | _ty: PhantomData, 258 | }; 259 | self.value.serialize(serializer) 260 | } 261 | } 262 | 263 | struct PartialSerializer<'a, S, T, F> 264 | where 265 | S: Serializer, 266 | T: ?Sized, 267 | { 268 | s: S, 269 | filter: &'a F, 270 | _ty: PhantomData, 271 | } 272 | 273 | impl<'a, S, T, F> Serializer for PartialSerializer<'a, S, T, F> 274 | where 275 | S: Serializer, 276 | T: ?Sized + for<'p> SerializePartial<'p>, 277 | F: SerializeFilter, 278 | { 279 | type Ok = S::Ok; 280 | type Error = S::Error; 281 | 282 | type SerializeStruct = serde_struct::PartialSerializeStruct<'a, S, T, F>; 283 | type SerializeMap = serde_map::PartialSerializeMap<'a, S, T, F>; 284 | 285 | fn serialize_struct( 286 | self, 287 | name: &'static str, 288 | len: usize, 289 | ) -> Result { 290 | let PartialSerializer { s, filter, _ty } = self; 291 | let len = filter.filtered_len(Some(len)).unwrap_or(len); 292 | let ss = s.serialize_struct(name, len)?; 293 | Ok(Self::SerializeStruct { ss, filter, _ty }) 294 | } 295 | 296 | fn serialize_map(self, len: Option) -> Result { 297 | let PartialSerializer { s, filter, _ty } = self; 298 | let len = filter.filtered_len(len).or(len); 299 | let sm = s.serialize_map(len)?; 300 | Ok(Self::SerializeMap { sm, filter, _ty }) 301 | } 302 | // collect_map not implemented because we explicitly want serde's default implementation 303 | 304 | type SerializeSeq = S::SerializeSeq; 305 | type SerializeTuple = S::SerializeTuple; 306 | type SerializeTupleStruct = S::SerializeTupleStruct; 307 | type SerializeTupleVariant = S::SerializeTupleVariant; 308 | type SerializeStructVariant = S::SerializeStructVariant; 309 | 310 | fn is_human_readable(&self) -> bool { 311 | self.s.is_human_readable() 312 | } 313 | fn serialize_bool(self, v: bool) -> Result { 314 | self.s.serialize_bool(v) 315 | } 316 | fn serialize_i8(self, v: i8) -> Result { 317 | self.s.serialize_i8(v) 318 | } 319 | fn serialize_i16(self, v: i16) -> Result { 320 | self.s.serialize_i16(v) 321 | } 322 | fn serialize_i32(self, v: i32) -> Result { 323 | self.s.serialize_i32(v) 324 | } 325 | fn serialize_i64(self, v: i64) -> Result { 326 | self.s.serialize_i64(v) 327 | } 328 | fn serialize_i128(self, v: i128) -> Result { 329 | self.s.serialize_i128(v) 330 | } 331 | fn serialize_u8(self, v: u8) -> Result { 332 | self.s.serialize_u8(v) 333 | } 334 | fn serialize_u16(self, v: u16) -> Result { 335 | self.s.serialize_u16(v) 336 | } 337 | fn serialize_u32(self, v: u32) -> Result { 338 | self.s.serialize_u32(v) 339 | } 340 | fn serialize_u64(self, v: u64) -> Result { 341 | self.s.serialize_u64(v) 342 | } 343 | fn serialize_u128(self, v: u128) -> Result { 344 | self.s.serialize_u128(v) 345 | } 346 | fn serialize_f32(self, v: f32) -> Result { 347 | self.s.serialize_f32(v) 348 | } 349 | fn serialize_f64(self, v: f64) -> Result { 350 | self.s.serialize_f64(v) 351 | } 352 | fn serialize_char(self, v: char) -> Result { 353 | self.s.serialize_char(v) 354 | } 355 | fn serialize_str(self, v: &str) -> Result { 356 | self.s.serialize_str(v) 357 | } 358 | fn serialize_bytes(self, v: &[u8]) -> Result { 359 | self.s.serialize_bytes(v) 360 | } 361 | fn serialize_none(self) -> Result { 362 | self.s.serialize_none() 363 | } 364 | fn serialize_some(self, value: &TT) -> Result 365 | where 366 | TT: Serialize, 367 | { 368 | self.s.serialize_some(value) 369 | } 370 | fn serialize_unit(self) -> Result { 371 | self.s.serialize_unit() 372 | } 373 | fn serialize_unit_struct(self, name: &'static str) -> Result { 374 | self.s.serialize_unit_struct(name) 375 | } 376 | fn serialize_unit_variant( 377 | self, 378 | name: &'static str, 379 | index: u32, 380 | variant: &'static str, 381 | ) -> Result { 382 | self.s.serialize_unit_variant(name, index, variant) 383 | } 384 | fn serialize_newtype_struct( 385 | self, 386 | name: &'static str, 387 | value: &TT, 388 | ) -> Result 389 | where 390 | TT: Serialize, 391 | { 392 | self.s.serialize_newtype_struct(name, value) 393 | } 394 | fn serialize_newtype_variant( 395 | self, 396 | name: &'static str, 397 | index: u32, 398 | variant: &'static str, 399 | value: &TT, 400 | ) -> Result 401 | where 402 | TT: Serialize, 403 | { 404 | self.s 405 | .serialize_newtype_variant(name, index, variant, value) 406 | } 407 | fn serialize_seq(self, len: Option) -> Result { 408 | self.s.serialize_seq(len) 409 | } 410 | fn serialize_tuple(self, len: usize) -> Result { 411 | self.s.serialize_tuple(len) 412 | } 413 | fn serialize_tuple_struct( 414 | self, 415 | name: &'static str, 416 | len: usize, 417 | ) -> Result { 418 | self.s.serialize_tuple_struct(name, len) 419 | } 420 | fn serialize_tuple_variant( 421 | self, 422 | name: &'static str, 423 | index: u32, 424 | variant: &'static str, 425 | len: usize, 426 | ) -> Result { 427 | self.s.serialize_tuple_variant(name, index, variant, len) 428 | } 429 | fn serialize_struct_variant( 430 | self, 431 | name: &'static str, 432 | index: u32, 433 | variant: &'static str, 434 | len: usize, 435 | ) -> Result { 436 | self.s.serialize_struct_variant(name, index, variant, len) 437 | } 438 | fn collect_str(self, value: &TT) -> Result 439 | where 440 | TT: fmt::Display, 441 | { 442 | self.s.collect_str(value) 443 | } 444 | fn collect_seq(self, iter: I) -> Result 445 | where 446 | I: IntoIterator, 447 | ::Item: Serialize, 448 | { 449 | self.s.collect_seq(iter) 450 | } 451 | } 452 | -------------------------------------------------------------------------------- /src/map.rs: -------------------------------------------------------------------------------- 1 | use core::marker::PhantomData; 2 | 3 | use serde::ser::{Error, Impossible, Serialize, SerializeMap, Serializer}; 4 | 5 | use crate::{Field, SerializeFilter, SerializePartial}; 6 | 7 | pub(crate) struct PartialSerializeMap<'a, S, T, F> 8 | where 9 | S: Serializer, 10 | T: ?Sized, 11 | { 12 | pub(crate) sm: S::SerializeMap, 13 | pub(crate) filter: &'a F, 14 | pub(crate) _ty: PhantomData, 15 | } 16 | 17 | struct KeySerializer<'a, T, F, E> 18 | where 19 | T: ?Sized, 20 | { 21 | filter: &'a F, 22 | _ty: PhantomData<(&'a T, E)>, 23 | } 24 | 25 | impl<'a, S, T, F> SerializeMap for PartialSerializeMap<'a, S, T, F> 26 | where 27 | S: Serializer, 28 | T: ?Sized + for<'p> SerializePartial<'p>, 29 | F: SerializeFilter, 30 | { 31 | type Ok = ::Ok; 32 | type Error = ::Error; 33 | 34 | fn serialize_key(&mut self, _key: &K) -> Result<(), Self::Error> 35 | where 36 | K: Serialize, 37 | { 38 | Err(Self::Error::custom("cannot perform partial serialization of lone keys, use `serialize_entry` instead if possible")) 39 | } 40 | 41 | fn serialize_value(&mut self, _value: &V) -> Result<(), Self::Error> 42 | where 43 | V: Serialize, 44 | { 45 | Err(Self::Error::custom("cannot perform partial serialization of lone values, use `serialize_entry` instead if possible")) 46 | } 47 | 48 | fn end(self) -> Result { 49 | self.sm.end() 50 | } 51 | 52 | fn serialize_entry( 53 | &mut self, 54 | key: &K, 55 | value: &V, 56 | ) -> Result<(), Self::Error> 57 | where 58 | K: Serialize, 59 | V: Serialize, 60 | { 61 | let skip = key.serialize(KeySerializer::<'_, T, F, Self::Error> { 62 | filter: self.filter, 63 | _ty: PhantomData, 64 | })?; 65 | if skip { 66 | Ok(()) 67 | } else { 68 | self.sm.serialize_entry(key, value) 69 | } 70 | } 71 | } 72 | 73 | static KEY_ERR: &str = "key should serialize to a string"; 74 | 75 | impl<'a, T, F, E> Serializer for KeySerializer<'a, T, F, E> 76 | where 77 | T: ?Sized + for<'p> SerializePartial<'p>, 78 | F: SerializeFilter, 79 | E: Error, 80 | { 81 | type Ok = bool; 82 | type Error = E; 83 | 84 | fn serialize_str(self, v: &str) -> Result { 85 | Ok(self.filter.skip(Field::new(v))) 86 | } 87 | 88 | type SerializeSeq = Impossible; 89 | type SerializeTuple = Impossible; 90 | type SerializeTupleStruct = Impossible; 91 | type SerializeTupleVariant = Impossible; 92 | type SerializeMap = Impossible; 93 | type SerializeStruct = Impossible; 94 | type SerializeStructVariant = Impossible; 95 | 96 | fn serialize_bool(self, _v: bool) -> Result { 97 | Err(Self::Error::custom(KEY_ERR)) 98 | } 99 | fn serialize_i8(self, _v: i8) -> Result { 100 | Err(Self::Error::custom(KEY_ERR)) 101 | } 102 | fn serialize_i16(self, _v: i16) -> Result { 103 | Err(Self::Error::custom(KEY_ERR)) 104 | } 105 | fn serialize_i32(self, _v: i32) -> Result { 106 | Err(Self::Error::custom(KEY_ERR)) 107 | } 108 | fn serialize_i64(self, _v: i64) -> Result { 109 | Err(Self::Error::custom(KEY_ERR)) 110 | } 111 | fn serialize_u8(self, _v: u8) -> Result { 112 | Err(Self::Error::custom(KEY_ERR)) 113 | } 114 | fn serialize_u16(self, _v: u16) -> Result { 115 | Err(Self::Error::custom(KEY_ERR)) 116 | } 117 | fn serialize_u32(self, _v: u32) -> Result { 118 | Err(Self::Error::custom(KEY_ERR)) 119 | } 120 | fn serialize_u64(self, _v: u64) -> Result { 121 | Err(Self::Error::custom(KEY_ERR)) 122 | } 123 | fn serialize_f32(self, _v: f32) -> Result { 124 | Err(Self::Error::custom(KEY_ERR)) 125 | } 126 | fn serialize_f64(self, _v: f64) -> Result { 127 | Err(Self::Error::custom(KEY_ERR)) 128 | } 129 | fn serialize_char(self, _v: char) -> Result { 130 | Err(Self::Error::custom(KEY_ERR)) 131 | } 132 | fn serialize_bytes(self, _v: &[u8]) -> Result { 133 | Err(Self::Error::custom(KEY_ERR)) 134 | } 135 | fn serialize_none(self) -> Result { 136 | Err(Self::Error::custom(KEY_ERR)) 137 | } 138 | fn serialize_some(self, _value: &TT) -> Result 139 | where 140 | TT: Serialize, 141 | { 142 | Err(Self::Error::custom(KEY_ERR)) 143 | } 144 | fn serialize_unit(self) -> Result { 145 | Err(Self::Error::custom(KEY_ERR)) 146 | } 147 | fn serialize_unit_struct(self, _name: &'static str) -> Result { 148 | Err(Self::Error::custom(KEY_ERR)) 149 | } 150 | fn serialize_unit_variant( 151 | self, 152 | _name: &'static str, 153 | _index: u32, 154 | _variant: &'static str, 155 | ) -> Result { 156 | Err(Self::Error::custom(KEY_ERR)) 157 | } 158 | fn serialize_newtype_struct( 159 | self, 160 | _name: &'static str, 161 | _value: &TT, 162 | ) -> Result 163 | where 164 | TT: Serialize, 165 | { 166 | Err(Self::Error::custom(KEY_ERR)) 167 | } 168 | fn serialize_newtype_variant( 169 | self, 170 | _name: &'static str, 171 | _index: u32, 172 | _variant: &'static str, 173 | _value: &TT, 174 | ) -> Result 175 | where 176 | TT: Serialize, 177 | { 178 | Err(Self::Error::custom(KEY_ERR)) 179 | } 180 | fn serialize_seq(self, _len: Option) -> Result { 181 | Err(Self::Error::custom(KEY_ERR)) 182 | } 183 | fn serialize_tuple(self, _len: usize) -> Result { 184 | Err(Self::Error::custom(KEY_ERR)) 185 | } 186 | fn serialize_tuple_struct( 187 | self, 188 | _name: &'static str, 189 | _len: usize, 190 | ) -> Result { 191 | Err(Self::Error::custom(KEY_ERR)) 192 | } 193 | fn serialize_tuple_variant( 194 | self, 195 | _name: &'static str, 196 | _index: u32, 197 | _variant: &'static str, 198 | _len: usize, 199 | ) -> Result { 200 | Err(Self::Error::custom(KEY_ERR)) 201 | } 202 | fn serialize_map(self, _len: Option) -> Result { 203 | Err(Self::Error::custom(KEY_ERR)) 204 | } 205 | fn serialize_struct( 206 | self, 207 | _name: &'static str, 208 | _len: usize, 209 | ) -> Result { 210 | Err(Self::Error::custom(KEY_ERR)) 211 | } 212 | fn serialize_struct_variant( 213 | self, 214 | _name: &'static str, 215 | _index: u32, 216 | _variant: &'static str, 217 | _len: usize, 218 | ) -> Result { 219 | Err(Self::Error::custom(KEY_ERR)) 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /src/std.rs: -------------------------------------------------------------------------------- 1 | use core::{ 2 | hash::{BuildHasher, Hash}, 3 | iter::Map, 4 | }; 5 | use std::collections::{ 6 | hash_map::{HashMap, Keys}, 7 | HashSet, 8 | }; 9 | 10 | use serde::Serialize; 11 | 12 | use crate::{Field, Partial, SerializeFilter, SerializePartial}; 13 | 14 | impl<'a, K, V, S> SerializePartial<'a> for HashMap 15 | where 16 | K: Hash + Eq + AsRef + Serialize + 'a, 17 | V: Serialize + 'a, 18 | S: BuildHasher + Default + 'a, 19 | { 20 | #[allow(clippy::type_complexity)] 21 | type Fields = Map, fn(&'a K) -> Field<'a, Self>>; 22 | type Filter = HashSet, S>; 23 | 24 | fn with_fields(&'a self, select: F) -> Partial<'a, Self> 25 | where 26 | F: FnOnce(Self::Fields) -> I, 27 | I: IntoIterator>, 28 | { 29 | let fields: Self::Fields = self.keys().map(|k| Field::new(k.as_ref())); 30 | let filter = select(fields).into_iter().collect(); 31 | Partial { 32 | value: self, 33 | filter, 34 | } 35 | } 36 | } 37 | 38 | impl<'a, K, V, S> SerializeFilter> for HashSet>, S> 39 | where 40 | S: BuildHasher, 41 | { 42 | fn skip(&self, field: Field<'_, HashMap>) -> bool { 43 | !self.contains(&field) 44 | } 45 | 46 | fn filtered_len(&self, _len: Option) -> Option { 47 | Some(self.len()) 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use crate::{Field, SerializePartial}; 54 | 55 | use std::collections::HashMap; 56 | 57 | #[test] 58 | fn hash_map() { 59 | let map = HashMap::from([("a", "b"), ("c", "d")]); 60 | let filtered = map.with_fields(|_| [Field::new("a")]); 61 | assert_eq!( 62 | serde_json::to_value(&filtered).unwrap(), 63 | serde_json::json!({ "a": "b" }) 64 | ) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/struct.rs: -------------------------------------------------------------------------------- 1 | use core::marker::PhantomData; 2 | 3 | use serde::ser::{Serialize, SerializeStruct, Serializer}; 4 | 5 | use crate::{Field, SerializeFilter, SerializePartial}; 6 | 7 | pub(crate) struct PartialSerializeStruct<'a, S, T, F> 8 | where 9 | S: Serializer, 10 | T: ?Sized, 11 | { 12 | pub(crate) ss: S::SerializeStruct, 13 | pub(crate) filter: &'a F, 14 | pub(crate) _ty: PhantomData, 15 | } 16 | 17 | impl<'a, S, T, F> SerializeStruct for PartialSerializeStruct<'a, S, T, F> 18 | where 19 | S: Serializer, 20 | T: ?Sized + for<'p> SerializePartial<'p>, 21 | F: SerializeFilter, 22 | { 23 | type Ok = ::Ok; 24 | type Error = ::Error; 25 | 26 | fn serialize_field( 27 | &mut self, 28 | key: &'static str, 29 | value: &TT, 30 | ) -> Result<(), Self::Error> 31 | where 32 | TT: Serialize, 33 | { 34 | if self.filter.skip(Field::new(key)) { 35 | self.skip_field(key) 36 | } else { 37 | self.ss.serialize_field(key, value) 38 | } 39 | } 40 | 41 | fn end(self) -> Result { 42 | self.ss.end() 43 | } 44 | 45 | fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { 46 | self.ss.skip_field(key) 47 | } 48 | } 49 | --------------------------------------------------------------------------------