Merge pull request #795 from TheBlueMatt/2021-02-features-bindings

Map Features objects in bindings
This commit is contained in:
Matt Corallo 2021-02-18 09:54:59 -08:00 committed by GitHub
commit de58bcf271
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 10565 additions and 6776 deletions

View file

@ -8,5 +8,8 @@ edition = "2018"
syn = { version = "1", features = ["full", "extra-traits"] }
proc-macro2 = "1"
[profile.release]
debug = true
# We're not in the workspace as we're just a binary code generator:
[workspace]

View file

@ -10,11 +10,10 @@
//! It also generates relevant memory-management functions and free-standing functions with
//! parameters mapped.
use std::collections::{HashMap, HashSet};
use std::collections::{HashMap, hash_map, HashSet};
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use std::process;
use proc_macro2::{TokenTree, TokenStream, Span};
@ -518,7 +517,6 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
write_cpp_wrapper(cpp_headers, &trait_name, true);
types.trait_declared(&t.ident, t);
}
/// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
@ -555,53 +553,18 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
writeln!(w, "\t\tret").unwrap();
writeln!(w, "\t}}\n}}").unwrap();
if attrs_derives_clone(attrs) {
writeln!(w, "impl Clone for {} {{", struct_name).unwrap();
writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
writeln!(w, "\t\tSelf {{").unwrap();
writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap();
writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
writeln!(w, "\t\t\tis_owned: true,").unwrap();
writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
writeln!(w, "#[allow(unused)]").unwrap();
writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", struct_name).unwrap();
writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", struct_name).unwrap();
writeln!(w, "}}").unwrap();
writeln!(w, "#[no_mangle]").unwrap();
writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", struct_name, struct_name, struct_name).unwrap();
writeln!(w, "\torig.clone()").unwrap();
writeln!(w, "}}").unwrap();
}
write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
}
fn declare_struct<'a, 'b>(s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>) -> bool {
let export = export_status(&s.attrs);
match export {
ExportStatus::Export => {},
ExportStatus::TestOnly => return false,
ExportStatus::NoExport => {
types.struct_ignored(&s.ident);
return false;
}
}
types.struct_imported(&s.ident, format!("{}", s.ident));
true
}
/// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
/// the struct itself, and then writing getters and setters for public, understood-type fields and
/// a constructor if every field is public.
fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
if !declare_struct(s, types) { return; }
if export_status(&s.attrs) != ExportStatus::Export { return; }
let struct_name = &format!("{}", s.ident);
writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
eprintln!("exporting fields for {}", struct_name);
if let syn::Fields::Named(fields) = &s.fields {
let mut gen_types = GenericTypes::new();
assert!(gen_types.learn_generics(&s.generics, types));
@ -934,20 +897,32 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
}
) );
write!(w, "\n").unwrap();
} else if let Some(trait_ident) = trait_path.1.get_ident() {
//XXX: implement for other things like ToString
match &format!("{}", trait_ident) as &str {
"From" => {},
"Default" => {
write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
write!(w, "}}\n").unwrap();
},
"PartialEq" => {},
// If we have no generics, try a manual implementation:
_ => maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types),
}
} else if path_matches_nongeneric(&trait_path.1, &["From"]) {
} else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
write!(w, "}}\n").unwrap();
} else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
} else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
types.c_type_has_inner_from_path(&resolved_path) {
writeln!(w, "impl Clone for {} {{", ident).unwrap();
writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
writeln!(w, "\t\tSelf {{").unwrap();
writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap();
writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
writeln!(w, "\t\t\tis_owned: true,").unwrap();
writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
writeln!(w, "#[allow(unused)]").unwrap();
writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
writeln!(w, "}}").unwrap();
writeln!(w, "#[no_mangle]").unwrap();
writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
writeln!(w, "\torig.clone()").unwrap();
writeln!(w, "}}").unwrap();
} else {
//XXX: implement for other things like ToString
// If we have no generics, try a manual implementation:
maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
}
@ -1001,44 +976,67 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
}
}
}
} else {
eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident);
}
}
}
}
/// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
/// type), otherwise it is mapped into a transparent, C-compatible version of itself.
fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
for var in e.variants.iter() {
if let syn::Fields::Unit = var.fields {
} else if let syn::Fields::Named(fields) = &var.fields {
for field in fields.named.iter() {
match export_status(&field.attrs) {
ExportStatus::Export|ExportStatus::TestOnly => {},
ExportStatus::NoExport => return true,
} else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
'alias_impls: for (alias, arguments) in aliases {
let alias_resolved = types.resolve_path(&alias, None);
for (idx, gen) in i.generics.params.iter().enumerate() {
match gen {
syn::GenericParam::Type(type_param) => {
'bounds_check: for bound in type_param.bounds.iter() {
if let syn::TypeParamBound::Trait(trait_bound) = bound {
if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
assert!(idx < t.args.len());
if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
let generic_arg = types.resolve_path(&p.path, None);
let generic_bound = types.resolve_path(&trait_bound.path, None);
if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
for trait_impld in traits_impld {
if *trait_impld == generic_bound { continue 'bounds_check; }
}
eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
continue 'alias_impls;
} else {
eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
continue 'alias_impls;
}
} else { unimplemented!(); }
} else { unimplemented!(); }
} else { unimplemented!(); }
}
},
syn::GenericParam::Lifetime(_) => {},
syn::GenericParam::Const(_) => unimplemented!(),
}
}
let aliased_impl = syn::ItemImpl {
attrs: i.attrs.clone(),
brace_token: syn::token::Brace(Span::call_site()),
defaultness: None,
generics: syn::Generics {
lt_token: None,
params: syn::punctuated::Punctuated::new(),
gt_token: None,
where_clause: None,
},
impl_token: syn::Token![impl](Span::call_site()),
items: i.items.clone(),
self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
trait_: i.trait_.clone(),
unsafety: None,
};
writeln_impl(w, &aliased_impl, types);
}
} else {
eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
}
} else {
eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
}
} else {
return true;
}
}
false
}
fn declare_enum<'a, 'b>(e: &'a syn::ItemEnum, types: &mut TypeResolver<'b, 'a>) {
match export_status(&e.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => return,
}
if is_enum_opaque(e) {
types.enum_ignored(&e.ident);
} else {
types.mirrored_enum_declared(&e.ident);
}
}
/// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
/// is unitary), we generate an equivalent enum with all types replaced with their C mapped
@ -1195,370 +1193,332 @@ fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &
// ********************************
// *** File/Crate Walking Logic ***
// ********************************
/// Simple utility to walk the modules in a crate - iterating over the modules (with file paths) in
/// a single File.
struct FileIter<'a, I: Iterator<Item = &'a syn::Item>> {
in_dir: &'a str,
path: &'a str,
module: &'a str,
item_iter: I,
/// A public module
struct ASTModule {
pub attrs: Vec<syn::Attribute>,
pub items: Vec<syn::Item>,
pub submods: Vec<String>,
}
impl<'a, I: Iterator<Item = &'a syn::Item>> Iterator for FileIter<'a, I> {
type Item = (String, String, &'a syn::ItemMod);
fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
loop {
match self.item_iter.next() {
Some(syn::Item::Mod(m)) => {
if let syn::Visibility::Public(_) = m.vis {
match export_status(&m.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let f_path = format!("{}/{}.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident);
let new_mod = if self.module.is_empty() { format!("{}", m.ident) } else { format!("{}::{}", self.module, m.ident) };
if let Ok(_) = File::open(&format!("{}/{}", self.in_dir, f_path)) {
return Some((f_path, new_mod, m));
/// A struct containing the syn::File AST for each file in the crate.
struct FullLibraryAST {
modules: HashMap<String, ASTModule, NonRandomHash>,
}
impl FullLibraryAST {
fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
let mut non_mod_items = Vec::with_capacity(items.len());
let mut submods = Vec::with_capacity(items.len());
for item in items.drain(..) {
match item {
syn::Item::Mod(m) if m.content.is_some() => {
if export_status(&m.attrs) == ExportStatus::Export {
if let syn::Visibility::Public(_) = m.vis {
let modident = format!("{}", m.ident);
let modname = if module != "" {
module.clone() + "::" + &modident
} else {
modident.clone()
};
self.load_module(modname, m.attrs, m.content.unwrap().1);
submods.push(modident);
} else {
return Some((
format!("{}/{}/mod.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident),
new_mod, m));
non_mod_items.push(syn::Item::Mod(m));
}
}
},
Some(_) => {},
None => return None,
syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
_ => { non_mod_items.push(item); }
}
}
self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
}
}
fn file_iter<'a>(file: &'a syn::File, in_dir: &'a str, path: &'a str, module: &'a str) ->
impl Iterator<Item = (String, String, &'a syn::ItemMod)> + 'a {
FileIter { in_dir, path, module, item_iter: file.items.iter() }
}
/// A struct containing the syn::File AST for each file in the crate.
struct FullLibraryAST {
files: HashMap<String, syn::File>,
pub fn load_lib(lib: syn::File) -> Self {
assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
let mut res = Self { modules: HashMap::default() };
res.load_module("".to_owned(), lib.attrs, lib.items);
res
}
}
/// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
/// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
/// at `module` from C.
fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, in_dir: &str, out_dir: &str, path: &str, orig_crate: &str, module: &str, header_file: &mut File, cpp_header_file: &mut File) {
let syntax = if let Some(ast) = libast.files.get(module) { ast } else { return };
fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
for (module, astmod) in libast.modules.iter() {
let ASTModule { ref attrs, ref items, ref submods } = astmod;
assert_eq!(export_status(&attrs), ExportStatus::Export);
assert!(syntax.shebang.is_none()); // Not sure what this is, hope we dont have one
let new_file_path = if submods.is_empty() {
format!("{}/{}.rs", out_dir, module.replace("::", "/"))
} else if module != "" {
format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
} else {
format!("{}/lib.rs", out_dir)
};
let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
.open(new_file_path).expect("Unable to open new src file");
let new_file_path = format!("{}/{}", out_dir, path);
let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
.open(new_file_path).expect("Unable to open new src file");
writeln_docs(&mut out, &attrs, "");
assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
writeln_docs(&mut out, &syntax.attrs, "");
if path.ends_with("/lib.rs") {
// Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
// and bitcoin hand-written modules.
writeln!(out, "#![allow(unknown_lints)]").unwrap();
writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
writeln!(out, "#![allow(non_snake_case)]").unwrap();
writeln!(out, "#![allow(unused_imports)]").unwrap();
writeln!(out, "#![allow(unused_variables)]").unwrap();
writeln!(out, "#![allow(unused_mut)]").unwrap();
writeln!(out, "#![allow(unused_parens)]").unwrap();
writeln!(out, "#![allow(unused_unsafe)]").unwrap();
writeln!(out, "#![allow(unused_braces)]").unwrap();
writeln!(out, "mod c_types;").unwrap();
writeln!(out, "mod bitcoin;").unwrap();
} else {
writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
}
for (path, new_mod, m) in file_iter(&syntax, in_dir, path, &module) {
writeln_docs(&mut out, &m.attrs, "");
writeln!(out, "pub mod {};", m.ident).unwrap();
convert_file(libast, crate_types, in_dir, out_dir, &path,
orig_crate, &new_mod, header_file, cpp_header_file);
}
eprintln!("Converting {} entries...", path);
let mut type_resolver = TypeResolver::new(orig_crate, module, crate_types);
// First pass over the items and fill in imports and file-declared objects in the type resolver
for item in syntax.items.iter() {
match item {
syn::Item::Use(u) => type_resolver.process_use(&mut out, &u),
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
declare_struct(&s, &mut type_resolver);
}
},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
declare_enum(&e, &mut type_resolver);
}
},
_ => {},
if module == "" {
// Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
// and bitcoin hand-written modules.
writeln!(out, "#![allow(unknown_lints)]").unwrap();
writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
writeln!(out, "#![allow(non_snake_case)]").unwrap();
writeln!(out, "#![allow(unused_imports)]").unwrap();
writeln!(out, "#![allow(unused_variables)]").unwrap();
writeln!(out, "#![allow(unused_mut)]").unwrap();
writeln!(out, "#![allow(unused_parens)]").unwrap();
writeln!(out, "#![allow(unused_unsafe)]").unwrap();
writeln!(out, "#![allow(unused_braces)]").unwrap();
writeln!(out, "mod c_types;").unwrap();
writeln!(out, "mod bitcoin;").unwrap();
} else {
writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
}
}
for item in syntax.items.iter() {
for m in submods {
writeln!(out, "pub mod {};", m).unwrap();
}
eprintln!("Converting {} entries...", module);
let import_resolver = ImportResolver::new(module, items);
let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
for item in items.iter() {
match item {
syn::Item::Use(_) => {}, // Handled above
syn::Item::Static(_) => {},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Impl(i) => {
writeln_impl(&mut out, &i, &mut type_resolver);
},
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Trait(t) => {
if let syn::Visibility::Public(_) = t.vis {
writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
syn::Item::Const(c) => {
// Re-export any primitive-type constants.
if let syn::Visibility::Public(_) = c.vis {
if let syn::Type::Path(p) = &*c.ty {
let resolved_path = type_resolver.resolve_path(&p.path, None);
if type_resolver.is_primitive(&resolved_path) {
writeln!(out, "\n#[no_mangle]").unwrap();
writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
}
}
}
},
syn::Item::Type(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let mut process_alias = true;
for tok in t.generics.params.iter() {
if let syn::GenericParam::Lifetime(_) = tok {}
else { process_alias = false; }
}
if process_alias {
match &*t.ty {
syn::Type::Path(_) =>
writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
_ => {}
}
}
}
},
syn::Item::Fn(f) => {
if let syn::Visibility::Public(_) = f.vis {
writeln_fn(&mut out, &f, &mut type_resolver);
}
},
syn::Item::Macro(m) => {
if m.ident.is_none() { // If its not a macro definition
convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
}
},
syn::Item::Verbatim(_) => {},
syn::Item::ExternCrate(_) => {},
_ => unimplemented!(),
}
}
out.flush().unwrap();
}
}
fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
for item in items.content.as_ref().unwrap().1.iter() {
match item {
syn::Item::Use(_) => {}, // Handled above
syn::Item::Static(_) => {},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
syn::Item::Impl(i) => {
writeln_impl(&mut out, &i, &mut type_resolver);
},
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Trait(t) => {
if let syn::Visibility::Public(_) = t.vis {
writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
}
},
syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
syn::Item::Const(c) => {
// Re-export any primitive-type constants.
if let syn::Visibility::Public(_) = c.vis {
if let syn::Type::Path(p) = &*c.ty {
let resolved_path = type_resolver.resolve_path(&p.path, None);
if type_resolver.is_primitive(&resolved_path) {
writeln!(out, "\n#[no_mangle]").unwrap();
writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
}
}
}
},
syn::Item::Type(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let mut process_alias = true;
for tok in t.generics.params.iter() {
if let syn::GenericParam::Lifetime(_) = tok {}
else { process_alias = false; }
}
if process_alias {
match &*t.ty {
syn::Type::Path(_) =>
writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
_ => {}
}
}
}
},
syn::Item::Fn(f) => {
if let syn::Visibility::Public(_) = f.vis {
writeln_fn(&mut out, &f, &mut type_resolver);
}
},
syn::Item::Macro(m) => {
if m.ident.is_none() { // If its not a macro definition
convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
}
},
syn::Item::Verbatim(_) => {},
syn::Item::ExternCrate(_) => {},
_ => unimplemented!(),
}
}
out.flush().unwrap();
}
/// Load the AST for each file in the crate, filling the FullLibraryAST object
fn load_ast(in_dir: &str, path: &str, module: String, ast_storage: &mut FullLibraryAST) {
eprintln!("Loading {}{}...", in_dir, path);
let mut file = File::open(format!("{}/{}", in_dir, path)).expect("Unable to open file");
let mut src = String::new();
file.read_to_string(&mut src).expect("Unable to read file");
let syntax = syn::parse_file(&src).expect("Unable to parse file");
assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
load_ast(in_dir, &path, new_mod, ast_storage);
}
ast_storage.files.insert(module, syntax);
}
/// Insert ident -> absolute Path resolutions into imports from the given UseTree and path-prefix.
fn process_use_intern<'a>(u: &'a syn::UseTree, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>, imports: &mut HashMap<&'a syn::Ident, syn::Path>) {
match u {
syn::UseTree::Path(p) => {
path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
process_use_intern(&p.tree, path, imports);
},
syn::UseTree::Name(n) => {
path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
imports.insert(&n.ident, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path });
},
syn::UseTree::Group(g) => {
for i in g.items.iter() {
process_use_intern(i, path.clone(), imports);
}
},
_ => {}
}
}
/// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
fn resolve_imported_refs(imports: &HashMap<&syn::Ident, syn::Path>, mut ty: syn::Type) -> syn::Type {
match &mut ty {
syn::Type::Path(p) => {
if let Some(ident) = p.path.get_ident() {
if let Some(newpath) = imports.get(ident) {
p.path = newpath.clone();
}
} else { unimplemented!(); }
},
syn::Type::Reference(r) => {
r.elem = Box::new(resolve_imported_refs(imports, (*r.elem).clone()));
},
syn::Type::Slice(s) => {
s.elem = Box::new(resolve_imported_refs(imports, (*s.elem).clone()));
},
syn::Type::Tuple(t) => {
for e in t.elems.iter_mut() {
*e = resolve_imported_refs(imports, e.clone());
}
},
_ => unimplemented!(),
}
ty
}
/// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
fn walk_ast<'a>(in_dir: &str, path: &str, module: String, ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
let syntax = if let Some(ast) = ast_storage.files.get(&module) { ast } else { return };
assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
walk_ast(in_dir, &path, new_mod, ast_storage, crate_types);
}
let mut import_maps = HashMap::new();
for item in syntax.items.iter() {
match item {
syn::Item::Use(u) => {
process_use_intern(&u.tree, syn::punctuated::Punctuated::new(), &mut import_maps);
},
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
match export_status(&s.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let struct_path = format!("{}::{}", module, s.ident);
if attrs_derives_clone(&s.attrs) {
crate_types.clonable_types.insert("crate::".to_owned() + &struct_path);
}
crate_types.opaques.insert(struct_path, &s.ident);
}
},
syn::Item::Trait(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let trait_path = format!("{}::{}", module, t.ident);
walk_supertraits!(t, None, (
("Clone", _) => {
crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
},
(_, _) => {}
) );
crate_types.traits.insert(trait_path, &t);
}
},
syn::Item::Type(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let type_path = format!("{}::{}", module, t.ident);
let mut process_alias = true;
for tok in t.generics.params.iter() {
if let syn::GenericParam::Lifetime(_) = tok {}
else { process_alias = false; }
}
if process_alias {
match &*t.ty {
syn::Type::Path(_) => {
// If its a path with no generics, assume we don't map the aliased type and map it opaque
crate_types.opaques.insert(type_path, &t.ident);
},
_ => {
crate_types.type_aliases.insert(type_path, resolve_imported_refs(&import_maps, (*t.ty).clone()));
if let &syn::Type::Path(ref p) = &*i.self_ty {
if let Some(trait_path) = i.trait_.as_ref() {
if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
match crate_types.trait_impls.entry(sp) {
hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
}
}
}
}
}
},
syn::Item::Enum(e) if is_enum_opaque(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let enum_path = format!("{}::{}", module, e.ident);
if attrs_derives_clone(&e.attrs) {
crate_types.clonable_types.insert("crate::".to_owned() + &enum_path);
}
crate_types.opaques.insert(enum_path, &e.ident);
}
},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let enum_path = format!("{}::{}", module, e.ident);
if attrs_derives_clone(&e.attrs) {
crate_types.clonable_types.insert("crate::".to_owned() + &enum_path);
}
crate_types.mirrored_enums.insert(enum_path, &e);
}
},
_ => {},
}
}
}
/// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
for (module, astmod) in ast_storage.modules.iter() {
let ASTModule { ref attrs, ref items, submods: _ } = astmod;
assert_eq!(export_status(&attrs), ExportStatus::Export);
let import_resolver = ImportResolver::new(module, items);
for item in items.iter() {
match item {
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
match export_status(&s.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let struct_path = format!("{}::{}", module, s.ident);
crate_types.opaques.insert(struct_path, &s.ident);
}
},
syn::Item::Trait(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let trait_path = format!("{}::{}", module, t.ident);
walk_supertraits!(t, None, (
("Clone", _) => {
crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
},
(_, _) => {}
) );
crate_types.traits.insert(trait_path, &t);
}
},
syn::Item::Type(t) => {
if let syn::Visibility::Public(_) = t.vis {
match export_status(&t.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let type_path = format!("{}::{}", module, t.ident);
let mut process_alias = true;
for tok in t.generics.params.iter() {
if let syn::GenericParam::Lifetime(_) = tok {}
else { process_alias = false; }
}
if process_alias {
match &*t.ty {
syn::Type::Path(p) => {
// If its a path with no generics, assume we don't map the aliased type and map it opaque
let mut segments = syn::punctuated::Punctuated::new();
segments.push(syn::PathSegment {
ident: t.ident.clone(),
arguments: syn::PathArguments::None,
});
let path_obj = syn::Path { leading_colon: None, segments };
let args_obj = p.path.segments.last().unwrap().arguments.clone();
match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
}
crate_types.opaques.insert(type_path.clone(), &t.ident);
},
_ => {
crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
}
}
}
}
},
syn::Item::Enum(e) if is_enum_opaque(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let enum_path = format!("{}::{}", module, e.ident);
crate_types.opaques.insert(enum_path, &e.ident);
}
},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
ExportStatus::Export => {},
ExportStatus::NoExport|ExportStatus::TestOnly => continue,
}
let enum_path = format!("{}::{}", module, e.ident);
crate_types.mirrored_enums.insert(enum_path, &e);
}
},
syn::Item::Impl(i) => {
if let &syn::Type::Path(ref p) = &*i.self_ty {
if let Some(trait_path) = i.trait_.as_ref() {
if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
}
}
if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
match crate_types.trait_impls.entry(sp) {
hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
}
}
}
}
}
},
syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
_ => {},
}
}
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 7 {
eprintln!("Usage: source/dir target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
if args.len() != 6 {
eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
process::exit(1);
}
let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
.open(&args[4]).expect("Unable to open new header file");
.open(&args[3]).expect("Unable to open new header file");
let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
.open(&args[5]).expect("Unable to open new header file");
.open(&args[4]).expect("Unable to open new header file");
let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
.open(&args[6]).expect("Unable to open new header file");
.open(&args[5]).expect("Unable to open new header file");
writeln!(header_file, "#if defined(__GNUC__)").unwrap();
writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
@ -1576,18 +1536,21 @@ fn main() {
// First parse the full crate's ASTs, caching them so that we can hold references to the AST
// objects in other datastructures:
let mut libast = FullLibraryAST { files: HashMap::new() };
load_ast(&args[1], "/lib.rs", "".to_string(), &mut libast);
let mut lib_src = String::new();
std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
let libast = FullLibraryAST::load_lib(lib_syntax);
// ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
// when parsing other file ASTs...
let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates,
clonable_types: HashSet::new() };
walk_ast(&args[1], "/lib.rs", "".to_string(), &libast, &mut libtypes);
type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
template_file: &mut derived_templates,
clonable_types: HashSet::new(), trait_impls: HashMap::new() };
walk_ast(&libast, &mut libtypes);
// ... finally, do the actual file conversion/mapping, writing out types as we go.
convert_file(&libast, &mut libtypes, &args[1], &args[2], "/lib.rs", &args[3], "", &mut header_file, &mut cpp_header_file);
convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
// For container templates which we created while walking the crate, make sure we add C++
// mapped types so that C++ users can utilize the auto-destructors available.

View file

@ -41,28 +41,13 @@ pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident>
} else { None }
}
pub fn attrs_derives_clone(attrs: &[syn::Attribute]) -> bool {
for attr in attrs.iter() {
let tokens_clone = attr.tokens.clone();
let mut token_iter = tokens_clone.into_iter();
if let Some(token) = token_iter.next() {
match token {
TokenTree::Group(g) => {
if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "derive" {
for id in g.stream().into_iter() {
if let TokenTree::Ident(i) = id {
if i == "Clone" {
return true;
}
}
}
}
},
_ => {},
}
}
pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
if p.segments.len() != exp.len() { return false; }
for (seg, e) in p.segments.iter().zip(exp.iter()) {
if seg.arguments != syn::PathArguments::None { return false; }
if &format!("{}", seg.ident) != *e { return false; }
}
false
true
}
#[derive(Debug, PartialEq)]
@ -125,6 +110,25 @@ pub fn assert_simple_bound(bound: &syn::TraitBound) {
if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
}
/// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
/// type), otherwise it is mapped into a transparent, C-compatible version of itself.
pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
for var in e.variants.iter() {
if let syn::Fields::Unit = var.fields {
} else if let syn::Fields::Named(fields) = &var.fields {
for field in fields.named.iter() {
match export_status(&field.attrs) {
ExportStatus::Export|ExportStatus::TestOnly => {},
ExportStatus::NoExport => return true,
}
}
} else {
return true;
}
}
false
}
/// A stack of sets of generic resolutions.
///
/// This tracks the template parameters for a function, struct, or trait, allowing resolution into
@ -165,6 +169,7 @@ impl<'a> GenericTypes<'a> {
if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
}
if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
assert_simple_bound(&trait_bound);
if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
@ -293,12 +298,225 @@ pub enum DeclType<'a> {
EnumIgnored,
}
pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
module_path: &'mod_lifetime str,
imports: HashMap<syn::Ident, (String, syn::Path)>,
declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
priv_modules: HashSet<syn::Ident>,
}
impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
match u {
syn::UseTree::Path(p) => {
let new_path = format!("{}{}::", partial_path, p.ident);
path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
Self::process_use_intern(imports, &p.tree, &new_path, path);
},
syn::UseTree::Name(n) => {
let full_path = format!("{}{}", partial_path, n.ident);
path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
},
syn::UseTree::Group(g) => {
for i in g.items.iter() {
Self::process_use_intern(imports, i, partial_path, path.clone());
}
},
syn::UseTree::Rename(r) => {
let full_path = format!("{}{}", partial_path, r.ident);
path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
},
syn::UseTree::Glob(_) => {
eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
},
}
}
fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
if let syn::Visibility::Public(_) = u.vis {
// We actually only use these for #[cfg(fuzztarget)]
eprintln!("Ignoring pub(use) tree!");
return;
}
if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
}
fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
let ident = syn::Ident::new(id, Span::call_site());
let mut path = syn::punctuated::Punctuated::new();
path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
}
pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
let mut imports = HashMap::new();
// Add primitives to the "imports" list:
Self::insert_primitive(&mut imports, "bool");
Self::insert_primitive(&mut imports, "u64");
Self::insert_primitive(&mut imports, "u32");
Self::insert_primitive(&mut imports, "u16");
Self::insert_primitive(&mut imports, "u8");
Self::insert_primitive(&mut imports, "usize");
Self::insert_primitive(&mut imports, "str");
Self::insert_primitive(&mut imports, "String");
// These are here to allow us to print native Rust types in trait fn impls even if we don't
// have C mappings:
Self::insert_primitive(&mut imports, "Result");
Self::insert_primitive(&mut imports, "Vec");
Self::insert_primitive(&mut imports, "Option");
let mut declared = HashMap::new();
let mut priv_modules = HashSet::new();
for item in contents.iter() {
match item {
syn::Item::Use(u) => Self::process_use(&mut imports, &u),
syn::Item::Struct(s) => {
if let syn::Visibility::Public(_) = s.vis {
match export_status(&s.attrs) {
ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
ExportStatus::TestOnly => continue,
}
}
},
syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
if let syn::Visibility::Public(_) = t.vis {
let mut process_alias = true;
for tok in t.generics.params.iter() {
if let syn::GenericParam::Lifetime(_) = tok {}
else { process_alias = false; }
}
if process_alias {
match &*t.ty {
syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
_ => {},
}
}
}
},
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
_ => continue,
}
}
},
syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
if let syn::Visibility::Public(_) = t.vis {
declared.insert(t.ident.clone(), DeclType::Trait(t));
}
},
syn::Item::Mod(m) => {
priv_modules.insert(m.ident.clone());
},
_ => {},
}
}
Self { module_path, imports, declared, priv_modules }
}
pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
self.declared.get(ident)
}
pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
self.declared.get(id)
}
pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
if let Some((imp, _)) = self.imports.get(id) {
Some(imp.clone())
} else if self.declared.get(id).is_some() {
Some(self.module_path.to_string() + "::" + &format!("{}", id))
} else { None }
}
pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
if let Some((imp, _)) = self.imports.get(id) {
Some(imp.clone())
} else if let Some(decl_type) = self.declared.get(id) {
match decl_type {
DeclType::StructIgnored => None,
_ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
}
} else { None }
}
pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
let p = if let Some(gen_types) = generics {
if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
synpath
} else { p_arg }
} else { p_arg };
if p.leading_colon.is_some() {
Some(p.segments.iter().enumerate().map(|(idx, seg)| {
format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
}).collect())
} else if let Some(id) = p.get_ident() {
self.maybe_resolve_ident(id)
} else {
if p.segments.len() == 1 {
let seg = p.segments.iter().next().unwrap();
return self.maybe_resolve_ident(&seg.ident);
}
let mut seg_iter = p.segments.iter();
let first_seg = seg_iter.next().unwrap();
let remaining: String = seg_iter.map(|seg| {
format!("::{}", seg.ident)
}).collect();
if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
if remaining != "" {
Some(imp.clone() + &remaining)
} else {
Some(imp.clone())
}
} else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
} else { None }
}
}
/// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
match &mut ty {
syn::Type::Path(p) => {
if let Some(ident) = p.path.get_ident() {
if let Some((_, newpath)) = self.imports.get(ident) {
p.path = newpath.clone();
}
} else { unimplemented!(); }
},
syn::Type::Reference(r) => {
r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
},
syn::Type::Slice(s) => {
s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
},
syn::Type::Tuple(t) => {
for e in t.elems.iter_mut() {
*e = self.resolve_imported_refs(e.clone());
}
},
_ => unimplemented!(),
}
ty
}
}
// templates_defined is walked to write the C++ header, so if we use the default hashing it get
// reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
// the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
// accomplish the same goals, so we just ignore it.
#[allow(deprecated)]
type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
/// Top-level struct tracking everything which has been defined while walking the crate.
pub struct CrateTypes<'a> {
@ -311,6 +529,8 @@ pub struct CrateTypes<'a> {
pub traits: HashMap<String, &'a syn::ItemTrait>,
/// Aliases from paths to some other Type
pub type_aliases: HashMap<String, syn::Type>,
/// Value is an alias to Key (maybe with some generics)
pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
/// Template continer types defined, map from mangled type name -> whether a destructor fn
/// exists.
///
@ -321,6 +541,8 @@ pub struct CrateTypes<'a> {
pub template_file: &'a mut File,
/// Set of containers which are clonable
pub clonable_types: HashSet<String>,
/// Key impls Value
pub trait_impls: HashMap<String, Vec<String>>,
}
/// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
@ -328,10 +550,8 @@ pub struct CrateTypes<'a> {
pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
pub orig_crate: &'mod_lifetime str,
pub module_path: &'mod_lifetime str,
imports: HashMap<syn::Ident, String>,
// ident -> is-mirrored-enum
declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
types: ImportResolver<'mod_lifetime, 'crate_lft>,
}
/// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
@ -346,24 +566,8 @@ enum EmptyValExpectedTy {
}
impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
pub fn new(orig_crate: &'a str, module_path: &'a str, crate_types: &'a mut CrateTypes<'c>) -> Self {
let mut imports = HashMap::new();
// Add primitives to the "imports" list:
imports.insert(syn::Ident::new("bool", Span::call_site()), "bool".to_string());
imports.insert(syn::Ident::new("u64", Span::call_site()), "u64".to_string());
imports.insert(syn::Ident::new("u32", Span::call_site()), "u32".to_string());
imports.insert(syn::Ident::new("u16", Span::call_site()), "u16".to_string());
imports.insert(syn::Ident::new("u8", Span::call_site()), "u8".to_string());
imports.insert(syn::Ident::new("usize", Span::call_site()), "usize".to_string());
imports.insert(syn::Ident::new("str", Span::call_site()), "str".to_string());
imports.insert(syn::Ident::new("String", Span::call_site()), "String".to_string());
// These are here to allow us to print native Rust types in trait fn impls even if we don't
// have C mappings:
imports.insert(syn::Ident::new("Result", Span::call_site()), "Result".to_string());
imports.insert(syn::Ident::new("Vec", Span::call_site()), "Vec".to_string());
imports.insert(syn::Ident::new("Option", Span::call_site()), "Option".to_string());
Self { orig_crate, module_path, imports, declared: HashMap::new(), crate_types }
pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
Self { orig_crate, module_path, types, crate_types }
}
// *************************************************
@ -408,7 +612,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
}
/// Gets the C-mapped type for types which are outside of the crate, or which are manually
/// ignored by for some reason need mapping anyway.
fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, ptr_for_ref: bool) -> Option<&'b str> {
fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
if self.is_primitive(full_path) {
return Some(full_path);
}
@ -462,14 +666,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some("*const std::os::raw::c_char"),
// List of structs we map that aren't detected:
"ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures"),
"ln::features::InitFeatures" if is_ref => Some("*const crate::ln::features::InitFeatures"),
"ln::features::InitFeatures" => Some("crate::ln::features::InitFeatures"),
_ => {
eprintln!(" Type {} (ref: {}) unresolvable in C", full_path, is_ref);
None
},
_ => None,
}
}
@ -528,16 +725,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
"ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
"ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
// List of structs we map (possibly during processing of other files):
"ln::features::InitFeatures" if !is_ref => Some("*unsafe { Box::from_raw("),
// List of traits we map (possibly during processing of other files):
"crate::util::logger::Logger" => Some(""),
_ => {
eprintln!(" Type {} unconvertable from C", full_path);
None
},
_ => None,
}.map(|s| s.to_owned())
}
fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
@ -586,17 +777,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
"ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
"ln::channelmanager::PaymentSecret" => Some(".data)"),
// List of structs we map (possibly during processing of other files):
"ln::features::InitFeatures" if is_ref => Some(".inner) }"),
"ln::features::InitFeatures" if !is_ref => Some(".take_inner()) }"),
// List of traits we map (possibly during processing of other files):
"crate::util::logger::Logger" => Some(""),
_ => {
eprintln!(" Type {} unconvertable from C", full_path);
None
},
_ => None,
}.map(|s| s.to_owned())
}
@ -620,7 +804,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
_ => None,
}.map(|s| s.to_owned())
}
fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
if self.is_primitive(full_path) {
return Some("".to_owned());
}
@ -673,18 +857,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some("local_"),
// List of structs we map (possibly during processing of other files):
"ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures { inner: &mut "),
"ln::features::InitFeatures" if is_ref => Some("Box::into_raw(Box::new(crate::ln::features::InitFeatures { inner: &mut "),
"ln::features::InitFeatures" if !is_ref => Some("crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new("),
_ => {
eprintln!(" Type {} (is_ref: {}) unconvertable to C", full_path, is_ref);
None
},
_ => None,
}.map(|s| s.to_owned())
}
fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
if self.is_primitive(full_path) {
return Some("".to_owned());
}
@ -738,15 +914,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some(".as_ptr()"),
// List of structs we map (possibly during processing of other files):
"ln::features::InitFeatures" if is_ref && ptr_for_ref => Some(", is_owned: false }"),
"ln::features::InitFeatures" if is_ref => Some(", is_owned: false }))"),
"ln::features::InitFeatures" => Some(")), is_owned: true }"),
_ => {
eprintln!(" Type {} unconvertable to C", full_path);
None
},
_ => None,
}.map(|s| s.to_owned())
}
@ -885,71 +1053,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
// *** Type definition during main.rs processing ***
// *************************************************
fn process_use_intern<W: std::io::Write>(&mut self, w: &mut W, u: &syn::UseTree, partial_path: &str) {
match u {
syn::UseTree::Path(p) => {
let new_path = format!("{}::{}", partial_path, p.ident);
self.process_use_intern(w, &p.tree, &new_path);
},
syn::UseTree::Name(n) => {
let full_path = format!("{}::{}", partial_path, n.ident);
self.imports.insert(n.ident.clone(), full_path);
},
syn::UseTree::Group(g) => {
for i in g.items.iter() {
self.process_use_intern(w, i, partial_path);
}
},
syn::UseTree::Rename(r) => {
let full_path = format!("{}::{}", partial_path, r.ident);
self.imports.insert(r.rename.clone(), full_path);
},
syn::UseTree::Glob(_) => {
eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
},
}
}
pub fn process_use<W: std::io::Write>(&mut self, w: &mut W, u: &syn::ItemUse) {
if let syn::Visibility::Public(_) = u.vis {
// We actually only use these for #[cfg(fuzztarget)]
eprintln!("Ignoring pub(use) tree!");
return;
}
match &u.tree {
syn::UseTree::Path(p) => {
let new_path = format!("{}", p.ident);
self.process_use_intern(w, &p.tree, &new_path);
},
syn::UseTree::Name(n) => {
let full_path = format!("{}", n.ident);
self.imports.insert(n.ident.clone(), full_path);
},
_ => unimplemented!(),
}
if u.leading_colon.is_some() { unimplemented!() }
}
pub fn mirrored_enum_declared(&mut self, ident: &syn::Ident) {
eprintln!("{} mirrored", ident);
self.declared.insert(ident.clone(), DeclType::MirroredEnum);
}
pub fn enum_ignored(&mut self, ident: &'c syn::Ident) {
self.declared.insert(ident.clone(), DeclType::EnumIgnored);
}
pub fn struct_imported(&mut self, ident: &'c syn::Ident, named: String) {
eprintln!("Imported {} as {}", ident, named);
self.declared.insert(ident.clone(), DeclType::StructImported);
}
pub fn struct_ignored(&mut self, ident: &syn::Ident) {
eprintln!("Not importing {}", ident);
self.declared.insert(ident.clone(), DeclType::StructIgnored);
}
pub fn trait_declared(&mut self, ident: &syn::Ident, t: &'c syn::ItemTrait) {
eprintln!("Trait {} created", ident);
self.declared.insert(ident.clone(), DeclType::Trait(t));
}
pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
self.declared.get(ident)
self.types.get_declared_type(ident)
}
/// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
@ -957,55 +1062,15 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
}
pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
if let Some(imp) = self.imports.get(id) {
Some(imp.clone())
} else if self.declared.get(id).is_some() {
Some(self.module_path.to_string() + "::" + &format!("{}", id))
} else { None }
self.types.maybe_resolve_ident(id)
}
pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
if let Some(imp) = self.imports.get(id) {
Some(imp.clone())
} else if let Some(decl_type) = self.declared.get(id) {
match decl_type {
DeclType::StructIgnored => None,
_ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
}
} else { None }
self.types.maybe_resolve_non_ignored_ident(id)
}
pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
let p = if let Some(gen_types) = generics {
if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
synpath
} else { p_arg }
} else { p_arg };
if p.leading_colon.is_some() {
Some(p.segments.iter().enumerate().map(|(idx, seg)| {
format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
}).collect())
} else if let Some(id) = p.get_ident() {
self.maybe_resolve_ident(id)
} else {
if p.segments.len() == 1 {
let seg = p.segments.iter().next().unwrap();
return self.maybe_resolve_ident(&seg.ident);
}
let mut seg_iter = p.segments.iter();
let first_seg = seg_iter.next().unwrap();
let remaining: String = seg_iter.map(|seg| {
format!("::{}", seg.ident)
}).collect();
if let Some(imp) = self.imports.get(&first_seg.ident) {
if remaining != "" {
Some(imp.clone() + &remaining)
} else {
Some(imp.clone())
}
} else { None }
}
self.types.maybe_resolve_path(p_arg, generics)
}
pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
self.maybe_resolve_path(p, generics).unwrap()
@ -1295,10 +1360,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
} else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
} else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
if let Some(_) = self.imports.get(ident) {
// crate_types lookup has to have succeeded:
panic!("Failed to print inline conversion for {}", ident);
} else if let Some(decl_type) = self.declared.get(ident) {
if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
} else { unimplemented!(); }
} else { unimplemented!(); }
@ -1623,7 +1685,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
true
} else if self.declared.get(ty_ident).is_some() {
} else if self.types.maybe_resolve_declared(ty_ident).is_some() {
false
} else { false }
} else { false }
@ -1896,7 +1958,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
}
} else {
let id = &&$p_arg.path.segments.iter().rev().next().unwrap().ident;
let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
write!(w, "{}", id).unwrap();
write!(mangled_type, "{}", id).unwrap();
if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {

View file

@ -6,7 +6,7 @@ set -x
# Generate (and reasonably test) C bindings
# First build the latest c-bindings-gen binary
cd c-bindings-gen && cargo build && cd ..
cd c-bindings-gen && cargo build --release && cd ..
# Then wipe all the existing C bindings (because we're being run in the right directory)
# note that we keep the few manually-generated files first:
@ -20,12 +20,15 @@ mv ./mod.rs lightning-c-bindings/src/c_types/
mv ./bitcoin lightning-c-bindings/src/
# Finally, run the c-bindings-gen binary, building fresh bindings.
SRC="$(pwd)/lightning/src"
OUT="$(pwd)/lightning-c-bindings/src"
OUT_TEMPL="$(pwd)/lightning-c-bindings/src/c_types/derived.rs"
OUT_F="$(pwd)/lightning-c-bindings/include/rust_types.h"
OUT_CPP="$(pwd)/lightning-c-bindings/include/lightningpp.hpp"
RUST_BACKTRACE=1 ./c-bindings-gen/target/debug/c-bindings-gen $SRC/ $OUT/ lightning $OUT_TEMPL $OUT_F $OUT_CPP
cd lightning
RUSTC_BOOTSTRAP=1 cargo rustc --profile=check -- -Zunstable-options --pretty=expanded |
RUST_BACKTRACE=1 ../c-bindings-gen/target/release/c-bindings-gen $OUT/ lightning $OUT_TEMPL $OUT_F $OUT_CPP
cd ..
# Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
PATH="$PATH:~/.cargo/bin"

View file

@ -385,8 +385,9 @@ int main() {
assert(channels2->datalen == 0);
LDK::RoutingMessageHandler net_msgs2 = NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2);
LDK::ChannelAnnouncement chan_ann = ChannelAnnouncement_read(LDKu8slice { .data = valid_node_announcement, .datalen = sizeof(valid_node_announcement) });
LDK::CResult_boolLightningErrorZ ann_res = net_msgs2->handle_channel_announcement(net_msgs2->this_arg, &chan_ann);
LDK::CResult_ChannelAnnouncementDecodeErrorZ chan_ann = ChannelAnnouncement_read(LDKu8slice { .data = valid_node_announcement, .datalen = sizeof(valid_node_announcement) });
assert(chan_ann->result_ok);
LDK::CResult_boolLightningErrorZ ann_res = net_msgs2->handle_channel_announcement(net_msgs2->this_arg, chan_ann->contents.result);
assert(ann_res->result_ok);
LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), std::move(net_msgs2));

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,39 @@
#else
#define NONNULL_PTR
#endif
struct nativeTxCreationKeysOpaque;
typedef struct nativeTxCreationKeysOpaque LDKnativeTxCreationKeys;
struct nativeChannelPublicKeysOpaque;
typedef struct nativeChannelPublicKeysOpaque LDKnativeChannelPublicKeys;
struct nativeHTLCOutputInCommitmentOpaque;
typedef struct nativeHTLCOutputInCommitmentOpaque LDKnativeHTLCOutputInCommitment;
struct nativeChannelTransactionParametersOpaque;
typedef struct nativeChannelTransactionParametersOpaque LDKnativeChannelTransactionParameters;
struct nativeCounterpartyChannelTransactionParametersOpaque;
typedef struct nativeCounterpartyChannelTransactionParametersOpaque LDKnativeCounterpartyChannelTransactionParameters;
struct nativeDirectedChannelTransactionParametersOpaque;
typedef struct nativeDirectedChannelTransactionParametersOpaque LDKnativeDirectedChannelTransactionParameters;
struct nativeHolderCommitmentTransactionOpaque;
typedef struct nativeHolderCommitmentTransactionOpaque LDKnativeHolderCommitmentTransaction;
struct nativeBuiltCommitmentTransactionOpaque;
typedef struct nativeBuiltCommitmentTransactionOpaque LDKnativeBuiltCommitmentTransaction;
struct nativeCommitmentTransactionOpaque;
typedef struct nativeCommitmentTransactionOpaque LDKnativeCommitmentTransaction;
struct nativeTrustedCommitmentTransactionOpaque;
typedef struct nativeTrustedCommitmentTransactionOpaque LDKnativeTrustedCommitmentTransaction;
struct nativeMessageHandlerOpaque;
typedef struct nativeMessageHandlerOpaque LDKnativeMessageHandler;
typedef struct LDKSocketDescriptor LDKSocketDescriptor;
struct nativePeerHandleErrorOpaque;
typedef struct nativePeerHandleErrorOpaque LDKnativePeerHandleError;
struct nativePeerManagerOpaque;
typedef struct nativePeerManagerOpaque LDKnativePeerManager;
struct nativeInitFeaturesOpaque;
typedef struct nativeInitFeaturesOpaque LDKnativeInitFeatures;
struct nativeNodeFeaturesOpaque;
typedef struct nativeNodeFeaturesOpaque LDKnativeNodeFeatures;
struct nativeChannelFeaturesOpaque;
typedef struct nativeChannelFeaturesOpaque LDKnativeChannelFeatures;
struct nativeChannelHandshakeConfigOpaque;
typedef struct nativeChannelHandshakeConfigOpaque LDKnativeChannelHandshakeConfig;
struct nativeChannelHandshakeLimitsOpaque;
@ -18,8 +51,26 @@ struct nativeChannelConfigOpaque;
typedef struct nativeChannelConfigOpaque LDKnativeChannelConfig;
struct nativeUserConfigOpaque;
typedef struct nativeUserConfigOpaque LDKnativeUserConfig;
struct nativeNetworkGraphOpaque;
typedef struct nativeNetworkGraphOpaque LDKnativeNetworkGraph;
struct nativeLockedNetworkGraphOpaque;
typedef struct nativeLockedNetworkGraphOpaque LDKnativeLockedNetworkGraph;
struct nativeNetGraphMsgHandlerOpaque;
typedef struct nativeNetGraphMsgHandlerOpaque LDKnativeNetGraphMsgHandler;
struct nativeDirectionalChannelInfoOpaque;
typedef struct nativeDirectionalChannelInfoOpaque LDKnativeDirectionalChannelInfo;
struct nativeChannelInfoOpaque;
typedef struct nativeChannelInfoOpaque LDKnativeChannelInfo;
struct nativeRoutingFeesOpaque;
typedef struct nativeRoutingFeesOpaque LDKnativeRoutingFees;
struct nativeNodeAnnouncementInfoOpaque;
typedef struct nativeNodeAnnouncementInfoOpaque LDKnativeNodeAnnouncementInfo;
struct nativeNodeInfoOpaque;
typedef struct nativeNodeInfoOpaque LDKnativeNodeInfo;
struct nativeChainMonitorOpaque;
typedef struct nativeChainMonitorOpaque LDKnativeChainMonitor;
struct nativeOutPointOpaque;
typedef struct nativeOutPointOpaque LDKnativeOutPoint;
struct nativeChannelMonitorUpdateOpaque;
typedef struct nativeChannelMonitorUpdateOpaque LDKnativeChannelMonitorUpdate;
struct nativeMonitorUpdateErrorOpaque;
@ -30,14 +81,6 @@ struct nativeHTLCUpdateOpaque;
typedef struct nativeHTLCUpdateOpaque LDKnativeHTLCUpdate;
struct nativeChannelMonitorOpaque;
typedef struct nativeChannelMonitorOpaque LDKnativeChannelMonitor;
struct nativeOutPointOpaque;
typedef struct nativeOutPointOpaque LDKnativeOutPoint;
struct LDKChannelKeys;
typedef struct LDKChannelKeys LDKChannelKeys;
struct nativeInMemoryChannelKeysOpaque;
typedef struct nativeInMemoryChannelKeysOpaque LDKnativeInMemoryChannelKeys;
struct nativeKeysManagerOpaque;
typedef struct nativeKeysManagerOpaque LDKnativeKeysManager;
struct nativeChannelManagerOpaque;
typedef struct nativeChannelManagerOpaque LDKnativeChannelManager;
struct nativeChannelDetailsOpaque;
@ -46,6 +89,18 @@ struct nativePaymentSendFailureOpaque;
typedef struct nativePaymentSendFailureOpaque LDKnativePaymentSendFailure;
struct nativeChannelManagerReadArgsOpaque;
typedef struct nativeChannelManagerReadArgsOpaque LDKnativeChannelManagerReadArgs;
struct LDKChannelKeys;
typedef struct LDKChannelKeys LDKChannelKeys;
struct nativeInMemoryChannelKeysOpaque;
typedef struct nativeInMemoryChannelKeysOpaque LDKnativeInMemoryChannelKeys;
struct nativeKeysManagerOpaque;
typedef struct nativeKeysManagerOpaque LDKnativeKeysManager;
struct nativeRouteHopOpaque;
typedef struct nativeRouteHopOpaque LDKnativeRouteHop;
struct nativeRouteOpaque;
typedef struct nativeRouteOpaque LDKnativeRoute;
struct nativeRouteHintOpaque;
typedef struct nativeRouteHintOpaque LDKnativeRouteHint;
struct nativeDecodeErrorOpaque;
typedef struct nativeDecodeErrorOpaque LDKnativeDecodeError;
struct nativeInitOpaque;
@ -116,58 +171,3 @@ struct nativeLightningErrorOpaque;
typedef struct nativeLightningErrorOpaque LDKnativeLightningError;
struct nativeCommitmentUpdateOpaque;
typedef struct nativeCommitmentUpdateOpaque LDKnativeCommitmentUpdate;
struct nativeMessageHandlerOpaque;
typedef struct nativeMessageHandlerOpaque LDKnativeMessageHandler;
typedef struct LDKSocketDescriptor LDKSocketDescriptor;
struct nativePeerHandleErrorOpaque;
typedef struct nativePeerHandleErrorOpaque LDKnativePeerHandleError;
struct nativePeerManagerOpaque;
typedef struct nativePeerManagerOpaque LDKnativePeerManager;
struct nativeTxCreationKeysOpaque;
typedef struct nativeTxCreationKeysOpaque LDKnativeTxCreationKeys;
struct nativeChannelPublicKeysOpaque;
typedef struct nativeChannelPublicKeysOpaque LDKnativeChannelPublicKeys;
struct nativeHTLCOutputInCommitmentOpaque;
typedef struct nativeHTLCOutputInCommitmentOpaque LDKnativeHTLCOutputInCommitment;
struct nativeChannelTransactionParametersOpaque;
typedef struct nativeChannelTransactionParametersOpaque LDKnativeChannelTransactionParameters;
struct nativeCounterpartyChannelTransactionParametersOpaque;
typedef struct nativeCounterpartyChannelTransactionParametersOpaque LDKnativeCounterpartyChannelTransactionParameters;
struct nativeDirectedChannelTransactionParametersOpaque;
typedef struct nativeDirectedChannelTransactionParametersOpaque LDKnativeDirectedChannelTransactionParameters;
struct nativeHolderCommitmentTransactionOpaque;
typedef struct nativeHolderCommitmentTransactionOpaque LDKnativeHolderCommitmentTransaction;
struct nativeBuiltCommitmentTransactionOpaque;
typedef struct nativeBuiltCommitmentTransactionOpaque LDKnativeBuiltCommitmentTransaction;
struct nativeCommitmentTransactionOpaque;
typedef struct nativeCommitmentTransactionOpaque LDKnativeCommitmentTransaction;
struct nativeTrustedCommitmentTransactionOpaque;
typedef struct nativeTrustedCommitmentTransactionOpaque LDKnativeTrustedCommitmentTransaction;
struct nativeInitFeaturesOpaque;
typedef struct nativeInitFeaturesOpaque LDKnativeInitFeatures;
struct nativeNodeFeaturesOpaque;
typedef struct nativeNodeFeaturesOpaque LDKnativeNodeFeatures;
struct nativeChannelFeaturesOpaque;
typedef struct nativeChannelFeaturesOpaque LDKnativeChannelFeatures;
struct nativeRouteHopOpaque;
typedef struct nativeRouteHopOpaque LDKnativeRouteHop;
struct nativeRouteOpaque;
typedef struct nativeRouteOpaque LDKnativeRoute;
struct nativeRouteHintOpaque;
typedef struct nativeRouteHintOpaque LDKnativeRouteHint;
struct nativeNetworkGraphOpaque;
typedef struct nativeNetworkGraphOpaque LDKnativeNetworkGraph;
struct nativeLockedNetworkGraphOpaque;
typedef struct nativeLockedNetworkGraphOpaque LDKnativeLockedNetworkGraph;
struct nativeNetGraphMsgHandlerOpaque;
typedef struct nativeNetGraphMsgHandlerOpaque LDKnativeNetGraphMsgHandler;
struct nativeDirectionalChannelInfoOpaque;
typedef struct nativeDirectionalChannelInfoOpaque LDKnativeDirectionalChannelInfo;
struct nativeChannelInfoOpaque;
typedef struct nativeChannelInfoOpaque LDKnativeChannelInfo;
struct nativeRoutingFeesOpaque;
typedef struct nativeRoutingFeesOpaque LDKnativeRoutingFees;
struct nativeNodeAnnouncementInfoOpaque;
typedef struct nativeNodeAnnouncementInfoOpaque LDKnativeNodeAnnouncementInfo;
struct nativeNodeInfoOpaque;
typedef struct nativeNodeInfoOpaque LDKnativeNodeInfo;

