X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning%2Foffers%2Foffer.rs;fp=lightning-c-bindings%2Fsrc%2Flightning%2Foffers%2Foffer.rs;h=0ae9fd6438d91aadcbeec94b145cdd005b07de47;hb=4870c930fc07067830277754bb6e42d7abd6e77f;hp=bc2bcb4f953bff435e47baf878f931426440990a;hpb=792f94eff769b4ae55bb78a5e0c6cc099f28ef6c;p=ldk-c-bindings diff --git a/lightning-c-bindings/src/lightning/offers/offer.rs b/lightning-c-bindings/src/lightning/offers/offer.rs index bc2bcb4..0ae9fd6 100644 --- a/lightning-c-bindings/src/lightning/offers/offer.rs +++ b/lightning-c-bindings/src/lightning/offers/offer.rs @@ -42,7 +42,8 @@ //! let pubkey = PublicKey::from(keys); //! //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60); -//! let offer = OfferBuilder::new(\"coffee, large\".to_string(), pubkey) +//! let offer = OfferBuilder::new(pubkey) +//! .description(\"coffee, large\".to_string()) //! .amount_msats(20_000) //! .supported_quantity(Quantity::Unbounded) //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap()) @@ -85,6 +86,121 @@ use crate::c_types::*; use alloc::{vec::Vec, boxed::Box}; +use lightning::offers::offer::OfferId as nativeOfferIdImport; +pub(crate) type nativeOfferId = nativeOfferIdImport; + +/// An identifier for an [`Offer`] built using [`DerivedMetadata`]. +#[must_use] +#[repr(C)] +pub struct OfferId { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeOfferId, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for OfferId { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeOfferId>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the OfferId, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn OfferId_free(this_obj: OfferId) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn OfferId_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOfferId) }; +} +#[allow(unused)] +impl OfferId { + pub(crate) fn get_native_ref(&self) -> &'static nativeOfferId { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOfferId { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeOfferId { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +#[no_mangle] +pub extern "C" fn OfferId_get_a(this_ptr: &OfferId) -> *const [u8; 32] { + let mut inner_val = &mut this_ptr.get_native_mut_ref().0; + inner_val +} +#[no_mangle] +pub extern "C" fn OfferId_set_a(this_ptr: &mut OfferId, mut val: crate::c_types::ThirtyTwoBytes) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.data; +} +/// Constructs a new OfferId given each field +#[must_use] +#[no_mangle] +pub extern "C" fn OfferId_new(mut a_arg: crate::c_types::ThirtyTwoBytes) -> OfferId { + OfferId { inner: ObjOps::heap_alloc(lightning::offers::offer::OfferId ( + a_arg.data, + )), is_owned: true } +} +impl Clone for OfferId { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeOfferId>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn OfferId_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeOfferId)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the OfferId +pub extern "C" fn OfferId_clone(orig: &OfferId) -> OfferId { + orig.clone() +} +/// Get a string which allows debug introspection of a OfferId object +pub extern "C" fn OfferId_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::OfferId }).into()} +/// Checks if two OfferIds contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn OfferId_eq(a: &OfferId, b: &OfferId) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} +#[no_mangle] +/// Serialize the OfferId object into a byte array which can be read by OfferId_read +pub extern "C" fn OfferId_write(obj: &crate::lightning::offers::offer::OfferId) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn OfferId_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOfferId) }) +} +#[no_mangle] +/// Read a OfferId from a byte array, created by OfferId_write +pub extern "C" fn OfferId_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OfferIdDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::offer::OfferId { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} + use lightning::offers::offer::Offer as nativeOfferImport; pub(crate) type nativeOffer = nativeOfferImport; @@ -191,23 +307,24 @@ pub extern "C" fn Offer_metadata(this_arg: &crate::lightning::offers::offer::Off } /// The minimum amount required for a successful payment of a single item. -/// -/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] -pub extern "C" fn Offer_amount(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Amount { +pub extern "C" fn Offer_amount(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_AmountZ { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount(); - let mut local_ret = crate::lightning::offers::offer::Amount { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning::offers::offer::Amount<>) as *mut _ }, is_owned: false }; + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_AmountZ::None } else { crate::c_types::derived::COption_AmountZ::Some( { crate::lightning::offers::offer::Amount::native_into(ret.unwrap()) }) }; local_ret } /// A complete description of the purpose of the payment. Intended to be displayed to the user /// but with the caveat that it has not been verified in any way. +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn Offer_description(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description(); - crate::lightning::util::string::PrintableString { inner: ObjOps::heap_alloc(ret), is_owned: true } + let mut local_ret = crate::lightning::util::string::PrintableString { inner: if ret.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true }; + local_ret } /// Features pertaining to the offer. @@ -256,15 +373,26 @@ pub extern "C" fn Offer_paths(this_arg: &crate::lightning::offers::offer::Offer) #[no_mangle] pub extern "C" fn Offer_supported_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Quantity { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supported_quantity(); - crate::lightning::offers::offer::Quantity { inner: ObjOps::heap_alloc(ret), is_owned: true } + crate::lightning::offers::offer::Quantity::native_into(ret) } /// The public key used by the recipient to sign invoices. +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn Offer_signing_pubkey(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::PublicKey { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signing_pubkey(); - crate::c_types::PublicKey::from_rust(&ret) + let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } }; + local_ret +} + +/// Returns the id of the offer. +#[must_use] +#[no_mangle] +pub extern "C" fn Offer_id(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::OfferId { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.id(); + crate::lightning::offers::offer::OfferId { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns whether the given chain is supported by the offer. @@ -309,6 +437,75 @@ pub extern "C" fn Offer_expects_quantity(this_arg: &crate::lightning::offers::of ret } +/// Similar to [`Offer::request_invoice`] except it: +/// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each +/// request, +/// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called +/// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was +/// requested using a base [`ExpandedKey`] from which the payer id was derived, and +/// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can +/// be used when sending the payment for the requested invoice. +/// +/// Useful to protect the sender's privacy. +/// +/// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id +/// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata +/// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify +/// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey +#[must_use] +#[no_mangle] +pub extern "C" fn Offer_request_invoice_deriving_payer_id(this_arg: &crate::lightning::offers::offer::Offer, expanded_key: &crate::lightning::ln::inbound_payment::ExpandedKey, mut entropy_source: crate::lightning::sign::EntropySource, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_InvoiceRequestWithDerivedPayerIdBuilderBolt12SemanticErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice_deriving_payer_id(expanded_key.get_native_ref(), entropy_source, secp256k1::global::SECP256K1, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithDerivedPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() }; + local_ret +} + +/// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the +/// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request. +/// +/// Useful for recurring payments using the same `payer_id` with different invoices. +/// +/// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id +#[must_use] +#[no_mangle] +pub extern "C" fn Offer_request_invoice_deriving_metadata(this_arg: &crate::lightning::offers::offer::Offer, mut payer_id: crate::c_types::PublicKey, expanded_key: &crate::lightning::ln::inbound_payment::ExpandedKey, mut entropy_source: crate::lightning::sign::EntropySource, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_InvoiceRequestWithExplicitPayerIdBuilderBolt12SemanticErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice_deriving_metadata(payer_id.into_rust(), expanded_key.get_native_ref(), entropy_source, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithExplicitPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() }; + local_ret +} + +/// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`, +/// which will be reflected in the `Bolt12Invoice` response. +/// +/// The `metadata` is useful for including information about the derivation of `payer_id` such +/// that invoice response handling can be stateless. Also serves as payer-provided entropy while +/// hashing in the signature calculation. +/// +/// This should not leak any information such as by using a simple BIP-32 derivation path. +/// Otherwise, payments may be correlated. +/// +/// Errors if the offer contains unknown required features. +/// +/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest +#[must_use] +#[no_mangle] +pub extern "C" fn Offer_request_invoice(this_arg: &crate::lightning::offers::offer::Offer, mut metadata: crate::c_types::derived::CVec_u8Z, mut payer_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_InvoiceRequestWithExplicitPayerIdBuilderBolt12SemanticErrorZ { + let mut local_metadata = Vec::new(); for mut item in metadata.into_rust().drain(..) { local_metadata.push( { item }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice(local_metadata, payer_id.into_rust()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithExplicitPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() }; + local_ret +} + +/// Generates a non-cryptographic 64-bit hash of the Offer. +#[no_mangle] +pub extern "C" fn Offer_hash(o: &Offer) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} #[no_mangle] /// Serialize the Offer object into a byte array which can be read by Offer_read pub extern "C" fn Offer_write(obj: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_u8Z { @@ -318,150 +515,241 @@ pub extern "C" fn Offer_write(obj: &crate::lightning::offers::offer::Offer) -> c pub(crate) extern "C" fn Offer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOffer) }) } - -use lightning::offers::offer::Amount as nativeAmountImport; -pub(crate) type nativeAmount = nativeAmountImport; - /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or /// another currency. +#[derive(Clone)] #[must_use] #[repr(C)] -pub struct Amount { - /// A pointer to the opaque Rust object. - - /// Nearly everywhere, inner must be non-null, however in places where - /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeAmount, - /// Indicates that this is the only struct which contains the same pointer. - - /// Rust functions which take ownership of an object provided via an argument require - /// this to be true and invalidate the object pointed to by inner. - pub is_owned: bool, -} +pub enum Amount { + /// An amount of bitcoin. + Bitcoin { + /// The amount in millisatoshi. + amount_msats: u64, + }, + /// An amount of currency specified using ISO 4712. + Currency { + /// The currency that the amount is denominated in. + iso4217_code: crate::c_types::ThreeBytes, + /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents). + amount: u64, + }, +} +use lightning::offers::offer::Amount as AmountImport; +pub(crate) type nativeAmount = AmountImport; -impl Drop for Amount { - fn drop(&mut self) { - if self.is_owned && !<*mut nativeAmount>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; - } - } -} -/// Frees any resources used by the Amount, if is_owned is set and inner is non-NULL. -#[no_mangle] -pub extern "C" fn Amount_free(this_obj: Amount) { } -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn Amount_free_void(this_ptr: *mut c_void) { - let _ = unsafe { Box::from_raw(this_ptr as *mut nativeAmount) }; -} -#[allow(unused)] impl Amount { - pub(crate) fn get_native_ref(&self) -> &'static nativeAmount { - unsafe { &*ObjOps::untweak_ptr(self.inner) } + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeAmount { + match self { + Amount::Bitcoin {ref amount_msats, } => { + let mut amount_msats_nonref = Clone::clone(amount_msats); + nativeAmount::Bitcoin { + amount_msats: amount_msats_nonref, + } + }, + Amount::Currency {ref iso4217_code, ref amount, } => { + let mut iso4217_code_nonref = Clone::clone(iso4217_code); + let mut amount_nonref = Clone::clone(amount); + nativeAmount::Currency { + iso4217_code: iso4217_code_nonref.data, + amount: amount_nonref, + } + }, + } } - pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeAmount { - unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeAmount { + match self { + Amount::Bitcoin {mut amount_msats, } => { + nativeAmount::Bitcoin { + amount_msats: amount_msats, + } + }, + Amount::Currency {mut iso4217_code, mut amount, } => { + nativeAmount::Currency { + iso4217_code: iso4217_code.data, + amount: amount, + } + }, + } } - /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy - pub(crate) fn take_inner(mut self) -> *mut nativeAmount { - assert!(self.is_owned); - let ret = ObjOps::untweak_ptr(self.inner); - self.inner = core::ptr::null_mut(); - ret + #[allow(unused)] + pub(crate) fn from_native(native: &AmountImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeAmount) }; + match native { + nativeAmount::Bitcoin {ref amount_msats, } => { + let mut amount_msats_nonref = Clone::clone(amount_msats); + Amount::Bitcoin { + amount_msats: amount_msats_nonref, + } + }, + nativeAmount::Currency {ref iso4217_code, ref amount, } => { + let mut iso4217_code_nonref = Clone::clone(iso4217_code); + let mut amount_nonref = Clone::clone(amount); + Amount::Currency { + iso4217_code: crate::c_types::ThreeBytes { data: iso4217_code_nonref }, + amount: amount_nonref, + } + }, + } } -} -impl Clone for Amount { - fn clone(&self) -> Self { - Self { - inner: if <*mut nativeAmount>::is_null(self.inner) { core::ptr::null_mut() } else { - ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, - is_owned: true, + #[allow(unused)] + pub(crate) fn native_into(native: nativeAmount) -> Self { + match native { + nativeAmount::Bitcoin {mut amount_msats, } => { + Amount::Bitcoin { + amount_msats: amount_msats, + } + }, + nativeAmount::Currency {mut iso4217_code, mut amount, } => { + Amount::Currency { + iso4217_code: crate::c_types::ThreeBytes { data: iso4217_code }, + amount: amount, + } + }, } } } +/// Frees any resources used by the Amount +#[no_mangle] +pub extern "C" fn Amount_free(this_ptr: Amount) { } +/// Creates a copy of the Amount +#[no_mangle] +pub extern "C" fn Amount_clone(orig: &Amount) -> Amount { + orig.clone() +} #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method pub(crate) extern "C" fn Amount_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeAmount)).clone() })) as *mut c_void + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Amount)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn Amount_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut Amount) }; } #[no_mangle] -/// Creates a copy of the Amount -pub extern "C" fn Amount_clone(orig: &Amount) -> Amount { - orig.clone() +/// Utility method to constructs a new Bitcoin-variant Amount +pub extern "C" fn Amount_bitcoin(amount_msats: u64) -> Amount { + Amount::Bitcoin { + amount_msats, + } +} +#[no_mangle] +/// Utility method to constructs a new Currency-variant Amount +pub extern "C" fn Amount_currency(iso4217_code: crate::c_types::ThreeBytes, amount: u64) -> Amount { + Amount::Currency { + iso4217_code, + amount, + } } /// Get a string which allows debug introspection of a Amount object pub extern "C" fn Amount_debug_str_void(o: *const c_void) -> Str { alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Amount }).into()} - -use lightning::offers::offer::Quantity as nativeQuantityImport; -pub(crate) type nativeQuantity = nativeQuantityImport; - /// Quantity of items supported by an [`Offer`]. +#[derive(Clone)] #[must_use] #[repr(C)] -pub struct Quantity { - /// A pointer to the opaque Rust object. - - /// Nearly everywhere, inner must be non-null, however in places where - /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeQuantity, - /// Indicates that this is the only struct which contains the same pointer. +pub enum Quantity { + /// Up to a specific number of items (inclusive). Use when more than one item can be requested + /// but is limited (e.g., because of per customer or inventory limits). + /// + /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item + /// is supported. + Bounded( + u64), + /// One or more items. Use when more than one item can be requested without any limit. + Unbounded, + /// Only one item. Use when only a single item can be requested. + One, +} +use lightning::offers::offer::Quantity as QuantityImport; +pub(crate) type nativeQuantity = QuantityImport; - /// Rust functions which take ownership of an object provided via an argument require - /// this to be true and invalidate the object pointed to by inner. - pub is_owned: bool, -} - -impl Drop for Quantity { - fn drop(&mut self) { - if self.is_owned && !<*mut nativeQuantity>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; - } - } -} -/// Frees any resources used by the Quantity, if is_owned is set and inner is non-NULL. -#[no_mangle] -pub extern "C" fn Quantity_free(this_obj: Quantity) { } -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn Quantity_free_void(this_ptr: *mut c_void) { - let _ = unsafe { Box::from_raw(this_ptr as *mut nativeQuantity) }; -} -#[allow(unused)] impl Quantity { - pub(crate) fn get_native_ref(&self) -> &'static nativeQuantity { - unsafe { &*ObjOps::untweak_ptr(self.inner) } + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeQuantity { + match self { + Quantity::Bounded (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeQuantity::Bounded ( + core::num::NonZeroU64::new(a_nonref).expect("Value must be non-zero"), + ) + }, + Quantity::Unbounded => nativeQuantity::Unbounded, + Quantity::One => nativeQuantity::One, + } } - pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeQuantity { - unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeQuantity { + match self { + Quantity::Bounded (mut a, ) => { + nativeQuantity::Bounded ( + core::num::NonZeroU64::new(a).expect("Value must be non-zero"), + ) + }, + Quantity::Unbounded => nativeQuantity::Unbounded, + Quantity::One => nativeQuantity::One, + } } - /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy - pub(crate) fn take_inner(mut self) -> *mut nativeQuantity { - assert!(self.is_owned); - let ret = ObjOps::untweak_ptr(self.inner); - self.inner = core::ptr::null_mut(); - ret + #[allow(unused)] + pub(crate) fn from_native(native: &QuantityImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeQuantity) }; + match native { + nativeQuantity::Bounded (ref a, ) => { + let mut a_nonref = Clone::clone(a); + Quantity::Bounded ( + a_nonref.into(), + ) + }, + nativeQuantity::Unbounded => Quantity::Unbounded, + nativeQuantity::One => Quantity::One, + } } -} -impl Clone for Quantity { - fn clone(&self) -> Self { - Self { - inner: if <*mut nativeQuantity>::is_null(self.inner) { core::ptr::null_mut() } else { - ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, - is_owned: true, + #[allow(unused)] + pub(crate) fn native_into(native: nativeQuantity) -> Self { + match native { + nativeQuantity::Bounded (mut a, ) => { + Quantity::Bounded ( + a.into(), + ) + }, + nativeQuantity::Unbounded => Quantity::Unbounded, + nativeQuantity::One => Quantity::One, } } } +/// Frees any resources used by the Quantity +#[no_mangle] +pub extern "C" fn Quantity_free(this_ptr: Quantity) { } +/// Creates a copy of the Quantity +#[no_mangle] +pub extern "C" fn Quantity_clone(orig: &Quantity) -> Quantity { + orig.clone() +} #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method pub(crate) extern "C" fn Quantity_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeQuantity)).clone() })) as *mut c_void + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Quantity)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn Quantity_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut Quantity) }; } #[no_mangle] -/// Creates a copy of the Quantity -pub extern "C" fn Quantity_clone(orig: &Quantity) -> Quantity { - orig.clone() +/// Utility method to constructs a new Bounded-variant Quantity +pub extern "C" fn Quantity_bounded(a: u64) -> Quantity { + Quantity::Bounded(a, ) } +#[no_mangle] +/// Utility method to constructs a new Unbounded-variant Quantity +pub extern "C" fn Quantity_unbounded() -> Quantity { + Quantity::Unbounded} +#[no_mangle] +/// Utility method to constructs a new One-variant Quantity +pub extern "C" fn Quantity_one() -> Quantity { + Quantity::One} /// Get a string which allows debug introspection of a Quantity object pub extern "C" fn Quantity_debug_str_void(o: *const c_void) -> Str { alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Quantity }).into()}