1 | //! [`Ord`](trait@std::cmp::Ord) implementation. |
2 | |
3 | use proc_macro2::TokenStream; |
4 | use quote::quote; |
5 | |
6 | use super::common_ord; |
7 | use crate::{Data, DeriveTrait, Item, SimpleType, SplitGenerics, TraitImpl}; |
8 | |
9 | /// Dummy-struct implement [`Trait`](crate::Trait) for |
10 | /// [`Ord`](trait@std::cmp::Ord). |
11 | pub struct Ord; |
12 | |
13 | impl TraitImpl for Ord { |
14 | fn as_str(&self) -> &'static str { |
15 | "Ord" |
16 | } |
17 | |
18 | fn default_derive_trait(&self) -> DeriveTrait { |
19 | DeriveTrait::Ord |
20 | } |
21 | |
22 | fn build_signature( |
23 | &self, |
24 | _any_bound: bool, |
25 | item: &Item, |
26 | generics: &SplitGenerics<'_>, |
27 | traits: &[DeriveTrait], |
28 | trait_: &DeriveTrait, |
29 | body: &TokenStream, |
30 | ) -> TokenStream { |
31 | let body = common_ord::build_ord_signature(item, generics, traits, trait_, body); |
32 | |
33 | quote! { |
34 | #[inline] |
35 | fn cmp(&self, __other: &Self) -> ::core::cmp::Ordering { |
36 | #body |
37 | } |
38 | } |
39 | } |
40 | |
41 | fn build_body( |
42 | &self, |
43 | _any_bound: bool, |
44 | _traits: &[DeriveTrait], |
45 | trait_: &DeriveTrait, |
46 | data: &Data, |
47 | ) -> TokenStream { |
48 | if data.is_empty(**trait_) { |
49 | TokenStream::new() |
50 | } else { |
51 | match data.simple_type() { |
52 | SimpleType::Struct(fields) | SimpleType::Tuple(fields) => { |
53 | let self_pattern = &fields.self_pattern; |
54 | let other_pattern = &fields.other_pattern; |
55 | let body = common_ord::build_ord_body(trait_, data); |
56 | |
57 | quote! { |
58 | (#self_pattern, #other_pattern) => #body, |
59 | } |
60 | } |
61 | SimpleType::Unit(_) => TokenStream::new(), |
62 | SimpleType::Union(_) => unreachable!("unexpected trait for union" ), |
63 | } |
64 | } |
65 | } |
66 | } |
67 | |