File diff suppressed because it is too large Load diff

View file

@ -56,24 +56,6 @@ impl ChannelMonitorUpdate {
ret
}
}
impl Clone for ChannelMonitorUpdate {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
orig.clone()
}
/// The sequence number of this update. Updates *must* be replayed in-order according to this
/// sequence number (and updates may panic if they are not). The update_id values are strictly
/// increasing and increase by one for each new update, with one exception specified below.
@ -109,6 +91,24 @@ pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUp
pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
unsafe { &mut *this_ptr.inner }.update_id = val;
}
impl Clone for ChannelMonitorUpdate {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
orig.clone()
}
#[no_mangle]
pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
@ -401,19 +401,17 @@ pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
}
#[no_mangle]
pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
}
#[no_mangle]
pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> HTLCUpdate {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
HTLCUpdate { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
HTLCUpdate { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;

View file

@ -531,7 +531,7 @@ pub struct KeysInterface {
/// contain no versioning scheme. You may wish to include your own version prefix and ensure
/// you've read all of the provided bytes to ensure no corruption occurred.
#[must_use]
pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChanKeySignerDecodeErrorZ,
pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelKeysDecodeErrorZ,
pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
}
unsafe impl Send for KeysInterface {}
@ -627,24 +627,6 @@ impl InMemoryChannelKeys {
ret
}
}
impl Clone for InMemoryChannelKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 InMemoryChannelKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemoryChannelKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn InMemoryChannelKeys_clone(orig: &InMemoryChannelKeys) -> InMemoryChannelKeys {
orig.clone()
}
/// Private key of anchor tx
#[no_mangle]
pub extern "C" fn InMemoryChannelKeys_get_funding_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
@ -711,6 +693,24 @@ pub extern "C" fn InMemoryChannelKeys_get_commitment_seed(this_ptr: &InMemoryCha
pub extern "C" fn InMemoryChannelKeys_set_commitment_seed(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::ThirtyTwoBytes) {
unsafe { &mut *this_ptr.inner }.commitment_seed = val.data;
}
impl Clone for InMemoryChannelKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 InMemoryChannelKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemoryChannelKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn InMemoryChannelKeys_clone(orig: &InMemoryChannelKeys) -> InMemoryChannelKeys {
orig.clone()
}
/// Create a new InMemoryChannelKeys
#[must_use]
#[no_mangle]
@ -1026,7 +1026,7 @@ extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const
crate::c_types::ThirtyTwoBytes { data: ret }
}
#[must_use]
extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChanKeySignerDecodeErrorZ {
extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelKeysDecodeErrorZ {
let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.read_chan_signer(reader.to_slice());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_ret

View file

@ -45,24 +45,6 @@ impl OutPoint {
ret
}
}
impl Clone for OutPoint {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 OutPoint_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOutPoint)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint {
orig.clone()
}
/// The referenced transaction's txid.
#[no_mangle]
pub extern "C" fn OutPoint_get_txid(this_ptr: &OutPoint) -> *const [u8; 32] {
@ -93,6 +75,24 @@ pub extern "C" fn OutPoint_new(mut txid_arg: crate::c_types::ThirtyTwoBytes, mut
index: index_arg,
})), is_owned: true }
}
impl Clone for OutPoint {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 OutPoint_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOutPoint)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint {
orig.clone()
}
/// Convert an `OutPoint` to a lightning channel id.
#[must_use]
#[no_mangle]
@ -103,17 +103,15 @@ pub extern "C" fn OutPoint_to_channel_id(this_arg: &OutPoint) -> crate::c_types:
#[no_mangle]
pub extern "C" fn OutPoint_write(obj: &OutPoint) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOutPoint) })
}
#[no_mangle]
pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> OutPoint {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
OutPoint { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
OutPoint { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutPointDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}

View file

@ -19,7 +19,7 @@ pub extern "C" fn build_commitment_secret(commitment_seed: *const [u8; 32], mut
/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
/// generated (ie our own).
#[no_mangle]
pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::PublicKey, base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeySecpErrorZ {
pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::PublicKey, base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeyErrorZ {
let mut ret = lightning::ln::chan_utils::derive_private_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *base_secret}[..]).unwrap());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -32,7 +32,7 @@ pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::P
/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
/// generated (ie our own).
#[no_mangle]
pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::PublicKey, mut base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeySecpErrorZ {
pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::PublicKey, mut base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeyErrorZ {
let mut ret = lightning::ln::chan_utils::derive_public_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &base_point.into_rust());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -48,7 +48,7 @@ pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::Pu
/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
/// generated (ie our own).
#[no_mangle]
pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u8; 32], countersignatory_revocation_base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeySecpErrorZ {
pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u8; 32], countersignatory_revocation_base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeyErrorZ {
let mut ret = lightning::ln::chan_utils::derive_private_revocation_key(&bitcoin::secp256k1::Secp256k1::new(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_secret}[..]).unwrap(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *countersignatory_revocation_base_secret}[..]).unwrap());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -66,7 +66,7 @@ pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u
/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
/// generated (ie our own).
#[no_mangle]
pub extern "C" fn derive_public_revocation_key(mut per_commitment_point: crate::c_types::PublicKey, mut countersignatory_revocation_base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeySecpErrorZ {
pub extern "C" fn derive_public_revocation_key(mut per_commitment_point: crate::c_types::PublicKey, mut countersignatory_revocation_base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeyErrorZ {
let mut ret = lightning::ln::chan_utils::derive_public_revocation_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &countersignatory_revocation_base_point.into_rust());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -120,24 +120,6 @@ impl TxCreationKeys {
ret
}
}
impl Clone for TxCreationKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 TxCreationKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeTxCreationKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys {
orig.clone()
}
/// The broadcaster's per-commitment public key which was used to derive the other keys.
#[no_mangle]
pub extern "C" fn TxCreationKeys_get_per_commitment_point(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
@ -208,21 +190,37 @@ pub extern "C" fn TxCreationKeys_new(mut per_commitment_point_arg: crate::c_type
broadcaster_delayed_payment_key: broadcaster_delayed_payment_key_arg.into_rust(),
})), is_owned: true }
}
impl Clone for TxCreationKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 TxCreationKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeTxCreationKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys {
orig.clone()
}
#[no_mangle]
pub extern "C" fn TxCreationKeys_write(obj: &TxCreationKeys) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeTxCreationKeys) })
}
#[no_mangle]
pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> TxCreationKeys {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
TxCreationKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
TxCreationKeys { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_TxCreationKeysDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::ln::chan_utils::ChannelPublicKeys as nativeChannelPublicKeysImport;
@ -262,24 +260,6 @@ impl ChannelPublicKeys {
ret
}
}
impl Clone for ChannelPublicKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelPublicKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelPublicKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPublicKeys {
orig.clone()
}
/// The public key which is used to sign all commitment transactions, as it appears in the
/// on-chain channel lock-in 2-of-2 multisig output.
#[no_mangle]
@ -364,27 +344,43 @@ pub extern "C" fn ChannelPublicKeys_new(mut funding_pubkey_arg: crate::c_types::
htlc_basepoint: htlc_basepoint_arg.into_rust(),
})), is_owned: true }
}
impl Clone for ChannelPublicKeys {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelPublicKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelPublicKeys)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPublicKeys {
orig.clone()
}
#[no_mangle]
pub extern "C" fn ChannelPublicKeys_write(obj: &ChannelPublicKeys) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelPublicKeys) })
}
#[no_mangle]
pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> ChannelPublicKeys {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
ChannelPublicKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelPublicKeysDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::ChannelPublicKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
/// Create per-state keys from channel base points and the per-commitment point.
/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
#[must_use]
#[no_mangle]
pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysSecpErrorZ {
pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
let mut ret = lightning::ln::chan_utils::TxCreationKeys::derive_new(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &broadcaster_delayed_payment_base.into_rust(), &broadcaster_htlc_base.into_rust(), &countersignatory_revocation_base.into_rust(), &countersignatory_htlc_base.into_rust());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -394,7 +390,7 @@ pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_t
/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
#[must_use]
#[no_mangle]
pub extern "C" fn TxCreationKeys_from_channel_static_keys(mut per_commitment_point: crate::c_types::PublicKey, broadcaster_keys: &crate::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TxCreationKeysSecpErrorZ {
pub extern "C" fn TxCreationKeys_from_channel_static_keys(mut per_commitment_point: crate::c_types::PublicKey, broadcaster_keys: &crate::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
local_ret
@ -447,24 +443,6 @@ impl HTLCOutputInCommitment {
ret
}
}
impl Clone for HTLCOutputInCommitment {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 HTLCOutputInCommitment_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCOutputInCommitment)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) -> HTLCOutputInCommitment {
orig.clone()
}
/// Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction).
/// Note that this is not the same as whether it is ountbound *from us*. To determine that you
/// need to compare this value to whether the commitment transaction in question is that of
@ -517,21 +495,37 @@ pub extern "C" fn HTLCOutputInCommitment_get_payment_hash(this_ptr: &HTLCOutputI
pub extern "C" fn HTLCOutputInCommitment_set_payment_hash(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::ThirtyTwoBytes) {
unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::channelmanager::PaymentHash(val.data);
}
impl Clone for HTLCOutputInCommitment {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 HTLCOutputInCommitment_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCOutputInCommitment)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) -> HTLCOutputInCommitment {
orig.clone()
}
#[no_mangle]
pub extern "C" fn HTLCOutputInCommitment_write(obj: &HTLCOutputInCommitment) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCOutputInCommitment) })
}
#[no_mangle]
pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> HTLCOutputInCommitment {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
HTLCOutputInCommitment { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
HTLCOutputInCommitment { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCOutputInCommitmentDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::HTLCOutputInCommitment { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
/// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
/// does not need to have its previous_output_index filled.
@ -599,24 +593,6 @@ impl ChannelTransactionParameters {
ret
}
}
impl Clone for ChannelTransactionParameters {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelTransactionParameters)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelTransactionParameters_clone(orig: &ChannelTransactionParameters) -> ChannelTransactionParameters {
orig.clone()
}
/// Holder public keys
#[no_mangle]
pub extern "C" fn ChannelTransactionParameters_get_holder_pubkeys(this_ptr: &ChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
@ -693,6 +669,24 @@ pub extern "C" fn ChannelTransactionParameters_new(mut holder_pubkeys_arg: crate
funding_outpoint: local_funding_outpoint_arg,
})), is_owned: true }
}
impl Clone for ChannelTransactionParameters {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelTransactionParameters)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelTransactionParameters_clone(orig: &ChannelTransactionParameters) -> ChannelTransactionParameters {
orig.clone()
}
use lightning::ln::chan_utils::CounterpartyChannelTransactionParameters as nativeCounterpartyChannelTransactionParametersImport;
type nativeCounterpartyChannelTransactionParameters = nativeCounterpartyChannelTransactionParametersImport;
@ -731,24 +725,6 @@ impl CounterpartyChannelTransactionParameters {
ret
}
}
impl Clone for CounterpartyChannelTransactionParameters {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 CounterpartyChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCounterpartyChannelTransactionParameters)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn CounterpartyChannelTransactionParameters_clone(orig: &CounterpartyChannelTransactionParameters) -> CounterpartyChannelTransactionParameters {
orig.clone()
}
/// Counter-party public keys
#[no_mangle]
pub extern "C" fn CounterpartyChannelTransactionParameters_get_pubkeys(this_ptr: &CounterpartyChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
@ -779,6 +755,24 @@ pub extern "C" fn CounterpartyChannelTransactionParameters_new(mut pubkeys_arg:
selected_contest_delay: selected_contest_delay_arg,
})), is_owned: true }
}
impl Clone for CounterpartyChannelTransactionParameters {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 CounterpartyChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCounterpartyChannelTransactionParameters)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn CounterpartyChannelTransactionParameters_clone(orig: &CounterpartyChannelTransactionParameters) -> CounterpartyChannelTransactionParameters {
orig.clone()
}
/// Whether the late bound parameters are populated.
#[must_use]
#[no_mangle]
@ -811,35 +805,31 @@ pub extern "C" fn ChannelTransactionParameters_as_counterparty_broadcastable(thi
#[no_mangle]
pub extern "C" fn CounterpartyChannelTransactionParameters_write(obj: &CounterpartyChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCounterpartyChannelTransactionParameters) })
}
#[no_mangle]
pub extern "C" fn CounterpartyChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> CounterpartyChannelTransactionParameters {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
CounterpartyChannelTransactionParameters { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn CounterpartyChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
#[no_mangle]
pub extern "C" fn ChannelTransactionParameters_write(obj: &ChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelTransactionParameters) })
}
#[no_mangle]
pub extern "C" fn ChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> ChannelTransactionParameters {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
ChannelTransactionParameters { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
ChannelTransactionParameters { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn ChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTransactionParametersDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::ChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::ln::chan_utils::DirectedChannelTransactionParameters as nativeDirectedChannelTransactionParametersImport;
@ -967,6 +957,23 @@ impl HolderCommitmentTransaction {
ret
}
}
/// Our counterparty's signature for the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig;
crate::c_types::Signature::from_rust(&(*inner_val))
}
/// Our counterparty's signature for the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) {
unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust();
}
/// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_SignatureZ) {
let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
unsafe { &mut *this_ptr.inner }.counterparty_htlc_sigs = local_val;
}
impl Clone for HolderCommitmentTransaction {
fn clone(&self) -> Self {
Self {
@ -985,38 +992,19 @@ pub(crate) extern "C" fn HolderCommitmentTransaction_clone_void(this_ptr: *const
pub extern "C" fn HolderCommitmentTransaction_clone(orig: &HolderCommitmentTransaction) -> HolderCommitmentTransaction {
orig.clone()
}
/// Our counterparty's signature for the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig;
crate::c_types::Signature::from_rust(&(*inner_val))
}
/// Our counterparty's signature for the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) {
unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust();
}
/// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_SignatureZ) {
let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
unsafe { &mut *this_ptr.inner }.counterparty_htlc_sigs = local_val;
}
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_write(obj: &HolderCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHolderCommitmentTransaction) })
}
#[no_mangle]
pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> HolderCommitmentTransaction {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
HolderCommitmentTransaction { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
HolderCommitmentTransaction { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HolderCommitmentTransactionDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::HolderCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
/// Create a new holder transaction with the given counterparty signatures.
/// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
@ -1066,24 +1054,6 @@ impl BuiltCommitmentTransaction {
ret
}
}
impl Clone for BuiltCommitmentTransaction {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 BuiltCommitmentTransaction_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBuiltCommitmentTransaction)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn BuiltCommitmentTransaction_clone(orig: &BuiltCommitmentTransaction) -> BuiltCommitmentTransaction {
orig.clone()
}
/// The commitment transaction
#[no_mangle]
pub extern "C" fn BuiltCommitmentTransaction_get_transaction(this_ptr: &BuiltCommitmentTransaction) -> crate::c_types::Transaction {
@ -1121,21 +1091,37 @@ pub extern "C" fn BuiltCommitmentTransaction_new(mut transaction_arg: crate::c_t
txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(),
})), is_owned: true }
}
impl Clone for BuiltCommitmentTransaction {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 BuiltCommitmentTransaction_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBuiltCommitmentTransaction)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn BuiltCommitmentTransaction_clone(orig: &BuiltCommitmentTransaction) -> BuiltCommitmentTransaction {
orig.clone()
}
#[no_mangle]
pub extern "C" fn BuiltCommitmentTransaction_write(obj: &BuiltCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeBuiltCommitmentTransaction) })
}
#[no_mangle]
pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) -> BuiltCommitmentTransaction {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
BuiltCommitmentTransaction { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BuiltCommitmentTransactionDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
/// Get the SIGHASH_ALL sighash value of the transaction.
///
@ -1219,19 +1205,17 @@ pub extern "C" fn CommitmentTransaction_clone(orig: &CommitmentTransaction) -> C
}
#[no_mangle]
pub extern "C" fn CommitmentTransaction_write(obj: &CommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCommitmentTransaction) })
}
#[no_mangle]
pub extern "C" fn CommitmentTransaction_read(ser: crate::c_types::u8slice) -> CommitmentTransaction {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
CommitmentTransaction { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
CommitmentTransaction { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn CommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentTransactionDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::CommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
/// The backwards-counting commitment number
#[must_use]

View file

@ -124,24 +124,6 @@ impl ChannelDetails {
ret
}
}
impl Clone for ChannelDetails {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
orig.clone()
}
/// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
/// thereafter this is the txid of the funding transaction xor the funding transaction output).
/// Note that this means this value is *not* persistent - it can change once during the
@ -176,7 +158,7 @@ pub extern "C" fn ChannelDetails_set_remote_network_id(this_ptr: &mut ChannelDet
#[no_mangle]
pub extern "C" fn ChannelDetails_get_counterparty_features(this_ptr: &ChannelDetails) -> crate::ln::features::InitFeatures {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_features;
crate::ln::features::InitFeatures { inner: &mut (*inner_val), is_owned: false }
crate::ln::features::InitFeatures { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
}
/// The Features the channel counterparty provided upon last connection.
/// Useful for routing as it is the most up-to-date copy of the counterparty's features and
@ -256,6 +238,24 @@ pub extern "C" fn ChannelDetails_get_is_live(this_ptr: &ChannelDetails) -> bool
pub extern "C" fn ChannelDetails_set_is_live(this_ptr: &mut ChannelDetails, mut val: bool) {
unsafe { &mut *this_ptr.inner }.is_live = val;
}
impl Clone for ChannelDetails {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
orig.clone()
}
use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailureImport;
type nativePaymentSendFailure = nativePaymentSendFailureImport;

View file

@ -20,6 +20,60 @@ use std::ffi::c_void;
use bitcoin::hashes::Hash;
use crate::c_types::*;
impl Clone for InitFeatures {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 InitFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInitFeatures)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn InitFeatures_clone(orig: &InitFeatures) -> InitFeatures {
orig.clone()
}
impl Clone for NodeFeatures {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 NodeFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeFeatures)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn NodeFeatures_clone(orig: &NodeFeatures) -> NodeFeatures {
orig.clone()
}
impl Clone for ChannelFeatures {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelFeatures)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelFeatures_clone(orig: &ChannelFeatures) -> ChannelFeatures {
orig.clone()
}
use lightning::ln::features::InitFeatures as nativeInitFeaturesImport;
type nativeInitFeatures = nativeInitFeaturesImport;
@ -134,3 +188,99 @@ impl ChannelFeatures {
ret
}
}
/// Create a blank Features with no features set
#[must_use]
#[no_mangle]
pub extern "C" fn InitFeatures_empty() -> InitFeatures {
let mut ret = lightning::ln::features::InitFeatures::empty();
InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
///
/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
#[must_use]
#[no_mangle]
pub extern "C" fn InitFeatures_known() -> InitFeatures {
let mut ret = lightning::ln::features::InitFeatures::known();
InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Create a blank Features with no features set
#[must_use]
#[no_mangle]
pub extern "C" fn NodeFeatures_empty() -> NodeFeatures {
let mut ret = lightning::ln::features::NodeFeatures::empty();
NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
///
/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
#[must_use]
#[no_mangle]
pub extern "C" fn NodeFeatures_known() -> NodeFeatures {
let mut ret = lightning::ln::features::NodeFeatures::known();
NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Create a blank Features with no features set
#[must_use]
#[no_mangle]
pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures {
let mut ret = lightning::ln::features::ChannelFeatures::empty();
ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
///
/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
#[must_use]
#[no_mangle]
pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures {
let mut ret = lightning::ln::features::ChannelFeatures::known();
ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
#[no_mangle]
pub extern "C" fn InitFeatures_write(obj: &InitFeatures) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInitFeatures) })
}
#[no_mangle]
pub extern "C" fn NodeFeatures_write(obj: &NodeFeatures) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn NodeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNodeFeatures) })
}
#[no_mangle]
pub extern "C" fn ChannelFeatures_write(obj: &ChannelFeatures) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn ChannelFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelFeatures) })
}
#[no_mangle]
pub extern "C" fn InitFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitFeaturesDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
#[no_mangle]
pub extern "C" fn NodeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeFeaturesDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::NodeFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
#[no_mangle]
pub extern "C" fn ChannelFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelFeaturesDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::ChannelFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}

