Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Derive Default on structs #152

Merged
merged 4 commits into from
Mar 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ serde_qs = "0.8"
smol_str = "0.1"
surf = { version = "2.1", optional = true }
tokio = { version = "1.2", optional = true }
smart-default = "0.6.0"

# webhook support
hmac = { version = "0.12", optional = true }
Expand Down
50 changes: 44 additions & 6 deletions openapi/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ fn main() -> Result<()> {
meta.schema_to_id_type(schema).unwrap_or_else(|| ("()".into(), CopyOrClone::Copy));
let struct_type = meta.schema_to_rust_type(schema);
out.push_str(&format!("#[cfg(not(feature = \"{}\"))]\n", feature));
out.push_str("#[derive(Clone, Debug, Deserialize, Serialize)]\n");
out.push_str("#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n");
out.push_str(&format!("pub struct {} {{\n", struct_type));
out.push_str(&format!("\tpub id: {},\n", id_type));
out.push_str("}\n\n");
Expand Down Expand Up @@ -380,7 +380,7 @@ fn gen_struct(
out.push_str(&doc_url);
out.push_str(">\n");
}
out.push_str("#[derive(Clone, Debug, Deserialize, Serialize)]\n");
out.push_str("#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n");
out.push_str("pub struct ");
out.push_str(&struct_name);
out.push_str(" {\n");
Expand Down Expand Up @@ -511,7 +511,7 @@ fn gen_generated_schemas(
{
let struct_name = meta.schema_to_rust_type(&schema_name);
out.push('\n');
out.push_str("#[derive(Clone, Debug, Deserialize, Serialize)]\n");
out.push_str("#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n");
out.push_str("pub struct ");
out.push_str(&struct_name);
out.push_str(" {\n");
Expand Down Expand Up @@ -1084,7 +1084,7 @@ fn gen_emitted_structs(
}
};
out.push('\n');
out.push_str("#[derive(Clone, Debug, Deserialize, Serialize)]\n");
out.push_str("#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n");
out.push_str("pub struct ");
out.push_str(&struct_name.to_camel_case());
out.push_str(" {\n");
Expand Down Expand Up @@ -1141,6 +1141,25 @@ fn gen_unions(out: &mut String, state: &mut Generated, meta: &Metadata) {
out.push_str("),\n");
}
out.push_str("}\n");

if let Some(first) = union_
.schema_variants
.iter()
.filter_map(|var| match var.trim() {
"" => None,
n => Some(n),
})
.map(|s| gen_variant_name(&s, meta))
.next()
{
out.push_str("impl std::default::Default for ");
out.push_str(&union_name.to_camel_case());
out.push_str(" {\n");
out.push_str(" fn default() -> Self {\n");
out.push_str(&format!(" Self::{}(Default::default())\n", first));
out.push_str(" }\n");
out.push_str("}\n");
}
}
}