File diff suppressed because it is too large Load diff

View file

@ -218,24 +218,6 @@ impl PeerHandleError {
ret
}
}
impl Clone for PeerHandleError {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 PeerHandleError_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePeerHandleError)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleError {
orig.clone()
}
/// Used to indicate that we probably can't make any future connections to this peer, implying
/// we should go ahead and force-close any channels we have with it.
#[no_mangle]
@ -256,6 +238,24 @@ pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> P
no_connection_possible: no_connection_possible_arg,
})), is_owned: true }
}
impl Clone for PeerHandleError {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 PeerHandleError_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePeerHandleError)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleError {
orig.clone()
}
use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport;
type nativePeerManager = nativePeerManagerImport<crate::ln::peer_handler::SocketDescriptor, crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler, crate::util::logger::Logger>;

View file

@ -334,24 +334,6 @@ impl DirectionalChannelInfo {
ret
}
}
impl Clone for DirectionalChannelInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 DirectionalChannelInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDirectionalChannelInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn DirectionalChannelInfo_clone(orig: &DirectionalChannelInfo) -> DirectionalChannelInfo {
orig.clone()
}
/// When the last update to the channel direction was issued.
/// Value is opaque, as set in the announcement.
#[no_mangle]
@ -428,21 +410,37 @@ pub extern "C" fn DirectionalChannelInfo_set_last_update_message(this_ptr: &mut
let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
unsafe { &mut *this_ptr.inner }.last_update_message = local_val;
}
impl Clone for DirectionalChannelInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 DirectionalChannelInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDirectionalChannelInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn DirectionalChannelInfo_clone(orig: &DirectionalChannelInfo) -> DirectionalChannelInfo {
orig.clone()
}
#[no_mangle]
pub extern "C" fn DirectionalChannelInfo_write(obj: &DirectionalChannelInfo) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn DirectionalChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeDirectionalChannelInfo) })
}
#[no_mangle]
pub extern "C" fn DirectionalChannelInfo_read(ser: crate::c_types::u8slice) -> DirectionalChannelInfo {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
DirectionalChannelInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
DirectionalChannelInfo { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn DirectionalChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_DirectionalChannelInfoDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::DirectionalChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::routing::network_graph::ChannelInfo as nativeChannelInfoImport;
@ -563,19 +561,17 @@ pub extern "C" fn ChannelInfo_set_announcement_message(this_ptr: &mut ChannelInf
}
#[no_mangle]
pub extern "C" fn ChannelInfo_write(obj: &ChannelInfo) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn ChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelInfo) })
}
#[no_mangle]
pub extern "C" fn ChannelInfo_read(ser: crate::c_types::u8slice) -> ChannelInfo {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
ChannelInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
ChannelInfo { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn ChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelInfoDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::ChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::routing::network_graph::RoutingFees as nativeRoutingFeesImport;
@ -615,24 +611,6 @@ impl RoutingFees {
ret
}
}
impl Clone for RoutingFees {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RoutingFees_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoutingFees)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RoutingFees_clone(orig: &RoutingFees) -> RoutingFees {
orig.clone()
}
/// Flat routing fee in satoshis
#[no_mangle]
pub extern "C" fn RoutingFees_get_base_msat(this_ptr: &RoutingFees) -> u32 {
@ -665,6 +643,24 @@ pub extern "C" fn RoutingFees_new(mut base_msat_arg: u32, mut proportional_milli
proportional_millionths: proportional_millionths_arg,
})), is_owned: true }
}
impl Clone for RoutingFees {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RoutingFees_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoutingFees)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RoutingFees_clone(orig: &RoutingFees) -> RoutingFees {
orig.clone()
}
#[no_mangle]
pub extern "C" fn RoutingFees_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RoutingFeesDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
@ -717,24 +713,6 @@ impl NodeAnnouncementInfo {
ret
}
}
impl Clone for NodeAnnouncementInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 NodeAnnouncementInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeAnnouncementInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn NodeAnnouncementInfo_clone(orig: &NodeAnnouncementInfo) -> NodeAnnouncementInfo {
orig.clone()
}
/// Protocol features the node announced support for
#[no_mangle]
pub extern "C" fn NodeAnnouncementInfo_get_features(this_ptr: &NodeAnnouncementInfo) -> crate::ln::features::NodeFeatures {
@ -824,6 +802,24 @@ pub extern "C" fn NodeAnnouncementInfo_new(mut features_arg: crate::ln::features
announcement_message: local_announcement_message_arg,
})), is_owned: true }
}
impl Clone for NodeAnnouncementInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 NodeAnnouncementInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeAnnouncementInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn NodeAnnouncementInfo_clone(orig: &NodeAnnouncementInfo) -> NodeAnnouncementInfo {
orig.clone()
}
#[no_mangle]
pub extern "C" fn NodeAnnouncementInfo_write(obj: &NodeAnnouncementInfo) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
@ -876,24 +872,6 @@ impl NodeInfo {
ret
}
}
impl Clone for NodeInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 NodeInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn NodeInfo_clone(orig: &NodeInfo) -> NodeInfo {
orig.clone()
}
/// All valid channels a node has announced
#[no_mangle]
pub extern "C" fn NodeInfo_set_channels(this_ptr: &mut NodeInfo, mut val: crate::c_types::derived::CVec_u64Z) {
@ -946,6 +924,24 @@ pub extern "C" fn NodeInfo_new(mut channels_arg: crate::c_types::derived::CVec_u
announcement_info: local_announcement_info_arg,
})), is_owned: true }
}
impl Clone for NodeInfo {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 NodeInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeInfo)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn NodeInfo_clone(orig: &NodeInfo) -> NodeInfo {
orig.clone()
}
#[no_mangle]
pub extern "C" fn NodeInfo_write(obj: &NodeInfo) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })

View file

@ -45,24 +45,6 @@ impl RouteHop {
ret
}
}
impl Clone for RouteHop {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RouteHop_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHop)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RouteHop_clone(orig: &RouteHop) -> RouteHop {
orig.clone()
}
/// The node_id of the node at this hop.
#[no_mangle]
pub extern "C" fn RouteHop_get_pubkey(this_ptr: &RouteHop) -> crate::c_types::PublicKey {
@ -147,6 +129,24 @@ pub extern "C" fn RouteHop_new(mut pubkey_arg: crate::c_types::PublicKey, mut no
cltv_expiry_delta: cltv_expiry_delta_arg,
})), is_owned: true }
}
impl Clone for RouteHop {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RouteHop_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHop)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RouteHop_clone(orig: &RouteHop) -> RouteHop {
orig.clone()
}
use lightning::routing::router::Route as nativeRouteImport;
type nativeRoute = nativeRouteImport;
@ -186,24 +186,6 @@ impl Route {
ret
}
}
impl Clone for Route {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 Route_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoute)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn Route_clone(orig: &Route) -> Route {
orig.clone()
}
/// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
/// last RouteHop in each path must be the same.
/// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
@ -223,6 +205,24 @@ pub extern "C" fn Route_new(mut paths_arg: crate::c_types::derived::CVec_CVec_Ro
paths: local_paths_arg,
})), is_owned: true }
}
impl Clone for Route {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 Route_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoute)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn Route_clone(orig: &Route) -> Route {
orig.clone()
}
#[no_mangle]
pub extern "C" fn Route_write(obj: &Route) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
@ -275,24 +275,6 @@ impl RouteHint {
ret
}
}
impl Clone for RouteHint {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RouteHint_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHint)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint {
orig.clone()
}
/// The node_id of the non-target end of the route
#[no_mangle]
pub extern "C" fn RouteHint_get_src_node_id(this_ptr: &RouteHint) -> crate::c_types::PublicKey {
@ -359,6 +341,24 @@ pub extern "C" fn RouteHint_new(mut src_node_id_arg: crate::c_types::PublicKey,
htlc_minimum_msat: htlc_minimum_msat_arg,
})), is_owned: true }
}
impl Clone for RouteHint {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 RouteHint_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHint)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint {
orig.clone()
}
/// Gets a route from us to the given target node.
///
/// Extra routing hops between known nodes and the target will be used if they are included in