Expand Down Expand Up @@ -1175,7 +1194,7 @@ fn gen_enums(out: &mut String, state: &mut Generated, meta: &Metadata) {
if wire_name.trim().is_empty() {
continue;
}
let variant_name = gen_variant_name(&wire_name.as_str(), meta);
let variant_name = gen_variant_name(&wire_name, meta);
if variant_name.trim().is_empty() {
panic!("unhandled enum variant: {:?}", wire_name)
}
Expand All @@ -1199,7 +1218,7 @@ fn gen_enums(out: &mut String, state: &mut Generated, meta: &Metadata) {
if wire_name.trim().is_empty() {
continue;
}
let variant_name = gen_variant_name(&wire_name.as_str(), meta);
let variant_name = gen_variant_name(&wire_name, meta);
out.push_str(" ");
out.push_str(&enum_name);
out.push_str("::");
Expand Down Expand Up @@ -1227,6 +1246,25 @@ fn gen_enums(out: &mut String, state: &mut Generated, meta: &Metadata) {
out.push_str(" self.as_str().fmt(f)\n");
out.push_str(" }\n");
out.push_str("}\n");

if let Some(first) = enum_
.options
.iter()
.filter_map(|var| match var.trim() {
"" => None,
n => Some(n),
})
.map(|s| gen_variant_name(&s, meta))
.next()
{
out.push_str("impl std::default::Default for ");
out.push_str(&enum_name);
out.push_str(" {\n");
out.push_str(" fn default() -> Self {\n");
out.push_str(&format!(" Self::{}\n", first));
out.push_str(" }\n");
out.push_str("}\n");
}
}
}

Expand Down
21 changes: 17 additions & 4 deletions src/ids.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use smart_default::SmartDefault;

macro_rules! def_id_serde_impls {
($struct_name:ident) => {
impl serde::Serialize for $struct_name {
Expand All @@ -24,7 +26,7 @@ macro_rules! def_id_serde_impls {

macro_rules! def_id {
($struct_name:ident: String) => {
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct $struct_name(smol_str::SmolStr);

impl $struct_name {
Expand Down Expand Up @@ -117,7 +119,7 @@ macro_rules! def_id {
///
/// This type _typically_ will not allocate and
/// therefore is usually cheaply clonable.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct $struct_name(smol_str::SmolStr);

impl $struct_name {
Expand Down Expand Up @@ -268,6 +270,12 @@ macro_rules! def_id {
}
}

impl std::default::Default for $enum_name {
fn default() -> Self {
$enum_name::None
}
}

impl std::str::FromStr for $enum_name {
type Err = ParseIdError;

Expand Down Expand Up @@ -318,10 +326,11 @@ macro_rules! def_id {
}
)*
};
(enum $enum_name:ident { $( $variant_name:ident($($variant_type:tt)*) ),* $(,)* }) => {
(enum $enum_name:ident { $( $(#[$test:meta])? $variant_name:ident($($variant_type:tt)*) ),+ $(,)? }) => {
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(SmartDefault)]
pub enum $enum_name {
$( $variant_name($($variant_type)*), )*
$( $(#[$test])* $variant_name($($variant_type)*), )*
}

impl $enum_name {
Expand Down Expand Up @@ -487,6 +496,7 @@ def_id!(InvoiceLineItemIdWebhook, "il_");

def_id!(
enum InvoiceLineItemId {
#[default]
Item(InvoiceItemId),
Subscription(SubscriptionLineId),
InvoiceLineItemIdWebhook(InvoiceLineItemIdWebhook),
Expand All @@ -505,6 +515,7 @@ def_id!(PaymentLinkId: String);
def_id!(PaymentMethodId, "pm_" | "card_" | "src_" | "ba_");
def_id!(
enum PaymentSourceId {
#[default]
Account(AccountId),
AlipayAccount(AlipayAccountId),
BankAccount(BankAccountId),
Expand All @@ -515,6 +526,7 @@ def_id!(
def_id!(PayoutId, "po_");
def_id!(
enum PayoutDestinationId {
#[default]
BankAccount(BankAccountId),
Card(CardId),
}
Expand Down Expand Up @@ -543,6 +555,7 @@ def_id!(TaxCodeId, "txcd_");
def_id!(TaxRateId, "txr_");
def_id!(
enum TokenId {
#[default]
Card(CardTokenId),
Bank(BankTokenId),
}
Expand Down
11 changes: 10 additions & 1 deletion src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub enum Expandable<T: Object> {
impl<T> Expandable<T>
where
T: Object,
T::Id: Clone,
T::Id: Clone + Default,
{
pub fn id(&self) -> T::Id {
match self {
Expand All @@ -86,6 +86,15 @@ where
}
}

impl<T: Object> Default for Expandable<T>
where
T::Id: Default,
{
fn default() -> Self {
Expandable::Id(Default::default())
}
}

impl<T: Object> Expandable<T> {
pub fn is_object(&self) -> bool {
match self {
Expand Down
1 change: 1 addition & 0 deletions src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ pub use {
invoice_payment_method_options_acss_debit::*,
invoice_payment_method_options_bancontact::*,
invoice_payment_method_options_card::*,
invoice_payment_method_options_konbini::*,
invoiceitem::*,
line_item::*,
plan::*,
Expand Down
12 changes: 12 additions & 0 deletions src/resources/balance_transaction_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ impl std::fmt::Display for BalanceTransactionStatus {
}
}

impl std::default::Default for BalanceTransactionStatus {
fn default() -> Self {
Self::Pending
}
}

/// An enum representing the possible values of an `Fee`'s `type` field.
#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -112,3 +118,9 @@ impl std::fmt::Display for FeeType {
self.as_str().fmt(f)
}
}

impl std::default::Default for FeeType {
fn default() -> Self {
FeeType::ApplicationFee
}
}
12 changes: 12 additions & 0 deletions src/resources/card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ pub enum CardBrand {
Unknown,
}

impl std::default::Default for CardBrand {
fn default() -> Self {
Self::Unknown
}
}

#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub enum CardType {
#[serde(rename = "credit")]
Expand All @@ -41,3 +47,9 @@ pub enum CardType {
#[serde(rename = "unknown")]
Unknown,
}

impl std::default::Default for CardType {
fn default() -> Self {
Self::Unknown
}
}
1 change: 1 addition & 0 deletions src/resources/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ pub mod billing {
pub mod invoice_payment_method_options_acss_debit;
pub mod invoice_payment_method_options_bancontact;
pub mod invoice_payment_method_options_card;
pub mod invoice_payment_method_options_konbini;
pub mod invoiceitem;
pub mod line_item;
pub mod plan;
Expand Down
Loading