View file

@ -45,24 +45,6 @@ impl ChannelHandshakeConfig {
ret
}
}
impl Clone for ChannelHandshakeConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelHandshakeConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelHandshakeConfig_clone(orig: &ChannelHandshakeConfig) -> ChannelHandshakeConfig {
orig.clone()
}
/// Confirmations we will wait for before considering the channel locked in.
/// Applied only for inbound channels (see ChannelHandshakeLimits::max_minimum_depth for the
/// equivalent limit applied to outbound channels).
@ -147,6 +129,24 @@ pub extern "C" fn ChannelHandshakeConfig_new(mut minimum_depth_arg: u32, mut our
our_htlc_minimum_msat: our_htlc_minimum_msat_arg,
})), is_owned: true }
}
impl Clone for ChannelHandshakeConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelHandshakeConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelHandshakeConfig_clone(orig: &ChannelHandshakeConfig) -> ChannelHandshakeConfig {
orig.clone()
}
#[must_use]
#[no_mangle]
pub extern "C" fn ChannelHandshakeConfig_default() -> ChannelHandshakeConfig {
@ -200,24 +200,6 @@ impl ChannelHandshakeLimits {
ret
}
}
impl Clone for ChannelHandshakeLimits {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelHandshakeLimits_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeLimits)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelHandshakeLimits_clone(orig: &ChannelHandshakeLimits) -> ChannelHandshakeLimits {
orig.clone()
}
/// Minimum allowed satoshis when a channel is funded, this is supplied by the sender and so
/// only applies to inbound channels.
///
@ -430,6 +412,24 @@ pub extern "C" fn ChannelHandshakeLimits_new(mut min_funding_satoshis_arg: u64,
their_to_self_delay: their_to_self_delay_arg,
})), is_owned: true }
}
impl Clone for ChannelHandshakeLimits {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelHandshakeLimits_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeLimits)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelHandshakeLimits_clone(orig: &ChannelHandshakeLimits) -> ChannelHandshakeLimits {
orig.clone()
}
#[must_use]
#[no_mangle]
pub extern "C" fn ChannelHandshakeLimits_default() -> ChannelHandshakeLimits {
@ -474,24 +474,6 @@ impl ChannelConfig {
ret
}
}
impl Clone for ChannelConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelConfig_clone(orig: &ChannelConfig) -> ChannelConfig {
orig.clone()
}
/// Amount (in millionths of a satoshi) the channel will charge per transferred satoshi.
/// This may be allowed to change at runtime in a later update, however doing so must result in
/// update messages sent to notify all nodes of our updated relay fee.
@ -582,6 +564,24 @@ pub extern "C" fn ChannelConfig_new(mut fee_proportional_millionths_arg: u32, mu
commit_upfront_shutdown_pubkey: commit_upfront_shutdown_pubkey_arg,
})), is_owned: true }
}
impl Clone for ChannelConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 ChannelConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn ChannelConfig_clone(orig: &ChannelConfig) -> ChannelConfig {
orig.clone()
}
#[must_use]
#[no_mangle]
pub extern "C" fn ChannelConfig_default() -> ChannelConfig {
@ -589,19 +589,17 @@ pub extern "C" fn ChannelConfig_default() -> ChannelConfig {
}
#[no_mangle]
pub extern "C" fn ChannelConfig_write(obj: &ChannelConfig) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
pub(crate) extern "C" fn ChannelConfig_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelConfig) })
}
#[no_mangle]
pub extern "C" fn ChannelConfig_read(ser: crate::c_types::u8slice) -> ChannelConfig {
if let Ok(res) = crate::c_types::deserialize_obj(ser) {
ChannelConfig { inner: Box::into_raw(Box::new(res)), is_owned: true }
} else {
ChannelConfig { inner: std::ptr::null_mut(), is_owned: true }
}
pub extern "C" fn ChannelConfig_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelConfigDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::util::config::ChannelConfig { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
use lightning::util::config::UserConfig as nativeUserConfigImport;
@ -644,24 +642,6 @@ impl UserConfig {
ret
}
}
impl Clone for UserConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 UserConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUserConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn UserConfig_clone(orig: &UserConfig) -> UserConfig {
orig.clone()
}
/// Channel config that we propose to our counterparty.
#[no_mangle]
pub extern "C" fn UserConfig_get_own_channel_config(this_ptr: &UserConfig) -> crate::util::config::ChannelHandshakeConfig {
@ -704,6 +684,24 @@ pub extern "C" fn UserConfig_new(mut own_channel_config_arg: crate::util::config
channel_options: *unsafe { Box::from_raw(channel_options_arg.take_inner()) },
})), is_owned: true }
}
impl Clone for UserConfig {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
Box::into_raw(Box::new(unsafe { &*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 UserConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUserConfig)).clone() })) as *mut c_void
}
#[no_mangle]
pub extern "C" fn UserConfig_clone(orig: &UserConfig) -> UserConfig {
orig.clone()
}
#[must_use]
#[no_mangle]
pub extern "C" fn UserConfig_default() -> UserConfig {

View file

@ -26,7 +26,6 @@
//! [`Context`]: sealed/trait.Context.html
use std::{cmp, fmt};
use std::result::Result;
use std::marker::PhantomData;
use ln::msgs::DecodeError;
@ -352,7 +351,7 @@ impl InitFeatures {
impl<T: sealed::Context> Features<T> {
/// Create a blank Features with no features set
pub fn empty() -> Features<T> {
pub fn empty() -> Self {
Features {
flags: Vec::new(),
mark: PhantomData,
@ -362,7 +361,7 @@ impl<T: sealed::Context> Features<T> {
/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
///
/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
pub fn known() -> Features<T> {
pub fn known() -> Self {
Self {
flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
mark: PhantomData,