hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
90d7cbee976d0d1dcbcec069bcb6eb627da1eb9f
23,079
#![feature(box_patterns)] #![feature(box_syntax)] #![feature(crate_visibility_modifier)] #![feature(const_panic)] #![feature(in_band_lifetimes)] #![feature(iter_zip)] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(option_get_or_insert_default)] #![feature(once_cell)] #![feature(never_type)] #![feature(trusted_step)] #![feature(try_blocks)] #![recursion_limit = "256"] #[macro_use] extern crate tracing; #[macro_use] extern crate rustc_middle; use required_consts::RequiredConstsVisitor; use rustc_const_eval::util; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::steal::Steal; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_index::vec::IndexVec; use rustc_middle::mir::visit::Visitor as _; use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, TyCtxt, TypeFoldable}; use rustc_span::{Span, Symbol}; mod abort_unwinding_calls; mod add_call_guards; mod add_moves_for_packed_drops; mod add_retag; mod check_const_item_mutation; mod check_packed_ref; pub mod check_unsafety; mod cleanup_post_borrowck; mod const_debuginfo; mod const_goto; mod const_prop; mod coverage; mod deaggregator; mod deduplicate_blocks; mod dest_prop; pub mod dump_mir; mod early_otherwise_branch; mod elaborate_drops; mod function_item_references; mod generator; mod inline; mod instcombine; mod lower_intrinsics; mod lower_slice_len; mod match_branches; mod multiple_return_terminators; mod nrvo; mod remove_noop_landing_pads; mod remove_storage_markers; mod remove_unneeded_drops; mod remove_zsts; mod required_consts; mod separate_const_switch; mod shim; mod simplify; mod simplify_branches; mod simplify_comparison_integral; mod simplify_try; mod uninhabited_enum_branching; mod unreachable_prop; use rustc_const_eval::transform::check_consts; use rustc_const_eval::transform::promote_consts; use rustc_const_eval::transform::validate; use rustc_const_eval::transform::MirPass; use rustc_mir_dataflow::rustc_peek; pub fn provide(providers: &mut Providers) { check_unsafety::provide(providers); check_packed_ref::provide(providers); coverage::query::provide(providers); shim::provide(providers); *providers = Providers { mir_keys, mir_const, mir_const_qualif: |tcx, def_id| { let def_id = def_id.expect_local(); if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) { tcx.mir_const_qualif_const_arg(def) } else { mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id)) } }, mir_const_qualif_const_arg: |tcx, (did, param_did)| { mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }) }, mir_promoted, mir_drops_elaborated_and_const_checked, mir_for_ctfe, mir_for_ctfe_of_const_arg, optimized_mir, is_mir_available, is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did), mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable, mir_inliner_callees: inline::cycle::mir_inliner_callees, promoted_mir: |tcx, def_id| { let def_id = def_id.expect_local(); if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) { tcx.promoted_mir_of_const_arg(def) } else { promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id)) } }, promoted_mir_of_const_arg: |tcx, (did, param_did)| { promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }) }, ..*providers }; } fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool { let def_id = def_id.expect_local(); tcx.mir_keys(()).contains(&def_id) } /// Finds the full set of `DefId`s within the current crate that have /// MIR associated with them. fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> { let mut set = FxHashSet::default(); // All body-owners have MIR associated with them. set.extend(tcx.body_owners()); // Additionally, tuple struct/variant constructors have MIR, but // they don't have a BodyId, so we need to build them separately. struct GatherCtors<'a, 'tcx> { tcx: TyCtxt<'tcx>, set: &'a mut FxHashSet<LocalDefId>, } impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> { fn visit_variant_data( &mut self, v: &'tcx hir::VariantData<'tcx>, _: Symbol, _: &'tcx hir::Generics<'tcx>, _: hir::HirId, _: Span, ) { if let hir::VariantData::Tuple(_, hir_id) = *v { self.set.insert(self.tcx.hir().local_def_id(hir_id)); } intravisit::walk_struct_def(self, v) } type Map = intravisit::ErasedMap<'tcx>; fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::None } } tcx.hir() .krate() .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor()); set } fn run_passes( tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, mir_phase: MirPhase, passes: &[&[&dyn MirPass<'tcx>]], ) { let phase_index = mir_phase.phase_index(); let validate = tcx.sess.opts.debugging_opts.validate_mir; if body.phase >= mir_phase { return; } if validate { validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase } .run_pass(tcx, body); } let mut index = 0; let mut run_pass = |pass: &dyn MirPass<'tcx>| { let run_hooks = |body: &_, index, is_after| { dump_mir::on_mir_pass( tcx, &format_args!("{:03}-{:03}", phase_index, index), &pass.name(), body, is_after, ); }; run_hooks(body, index, false); pass.run_pass(tcx, body); run_hooks(body, index, true); if validate { validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase), mir_phase, } .run_pass(tcx, body); } index += 1; }; for pass_group in passes { for pass in *pass_group { run_pass(*pass); } } body.phase = mir_phase; if mir_phase == MirPhase::Optimization { validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase } .run_pass(tcx, body); } } fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs { let const_kind = tcx.hir().body_const_context(def.did); // No need to const-check a non-const `fn`. if const_kind.is_none() { return Default::default(); } // N.B., this `borrow()` is guaranteed to be valid (i.e., the value // cannot yet be stolen), because `mir_promoted()`, which steals // from `mir_const(), forces this query to execute before // performing the steal. let body = &tcx.mir_const(def).borrow(); if body.return_ty().references_error() { tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors"); return Default::default(); } let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) }; let mut validator = check_consts::check::Checker::new(&ccx); validator.check_body(); // We return the qualifs in the return place for every MIR body, even though it is only used // when deciding to promote a reference to a `const` for now. validator.qualifs_in_return_place() } /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts! fn mir_const<'tcx>( tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>, ) -> &'tcx Steal<Body<'tcx>> { if let Some(def) = def.try_upgrade(tcx) { return tcx.mir_const(def); } // Unsafety check uses the raw mir, so make sure it is run. if !tcx.sess.opts.debugging_opts.thir_unsafeck { if let Some(param_did) = def.const_param_did { tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did)); } else { tcx.ensure().unsafety_check_result(def.did); } } let mut body = tcx.mir_built(def).steal(); rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(())); run_passes( tcx, &mut body, MirPhase::Const, &[&[ // MIR-level lints. &check_packed_ref::CheckPackedRef, &check_const_item_mutation::CheckConstItemMutation, &function_item_references::FunctionItemReferences, // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, ]], ); tcx.alloc_steal_mir(body) } /// Compute the main MIR body and the list of MIR bodies of the promoteds. fn mir_promoted( tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>, ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) { if let Some(def) = def.try_upgrade(tcx) { return tcx.mir_promoted(def); } // Ensure that we compute the `mir_const_qualif` for constants at // this point, before we steal the mir-const result. // Also this means promotion can rely on all const checks having been done. let _ = tcx.mir_const_qualif_opt_const_arg(def); let mut body = tcx.mir_const(def).steal(); let mut required_consts = Vec::new(); let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts); for (bb, bb_data) in traversal::reverse_postorder(&body) { required_consts_visitor.visit_basic_block_data(bb, bb_data); } body.required_consts = required_consts; let promote_pass = promote_consts::PromoteTemps::default(); let promote: &[&dyn MirPass<'tcx>] = &[ // What we need to run borrowck etc. &promote_pass, &simplify::SimplifyCfg::new("promote-consts"), ]; let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] }; run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]); let promoted = promote_pass.promoted_fragments.into_inner(); (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted)) } /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it) fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> { let did = def_id.expect_local(); if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { tcx.mir_for_ctfe_of_const_arg(def) } else { tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did))) } } /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter. /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck /// the const parameter while type checking the main body, which in turn would try /// to type check the main body again. fn mir_for_ctfe_of_const_arg<'tcx>( tcx: TyCtxt<'tcx>, (did, param_did): (LocalDefId, DefId), ) -> &'tcx Body<'tcx> { tcx.arena.alloc(inner_mir_for_ctfe( tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }, )) } fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> { // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries if tcx.is_constructor(def.did.to_def_id()) { // There's no reason to run all of the MIR passes on constructors when // we can just output the MIR we want directly. This also saves const // qualification and borrow checking the trouble of special casing // constructors. return shim::build_adt_ctor(tcx, def.did.to_def_id()); } let context = tcx .hir() .body_const_context(def.did) .expect("mir_for_ctfe should not be used for runtime functions"); let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone(); match context { // Do not const prop functions, either they get executed at runtime or exported to metadata, // so we run const prop on them, or they don't, in which case we const evaluate some control // flow paths of the function and any errors in those paths will get emitted as const eval // errors. hir::ConstContext::ConstFn => {} // Static items always get evaluated, so we can just let const eval see if any erroneous // control flow paths get executed. hir::ConstContext::Static(_) => {} // Associated constants get const prop run so we detect common failure situations in the // crate that defined the constant. // Technically we want to not run on regular const items, but oli-obk doesn't know how to // conveniently detect that at this point without looking at the HIR. hir::ConstContext::Const => { #[rustfmt::skip] let optimizations: &[&dyn MirPass<'_>] = &[ &const_prop::ConstProp, ]; #[rustfmt::skip] run_passes( tcx, &mut body, MirPhase::Optimization, &[ optimizations, ], ); } } debug_assert!(!body.has_free_regions(tcx), "Free regions in MIR for CTFE"); body } /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't /// end up missing the source MIR due to stealing happening. fn mir_drops_elaborated_and_const_checked<'tcx>( tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>, ) -> &'tcx Steal<Body<'tcx>> { if let Some(def) = def.try_upgrade(tcx) { return tcx.mir_drops_elaborated_and_const_checked(def); } // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to // execute before we can steal. if let Some(param_did) = def.const_param_did { tcx.ensure().mir_borrowck_const_arg((def.did, param_did)); } else { tcx.ensure().mir_borrowck(def.did); } let hir_id = tcx.hir().local_def_id_to_hir_id(def.did); use rustc_middle::hir::map::blocks::FnLikeNode; let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some(); if is_fn_like { let did = def.did.to_def_id(); let def = ty::WithOptConstParam::unknown(did); // Do not compute the mir call graph without said call graph actually being used. if inline::is_enabled(tcx) { let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def)); } } let (body, _) = tcx.mir_promoted(def); let mut body = body.steal(); run_post_borrowck_cleanup_passes(tcx, &mut body); check_consts::post_drop_elaboration::check_live_drops(tcx, &body); tcx.alloc_steal_mir(body) } /// After this series of passes, no lifetime analysis based on borrowing can be done. fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { debug!("post_borrowck_cleanup({:?})", body.source.def_id()); let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[ // Remove all things only needed by analysis &simplify_branches::SimplifyBranches::new("initial"), &remove_noop_landing_pads::RemoveNoopLandingPads, &cleanup_post_borrowck::CleanupNonCodegenStatements, &simplify::SimplifyCfg::new("early-opt"), // These next passes must be executed together &add_call_guards::CriticalCallEdges, &elaborate_drops::ElaborateDrops, // This will remove extraneous landing pads which are no longer // necessary as well as well as forcing any call in a non-unwinding // function calling a possibly-unwinding function to abort the process. &abort_unwinding_calls::AbortUnwindingCalls, // AddMovesForPackedDrops needs to run after drop // elaboration. &add_moves_for_packed_drops::AddMovesForPackedDrops, // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late, // but before optimizations begin. &add_retag::AddRetag, &lower_intrinsics::LowerIntrinsics, &simplify::SimplifyCfg::new("elaborate-drops"), // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening // and it can help optimizations. &deaggregator::Deaggregator, ]; run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]); } fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let mir_opt_level = tcx.sess.mir_opt_level(); // Lowering generator control-flow and variables has to happen before we do anything else // to them. We run some optimizations before that, because they may be harder to do on the state // machine than on MIR with async primitives. let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[ &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first &unreachable_prop::UnreachablePropagation, &uninhabited_enum_branching::UninhabitedEnumBranching, &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"), &inline::Inline, &generator::StateTransform, ]; // Even if we don't do optimizations, we still have to lower generators for codegen. let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform]; // The main optimizations that we do on MIR. let optimizations: &[&dyn MirPass<'tcx>] = &[ &remove_storage_markers::RemoveStorageMarkers, &remove_zsts::RemoveZsts, &const_goto::ConstGoto, &remove_unneeded_drops::RemoveUnneededDrops, &match_branches::MatchBranchSimplification, // inst combine is after MatchBranchSimplification to clean up Ne(_1, false) &multiple_return_terminators::MultipleReturnTerminators, &instcombine::InstCombine, &separate_const_switch::SeparateConstSwitch, &const_prop::ConstProp, &simplify_branches::SimplifyBranches::new("after-const-prop"), &early_otherwise_branch::EarlyOtherwiseBranch, &simplify_comparison_integral::SimplifyComparisonIntegral, &simplify_try::SimplifyArmIdentity, &simplify_try::SimplifyBranchSame, &dest_prop::DestinationPropagation, &simplify_branches::SimplifyBranches::new("final"), &remove_noop_landing_pads::RemoveNoopLandingPads, &simplify::SimplifyCfg::new("final"), &nrvo::RenameReturnPlace, &const_debuginfo::ConstDebugInfo, &simplify::SimplifyLocals, &multiple_return_terminators::MultipleReturnTerminators, &deduplicate_blocks::DeduplicateBlocks, ]; // Optimizations to run even if mir optimizations have been disabled. let no_optimizations: &[&dyn MirPass<'tcx>] = &[ // FIXME(#70073): This pass is responsible for both optimization as well as some lints. &const_prop::ConstProp, ]; // Some cleanup necessary at least for LLVM and potentially other codegen backends. let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[ &add_call_guards::CriticalCallEdges, // Dump the end result for testing and debugging purposes. &dump_mir::Marker("PreCodegen"), ]; // End of pass declarations, now actually run the passes. // Generator Lowering #[rustfmt::skip] run_passes( tcx, body, MirPhase::GeneratorLowering, &[ if mir_opt_level > 0 { optimizations_with_generators } else { no_optimizations_with_generators } ], ); // Main optimization passes #[rustfmt::skip] run_passes( tcx, body, MirPhase::Optimization, &[ if mir_opt_level > 0 { optimizations } else { no_optimizations }, pre_codegen_cleanup, ], ); } /// Optimize the MIR and prepare it for codegen. fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> { let did = did.expect_local(); assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None); tcx.arena.alloc(inner_optimized_mir(tcx, did)) } fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { if tcx.is_constructor(did.to_def_id()) { // There's no reason to run all of the MIR passes on constructors when // we can just output the MIR we want directly. This also saves const // qualification and borrow checking the trouble of special casing // constructors. return shim::build_adt_ctor(tcx, did.to_def_id()); } match tcx.hir().body_const_context(did) { // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked` // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it // computes and caches its result. Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did), None => {} Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other), } let mut body = tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal(); run_optimization_passes(tcx, &mut body); debug_assert!(!body.has_free_regions(tcx), "Free regions in optimized MIR"); body } /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for /// constant evaluation once all substitutions become known. fn promoted_mir<'tcx>( tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>, ) -> &'tcx IndexVec<Promoted, Body<'tcx>> { if tcx.is_constructor(def.did.to_def_id()) { return tcx.arena.alloc(IndexVec::new()); } if let Some(param_did) = def.const_param_did { tcx.ensure().mir_borrowck_const_arg((def.did, param_did)); } else { tcx.ensure().mir_borrowck(def.did); } let (_, promoted) = tcx.mir_promoted(def); let mut promoted = promoted.steal(); for body in &mut promoted { run_post_borrowck_cleanup_passes(tcx, body); } debug_assert!(!promoted.has_free_regions(tcx), "Free regions in promoted MIR"); tcx.arena.alloc(promoted) }
36.517405
167
0.655228
6194b3396ab597fef54a16fd3a42e61fabea1b19
2,365
#![feature(test)] extern crate test; use test::Bencher; extern crate terminus_spaceport; use rand::Rng; use std::ops::Deref; use terminus_spaceport::memory::region::*; use terminus_spaceport::space::Space; #[cfg(feature = "memprof")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; const MAX_RND: usize = 1000000; #[bench] fn bench_model_access(b: &mut Bencher) { let region = GHEAP.alloc(0x1_0000_0000, 1).unwrap(); let mut rng = rand::thread_rng(); let mut addrs = vec![]; for _ in 0..MAX_RND { addrs.push((rng.gen::<u64>() % 0x1_0000_0000 >> 3) << 3) } let mut i = 0; let mut get_addr = || { let data = addrs.get(i).unwrap(); if i == MAX_RND - 1 { i = 0 } else { i = i + 1 } data }; b.iter(|| { U64Access::write(region.deref(), get_addr(), 0xaa); U64Access::read(region.deref(), get_addr()); }); #[cfg(feature = "memprof")] unsafe { jemalloc_sys::malloc_stats_print(None, null_mut(), null()) }; } #[bench] fn bench_space_access(b: &mut Bencher) { let region = GHEAP.alloc(0x1_0000_0000, 1).unwrap(); let region2 = GHEAP.lazy_alloc(0x000c0000, 1).unwrap(); let region3 = GHEAP.lazy_alloc(0x0001000, 1).unwrap(); let mut space = Space::new(); space .add_region("memory", &Region::remap(0x8000_0000, &region)) .unwrap(); space .add_region("memory2", &Region::remap(0x200_0000, &region2)) .unwrap(); space .add_region("memory3", &Region::remap(0x2000_0000, &region3)) .unwrap(); let mut rng = rand::thread_rng(); let mut addrs = vec![]; for _ in 0..MAX_RND { addrs.push(0x8000_0000 + ((rng.gen::<u64>() % 0x1_0000_0000 >> 3) << 3)) } let mut i = 0; let mut get_addr = || { let data = addrs.get(i).unwrap(); if i == MAX_RND - 1 { i = 0 } else { i = i + 1 } data }; b.iter(|| { space .write_bytes(get_addr(), &0xaau64.to_le_bytes()) .unwrap(); let mut data = [0u8; 8]; space.read_bytes(get_addr(), &mut data).unwrap(); }); #[cfg(feature = "memprof")] unsafe { jemalloc_sys::malloc_stats_print(None, null_mut(), null()) }; }
25.989011
80
0.556025
db77307cbd1ad108688bd0dd85ced811cd65abfd
814
// https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/ // Runtime: 0 ms // Memory Usage: 2.1 MB use std::collections::HashMap; pub fn longest_substring(s: String, k: i32) -> i32 { let mut hm: HashMap<char, usize> = HashMap::new(); for c in s.chars() { *hm.entry(c).or_default() += 1; } for (c, v) in hm { if v < k as usize { return s .split_terminator(c) .map(|s| longest_substring(s.to_string(), k)) .max() .unwrap(); } } s.len() as i32 } #[test] fn test395() { assert_eq!(longest_substring("aaabb".to_string(), 3), 3); assert_eq!(longest_substring("ababbc".to_string(), 2), 5); assert_eq!(longest_substring("ababbc".to_string(), 3), 0); }
30.148148
91
0.562654
1e50fee488f7c330e4a0f9b30665ce65bcb00390
4,370
use std::collections::{HashMap, VecDeque}; use days::day10::part2::parse as knot_hash; #[derive(Debug, Clone)] enum Cell { Unknown, Empty, Region(usize), } fn to_bits(byte: u32) -> Vec<bool> { let byte = byte.to_le(); (0..4) .map(|n| byte & (1 << n) != 0) .rev() // TODO: Not fair .collect::<Vec<_>>() } pub fn parse(input: &str) -> usize { let mut grid: HashMap<(usize, usize), Cell> = HashMap::with_capacity(128 * 128); let iter = (0..128) .map(|line| knot_hash(&format!("{}-{}", input, line))) .map(|hash| { hash.chars() .map(|chr| chr.to_digit(16).unwrap()) .flat_map(to_bits) .map(|bit| { if bit { Cell::Unknown } else { Cell::Empty } }) .enumerate() .collect::<Vec<_>>() }) .enumerate(); // TODO: Can I generate an `grid` from the iterator directly? for (y, row) in iter { for &(x, ref cell) in row.iter() { grid.insert((x, y), (*cell).clone()); } } let mut regions = 0usize; // TODO: I got tired fighting with a borrow checker let keys = grid.keys().map(|&(x, y)| (x, y)).collect::<Vec<_>>(); for &(x, y) in keys.iter() { match grid.get(&(x, y)).unwrap() { &Cell::Empty => continue, &Cell::Region(_) => continue, &Cell::Unknown => { println!("{}x{}", x, y); let mut current_region: Vec<(usize, usize)> = vec![]; let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); queue.push_back((x, y)); loop { if let Some((x, y)) = queue.pop_front() { if x > 127 || y > 127 { continue; } if current_region.contains(&(x, y)) { continue; } match grid.get(&(x, y)) { Some(&Cell::Unknown) => { current_region.push((x, y)); println!("Got {}x{}", x, y); if let Some(top_y) = y.checked_sub(1) { queue.push_back((x, top_y)); } if let Some(right_x) = x.checked_add(1) { queue.push_back((right_x, y)); } if let Some(bottom_y) = y.checked_add(1) { queue.push_back((x, bottom_y)); } if let Some(left_x) = x.checked_sub(1) { queue.push_back((left_x, y)); } }, _ => {} } } else { println!("Queue empty"); break; } } if current_region.len() > 0 { println!("Got a new region #{} with {} elements", regions, current_region.len()); for key in current_region.iter() { let entry = grid.entry(*key).or_insert(Cell::Unknown); *entry = Cell::Region(regions); } regions += 1; } } } } println!("\n\n"); for x in 0..128usize { for y in 0..128usize { match grid.get(&(x, y)) { Some(&Cell::Unknown) => print!("?"), Some(&Cell::Region(region)) => { let repr = format!("{}", region); print!("{}", repr.chars().last().unwrap()); }, _ => print!("."), } } println!(""); } println!("\n\n"); regions } #[cfg(test)] mod tests { use super::parse; #[test] fn day14_part2_test1() { let input = "flqrgnkx"; assert_eq!(1242, parse(input)); } }
29.328859
101
0.36659
b9ac5e3c3559fef73436328f1284d52dc5afe937
91
fn main() { let a: int = 0; let a: int = 1; //! ERROR(3:9): cannot redeclare `a` }
22.75
57
0.494505
16721bb26234e29c17878921ebdbfadd373c6eb0
11,324
use crate::{ config::Config, de::{BorrowDecode, BorrowDecoder, Decode}, error::DecodeError, }; use core::marker::PhantomData; use serde_incl::de::*; /// Decode a borrowed type from the given slice. Some parts of the decoded type are expected to be referring to the given slice pub fn decode_borrowed_from_slice<'de, T, C>(slice: &'de [u8], config: C) -> Result<T, DecodeError> where T: Deserialize<'de>, C: Config, { let reader = crate::de::read::SliceReader::new(slice); let mut decoder = crate::de::DecoderImpl::new(reader, config); let serde_decoder = SerdeDecoder { de: &mut decoder, pd: PhantomData, }; T::deserialize(serde_decoder) } pub(super) struct SerdeDecoder<'a, 'de, DE: BorrowDecoder<'de>> { pub(super) de: &'a mut DE, pub(super) pd: PhantomData<&'de ()>, } impl<'a, 'de, DE: BorrowDecoder<'de>> Deserializer<'de> for SerdeDecoder<'a, 'de, DE> { type Error = DecodeError; fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { Err(DecodeError::SerdeAnyNotSupported) } fn deserialize_bool<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_bool(Decode::decode(&mut self.de)?) } fn deserialize_i8<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_i8(Decode::decode(&mut self.de)?) } fn deserialize_i16<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_i16(Decode::decode(&mut self.de)?) } fn deserialize_i32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_i32(Decode::decode(&mut self.de)?) } fn deserialize_i64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_i64(Decode::decode(&mut self.de)?) } fn deserialize_u8<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_u8(Decode::decode(&mut self.de)?) } fn deserialize_u16<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_u16(Decode::decode(&mut self.de)?) } fn deserialize_u32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_u32(Decode::decode(&mut self.de)?) } fn deserialize_u64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_u64(Decode::decode(&mut self.de)?) } fn deserialize_f32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_f32(Decode::decode(&mut self.de)?) } fn deserialize_f64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_f64(Decode::decode(&mut self.de)?) } fn deserialize_char<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_char(Decode::decode(&mut self.de)?) } fn deserialize_str<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { let str = <&'de str>::borrow_decode(&mut self.de)?; visitor.visit_borrowed_str(str) } fn deserialize_string<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_string(Decode::decode(&mut self.de)?) } fn deserialize_bytes<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { let bytes = <&'de [u8]>::borrow_decode(&mut self.de)?; visitor.visit_borrowed_bytes(bytes) } fn deserialize_byte_buf<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_byte_buf(Decode::decode(&mut self.de)?) } fn deserialize_option<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { let variant = crate::de::decode_option_variant(&mut self.de, "Option<T>")?; if variant.is_some() { visitor.visit_some(self) } else { visitor.visit_none() } } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { let len = u32::decode(&mut self.de)?; self.deserialize_tuple(len as usize, visitor) } fn deserialize_tuple<V>(mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> { deserializer: &'a mut SerdeDecoder<'b, 'de, DE>, len: usize, } impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> SeqAccess<'de> for Access<'a, 'b, 'de, DE> { type Error = DecodeError; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DecodeError> where T: DeserializeSeed<'de>, { if self.len > 0 { self.len -= 1; let value = DeserializeSeed::deserialize( seed, SerdeDecoder { de: self.deserializer.de, pd: PhantomData, }, )?; Ok(Some(value)) } else { Ok(None) } } fn size_hint(&self) -> Option<usize> { Some(self.len) } } visitor.visit_seq(Access { deserializer: &mut self, len, }) } fn deserialize_tuple_struct<V>( self, _name: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { self.deserialize_tuple(len, visitor) } fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> { deserializer: &'a mut SerdeDecoder<'b, 'de, DE>, len: usize, } impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> MapAccess<'de> for Access<'a, 'b, 'de, DE> { type Error = DecodeError; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, DecodeError> where K: DeserializeSeed<'de>, { if self.len > 0 { self.len -= 1; let key = DeserializeSeed::deserialize( seed, SerdeDecoder { de: self.deserializer.de, pd: PhantomData, }, )?; Ok(Some(key)) } else { Ok(None) } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, DecodeError> where V: DeserializeSeed<'de>, { let value = DeserializeSeed::deserialize( seed, SerdeDecoder { de: self.deserializer.de, pd: PhantomData, }, )?; Ok(value) } fn size_hint(&self) -> Option<usize> { Some(self.len) } } let len = usize::decode(&mut self.de)?; visitor.visit_map(Access { deserializer: &mut self, len, }) } fn deserialize_struct<V>( self, _name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { self.deserialize_tuple(fields.len(), visitor) } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { visitor.visit_enum(self) } fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { Err(DecodeError::SerdeIdentifierNotSupported) } fn deserialize_ignored_any<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde_incl::de::Visitor<'de>, { Err(DecodeError::SerdeIgnoredAnyNotSupported) } } impl<'de, 'a, DE: BorrowDecoder<'de>> EnumAccess<'de> for SerdeDecoder<'a, 'de, DE> { type Error = DecodeError; type Variant = Self; fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'de>, { let idx = u32::decode(&mut self.de)?; let val = seed.deserialize(idx.into_deserializer())?; Ok((val, self)) } } impl<'de, 'a, DE: BorrowDecoder<'de>> VariantAccess<'de> for SerdeDecoder<'a, 'de, DE> { type Error = DecodeError; fn unit_variant(self) -> Result<(), Self::Error> { Ok(()) } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de>, { DeserializeSeed::deserialize(seed, self) } fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Deserializer::deserialize_tuple(self, len, visitor) } fn struct_variant<V>( self, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Deserializer::deserialize_tuple(self, fields.len(), visitor) } }
28.380952
127
0.530201
9c58a958b07395eb1c83e4d73bd6d8597825340f
444
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. #![feature(box_patterns)] // TODO remove following allows. #![allow(dead_code)] #![allow(unused_imports)] #[macro_use] extern crate slog_global; #[macro_use] extern crate failure; mod delegate; mod endpoint; mod errors; mod observer; mod service; pub use endpoint::{Endpoint, Task}; pub use errors::{Error, Result}; pub use observer::CdcObserver; pub use service::Service;
19.304348
66
0.75
ed23837ce48cb67ba42f40976f44a15d1ae2e0fd
9,718
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Appliance { #[serde(flatten)] pub generic_resource: GenericResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ApplianceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<Plan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppliancePatchable { #[serde(flatten)] pub generic_resource: GenericResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppliancePropertiesPatchable>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<PlanPatchable>, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceDefinition { #[serde(flatten)] pub generic_resource: GenericResource, pub properties: ApplianceDefinitionProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceProperties { #[serde(rename = "managedResourceGroupId")] pub managed_resource_group_id: String, #[serde(rename = "applianceDefinitionId", default, skip_serializing_if = "Option::is_none")] pub appliance_definition_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<serde_json::Value>, #[serde(skip_serializing)] pub outputs: Option<serde_json::Value>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<ProvisioningState>, #[serde(rename = "uiDefinitionUri", default, skip_serializing_if = "Option::is_none")] pub ui_definition_uri: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppliancePropertiesPatchable { #[serde(rename = "managedResourceGroupId", default, skip_serializing_if = "Option::is_none")] pub managed_resource_group_id: Option<String>, #[serde(rename = "applianceDefinitionId", default, skip_serializing_if = "Option::is_none")] pub appliance_definition_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<serde_json::Value>, #[serde(skip_serializing)] pub outputs: Option<serde_json::Value>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<ProvisioningState>, #[serde(rename = "uiDefinitionUri", default, skip_serializing_if = "Option::is_none")] pub ui_definition_uri: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceDefinitionProperties { #[serde(rename = "lockLevel")] pub lock_level: ApplianceLockLevel, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, pub authorizations: Vec<ApplianceProviderAuthorization>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub artifacts: Vec<ApplianceArtifact>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "packageFileUri")] pub package_file_uri: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Plan { pub name: String, pub publisher: String, pub product: String, #[serde(rename = "promotionCode", default, skip_serializing_if = "Option::is_none")] pub promotion_code: Option<String>, pub version: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlanPatchable { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub publisher: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(rename = "promotionCode", default, skip_serializing_if = "Option::is_none")] pub promotion_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenericResource { #[serde(flatten)] pub resource: Resource, #[serde(rename = "managedBy", default, skip_serializing_if = "Option::is_none")] pub managed_by: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<Identity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub family: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identity { #[serde(rename = "principalId", skip_serializing)] pub principal_id: Option<String>, #[serde(rename = "tenantId", skip_serializing)] pub tenant_id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<identity::Type>, } pub mod identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(skip_serializing)] pub id: Option<String>, #[serde(skip_serializing)] pub name: Option<String>, #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Appliance>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceDefinitionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ApplianceDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Accepted, Running, Ready, Creating, Created, Deleting, Deleted, Canceled, Failed, Succeeded, Updating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ApplianceLockLevel { CanNotDelete, ReadOnly, None, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ApplianceArtifactType { Template, Custom, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceArtifact { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub uri: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<ApplianceArtifactType>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplianceProviderAuthorization { #[serde(rename = "principalId")] pub principal_id: String, #[serde(rename = "roleDefinitionId")] pub role_definition_id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(rename = "httpStatus", default, skip_serializing_if = "Option::is_none")] pub http_status: Option<String>, #[serde(rename = "errorCode", default, skip_serializing_if = "Option::is_none")] pub error_code: Option<String>, #[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, }
39.99177
97
0.706936
7905074740b7941fc9471c4fb919908cb8147cc1
1,268
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use benchmarks::chain::ChainBencher; #[allow(deprecated)] use criterion::{criterion_group, criterion_main, Benchmark, Criterion}; #[allow(deprecated)] fn block_apply(c: &mut Criterion) { ::logger::init(); for i in &[10u64, 1000] { c.bench( "block_apply", Benchmark::new(format!("block_apply_{:?}", i), move |b| { let bencher = ChainBencher::new(Some(*i)); bencher.bench(b) }) .sample_size(10), ); } } #[allow(deprecated)] fn query_block(c: &mut Criterion) { ::logger::init(); for block_num in &[10u64, 1000u64] { let bencher = ChainBencher::new(Some(*block_num)); bencher.execute(); for i in &[100u64, 1000, 10000] { let id = format!("query_block_in({:?})_times({:?})", block_num, i,); let bencher_local = bencher.clone(); c.bench( "query_block", Benchmark::new(id, move |b| bencher_local.query_bench(b, *i)).sample_size(10), ); } } } criterion_group!(starcoin_chain_benches, block_apply, query_block); criterion_main!(starcoin_chain_benches);
29.488372
94
0.578864
29baf4e1ddb661c4a4a421e9c58e3b0a81e50afc
6,284
use std::fmt; use std::hash::Hash; use std::iter::FromIterator; use super::map::SsoHashMap; /// Small-storage-optimized implementation of a set. /// /// Stores elements in a small array up to a certain length /// and switches to `HashSet` when that length is exceeded. // // FIXME: Implements subset of HashSet API. // // Missing HashSet API: // all hasher-related // try_reserve // shrink_to (unstable) // drain_filter (unstable) // replace // get_or_insert/get_or_insert_owned/get_or_insert_with (unstable) // difference/symmetric_difference/intersection/union // is_disjoint/is_subset/is_superset // PartialEq/Eq (requires SsoHashMap implementation) // BitOr/BitAnd/BitXor/Sub #[derive(Clone)] pub struct SsoHashSet<T> { map: SsoHashMap<T, ()>, } /// Adapter function used ot return /// result if SsoHashMap functions into /// result SsoHashSet should return. #[inline(always)] fn entry_to_key<K, V>((k, _v): (K, V)) -> K { k } impl<T> SsoHashSet<T> { /// Creates an empty `SsoHashSet`. #[inline] pub fn new() -> Self { Self { map: SsoHashMap::new() } } /// Creates an empty `SsoHashSet` with the specified capacity. #[inline] pub fn with_capacity(cap: usize) -> Self { Self { map: SsoHashMap::with_capacity(cap) } } /// Clears the set, removing all values. #[inline] pub fn clear(&mut self) { self.map.clear() } /// Returns the number of elements the set can hold without reallocating. #[inline] pub fn capacity(&self) -> usize { self.map.capacity() } /// Returns the number of elements in the set. #[inline] pub fn len(&self) -> usize { self.map.len() } /// Returns `true` if the set contains no elements. #[inline] pub fn is_empty(&self) -> bool { self.map.is_empty() } /// An iterator visiting all elements in arbitrary order. /// The iterator element type is `&'a T`. #[inline] pub fn iter(&'a self) -> impl Iterator<Item = &'a T> { self.into_iter() } /// Clears the set, returning all elements in an iterator. #[inline] pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ { self.map.drain().map(entry_to_key) } } impl<T: Eq + Hash> SsoHashSet<T> { /// Reserves capacity for at least `additional` more elements to be inserted /// in the `SsoHashSet`. The collection may reserve more space to avoid /// frequent reallocations. #[inline] pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional) } /// Shrinks the capacity of the set as much as possible. It will drop /// down as much as possible while maintaining the internal rules /// and possibly leaving some space in accordance with the resize policy. #[inline] pub fn shrink_to_fit(&mut self) { self.map.shrink_to_fit() } /// Retains only the elements specified by the predicate. #[inline] pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool, { self.map.retain(|k, _v| f(k)) } /// Removes and returns the value in the set, if any, that is equal to the given one. #[inline] pub fn take(&mut self, value: &T) -> Option<T> { self.map.remove_entry(value).map(entry_to_key) } /// Returns a reference to the value in the set, if any, that is equal to the given value. #[inline] pub fn get(&self, value: &T) -> Option<&T> { self.map.get_key_value(value).map(entry_to_key) } /// Adds a value to the set. /// /// If the set did not have this value present, `true` is returned. /// /// If the set did have this value present, `false` is returned. #[inline] pub fn insert(&mut self, elem: T) -> bool { self.map.insert(elem, ()).is_none() } /// Removes a value from the set. Returns whether the value was /// present in the set. #[inline] pub fn remove(&mut self, value: &T) -> bool { self.map.remove(value).is_some() } /// Returns `true` if the set contains a value. #[inline] pub fn contains(&self, value: &T) -> bool { self.map.contains_key(value) } } impl<T: Eq + Hash> FromIterator<T> for SsoHashSet<T> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> SsoHashSet<T> { let mut set: SsoHashSet<T> = Default::default(); set.extend(iter); set } } impl<T> Default for SsoHashSet<T> { #[inline] fn default() -> Self { Self::new() } } impl<T: Eq + Hash> Extend<T> for SsoHashSet<T> { fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item = T>, { for val in iter.into_iter() { self.insert(val); } } #[inline] fn extend_one(&mut self, item: T) { self.insert(item); } #[inline] fn extend_reserve(&mut self, additional: usize) { self.map.extend_reserve(additional) } } impl<'a, T> Extend<&'a T> for SsoHashSet<T> where T: 'a + Eq + Hash + Copy, { #[inline] fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } #[inline] fn extend_one(&mut self, &item: &'a T) { self.insert(item); } #[inline] fn extend_reserve(&mut self, additional: usize) { Extend::<T>::extend_reserve(self, additional) } } impl<T> IntoIterator for SsoHashSet<T> { type IntoIter = std::iter::Map<<SsoHashMap<T, ()> as IntoIterator>::IntoIter, fn((T, ())) -> T>; type Item = <Self::IntoIter as Iterator>::Item; #[inline] fn into_iter(self) -> Self::IntoIter { self.map.into_iter().map(entry_to_key) } } impl<'a, T> IntoIterator for &'a SsoHashSet<T> { type IntoIter = std::iter::Map< <&'a SsoHashMap<T, ()> as IntoIterator>::IntoIter, fn((&'a T, &'a ())) -> &'a T, >; type Item = <Self::IntoIter as Iterator>::Item; #[inline] fn into_iter(self) -> Self::IntoIter { self.map.iter().map(entry_to_key) } } impl<T> fmt::Debug for SsoHashSet<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } }
26.403361
100
0.598345
76283e306395dc80ef2aa072da0c6fe3fae7de98
5,578
use crate::{ Cache, Clipboard, Command, Debug, Event, Point, Program, Renderer, Size, UserInterface, }; /// The execution state of a [`Program`]. It leverages caching, event /// processing, and rendering primitive storage. /// /// [`Program`]: trait.Program.html #[allow(missing_debug_implementations)] pub struct State<P> where P: Program + 'static, { program: P, cache: Option<Cache>, primitive: <P::Renderer as Renderer>::Output, queued_events: Vec<Event>, queued_messages: Vec<P::Message>, } impl<P> State<P> where P: Program + 'static, { /// Creates a new [`State`] with the provided [`Program`], initializing its /// primitive with the given logical bounds and renderer. /// /// [`State`]: struct.State.html /// [`Program`]: trait.Program.html pub fn new( mut program: P, bounds: Size, cursor_position: Point, renderer: &mut P::Renderer, debug: &mut Debug, ) -> Self { let mut user_interface = build_user_interface( &mut program, Cache::default(), renderer, bounds, debug, ); debug.draw_started(); let primitive = user_interface.draw(renderer, cursor_position); debug.draw_finished(); let cache = Some(user_interface.into_cache()); State { program, cache, primitive, queued_events: Vec::new(), queued_messages: Vec::new(), } } /// Returns a reference to the [`Program`] of the [`State`]. /// /// [`Program`]: trait.Program.html /// [`State`]: struct.State.html pub fn program(&self) -> &P { &self.program } /// Returns a reference to the current rendering primitive of the [`State`]. /// /// [`State`]: struct.State.html pub fn primitive(&self) -> &<P::Renderer as Renderer>::Output { &self.primitive } /// Queues an event in the [`State`] for processing during an [`update`]. /// /// [`State`]: struct.State.html /// [`update`]: #method.update pub fn queue_event(&mut self, event: Event) { self.queued_events.push(event); } /// Queues a message in the [`State`] for processing during an [`update`]. /// /// [`State`]: struct.State.html /// [`update`]: #method.update pub fn queue_message(&mut self, message: P::Message) { self.queued_messages.push(message); } /// Returns whether the event queue of the [`State`] is empty or not. /// /// [`State`]: struct.State.html pub fn is_queue_empty(&self) -> bool { self.queued_events.is_empty() && self.queued_messages.is_empty() } /// Processes all the queued events and messages, rebuilding and redrawing /// the widgets of the linked [`Program`] if necessary. /// /// Returns the [`Command`] obtained from [`Program`] after updating it, /// only if an update was necessary. /// /// [`Program`]: trait.Program.html pub fn update( &mut self, bounds: Size, cursor_position: Point, clipboard: Option<&dyn Clipboard>, renderer: &mut P::Renderer, debug: &mut Debug, ) -> Option<Command<P::Message>> { let mut user_interface = build_user_interface( &mut self.program, self.cache.take().unwrap(), renderer, bounds, debug, ); debug.event_processing_started(); let mut messages = Vec::new(); let _ = user_interface.update( &self.queued_events, cursor_position, clipboard, renderer, &mut messages, ); messages.extend(self.queued_messages.drain(..)); self.queued_events.clear(); debug.event_processing_finished(); if messages.is_empty() { debug.draw_started(); self.primitive = user_interface.draw(renderer, cursor_position); debug.draw_finished(); self.cache = Some(user_interface.into_cache()); None } else { // When there are messages, we are forced to rebuild twice // for now :^) let temp_cache = user_interface.into_cache(); let commands = Command::batch(messages.into_iter().map(|message| { debug.log_message(&message); debug.update_started(); let command = self.program.update(message); debug.update_finished(); command })); let mut user_interface = build_user_interface( &mut self.program, temp_cache, renderer, bounds, debug, ); debug.draw_started(); self.primitive = user_interface.draw(renderer, cursor_position); debug.draw_finished(); self.cache = Some(user_interface.into_cache()); Some(commands) } } } fn build_user_interface<'a, P: Program>( program: &'a mut P, cache: Cache, renderer: &mut P::Renderer, size: Size, debug: &mut Debug, ) -> UserInterface<'a, P::Message, P::Renderer> { debug.view_started(); let view = program.view(); debug.view_finished(); debug.layout_started(); let user_interface = UserInterface::build(view, size, cache, renderer); debug.layout_finished(); user_interface }
28.314721
80
0.560954
0845c03a49f3572590deca08c1eb1b8b71265975
2,514
use linfa::{ dataset::DatasetBase, traits::{Fit, Predict}, }; use linfa_ica::fast_ica::{FastIca, GFunc}; use ndarray::{array, stack}; use ndarray::{Array, Array2, Axis}; use ndarray_npy::write_npy; use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt}; use rand_isaac::Isaac64Rng; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { // Create sample dataset for the model // `sources_original` has the unmixed sources (we merely have it to save to disk) // `sources_mixed` is the mixed source that will be unmixed using ICA // Shape of the data will be (2000 x 2) let (sources_original, sources_mixed) = create_data(); // Fitting the model // We set the G function used in the approximation of neg-entropy as logcosh // with its alpha value as 1 // `ncomponents` is not set, it will be automatically be assigned 2 from // the input let ica = FastIca::new().gfunc(GFunc::Logcosh(1.0)); let ica = ica.fit(&DatasetBase::from(sources_mixed.view()))?; // Here we unmix the data to recover back the original signals let sources_ica = ica.predict(&sources_mixed); // Saving to disk write_npy("sources_original.npy", sources_original).expect("Failed to write .npy file"); write_npy("sources_mixed.npy", sources_mixed).expect("Failed to write .npy file"); write_npy("sources_ica.npy", sources_ica).expect("Failed to write .npy file"); Ok(()) } // Helper function to create two signals (sources) and mix them together // as input for the ICA model fn create_data() -> (Array2<f64>, Array2<f64>) { let nsamples = 2000; // Creating a sine wave signal let source1 = Array::linspace(0., 8., nsamples).mapv(|x| (2f64 * x).sin()); // Creating a sawtooth signal let source2 = Array::linspace(0., 8., nsamples).mapv(|x| { let tmp = (4f64 * x).sin(); if tmp > 0. { return 1.; } -1. }); // Column stacking both the signals let mut sources_original = stack![ Axis(1), source1.insert_axis(Axis(1)), source2.insert_axis(Axis(1)) ]; // Adding noise to the signals let mut rng = Isaac64Rng::seed_from_u64(42); sources_original += &Array::random_using((2000, 2), Uniform::new(0.0, 1.0), &mut rng).mapv(|x| x * 0.2); // Mixing the two signals let mixing = array![[1., 1.], [0.5, 2.]]; let sources_mixed = sources_original.dot(&mixing.t()); (sources_original, sources_mixed) }
33.972973
92
0.646778
48cdc4ef7b838c1f0154dc69d393fc32d7565fa4
2,220
use crate::ring_buffer; #[test] fn pop_reads_correct_data() { let (mut tx, mut rx) = ring_buffer::with_capacity(4); let correct = [4i32, -1, 4, 149]; tx.push(&correct).unwrap(); let mut result = vec![0; 4]; rx.pop_full(&mut result).unwrap(); assert_eq!(result[..], correct[..]); } #[test] fn cannot_push_more_than_capacity() { let (mut tx, mut rx) = ring_buffer::with_capacity(4); tx.push(&[1i32, 5, 23]).unwrap(); let result = tx.push(&[15, 44]); assert_eq!(result, Err(1)); rx.pop_full(&mut [0; 4]).unwrap(); let result = tx.push(&[1, 2, 3, 4, 5]); assert_eq!(result, Err(4)); let result = tx.push(&[1, 2, 3, 4, 5]); assert_eq!(result, Err(0)); } #[test] fn cannot_pop_more_than_available() { let (mut tx, mut rx) = ring_buffer::with_capacity(4); tx.push(&[1i32, 2, 3]).unwrap(); let mut array = [0; 4]; let result = rx.pop_full(&mut array); assert_eq!(result, Err(3)); assert_eq!(array, [0; 4]); } #[test] fn all_possible_read_write_index_combinations() { const N: usize = 8; let (mut tx, mut rx) = ring_buffer::with_capacity(N); for _ in 0..=N { for v in 0..N { tx.push(&[v]).unwrap(); } let result = tx.push(&[N]); assert_eq!(result, Err(0)); let mut array = [N + 1]; for v in 0..N { rx.pop_full(&mut array).unwrap(); assert_eq!(array[0], v); } let result = rx.pop_full(&mut array); assert_eq!(result, Err(0)); } } #[test] fn multithreading() { let (mut tx, mut rx) = ring_buffer::with_capacity(4); let rx_handle = std::thread::spawn(move || { for _try in 0..100 { let mut array = [0; 4]; match rx.pop_full(&mut array) { Ok(()) => { assert_eq!(array, [1, 2, 3, 4]); return; } Err(_) => (), } std::thread::sleep(std::time::Duration::from_millis(1)); } panic!(); }); let tx_handle = std::thread::spawn(move || { tx.push(&[1i64, 2, 3, 4]).unwrap(); }); tx_handle.join().unwrap(); rx_handle.join().unwrap(); }
28.101266
68
0.519369
e4c252668f36d2268aa51933298f67c0f92246e9
9,965
// DO NOT EDIT ! // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! //! This documentation was generated from *Resource Settings* crate version *3.0.0+20220305*, where *20220305* is the exact revision of the *resourcesettings:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v3.0.0*. //! //! Everything else about the *Resource Settings* *v1* API can be found at the //! [official documentation site](https://cloud.google.com/resource-manager/docs/resource-settings/overview). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/main/gen/resourcesettings1). //! # Features //! //! Handle the following *Resources* with ease from the central [hub](ResourceSettings) ... //! //! * folders //! * [*settings get*](api::FolderSettingGetCall), [*settings list*](api::FolderSettingListCall) and [*settings patch*](api::FolderSettingPatchCall) //! * organizations //! * [*settings get*](api::OrganizationSettingGetCall), [*settings list*](api::OrganizationSettingListCall) and [*settings patch*](api::OrganizationSettingPatchCall) //! * projects //! * [*settings get*](api::ProjectSettingGetCall), [*settings list*](api::ProjectSettingListCall) and [*settings patch*](api::ProjectSettingPatchCall) //! //! //! //! //! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs). //! //! # Structure of this Library //! //! The API is structured into the following primary items: //! //! * **[Hub](ResourceSettings)** //! * a central object to maintain state and allow accessing all *Activities* //! * creates [*Method Builders*](client::MethodsBuilder) which in turn //! allow access to individual [*Call Builders*](client::CallBuilder) //! * **[Resources](client::Resource)** //! * primary types that you can apply *Activities* to //! * a collection of properties and *Parts* //! * **[Parts](client::Part)** //! * a collection of properties //! * never directly used in *Activities* //! * **[Activities](client::CallBuilder)** //! * operations to apply to *Resources* //! //! All *structures* are marked with applicable traits to further categorize them and ease browsing. //! //! Generally speaking, you can invoke *Activities* like this: //! //! ```Rust,ignore //! let r = hub.resource().activity(...).doit().await //! ``` //! //! Or specifically ... //! //! ```ignore //! let r = hub.folders().settings_get(...).doit().await //! let r = hub.folders().settings_patch(...).doit().await //! let r = hub.organizations().settings_get(...).doit().await //! let r = hub.organizations().settings_patch(...).doit().await //! let r = hub.projects().settings_get(...).doit().await //! let r = hub.projects().settings_patch(...).doit().await //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` //! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be //! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. //! The `doit()` method performs the actual communication with the server and returns the respective result. //! //! # Usage //! //! ## Setting up your Project //! //! To use this library, you would put the following lines into your `Cargo.toml` file: //! //! ```toml //! [dependencies] //! google-resourcesettings1 = "*" //! serde = "^1.0" //! serde_json = "^1.0" //! ``` //! //! ## A complete example //! //! ```test_harness,no_run //! extern crate hyper; //! extern crate hyper_rustls; //! extern crate google_resourcesettings1 as resourcesettings1; //! use resourcesettings1::{Result, Error}; //! # async fn dox() { //! use std::default::Default; //! use resourcesettings1::{ResourceSettings, oauth2, hyper, hyper_rustls}; //! //! // Get an ApplicationSecret instance by some means. It contains the `client_id` and //! // `client_secret`, among other things. //! let secret: oauth2::ApplicationSecret = Default::default(); //! // Instantiate the authenticator. It will choose a suitable authentication flow for you, //! // unless you replace `None` with the desired Flow. //! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about //! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and //! // retrieve them from storage. //! let auth = oauth2::InstalledFlowAuthenticator::builder( //! secret, //! oauth2::InstalledFlowReturnMethod::HTTPRedirect, //! ).build().await.unwrap(); //! let mut hub = ResourceSettings::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); //! // You can configure optional parameters by calling the respective setters at will, and //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.folders().settings_get("name") //! .view("ipsum") //! .doit().await; //! //! match result { //! Err(e) => match e { //! // The Error enum provides details about what exactly happened. //! // You can also just use its `Debug`, `Display` or `Error` traits //! Error::HttpError(_) //! |Error::Io(_) //! |Error::MissingAPIKey //! |Error::MissingToken(_) //! |Error::Cancelled //! |Error::UploadSizeLimitExceeded(_, _) //! |Error::Failure(_) //! |Error::BadRequest(_) //! |Error::FieldClash(_) //! |Error::JsonDecodeError(_, _) => println!("{}", e), //! }, //! Ok(res) => println!("Success: {:?}", res), //! } //! # } //! ``` //! ## Handling Errors //! //! All errors produced by the system are provided either as [Result](client::Result) enumeration as return value of //! the doit() methods, or handed as possibly intermediate results to either the //! [Hub Delegate](client::Delegate), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html). //! //! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This //! makes the system potentially resilient to all kinds of errors. //! //! ## Uploads and Downloads //! If a method supports downloads, the response body, which is part of the [Result](client::Result), should be //! read by you to obtain the media. //! If such a method also supports a [Response Result](client::ResponseResult), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`. //! //! Methods supporting uploads can do so using up to 2 different protocols: //! *simple* and *resumable*. The distinctiveness of each is represented by customized //! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. //! //! ## Customization and Callbacks //! //! You may alter the way an `doit()` method is called by providing a [delegate](client::Delegate) to the //! [Method Builder](client::CallBuilder) before making the final `doit()` call. //! Respective methods will be called to provide progress information, as well as determine whether the system should //! retry on failure. //! //! The [delegate trait](client::Delegate) is default-implemented, allowing you to customize it with minimal effort. //! //! ## Optional Parts in Server-Requests //! //! All structures provided by this library are made to be [encodable](client::RequestValue) and //! [decodable](client::ResponseResult) via *json*. Optionals are used to indicate that partial requests are responses //! are valid. //! Most optionals are are considered [Parts](client::Part) which are identifiable by name, which will be sent to //! the server to indicate either the set parts of the request or the desired parts in the response. //! //! ## Builder Arguments //! //! Using [method builders](client::CallBuilder), you are able to prepare an action call by repeatedly calling it's methods. //! These will always take a single argument, for which the following statements are true. //! //! * [PODs][wiki-pod] are handed by copy //! * strings are passed as `&str` //! * [request values](client::RequestValue) are moved //! //! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. //! //! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure //! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern //! [google-go-api]: https://github.com/google/google-api-go-client //! //! // Unused attributes happen thanks to defined, but unused structures // We don't warn about this, as depending on the API, some data structures or facilities are never used. // Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any // unused imports in fully featured APIs. Same with unused_mut ... . #![allow(unused_imports, unused_mut, dead_code)] // DO NOT EDIT ! // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! #[macro_use] extern crate serde_derive; // Re-export the hyper and hyper_rustls crate, they are required to build the hub pub extern crate hyper; pub extern crate hyper_rustls; extern crate serde; extern crate serde_json; // Re-export the yup_oauth2 crate, that is required to call some methods of the hub and the client pub extern crate yup_oauth2 as oauth2; extern crate mime; extern crate url; pub mod api; pub mod client; // Re-export the hub type and some basic client structs pub use api::ResourceSettings; pub use client::{Result, Error, Delegate};
46.784038
244
0.687205
f89c1f580be14af0e4377e463e661a02ce12e076
7,187
// Copyright 2018-2022 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Traits and interfaces to operate with storage entities. //! //! Generally a type is said to be a storage entity if it implements the //! `SpreadLayout` trait. This defines certain constants and routines in order //! to tell a smart contract how to load and store instances of this type //! from and to the contract's storage. //! //! The `PackedLayout` trait can then be implemented on top of the `SpreadLayout` //! for types that further allow to be stored in the contract storage in a more //! compressed format to a single storage cell. mod impls; mod keyptr; mod optspec; mod packed; mod spread; #[cfg(feature = "std")] mod layout; #[cfg(feature = "std")] pub use self::layout::{ LayoutCryptoHasher, StorageLayout, }; pub(crate) use self::optspec::pull_packed_root_opt; pub use self::{ impls::{ forward_allocate_packed, forward_clear_packed, forward_pull_packed, forward_push_packed, }, keyptr::{ ExtKeyPtr, KeyPtr, }, packed::{ PackedAllocate, PackedLayout, }, spread::{ SpreadAllocate, SpreadLayout, FOOTPRINT_CLEANUP_THRESHOLD, }, }; use ink_primitives::Key; pub use ink_storage_derive::{ PackedLayout, SpreadAllocate, SpreadLayout, StorageLayout, }; /// Pulls an instance of type `T` from the contract storage using spread layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being pulled from. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`SpreadLayout`]. pub fn pull_spread_root<T>(root_key: &Key) -> T where T: SpreadLayout, { let mut ptr = KeyPtr::from(*root_key); <T as SpreadLayout>::pull_spread(&mut ptr) } /// Pulls an instance of type `T` from the contract storage using spread layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being pulled from. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait method on [`SpreadAllocate`]. pub fn allocate_spread_root<T>(root_key: &Key) -> T where T: SpreadAllocate, { let mut ptr = KeyPtr::from(*root_key); <T as SpreadAllocate>::allocate_spread(&mut ptr) } /// Clears the entity from the contract storage using spread layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being cleared from. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`SpreadLayout`]. pub fn clear_spread_root<T>(entity: &T, root_key: &Key) where T: SpreadLayout, { let mut ptr = KeyPtr::from(*root_key); <T as SpreadLayout>::clear_spread(entity, &mut ptr); } /// Pushes the entity to the contract storage using spread layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being pushed to. /// /// # Note /// /// - The routine will push the given entity to the contract storage using /// spread layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`SpreadLayout`]. pub fn push_spread_root<T>(entity: &T, root_key: &Key) where T: SpreadLayout, { let mut ptr = KeyPtr::from(*root_key); <T as SpreadLayout>::push_spread(entity, &mut ptr); } /// Pulls an instance of type `T` from the contract storage using packed layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being pulled from. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`PackedLayout`]. pub fn pull_packed_root<T>(root_key: &Key) -> T where T: PackedLayout, { let mut entity = ink_env::get_contract_storage::<T>(root_key) .expect("could not properly decode storage entry") .expect("storage entry was empty"); <T as PackedLayout>::pull_packed(&mut entity, root_key); entity } /// Allocates an instance of type `T` to the contract storage using packed layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being allocated to. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait method on [`PackedAllocate`]. pub fn allocate_packed_root<T>(root_key: &Key) -> T where T: PackedAllocate + Default, { let mut entity = <T as Default>::default(); <T as PackedAllocate>::allocate_packed(&mut entity, root_key); entity } /// Pushes the entity to the contract storage using packed layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being pushed to. /// /// # Note /// /// - The routine will push the given entity to the contract storage using /// packed layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`PackedLayout`]. pub fn push_packed_root<T>(entity: &T, root_key: &Key) -> Option<u32> where T: PackedLayout, { <T as PackedLayout>::push_packed(entity, root_key); ink_env::set_contract_storage(root_key, entity) } /// Clears the entity from the contract storage using packed layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being cleared from. /// /// # Note /// /// - The routine assumes that the instance has previously been stored to /// the contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`PackedLayout`]. pub fn clear_packed_root<T>(entity: &T, root_key: &Key) where T: PackedLayout, { <T as PackedLayout>::clear_packed(entity, root_key); ink_env::clear_contract_storage(root_key); }
31.942222
82
0.700014
4b4236f90a9b1e990e43578f0f9655eca8524d7f
4,894
use crossterm::{ cursor::{Hide, Show}, event::{self, Event, KeyCode}, terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}, ExecutableCommand, }; use rusty_audio::Audio; use std::{ error::Error, sync::mpsc::{self, Receiver}, time::{Duration, Instant}, {io, thread}, }; use invaders::{ frame::{self, new_frame, Drawable, Frame}, invaders::Invaders, level::Level, menu::Menu, player::Player, render, score::Score, }; fn render_screen(render_rx: Receiver<Frame>) { let mut last_frame = frame::new_frame(); let mut stdout = io::stdout(); render::render(&mut stdout, &last_frame, &last_frame, true); while let Ok(curr_frame) = render_rx.recv() { render::render(&mut stdout, &last_frame, &curr_frame, false); last_frame = curr_frame; } } fn reset_game(in_menu: &mut bool, player: &mut Player, invaders: &mut Invaders) { *in_menu = true; *player = Player::new(); *invaders = Invaders::new(); } fn main() -> Result<(), Box<dyn Error>> { let mut audio = Audio::new(); for item in &["explode", "lose", "move", "pew", "startup", "win"] { audio.add(item, &format!("{}.wav", item)); } audio.play("startup"); // Terminal let mut stdout = io::stdout(); terminal::enable_raw_mode()?; stdout.execute(EnterAlternateScreen)?; stdout.execute(Hide)?; // Render loop in a separate thread let (render_tx, render_rx) = mpsc::channel(); let render_handle = thread::spawn(move || { render_screen(render_rx); }); // Game loop let mut player = Player::new(); let mut instant = Instant::now(); let mut invaders = Invaders::new(); let mut score = Score::new(); let mut menu = Menu::new(); let mut in_menu = true; let mut level = Level::new(); 'gameloop: loop { // Per-frame init let delta = instant.elapsed(); instant = Instant::now(); let mut curr_frame = new_frame(); if in_menu { // Input handlers for the menu while event::poll(Duration::default())? { if let Event::Key(key_event) = event::read()? { match key_event.code { KeyCode::Up => menu.change_option(true), KeyCode::Down => menu.change_option(false), KeyCode::Char(' ') | KeyCode::Enter => { if menu.selection == 0 { in_menu = false; } else { break 'gameloop; } } _ => {} } } } menu.draw(&mut curr_frame); let _ = render_tx.send(curr_frame); thread::sleep(Duration::from_millis(1)); continue; } // Input handlers for the game while event::poll(Duration::default())? { if let Event::Key(key_event) = event::read()? { match key_event.code { KeyCode::Left => player.move_left(), KeyCode::Right => player.move_right(), KeyCode::Char(' ') | KeyCode::Enter => { if player.shoot() { audio.play("pew"); } } KeyCode::Esc | KeyCode::Char('q') => { audio.play("lose"); reset_game(&mut in_menu, &mut player, &mut invaders); } _ => {} } } } // Updates player.update(delta); if invaders.update(delta) { audio.play("move"); } let hits: u16 = player.detect_hits(&mut invaders); if hits > 0 { audio.play("explode"); score.add_points(hits); } // Draw & render let drawables: Vec<&dyn Drawable> = vec![&player, &invaders, &score, &level]; for drawable in drawables { drawable.draw(&mut curr_frame); } let _ = render_tx.send(curr_frame); thread::sleep(Duration::from_millis(1)); // Win or lose? if invaders.all_killed() { if level.increment_level() { audio.play("win"); break 'gameloop; } invaders = Invaders::new(); } else if invaders.reached_bottom() { audio.play("lose"); reset_game(&mut in_menu, &mut player, &mut invaders); } } // Cleanup drop(render_tx); render_handle.join().unwrap(); audio.wait(); stdout.execute(Show)?; stdout.execute(LeaveAlternateScreen)?; terminal::disable_raw_mode()?; Ok(()) }
30.397516
85
0.495709
486924e8616088515776e4a10cb4930d3db19519
692
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod dir; pub mod socket; pub mod symlink; pub mod tree;
36.421053
75
0.74422
edb2084c7167a57895ce415cdafc0dad10755be5
63,702
// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may not use this file except in accordance with one or both of these // licenses. //! Top level peer message handling and socket handling logic lives here. //! //! Instead of actually servicing sockets ourselves we require that you implement the //! SocketDescriptor interface and use that to receive actions which you should perform on the //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages //! they should handle, and encoding/sending response messages. use bitcoin::secp256k1::key::{SecretKey,PublicKey}; use ln::features::InitFeatures; use ln::msgs; use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler}; use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}; use util::ser::{VecWriter, Writeable}; use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep}; use ln::wire; use ln::wire::Encode; use util::byte_utils; use util::events::{MessageSendEvent, MessageSendEventsProvider}; use util::logger::Logger; use routing::network_graph::NetGraphMsgHandler; use std::collections::{HashMap,hash_map,HashSet,LinkedList}; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::{cmp,error,hash,fmt}; use std::ops::Deref; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256::HashEngine as Sha256Engine; use bitcoin::hashes::{HashEngine, Hash}; /// Provides references to trait impls which handle different types of messages. pub struct MessageHandler<CM: Deref, RM: Deref> where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler { /// A message handler which handles messages specific to channels. Usually this is just a /// ChannelManager object. pub chan_handler: CM, /// A message handler which handles messages updating our knowledge of the network channel /// graph. Usually this is just a NetGraphMsgHandlerMonitor object. pub route_handler: RM, } /// Provides an object which can be used to send data to and which uniquely identifies a connection /// to a remote host. You will need to be able to generate multiple of these which meet Eq and /// implement Hash to meet the PeerManager API. /// /// For efficiency, Clone should be relatively cheap for this type. /// /// You probably want to just extend an int and put a file descriptor in a struct and implement /// send_data. Note that if you are using a higher-level net library that may call close() itself, /// be careful to ensure you don't have races whereby you might register a new connection with an /// fd which is the same as a previous one which has yet to be removed via /// PeerManager::socket_disconnected(). pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone { /// Attempts to send some data from the given slice to the peer. /// /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected. /// Note that in the disconnected case, socket_disconnected must still fire and further write /// attempts may occur until that time. /// /// If the returned size is smaller than data.len(), a write_available event must /// trigger the next time more data can be written. Additionally, until the a send_data event /// completes fully, no further read_events should trigger on the same peer! /// /// If a read_event on this descriptor had previously returned true (indicating that read /// events should be paused to prevent DoS in the send buffer), resume_read may be set /// indicating that read events on this descriptor should resume. A resume_read of false does /// *not* imply that further read events should be paused. fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize; /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with /// this descriptor. No socket_disconnected call should be generated as a result of this call, /// though races may occur whereby disconnect_socket is called after a call to /// socket_disconnected but prior to socket_disconnected returning. fn disconnect_socket(&mut self); } /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and /// generate no further read_event/write_buffer_space_avail calls for the descriptor, only /// triggering a single socket_disconnected call (unless it was provided in response to a /// new_*_connection event, in which case no such socket_disconnected() must be called and the /// socket silently disconencted). pub struct PeerHandleError { /// 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. pub no_connection_possible: bool, } impl fmt::Debug for PeerHandleError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("Peer Sent Invalid Data") } } impl fmt::Display for PeerHandleError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("Peer Sent Invalid Data") } } impl error::Error for PeerHandleError { fn description(&self) -> &str { "Peer Sent Invalid Data" } } enum InitSyncTracker{ NoSyncRequested, ChannelsSyncing(u64), NodesSyncing(PublicKey), } struct Peer { channel_encryptor: PeerChannelEncryptor, outbound: bool, their_node_id: Option<PublicKey>, their_features: Option<InitFeatures>, pending_outbound_buffer: LinkedList<Vec<u8>>, pending_outbound_buffer_first_msg_offset: usize, awaiting_write_event: bool, pending_read_buffer: Vec<u8>, pending_read_buffer_pos: usize, pending_read_is_header: bool, sync_status: InitSyncTracker, awaiting_pong: bool, } impl Peer { /// Returns true if the channel announcements/updates for the given channel should be /// forwarded to this peer. /// If we are sending our routing table to this peer and we have not yet sent channel /// announcements/updates for the given channel_id then we will send it when we get to that /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already /// sent the old versions, we should send the update, and so return true here. fn should_forward_channel_announcement(&self, channel_id: u64)->bool{ match self.sync_status { InitSyncTracker::NoSyncRequested => true, InitSyncTracker::ChannelsSyncing(i) => i < channel_id, InitSyncTracker::NodesSyncing(_) => true, } } /// Similar to the above, but for node announcements indexed by node_id. fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool { match self.sync_status { InitSyncTracker::NoSyncRequested => true, InitSyncTracker::ChannelsSyncing(_) => false, InitSyncTracker::NodesSyncing(pk) => pk < node_id, } } } struct PeerHolder<Descriptor: SocketDescriptor> { peers: HashMap<Descriptor, Peer>, /// Added to by do_read_event for cases where we pushed a message onto the send buffer but /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events() peers_needing_send: HashSet<Descriptor>, /// Only add to this set when noise completes: node_id_to_descriptor: HashMap<PublicKey, Descriptor>, } #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] fn _check_usize_is_32_or_64() { // See below, less than 32 bit pointers may be unsafe here! unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); } } /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g. /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static /// lifetimes). Other times you can afford a reference, which is more efficient, in which case /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents /// issues such as overly long function definitions. pub type SimpleArcPeerManager<SD, M, T, F, C, L> = Arc<PeerManager<SD, SimpleArcChannelManager<M, T, F, L>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>>>; /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes). /// But if this is not necessary, using a reference is more efficient. Defining these type aliases /// helps with issues such as long function definitions. pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g C, &'f L>, &'f L>; /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket /// events into messages which it passes on to its MessageHandlers. /// /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but /// essentially you should default to using a SimpleRefPeerManager, and use a /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when /// you're using lightning-net-tokio. pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, L::Target: Logger { message_handler: MessageHandler<CM, RM>, peers: Mutex<PeerHolder<Descriptor>>, our_node_secret: SecretKey, ephemeral_key_midstate: Sha256Engine, // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64 // bits we will never realistically count into high: peer_counter_low: AtomicUsize, peer_counter_high: AtomicUsize, logger: L, } enum MessageHandlingError { PeerHandleError(PeerHandleError), LightningError(LightningError), } impl From<PeerHandleError> for MessageHandlingError { fn from(error: PeerHandleError) -> Self { MessageHandlingError::PeerHandleError(error) } } impl From<LightningError> for MessageHandlingError { fn from(error: LightningError) -> Self { MessageHandlingError::LightningError(error) } } macro_rules! encode_msg { ($msg: expr) => {{ let mut buffer = VecWriter(Vec::new()); wire::write($msg, &mut buffer).unwrap(); buffer.0 }} } /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds. /// PeerIds may repeat, but only after socket_disconnected() has been called. impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<Descriptor, CM, RM, L> where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, L::Target: Logger { /// Constructs a new PeerManager with the given message handlers and node_id secret key /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { let mut ephemeral_key_midstate = Sha256::engine(); ephemeral_key_midstate.input(ephemeral_random_data); PeerManager { message_handler, peers: Mutex::new(PeerHolder { peers: HashMap::new(), peers_needing_send: HashSet::new(), node_id_to_descriptor: HashMap::new() }), our_node_secret, ephemeral_key_midstate, peer_counter_low: AtomicUsize::new(0), peer_counter_high: AtomicUsize::new(0), logger, } } /// Get the list of node ids for peers which have completed the initial handshake. /// /// For outbound connections, this will be the same as the their_node_id parameter passed in to /// new_outbound_connection, however entries will only appear once the initial handshake has /// completed and we are sure the remote peer has the private key for the given node_id. pub fn get_peer_node_ids(&self) -> Vec<PublicKey> { let peers = self.peers.lock().unwrap(); peers.peers.values().filter_map(|p| { if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() { return None; } p.their_node_id }).collect() } fn get_ephemeral_key(&self) -> SecretKey { let mut ephemeral_hash = self.ephemeral_key_midstate.clone(); let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel); let high = if low == 0 { self.peer_counter_high.fetch_add(1, Ordering::AcqRel) } else { self.peer_counter_high.load(Ordering::Acquire) }; ephemeral_hash.input(&byte_utils::le64_to_array(low as u64)); ephemeral_hash.input(&byte_utils::le64_to_array(high as u64)); SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!") } /// Indicates a new outbound connection has been established to a node with the given node_id. /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new /// descriptor but must disconnect the connection immediately. /// /// Returns a small number of bytes to send to the remote node (currently always 50). /// /// Panics if descriptor is duplicative with some other descriptor which has not yet had a /// socket_disconnected(). pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> { let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key()); let res = peer_encryptor.get_act_one().to_vec(); let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes let mut peers = self.peers.lock().unwrap(); if peers.peers.insert(descriptor, Peer { channel_encryptor: peer_encryptor, outbound: true, their_node_id: None, their_features: None, pending_outbound_buffer: LinkedList::new(), pending_outbound_buffer_first_msg_offset: 0, awaiting_write_event: false, pending_read_buffer: pending_read_buffer, pending_read_buffer_pos: 0, pending_read_is_header: false, sync_status: InitSyncTracker::NoSyncRequested, awaiting_pong: false, }).is_some() { panic!("PeerManager driver duplicated descriptors!"); }; Ok(res) } /// Indicates a new inbound connection has been established. /// /// May refuse the connection by returning an Err, but will never write bytes to the remote end /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT /// call socket_disconnected for the new descriptor but must disconnect the connection /// immediately. /// /// Panics if descriptor is duplicative with some other descriptor which has not yet had /// socket_disconnected called. pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> { let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret); let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes let mut peers = self.peers.lock().unwrap(); if peers.peers.insert(descriptor, Peer { channel_encryptor: peer_encryptor, outbound: false, their_node_id: None, their_features: None, pending_outbound_buffer: LinkedList::new(), pending_outbound_buffer_first_msg_offset: 0, awaiting_write_event: false, pending_read_buffer: pending_read_buffer, pending_read_buffer_pos: 0, pending_read_is_header: false, sync_status: InitSyncTracker::NoSyncRequested, awaiting_pong: false, }).is_some() { panic!("PeerManager driver duplicated descriptors!"); }; Ok(()) } fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) { macro_rules! encode_and_send_msg { ($msg: expr) => { { log_trace!(self.logger, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap())); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..])); } } } const MSG_BUFF_SIZE: usize = 10; while !peer.awaiting_write_event { if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE { match peer.sync_status { InitSyncTracker::NoSyncRequested => {}, InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => { let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8; let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps); for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() { encode_and_send_msg!(announce); if let &Some(ref update_a) = update_a_option { encode_and_send_msg!(update_a); } if let &Some(ref update_b) = update_b_option { encode_and_send_msg!(update_b); } peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1); } if all_messages.is_empty() || all_messages.len() != steps as usize { peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff); } }, InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => { let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8; let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps); for msg in all_messages.iter() { encode_and_send_msg!(msg); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); } if all_messages.is_empty() || all_messages.len() != steps as usize { peer.sync_status = InitSyncTracker::NoSyncRequested; } }, InitSyncTracker::ChannelsSyncing(_) => unreachable!(), InitSyncTracker::NodesSyncing(key) => { let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8; let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps); for msg in all_messages.iter() { encode_and_send_msg!(msg); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); } if all_messages.is_empty() || all_messages.len() != steps as usize { peer.sync_status = InitSyncTracker::NoSyncRequested; } }, } } if { let next_buff = match peer.pending_outbound_buffer.front() { None => return, Some(buff) => buff, }; let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE; let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..]; let data_sent = descriptor.send_data(pending, should_be_reading); peer.pending_outbound_buffer_first_msg_offset += data_sent; if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false } } { peer.pending_outbound_buffer_first_msg_offset = 0; peer.pending_outbound_buffer.pop_front(); } else { peer.awaiting_write_event = true; } } } /// Indicates that there is room to write data to the given socket descriptor. /// /// May return an Err to indicate that the connection should be closed. /// /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The /// invariants around calling write_buffer_space_avail in case a write did not fully complete /// must still hold - be ready to call write_buffer_space_avail again if a write call generated /// here isn't sufficient! Panics if the descriptor was not previously registered in a /// new_\*_connection event. pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> { let mut peers = self.peers.lock().unwrap(); match peers.peers.get_mut(descriptor) { None => panic!("Descriptor for write_event is not already known to PeerManager"), Some(peer) => { peer.awaiting_write_event = false; self.do_attempt_write_data(descriptor, peer); } }; Ok(()) } /// Indicates that data was read from the given socket descriptor. /// /// May return an Err to indicate that the connection should be closed. /// /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity. /// Thus, however, you almost certainly want to call process_events() after any read_event to /// generate send_data calls to handle responses. /// /// If Ok(true) is returned, further read_events should not be triggered until a send_data call /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer). /// /// Panics if the descriptor was not previously registered in a new_*_connection event. pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> { match self.do_read_event(peer_descriptor, data) { Ok(res) => Ok(res), Err(e) => { self.disconnect_event_internal(peer_descriptor, e.no_connection_possible); Err(e) } } } /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly. fn enqueue_message<M: Encode + Writeable>(&self, peers_needing_send: &mut HashSet<Descriptor>, peer: &mut Peer, descriptor: Descriptor, message: &M) { let mut buffer = VecWriter(Vec::new()); wire::write(message, &mut buffer).unwrap(); // crash if the write failed let encoded_message = buffer.0; log_trace!(self.logger, "Enqueueing message of type {} to {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap())); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..])); peers_needing_send.insert(descriptor); } fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> { let pause_read = { let mut peers_lock = self.peers.lock().unwrap(); let peers = &mut *peers_lock; let pause_read = match peers.peers.get_mut(peer_descriptor) { None => panic!("Descriptor for read_event is not already known to PeerManager"), Some(peer) => { assert!(peer.pending_read_buffer.len() > 0); assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos); let mut read_pos = 0; while read_pos < data.len() { { let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos); peer.pending_read_buffer[peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy].copy_from_slice(&data[read_pos..read_pos + data_to_copy]); read_pos += data_to_copy; peer.pending_read_buffer_pos += data_to_copy; } if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() { peer.pending_read_buffer_pos = 0; macro_rules! try_potential_handleerror { ($thing: expr) => { match $thing { Ok(x) => x, Err(e) => { match e.action { msgs::ErrorAction::DisconnectPeer { msg: _ } => { //TODO: Try to push msg log_trace!(self.logger, "Got Err handling message, disconnecting peer because {}", e.err); return Err(PeerHandleError{ no_connection_possible: false }); }, msgs::ErrorAction::IgnoreError => { log_trace!(self.logger, "Got Err handling message, ignoring because {}", e.err); continue; }, msgs::ErrorAction::SendErrorMessage { msg } => { log_trace!(self.logger, "Got Err handling message, sending Error message because {}", e.err); self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &msg); continue; }, } } }; } } macro_rules! insert_node_id { () => { match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) { hash_map::Entry::Occupied(_) => { log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap())); peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event return Err(PeerHandleError{ no_connection_possible: false }) }, hash_map::Entry::Vacant(entry) => { log_trace!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap())); entry.insert(peer_descriptor.clone()) }, }; } } let next_step = peer.channel_encryptor.get_noise_step(); match next_step { NextNoiseStep::ActOne => { let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec(); peer.pending_outbound_buffer.push_back(act_two); peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long }, NextNoiseStep::ActTwo => { let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)); peer.pending_outbound_buffer.push_back(act_three.to_vec()); peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes peer.pending_read_is_header = true; peer.their_node_id = Some(their_node_id); insert_node_id!(); let mut features = InitFeatures::known(); if !self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) { features.clear_initial_routing_sync(); } let resp = msgs::Init { features }; self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp); }, NextNoiseStep::ActThree => { let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..])); peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes peer.pending_read_is_header = true; peer.their_node_id = Some(their_node_id); insert_node_id!(); }, NextNoiseStep::NoiseComplete => { if peer.pending_read_is_header { let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..])); peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16); peer.pending_read_buffer.resize(msg_len as usize + 16, 0); if msg_len < 2 { // Need at least the message type tag return Err(PeerHandleError{ no_connection_possible: false }); } peer.pending_read_is_header = false; } else { let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..])); assert!(msg_data.len() >= 2); // Reset read buffer peer.pending_read_buffer = [0; 18].to_vec(); peer.pending_read_is_header = true; let mut reader = ::std::io::Cursor::new(&msg_data[..]); let message_result = wire::read(&mut reader); let message = match message_result { Ok(x) => x, Err(e) => { match e { msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }), msgs::DecodeError::UnknownRequiredFeature => { log_debug!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!"); continue; } msgs::DecodeError::InvalidValue => { log_debug!(self.logger, "Got an invalid value while deserializing message"); return Err(PeerHandleError { no_connection_possible: false }); } msgs::DecodeError::ShortRead => { log_debug!(self.logger, "Deserialization failed due to shortness of message"); return Err(PeerHandleError { no_connection_possible: false }); } msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }), msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }), } } }; if let Err(handling_error) = self.handle_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), message){ match handling_error { MessageHandlingError::PeerHandleError(e) => { return Err(e) }, MessageHandlingError::LightningError(e) => { try_potential_handleerror!(Err(e)); }, } } } } } } } self.do_attempt_write_data(peer_descriptor, peer); peer.pending_outbound_buffer.len() > 10 // pause_read } }; pause_read }; Ok(pause_read) } /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer fn handle_message(&self, peers_needing_send: &mut HashSet<Descriptor>, peer: &mut Peer, peer_descriptor: Descriptor, message: wire::Message) -> Result<(), MessageHandlingError> { log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap())); // Need an Init as first message if let wire::Message::Init(_) = message { } else if peer.their_features.is_none() { log_trace!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap())); return Err(PeerHandleError{ no_connection_possible: false }.into()); } match message { // Setup and Control messages: wire::Message::Init(msg) => { if msg.features.requires_unknown_bits() { log_info!(self.logger, "Peer global features required unknown version bits"); return Err(PeerHandleError{ no_connection_possible: true }.into()); } if msg.features.requires_unknown_bits() { log_info!(self.logger, "Peer local features required unknown version bits"); return Err(PeerHandleError{ no_connection_possible: true }.into()); } if peer.their_features.is_some() { return Err(PeerHandleError{ no_connection_possible: false }.into()); } log_info!( self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, static_remote_key: {}, unknown flags (local and global): {}", if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"}, if msg.features.initial_routing_sync() { "requested" } else { "not requested" }, if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"}, if msg.features.supports_static_remote_key() { "supported" } else { "not supported"}, if msg.features.supports_unknown_bits() { "present" } else { "none" } ); if msg.features.initial_routing_sync() { peer.sync_status = InitSyncTracker::ChannelsSyncing(0); peers_needing_send.insert(peer_descriptor.clone()); } if !msg.features.supports_static_remote_key() { log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap())); return Err(PeerHandleError{ no_connection_possible: true }.into()); } if !peer.outbound { let mut features = InitFeatures::known(); if !self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) { features.clear_initial_routing_sync(); } let resp = msgs::Init { features }; self.enqueue_message(peers_needing_send, peer, peer_descriptor.clone(), &resp); } self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg); peer.their_features = Some(msg.features); }, wire::Message::Error(msg) => { let mut data_is_printable = true; for b in msg.data.bytes() { if b < 32 || b > 126 { data_is_printable = false; break; } } if data_is_printable { log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data); } else { log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap())); } self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg); if msg.channel_id == [0; 32] { return Err(PeerHandleError{ no_connection_possible: true }.into()); } }, wire::Message::Ping(msg) => { if msg.ponglen < 65532 { let resp = msgs::Pong { byteslen: msg.ponglen }; self.enqueue_message(peers_needing_send, peer, peer_descriptor.clone(), &resp); } }, wire::Message::Pong(_msg) => { peer.awaiting_pong = false; }, // Channel messages: wire::Message::OpenChannel(msg) => { self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); }, wire::Message::AcceptChannel(msg) => { self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); }, wire::Message::FundingCreated(msg) => { self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg); }, wire::Message::FundingSigned(msg) => { self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg); }, wire::Message::FundingLocked(msg) => { self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg); }, wire::Message::Shutdown(msg) => { self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg); }, wire::Message::ClosingSigned(msg) => { self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg); }, // Commitment messages: wire::Message::UpdateAddHTLC(msg) => { self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg); }, wire::Message::UpdateFulfillHTLC(msg) => { self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg); }, wire::Message::UpdateFailHTLC(msg) => { self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg); }, wire::Message::UpdateFailMalformedHTLC(msg) => { self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg); }, wire::Message::CommitmentSigned(msg) => { self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg); }, wire::Message::RevokeAndACK(msg) => { self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg); }, wire::Message::UpdateFee(msg) => { self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg); }, wire::Message::ChannelReestablish(msg) => { self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg); }, // Routing messages: wire::Message::AnnouncementSignatures(msg) => { self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg); }, wire::Message::ChannelAnnouncement(msg) => { let should_forward = match self.message_handler.route_handler.handle_channel_announcement(&msg) { Ok(v) => v, Err(e) => { return Err(e.into()); }, }; if should_forward { // TODO: forward msg along to all our other peers! } }, wire::Message::NodeAnnouncement(msg) => { let should_forward = match self.message_handler.route_handler.handle_node_announcement(&msg) { Ok(v) => v, Err(e) => { return Err(e.into()); }, }; if should_forward { // TODO: forward msg along to all our other peers! } }, wire::Message::ChannelUpdate(msg) => { let should_forward = match self.message_handler.route_handler.handle_channel_update(&msg) { Ok(v) => v, Err(e) => { return Err(e.into()); }, }; if should_forward { // TODO: forward msg along to all our other peers! } }, // Unknown messages: wire::Message::Unknown(msg_type) if msg_type.is_even() => { log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", msg_type); // Fail the channel if message is an even, unknown type as per BOLT #1. return Err(PeerHandleError{ no_connection_possible: true }.into()); }, wire::Message::Unknown(msg_type) => { log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", msg_type); } }; Ok(()) } /// Checks for any events generated by our handlers and processes them. Includes sending most /// response messages as well as messages generated by calls to handler functions directly (eg /// functions like ChannelManager::process_pending_htlc_forward or send_payment). pub fn process_events(&self) { { // TODO: There are some DoS attacks here where you can flood someone's outbound send // buffer by doing things like announcing channels on another node. We should be willing to // drop optional-ish messages when send buffers get full! let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events(); let mut peers_lock = self.peers.lock().unwrap(); let peers = &mut *peers_lock; for event in events_generated.drain(..) { macro_rules! get_peer_for_forwarding { ($node_id: expr, $handle_no_such_peer: block) => { { let descriptor = match peers.node_id_to_descriptor.get($node_id) { Some(descriptor) => descriptor.clone(), None => { $handle_no_such_peer; continue; }, }; match peers.peers.get_mut(&descriptor) { Some(peer) => { if peer.their_features.is_none() { $handle_no_such_peer; continue; } (descriptor, peer) }, None => panic!("Inconsistent peers set state!"), } } } } match event { MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.temporary_channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Drop the pending channel? (or just let it timeout, but that sucks) }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.temporary_channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Drop the pending channel? (or just let it timeout, but that sucks) }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})", log_pubkey!(node_id), log_bytes!(msg.temporary_channel_id), log_funding_channel_id!(msg.funding_txid, msg.funding_output_index)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: generate a DiscardFunding event indicating to the wallet that //they should just throw away this funding transaction }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: generate a DiscardFunding event indicating to the wallet that //they should just throw away this funding transaction }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: generate a DiscardFunding event indicating to the wallet that //they should just throw away this funding transaction }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => { log_trace!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}", log_pubkey!(node_id), update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), log_bytes!(commitment_signed.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); for msg in update_add_htlcs { peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); } for msg in update_fulfill_htlcs { peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); } for msg in update_fail_htlcs { peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); } for msg in update_fail_malformed_htlcs { peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); } if let &Some(ref msg) = update_fee { peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); } peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendShutdown { ref node_id, ref msg } => { log_trace!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}", log_pubkey!(node_id), log_bytes!(msg.channel_id)); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => { log_trace!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id); if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() { let encoded_msg = encode_msg!(msg); let encoded_update_msg = encode_msg!(update_msg); for (ref descriptor, ref mut peer) in peers.peers.iter_mut() { if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || !peer.should_forward_channel_announcement(msg.contents.short_channel_id) { continue } match peer.their_node_id { None => continue, Some(their_node_id) => { if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 { continue } } } peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..])); self.do_attempt_write_data(&mut (*descriptor).clone(), peer); } } }, MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => { log_trace!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler"); if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() { let encoded_msg = encode_msg!(msg); for (ref descriptor, ref mut peer) in peers.peers.iter_mut() { if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || !peer.should_forward_node_announcement(msg.contents.node_id) { continue } peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); self.do_attempt_write_data(&mut (*descriptor).clone(), peer); } } }, MessageSendEvent::BroadcastChannelUpdate { ref msg } => { log_trace!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id); if self.message_handler.route_handler.handle_channel_update(msg).is_ok() { let encoded_msg = encode_msg!(msg); for (ref descriptor, ref mut peer) in peers.peers.iter_mut() { if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || !peer.should_forward_channel_announcement(msg.contents.short_channel_id) { continue } peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..])); self.do_attempt_write_data(&mut (*descriptor).clone(), peer); } } }, MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => { self.message_handler.route_handler.handle_htlc_fail_channel_update(update); }, MessageSendEvent::HandleError { ref node_id, ref action } => { match *action { msgs::ErrorAction::DisconnectPeer { ref msg } => { if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) { peers.peers_needing_send.remove(&descriptor); if let Some(mut peer) = peers.peers.remove(&descriptor) { if let Some(ref msg) = *msg { log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}", log_pubkey!(node_id), msg.data); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); // This isn't guaranteed to work, but if there is enough free // room in the send buffer, put the error message there... self.do_attempt_write_data(&mut descriptor, &mut peer); } else { log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id)); } } descriptor.disconnect_socket(); self.message_handler.chan_handler.peer_disconnected(&node_id, false); } }, msgs::ErrorAction::IgnoreError => {}, msgs::ErrorAction::SendErrorMessage { ref msg } => { log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}", log_pubkey!(node_id), msg.data); let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, { //TODO: Do whatever we're gonna do for handling dropped messages }); peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); self.do_attempt_write_data(&mut descriptor, peer); }, } } } } for mut descriptor in peers.peers_needing_send.drain() { match peers.peers.get_mut(&descriptor) { Some(peer) => self.do_attempt_write_data(&mut descriptor, peer), None => panic!("Inconsistent peers set state!"), } } } } /// Indicates that the given socket descriptor's connection is now closed. /// /// This must only be called if the socket has been disconnected by the peer or your own /// decision to disconnect it and must NOT be called in any case where other parts of this /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect /// the peer. /// /// Panics if the descriptor was not previously registered in a successful new_*_connection event. pub fn socket_disconnected(&self, descriptor: &Descriptor) { self.disconnect_event_internal(descriptor, false); } fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) { let mut peers = self.peers.lock().unwrap(); peers.peers_needing_send.remove(descriptor); let peer_option = peers.peers.remove(descriptor); match peer_option { None => panic!("Descriptor for disconnect_event is not already known to PeerManager"), Some(peer) => { match peer.their_node_id { Some(node_id) => { peers.node_id_to_descriptor.remove(&node_id); self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible); }, None => {} } } }; } /// This function should be called roughly once every 30 seconds. /// It will send pings to each peer and disconnect those which did not respond to the last round of pings. /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues! pub fn timer_tick_occured(&self) { let mut peers_lock = self.peers.lock().unwrap(); { let peers = &mut *peers_lock; let peers_needing_send = &mut peers.peers_needing_send; let node_id_to_descriptor = &mut peers.node_id_to_descriptor; let peers = &mut peers.peers; let mut descriptors_needing_disconnect = Vec::new(); peers.retain(|descriptor, peer| { if peer.awaiting_pong { peers_needing_send.remove(descriptor); descriptors_needing_disconnect.push(descriptor.clone()); match peer.their_node_id { Some(node_id) => { log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id); node_id_to_descriptor.remove(&node_id); self.message_handler.chan_handler.peer_disconnected(&node_id, false); } None => { // This can't actually happen as we should have hit // is_ready_for_encryption() previously on this same peer. unreachable!(); }, } return false; } if !peer.channel_encryptor.is_ready_for_encryption() { // The peer needs to complete its handshake before we can exchange messages return true; } let ping = msgs::Ping { ponglen: 0, byteslen: 64, }; peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&ping))); let mut descriptor_clone = descriptor.clone(); self.do_attempt_write_data(&mut descriptor_clone, peer); peer.awaiting_pong = true; true }); for mut descriptor in descriptors_needing_disconnect.drain(..) { descriptor.disconnect_socket(); } } } } #[cfg(test)] mod tests { use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor}; use ln::msgs; use util::events; use util::test_utils; use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::key::{SecretKey, PublicKey}; use std; use std::sync::{Arc, Mutex}; use std::sync::atomic::Ordering; #[derive(Clone)] struct FileDescriptor { fd: u16, outbound_data: Arc<Mutex<Vec<u8>>>, } impl PartialEq for FileDescriptor { fn eq(&self, other: &Self) -> bool { self.fd == other.fd } } impl Eq for FileDescriptor { } impl std::hash::Hash for FileDescriptor { fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) { self.fd.hash(hasher) } } impl SocketDescriptor for FileDescriptor { fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize { self.outbound_data.lock().unwrap().extend_from_slice(data); data.len() } fn disconnect_socket(&mut self) {} } struct PeerManagerCfg { chan_handler: test_utils::TestChannelMessageHandler, routing_handler: test_utils::TestRoutingMessageHandler, logger: test_utils::TestLogger, } fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> { let mut cfgs = Vec::new(); for _ in 0..peer_count { cfgs.push( PeerManagerCfg{ chan_handler: test_utils::TestChannelMessageHandler::new(), logger: test_utils::TestLogger::new(), routing_handler: test_utils::TestRoutingMessageHandler::new(), } ); } cfgs } fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>> { let mut peers = Vec::new(); for i in 0..peer_count { let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap(); let ephemeral_bytes = [i as u8; 32]; let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler }; let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger); peers.push(peer); } peers } fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>) -> (FileDescriptor, FileDescriptor) { let secp_ctx = Secp256k1::new(); let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret); let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap(); peer_a.new_inbound_connection(fd_a.clone()).unwrap(); assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false); assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); (fd_a.clone(), fd_b.clone()) } fn establish_connection_and_read_events<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>) -> (FileDescriptor, FileDescriptor) { let (mut fd_a, mut fd_b) = establish_connection(peer_a, peer_b); assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); (fd_a.clone(), fd_b.clone()) } #[test] fn test_disconnect_peer() { // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and // push a DisconnectPeer event to remove the node flagged by id let cfgs = create_peermgr_cfgs(2); let chan_handler = test_utils::TestChannelMessageHandler::new(); let mut peers = create_network(2, &cfgs); establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); let secp_ctx = Secp256k1::new(); let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret); chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError { node_id: their_id, action: msgs::ErrorAction::DisconnectPeer { msg: None }, }); assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1); peers[0].message_handler.chan_handler = &chan_handler; peers[0].process_events(); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0); } #[test] fn test_timer_tick_occurred() { // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer. let cfgs = create_peermgr_cfgs(2); let peers = create_network(2, &cfgs); establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); // peers[0] awaiting_pong is set to true, but the Peer is still connected peers[0].timer_tick_occured(); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected peers[0].timer_tick_occured(); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0); } #[test] fn test_do_attempt_write_data() { // Create 2 peers with custom TestRoutingMessageHandlers and connect them. let cfgs = create_peermgr_cfgs(2); cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release); cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release); let peers = create_network(2, &cfgs); // By calling establish_connect, we trigger do_attempt_write_data between // the peers. Previously this function would mistakenly enter an infinite loop // when there were more channel messages available than could fit into a peer's // buffer. This issue would now be detected by this test (because we use custom // RoutingMessageHandlers that intentionally return more channel messages // than can fit into a peer's buffer). let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]); // Make each peer to read the messages that the other peer just wrote to them. peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(); peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(); // Check that each peer has received the expected number of channel updates and channel // announcements. assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); } #[test] fn limit_initial_routing_sync_requests() { // Inbound peer 0 requests initial_routing_sync, but outbound peer 1 does not. { let cfgs = create_peermgr_cfgs(2); cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release); let peers = create_network(2, &cfgs); let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]); let peer_0 = peers[0].peers.lock().unwrap(); let peer_1 = peers[1].peers.lock().unwrap(); let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref(); let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref(); assert!(peer_0_features.unwrap().initial_routing_sync()); assert!(!peer_1_features.unwrap().initial_routing_sync()); } // Outbound peer 1 requests initial_routing_sync, but inbound peer 0 does not. { let cfgs = create_peermgr_cfgs(2); cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release); let peers = create_network(2, &cfgs); let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]); let peer_0 = peers[0].peers.lock().unwrap(); let peer_1 = peers[1].peers.lock().unwrap(); let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref(); let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref(); assert!(!peer_0_features.unwrap().initial_routing_sync()); assert!(peer_1_features.unwrap().initial_routing_sync()); } } }
44.923836
386
0.705535
fbf720f8fa65774de2846e27118f6c573a773960
4,561
use std::io::Write; use std::path::Path; use openssl::ssl::{SslConnectorBuilder, SslConnector, SslMethod}; use openssl::error::ErrorStack; use openssl::x509::X509_FILETYPE_PEM; use openssl_sys::TLSv1_2_method; use hyper::net::{HttpsConnector, Fresh}; use hyper_openssl::OpensslClient; use hyper::method::Method; use hyper::Client; use hyper::client::RequestBuilder; use hyper::client::request::Request; use url::Url; pub fn ssl_connector<C>(cacert: C, cert: Option<C>, key: Option<C>) -> Result<SslConnector, ErrorStack> where C: AsRef<Path> { unsafe { let mut connector = SslConnectorBuilder::new(SslMethod::from_ptr(TLSv1_2_method())).unwrap(); { let mut ctx = connector.builder_mut(); try!(ctx.set_cipher_list("DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:\ DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:\ DHE-RSA-CAMELLIA128-SHA:DHE-RSA-AES128-SHA:\ DHE-RSA-CAMELLIA256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:\ AES256-GCM-SHA384:CAMELLIA128-SHA:AES128-SHA:!aNULL:!eNULL:\ !EXPORT:!DES:!3DES:!RC4:!MD5")); try!(ctx.set_ca_file(cacert.as_ref())); // TODO should validate both key and cert are set when either one is // specified if let Some(cert) = cert { try!(ctx.set_certificate_file(cert.as_ref(), X509_FILETYPE_PEM)); }; if let Some(key) = key { try!(ctx.set_private_key_file(key.as_ref(), X509_FILETYPE_PEM)); }; } Ok(connector.build()) } } pub fn https_connector<C>(cacert: C, cert: Option<C>, key: Option<C>) -> HttpsConnector<OpensslClient> where C: AsRef<Path> { let connector = match ssl_connector(cacert, cert, key) { Ok(connector) => connector, Err(e) => pretty_panic!("Error opening certificate files: {}", e), }; HttpsConnector::new(OpensslClient::from(connector)) } header! { (XAuthentication, "X-Authentication") => [String] } pub enum Auth { CertAuth { cacert: String, cert: String, key: String, }, NoAuth, TokenAuth { cacert: String, token: String, }, } impl Auth { pub fn client(&self) -> Client { match self { &Auth::CertAuth { ref cacert, ref cert, ref key } => { let conn = https_connector(Path::new(cacert), Some(Path::new(cert)), Some(Path::new(key))); Client::with_connector(conn) } &Auth::TokenAuth { ref cacert, .. } => { let conn = https_connector(Path::new(cacert), None, None); Client::with_connector(conn) } &Auth::NoAuth => Client::new(), } } pub fn request(&self, method: Method, url: Url) -> Request<Fresh> { match self { &Auth::CertAuth { ref cacert, ref cert, ref key } => { let conn = https_connector(Path::new(cacert), Some(Path::new(cert)), Some(Path::new(key))); Request::<Fresh>::with_connector(method, url, &conn).unwrap() } &Auth::TokenAuth { ref cacert, ref token, .. } => { let conn = https_connector(Path::new(cacert), None, None); let mut req = Request::<Fresh>::with_connector(method, url, &conn).unwrap(); req.headers_mut().set(XAuthentication(token.clone())); req } &Auth::NoAuth => Request::<Fresh>::new(method, url).unwrap(), } } pub fn auth_header<'a>(&self, request_builder: RequestBuilder<'a>) -> RequestBuilder<'a> { match self { &Auth::TokenAuth { ref token, .. } => { request_builder.header(XAuthentication(token.clone())) } _ => request_builder, } } } /// Checks whether the vector of urls contains a url that needs to use SSL, i.e. /// has `https` as the scheme. pub fn is_ssl(server_urls: &Vec<String>) -> bool { server_urls.into_iter() .any(|url| { "https" == Url::parse(&url) .unwrap_or_else(|e| pretty_panic!("Error parsing url {:?}: {}", url, e)) .scheme() }) }
36.198413
103
0.532997
e9d73251c9471787a3a5af8d03674cccc8119cb8
1,499
use super::*; mod private { pub trait Sealed<T> {} impl<T> Sealed<T> for T {} impl<T, A: Sealed<T>> Sealed<T> for (A, T) {} impl<T> Sealed<T> for Option<T> {} impl<T> Sealed<T> for Vec<T> {} impl Sealed<char> for String {} } /// A utility trait that facilitates chaining parser outputs together into [`Vec`]s. /// /// See [`Parser::chain`] pub trait Chain<T>: private::Sealed<T> { /// The number of items that this chain link consists of. fn len(&self) -> usize; /// Append the elements in this link to the chain. fn append_to(self, v: &mut Vec<T>); } impl<T> Chain<T> for T { fn len(&self) -> usize { 1 } fn append_to(self, v: &mut Vec<T>) { v.push(self); } } impl<T, A: Chain<T>> Chain<T> for (A, T) { fn len(&self) -> usize { 1 } fn append_to(self, v: &mut Vec<T>) { self.0.append_to(v); v.push(self.1); } } impl<T> Chain<T> for Option<T> { fn len(&self) -> usize { self.is_some() as usize } fn append_to(self, v: &mut Vec<T>) { self.map(|x| v.push(x)); } } impl<T> Chain<T> for Vec<T> { fn len(&self) -> usize { self.as_slice().len() } fn append_to(mut self, v: &mut Vec<T>) { v.append(&mut self); } } impl Chain<char> for String { // TODO: Quite inefficient fn len(&self) -> usize { self.chars().count() } fn append_to(self, v: &mut Vec<char>) { v.extend(self.chars()); } }
21.724638
84
0.533022
0e91460fe0bf2bb67031e39dca843812aaa0bfbf
3,959
// Copyright (c) 2022, Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use serde::ser::Error; use serde::Serialize; use std::fmt; use std::fmt::Write; use std::fmt::{Display, Formatter}; use sui_types::base_types::ObjectRef; use sui_types::gas_coin::GasCoin; use sui_types::messages::CertifiedTransaction; use sui_types::object::Object; #[derive(Serialize)] pub struct SplitCoinResponse { /// Certificate of the transaction pub certificate: CertifiedTransaction, /// The updated original coin object after split pub updated_coin: Object, /// All the newly created coin objects generated from the split pub new_coins: Vec<Object>, /// The updated gas payment object after deducting payment pub updated_gas: Object, } impl Display for SplitCoinResponse { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut writer = String::new(); writeln!(writer, "----- Certificate ----")?; write!(writer, "{}", self.certificate)?; writeln!(writer, "----- Split Coin Results ----")?; let coin = GasCoin::try_from(&self.updated_coin).map_err(fmt::Error::custom)?; writeln!(writer, "Updated Coin : {}", coin)?; let mut new_coin_text = Vec::new(); for coin in &self.new_coins { let coin = GasCoin::try_from(coin).map_err(fmt::Error::custom)?; new_coin_text.push(format!("{}", coin)) } writeln!( writer, "New Coins : {}", new_coin_text.join(",\n ") )?; let gas_coin = GasCoin::try_from(&self.updated_gas).map_err(fmt::Error::custom)?; writeln!(writer, "Updated Gas : {}", gas_coin)?; write!(f, "{}", writer) } } #[derive(Serialize)] pub struct MergeCoinResponse { /// Certificate of the transaction pub certificate: CertifiedTransaction, /// The updated original coin object after merge pub updated_coin: Object, /// The updated gas payment object after deducting payment pub updated_gas: Object, } impl Display for MergeCoinResponse { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut writer = String::new(); writeln!(writer, "----- Certificate ----")?; write!(writer, "{}", self.certificate)?; writeln!(writer, "----- Merge Coin Results ----")?; let coin = GasCoin::try_from(&self.updated_coin).map_err(fmt::Error::custom)?; writeln!(writer, "Updated Coin : {}", coin)?; let gas_coin = GasCoin::try_from(&self.updated_gas).map_err(fmt::Error::custom)?; writeln!(writer, "Updated Gas : {}", gas_coin)?; write!(f, "{}", writer) } } #[derive(Serialize)] pub struct PublishResponse { /// Certificate of the transaction pub certificate: CertifiedTransaction, /// The newly published package object reference. pub package: ObjectRef, /// List of Move objects created as part of running the module initializers in the package pub created_objects: Vec<Object>, /// The updated gas payment object after deducting payment pub updated_gas: Object, } impl Display for PublishResponse { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut writer = String::new(); writeln!(writer, "----- Certificate ----")?; write!(writer, "{}", self.certificate)?; writeln!(writer, "----- Publish Results ----")?; writeln!( writer, "The newly published package object: {:?}", self.package )?; writeln!( writer, "List of objects created by running module initializers:" )?; for obj in &self.created_objects { writeln!(writer, "{}", obj)?; } let gas_coin = GasCoin::try_from(&self.updated_gas).map_err(fmt::Error::custom)?; writeln!(writer, "Updated Gas : {}", gas_coin)?; write!(f, "{}", writer) } }
35.666667
94
0.60874
91563faacdf8a87bae05e7b4d0f07ff8de008a6c
2,723
use crate::game::stage::NetRelay; use crate::game::Game; use crate::game::{GameSettings, Stage}; use crate::net::NetworkMode; use crate::server::{ServerConfig, ServerHandle}; use std::net::ToSocketAddrs; use std::sync::mpsc::channel; use std::sync::mpsc::Sender as TSender; use std::thread; use ws::Sender as WsSender; use ws::{Builder, Factory}; pub fn listen<A: ToSocketAddrs>(ip: A, id: usize, max_players: usize) { let settings = ServerConfig::from_disk().into(); let game_settings = GameSettings::new(id, max_players, NetworkMode::Server); let (send, stage) = Stage::build(game_settings); let builder = thread::Builder::new().name(format!("server_{}", id)); let thread_handle = builder.spawn(move || stage.run_authority()); let factory = ServerFactory { sender: send, active_connections: 0, max_players, next_player_id: 0, }; let ws = Builder::new().with_settings(settings).build(factory); ws.unwrap() .listen(ip) .expect("Couldn't listen or connection panic! for server."); info!("Waiting for server game thread to close."); thread_handle.unwrap().join().unwrap(); info!("Server Done!"); } struct ServerFactory { sender: TSender<NetRelay>, active_connections: usize, max_players: usize, next_player_id: usize, } impl Factory for ServerFactory { type Handler = ServerHandle; fn connection_made(&mut self, out: WsSender) -> ServerHandle { let id = self.next_player_id; self.next_player_id += 1; let role = if self.next_player_id > self.max_players { Role::GameFull } else if self.next_player_id == self.max_players { Role::Player(true) // true if final player to connect. } else { Role::Player(false) }; self.active_connections += 1; ServerHandle::new(out, self.sender.clone(), id, role) } fn connection_lost(&mut self, handle: ServerHandle) { info!("Connection #{} lost.", handle.player_id); self.active_connections -= 1; // The last connecction will shutdown the server. if self.active_connections == 0 { info!("All connections lost: Begin shutdown."); if handle.ws.shutdown().is_err() { warn!("Unable to send shutdown. Have we stopped already?") } } } fn on_shutdown(&mut self) { info!("ServerFactory received WebSocket shutdown request."); let ev = NetRelay::Shutdown(std::usize::MAX); if self.sender.send(ev).is_ok() { info!("Sending 'StopAndExit' to core.") } } } pub enum Role { Player(bool), Spectator, GameFull, }
32.035294
80
0.626148
1d340c55fb315bcbe8cc6c8a62b36ba4b513ff43
10,362
use core::{ cell::UnsafeCell, mem::{ManuallyDrop, MaybeUninit}, ptr, sync::atomic::{AtomicU8, Ordering}, }; /// A slot containing an element. pub(crate) struct Slot<T> { /// The element stored in the slot, the initialization state being defined the slot's state mask. inner: UnsafeCell<MaybeUninit<T>>, /// The flags indicating the slot's initialization state. state: AtomicU8, } /// The state bits of a completely uninitialized slot. const UNINIT: u8 = 0; /// The state bit indicating a producer/consumer detecting it should call /// `Node::check_slots_and_try_reclaim` (resume it) from the next slot on. const CONTINUE_CHECK: u8 = 0b0001; /// The state bit set by a producer AFTER writing an element into the slot, marking it as ready. const PRODUCER: u8 = 0b0010; /// The state bit set by a consumer AFTER having invalidated or consumed the slot. const CONSUMED_OR_INVALIDATED: u8 = 0b0100; /// The state bit set by a consumer BEFORE attempting to invalidate the slot. const NO_PRODUCER_YET: u8 = 0b1000; /// The bit mask indicating a slot has been successfully consumed. const CONSUMED: u8 = PRODUCER | CONSUMED_OR_INVALIDATED; impl<T> Slot<T> { /// Creates a new uninitialized slot. pub(crate) const fn new() -> Self { Self { inner: UnsafeCell::new(MaybeUninit::uninit()), state: AtomicU8::new(UNINIT) } } /// Creates a new slot initialized with `elem`. pub(crate) const fn with(elem: T) -> Self { Self { inner: UnsafeCell::new(MaybeUninit::new(elem)), state: AtomicU8::new(PRODUCER) } } /// Creates a new slot tentatively initialized with `elem`. /// /// # Safety /// /// The write must subsequently be either affirmed or denied, in which case the stored element /// must not be accessed any further. pub(crate) unsafe fn with_tentative(elem: &ManuallyDrop<T>) -> Self { Self { inner: UnsafeCell::new(MaybeUninit::new(ptr::read(&**elem))), state: AtomicU8::new(PRODUCER), } } /// Returns a raw pointer to the slot's element. pub(crate) fn as_mut_ptr(&self) -> *mut T { unsafe { (*self.inner.get()).as_mut_ptr() } } /// Inspects the state and contents of this slots and returns a reference to the element, if it /// is initialized. pub(crate) unsafe fn inspect_unsync(&self) -> Option<&T> { (self.state.load(Ordering::Relaxed) == PRODUCER).then(move || unsafe { let slot = &(*self.inner.get()); slot.assume_init_ref() }) } /// Returns `true` if the slot is consumed. pub(crate) fn is_consumed(&self) -> bool { self.state.load(Ordering::Acquire) & CONSUMED == CONSUMED } /// Atomically sets the [`CONTINUE_CHECK`] bit in the slots state mask. /// /// # Safety /// /// Must only be called during the *check slots* procedure and after determining, the slot has /// not yet been consumed. pub(crate) unsafe fn set_continue_bit(&self) -> bool { self.state.fetch_add(CONTINUE_CHECK, Ordering::Relaxed) & CONSUMED == CONSUMED } pub(crate) unsafe fn try_consume(&self) -> ConsumeResult<T> { const CONTINUE_OR_PRODUCER: u8 = CONTINUE_CHECK | PRODUCER; // loop a bounded number of steps in order to allow the corresponding producer to complete // its corresponding call to `write_tentative` for _ in 0..16 { // (slot:x) this acquire load syncs-with the release FAA (slot:y) if self.state.load(Ordering::Acquire) & PRODUCER == PRODUCER { // SAFETY: Since the PRODUCER bit is already set, the slot can be safely read (no // data race is possible) and the CONSUMED_OR_INVALIDATED bit can be set right away, // as no 2-step invalidation is necessary let elem = unsafe { self.read() }; return match self.state.fetch_add(CONSUMED_OR_INVALIDATED, Ordering::Release) { // the expected/likely case PRODUCER => ConsumeResult::Success { elem, resume_check: false }, // RESUME can only be set if there are multiple consumers CONTINUE_OR_PRODUCER => ConsumeResult::Success { elem, resume_check: true }, // SAFETY: no other combination of state bits is possible at this point _ => unsafe { core::hint::unreachable_unchecked() }, }; } } // after an unsuccessful bounded wait, try one final time or invalidate (abandon) the slot // if this fails as well due to the producer still not having finished its operation // NOTE: this is expensive but is unlikely to occur, i.e. the bounded wait will usually // suffice unsafe { self.try_consume_unlikely() } } /// Consumes the element from this slot without performing any checks. /// /// # Safety /// /// The slot must have been written to before. pub(crate) unsafe fn consume_unchecked_unsync(&mut self) -> T { self.state.store(CONSUMED, Ordering::Relaxed); (*self.inner.get()).as_ptr().read() } /// Writes `elem` into the slot (used only by `OwnedQueue`). /// /// Should only be called once, since already written elements will be silently overwritten and /// leaked. pub(crate) fn write_unsync(&mut self, elem: T) { *self = Self::with(elem); } /// Writes `elem` tentatively into the slot. pub(crate) unsafe fn write_tentative(&self, elem: &ManuallyDrop<T>) -> WriteResult { // if a slot has already been visited and marked for abandonment AND halted at in an attempt // to check if all slots have yet been consumed, a producer must abandon that slot and // resume the slot check procedure const PRODUCER_RESUMES: u8 = NO_PRODUCER_YET | CONSUMED_OR_INVALIDATED | CONTINUE_CHECK; // write the element's bits tentatively into the slot, i.e. the write may yet be revoked, in // which case the source must remain valid self.write(elem); // after the slot is initialized, set the WRITER bit in the slot's state field and assess, // if any other bits had been set by other (consumer) threads match self.state.fetch_add(PRODUCER, Ordering::Release) { // either no bit or ONLY the continue bit is set => success, the continue bit will only // matter for the corresponding consumer, when it sets its bit in the same slot UNINIT | CONTINUE_CHECK => WriteResult::Success, PRODUCER_RESUMES => WriteResult::Abandon { resume_check: true }, _ => WriteResult::Abandon { resume_check: false }, } } #[cold] unsafe fn try_consume_unlikely(&self) -> ConsumeResult<T> { // FIXME: could be replaced with inline const const CONSUMER_RESUMES_A: u8 = PRODUCER | CONTINUE_CHECK; // set the NO_PRODUCER_YET bit, which leads to all subsequent write attempts to fail, but // check, if the PRODUCER bit has been set before by now let (res, mut resume_check) = match self.state.fetch_add(NO_PRODUCER_YET, Ordering::Acquire) { // the slot has now been initialized, so the slot can now be consumed PRODUCER => (Some(self.read()), false), // the slot has now been initialized, but the slot check must be resumed CONSUMER_RESUMES_A => (Some(self.read()), true), // the slot has still not been initialized, so it must truly be abandoned now _ => (None, false), }; // set the CONSUMED_OR_INVALIDATED bit to mark the consume operation as completed; whether // a write has occurred or not is no longer relevant at this point let state = self.state.fetch_add(CONSUMED_OR_INVALIDATED, Ordering::Release); // if the CONTINUE_CHECK bit was not previously set but is now, the slot check must now be resumed if !resume_check && state == NO_PRODUCER_YET | CONSUMER_RESUMES_A { resume_check = true; } match res { Some(elem) => ConsumeResult::Success { elem, resume_check }, None => ConsumeResult::Abandon { resume_check }, } } /// Reads the bytes of this slot without performing any checks. unsafe fn read(&self) -> T { unsafe { (*self.inner.get()).as_ptr().read() } } /// Writes the bytes of `elem` into this slot without performing any checks. unsafe fn write(&self, elem: &ManuallyDrop<T>) { unsafe { let ptr = (*self.inner.get()).as_mut_ptr(); ptr.copy_from_nonoverlapping(&**elem, 1); } } } /// An (unsafe) transparent wrapper for slot that automatically drops the /// contained type. /// /// N.B: There is deliberately no (safe) way to create a `DropSlot` outside of this module #[repr(transparent)] pub(crate) struct DropSlot<T>(Slot<T>); impl<T> Drop for DropSlot<T> { fn drop(&mut self) { // SAFETY: this in fact NOT safe in general, because it neither checks if the wrapped slot // has ever been initialized, nor if it has not yet been consumed, but `drop` can not be an // `unsafe` function; but: // - the type can not be safely constructed at all, only using unsafe pointer casts // - the type is only used internally and only in one place (`OwnedQueue::drop`) // - the drop code carefully identifies the slots that are safe to drop and casts only // those into `DropSlot`s unsafe { self.0.as_mut_ptr().drop_in_place() }; } } /// The result of a consume operation on a slot. pub(crate) enum ConsumeResult<T> { /// The slot was successfully consumed and the element can be returned. Success { resume_check: bool, elem: T }, /// The slot was not consumed because it was not yet initialized and has to be abandoned. Abandon { resume_check: bool }, } /// The result of a write (produce) operation on a slot. pub(crate) enum WriteResult { /// The operation was successful and the slot was initialized. Success, /// The operation failed, because a concurrent consumer had previously invalidated the slot, /// marking it for abandonment. Abandon { resume_check: bool }, }
44.093617
106
0.643119
5df7576133a684ab8f887f442084e99062eb4886
23
// nothing to see here
11.5
22
0.695652
6457d61b8ce611b1fb26af4f6d665f99841d97ac
1,543
//! `revhex` subcommand - reverses hex endianness. #![allow(clippy::never_loop)] use abscissa_core::{Command, Options, Runnable}; use std::io::stdin; /// Returns the hexadecimal-encoded string `s` in byte-reversed order. pub fn byte_reverse_hex(s: &str) -> String { String::from_utf8( s.as_bytes() .chunks(2) .rev() .map(|c| c.iter()) .flatten() .cloned() .collect::<Vec<u8>>(), ) .expect("input should be ascii") } /// `revhex` subcommand #[derive(Command, Debug, Default, Options)] pub struct RevhexCmd { /// The hex string whose endianness will be reversed. /// /// When input is "-" or empty, reads lines from standard input, and /// reverses each line. #[options(free)] input: String, } impl Runnable for RevhexCmd { /// Print endian-reversed hex string. fn run(&self) { if self.input.is_empty() || self.input == "-" { // "-" is a typical command-line argument for "read standard input" let mut input = String::new(); // Unlike similar C APIs, read_line returns Ok(0) on EOF. // We can distinguish EOF from an empty line, because the newline is // included in the buffer, so empty lines return Ok(1). while stdin().read_line(&mut input).unwrap_or(0) > 0 { println!("{}", byte_reverse_hex(&input.trim())); } } else { println!("{}", byte_reverse_hex(&self.input)); } } }
30.86
80
0.569021
d61a751828c166c1d2966871db89283773e7dc0a
3,129
use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::sync::Arc; use chashmap::CHashMap; use crate::declaration::FunctionPath; use crate::error::Diagnostic; use crate::node::{ExpressionKey, FunctionContext, Variable}; use crate::span::{Span, Spanned}; use super::{InferenceType, TypeEngine, TypeResolution, TypeVariable}; pub type TypeContexts = CHashMap<Arc<FunctionPath>, Arc<TypeContext>>; #[derive(Debug, Default)] pub struct Environment { variables: HashMap<Variable, (TypeVariable, Span)>, expressions: HashMap<ExpressionKey, Arc<InferenceType>>, } impl Environment { pub fn variable(&mut self, variable: Variable, type_variable: TypeVariable, span: Span) { if self.variables.insert(variable.clone(), (type_variable, span)).is_some() { panic!("Variable: {}, already exists in inference environment", variable); } } pub fn expression(&mut self, expression: ExpressionKey, inference_type: Arc<InferenceType>) { if self.expressions.insert(expression, inference_type).is_some() { panic!("Expression: {:?}, already exists in inference environment", expression); } } pub fn context(self, function: &FunctionContext, engine: &mut TypeEngine) -> Result<TypeContext, Diagnostic> { let construct = &mut |engine: &mut TypeEngine, inference: Arc<InferenceType>, span| engine.resolve(inference).map_err(|error| Diagnostic::new(Spanned::new(error, span))); let variables = self.variables.into_iter().map(|(variable, (type_variable, span))| construct(engine, Arc::new(InferenceType::Variable(type_variable)), span) .map(|resolution| (variable, resolution))).collect::<Result<_, _>>()?; let expressions = self.expressions.into_iter().map(|(expression, inference)| construct(engine, inference, function[&expression].span) .map(|resolution| (expression, resolution))).collect::<Result<_, _>>()?; Ok(TypeContext { variables, expressions }) } } impl Index<&Variable> for Environment { type Output = TypeVariable; fn index(&self, index: &Variable) -> &Self::Output { let (type_variable, _) = &self.variables[index]; type_variable } } impl IndexMut<&Variable> for Environment { fn index_mut(&mut self, index: &Variable) -> &mut Self::Output { let (type_variable, _) = self.variables.get_mut(index).unwrap(); type_variable } } impl Index<&ExpressionKey> for Environment { type Output = Arc<InferenceType>; fn index(&self, index: &ExpressionKey) -> &Self::Output { &self.expressions[index] } } impl IndexMut<&ExpressionKey> for Environment { fn index_mut(&mut self, index: &ExpressionKey) -> &mut Self::Output { self.expressions.get_mut(index).unwrap() } } #[derive(Debug)] pub struct TypeContext { variables: HashMap<Variable, TypeResolution>, expressions: HashMap<ExpressionKey, TypeResolution>, } impl Index<&Variable> for TypeContext { type Output = TypeResolution; fn index(&self, index: &Variable) -> &Self::Output { &self.variables[index] } } impl Index<&ExpressionKey> for TypeContext { type Output = TypeResolution; fn index(&self, index: &ExpressionKey) -> &Self::Output { &self.expressions[index] } }
31.29
94
0.719719
6176e75380a94549d46071962254d47bfdb1c307
528
// tests3.rs // This test isn't testing our function -- make it do that in such a way that // the test passes. Then write a second test that tests whether we get the result // we expect to get when we call `is_even(5)`. // Execute `rustlings hint tests3` for hints :) pub fn is_even(num: i32) -> bool { num % 2 == 0 } #[cfg(test)] mod tests { use super::*; #[test] fn is_true_when_even() { assert!(is_even(2)); } #[test] fn is_false_when_odd() { assert!(!is_even(2 + 1)); } }
21.12
81
0.600379
678d360b977658051940f0e4d7bfb180369266e3
20,419
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ counters, executor_proxy::ExecutorProxyTrait, peer_manager::{PeerManager, PeerScoreUpdateType}, LedgerInfo, PeerId, }; use config::config::StateSyncConfig; use execution_proto::proto::execution::{ExecuteChunkRequest, ExecuteChunkResponse}; use failure::prelude::*; use futures::{ channel::{mpsc, oneshot}, compat::Stream01CompatExt, stream::{futures_unordered::FuturesUnordered, select_all}, StreamExt, }; use logger::prelude::*; use network::{ proto::{GetChunkRequest, GetChunkResponse, StateSynchronizerMsg}, validator_network::{Event, StateSynchronizerEvents, StateSynchronizerSender}, }; use proto_conv::{FromProto, IntoProto}; use std::{ collections::HashMap, str::FromStr, time::{Duration, SystemTime, UNIX_EPOCH}, }; use tokio::timer::Interval; use types::{ crypto_proxies::LedgerInfoWithSignatures, proto::transaction::TransactionListWithProof, }; /// message used by StateSyncClient for communication with Coordinator pub enum CoordinatorMessage { // used to initiate new sync Requested(LedgerInfo, oneshot::Sender<bool>), // used to notify about new txn commit Commit(u64), GetState(oneshot::Sender<u64>), } /// used to coordinate synchronization process /// handles external sync requests and drives synchronization with remote peers pub(crate) struct SyncCoordinator<T> { // used to process client requests client_events: mpsc::UnboundedReceiver<CoordinatorMessage>, // last committed version that validator is aware of known_version: u64, // target state to sync to target: Option<LedgerInfo>, // config config: StateSyncConfig, // if autosync is on, StateSynchronizer will keep fetching chunks from upstream peers // even if no target state was specified autosync: bool, // peers used for synchronization. TBD: value is meta information about peer sync quality peer_manager: PeerManager, // option callback. Called when state sync reaches target version callback: Option<oneshot::Sender<bool>>, // timestamp of last commit last_commit: Option<SystemTime>, // queue of incoming long polling requests // peer will be notified about new chunk of transactions if it's available before expiry time // value format is (expiration_time, known_version, limit) subscriptions: HashMap<PeerId, (SystemTime, u64, u64)>, executor_proxy: T, } impl<T: ExecutorProxyTrait> SyncCoordinator<T> { pub fn new( client_events: mpsc::UnboundedReceiver<CoordinatorMessage>, config: StateSyncConfig, executor_proxy: T, ) -> Self { let upstream_peers: Vec<_> = config .upstream_peers .upstream_peers .iter() .map(|peer_id_str| { PeerId::from_str(peer_id_str).unwrap_or_else(|_| { panic!("Failed to parse peer_id from string: {}", peer_id_str) }) }) .collect(); Self { client_events, known_version: 0, target: None, config, // Note: We use upstream peer ids being non-empty as a proxy for a node being a full // node. autosync: !upstream_peers.is_empty(), peer_manager: PeerManager::new(upstream_peers), subscriptions: HashMap::new(), callback: None, last_commit: None, executor_proxy, } } /// main routine. starts sync coordinator that listens for CoordinatorMsg pub async fn start(mut self, network: Vec<(StateSynchronizerSender, StateSynchronizerEvents)>) { self.known_version = self .executor_proxy .get_latest_version() .await .expect("[start sync] failed to fetch latest version from storage"); let mut interval = Interval::new_interval(Duration::from_millis(self.config.tick_interval_ms)) .compat() .fuse(); let network_senders: Vec<StateSynchronizerSender> = network.iter().map(|t| t.0.clone()).collect(); let events: Vec<_> = network .into_iter() .enumerate() .map(|(idx, t)| t.1.map(move |e| (idx, e))) .collect(); let mut network_events = select_all(events).fuse(); loop { ::futures::select! { msg = self.client_events.select_next_some() => { match msg { CoordinatorMessage::Requested(target, subscription) => { self.request_sync(target, subscription).await; } CoordinatorMessage::Commit(version) => { self.commit(version).await; } CoordinatorMessage::GetState(callback) => { self.get_state(callback); } }; }, (idx, network_event) = network_events.select_next_some() => { match network_event { Ok(event) => { match event { Event::NewPeer(peer_id) => { debug!("[state sync] new peer {}", peer_id); self.peer_manager.enable_peer(peer_id, network_senders[idx].clone()); self.check_progress().await; } Event::LostPeer(peer_id) => { debug!("[state sync] lost peer {}", peer_id); self.peer_manager.disable_peer(&peer_id); } Event::Message((peer_id, mut message)) => { if message.has_chunk_request() { let known_version = message.get_chunk_request().get_known_version(); if let Err(err) = self.process_chunk_request(peer_id, message.take_chunk_request()).await { error!("[state sync] failed to serve chunk request to {} with known version {}: {:?}", peer_id, known_version, err); } } if message.has_chunk_response() { if let Err(err) = self.process_chunk_response(&peer_id, message.take_chunk_response()).await { error!("[state sync] failed to process chunk response from {}: {:?}", peer_id, err); } else { self.peer_manager.update_score(&peer_id, PeerScoreUpdateType::Success); } } } _ => {} } }, Err(err) => { error!("[state sync] network error {:?}", err); }, } }, _ = interval.select_next_some() => { self.check_progress().await; } } } } fn target_version(&self) -> u64 { match &self.target { Some(target) => target.ledger_info().version(), None => 0, } } async fn request_sync(&mut self, target: LedgerInfo, callback: oneshot::Sender<bool>) { let requested_version = target.ledger_info().version(); self.known_version = self .executor_proxy .get_latest_version() .await .expect("[state sync] failed to fetch latest version from storage"); debug!( "[state sync] sync requested. Known version: {}, requested_version: {}", self.known_version, requested_version ); // if requested version equals to current committed, just pass ledger info to executor // there might be still empty blocks between committed state and requested if requested_version <= self.known_version { debug!("[state sync] sync contains only empty blocks"); self.store_transactions(target.clone(), TransactionListWithProof::new()) .await .expect("[state sync] failed to execute empty blocks"); if callback.send(true).is_err() { error!("[state sync] coordinator failed to notify subscriber"); } return; } // TODO: Should we be changing peer manager peer set for every target? self.peer_manager .set_peers(target.signatures().keys().copied().collect()); self.target = Some(target); self.request_next_chunk(0).await; self.callback = Some(callback); } async fn commit(&mut self, version: u64) { debug!( "[state sync] commit. Known version: {}, version: {}", self.known_version, version ); let is_update = version > self.known_version; self.known_version = std::cmp::max(version, self.known_version); if is_update { self.last_commit = Some(SystemTime::now()); if let Err(err) = self.check_subscriptions().await { error!("[state sync] failed to check subscriptions: {:?}", err); } } if self.known_version == self.target_version() { debug!("[state sync] synchronization is finished"); if let Some(cb) = self.callback.take() { if cb.send(true).is_err() { error!("[state sync] failed to notify subscriber"); } } } } fn get_state(&self, callback: oneshot::Sender<u64>) { if callback.send(self.known_version).is_err() { error!("[state sync] failed to fetch internal state"); } } /// Get a batch of transactions async fn process_chunk_request( &mut self, peer_id: PeerId, mut request: GetChunkRequest, ) -> Result<()> { if request.timeout > self.config.max_timeout_ms || request.limit > self.config.max_chunk_limit { return Err(format_err!( "[state sync] timeout: {:?}, chunk limit: {:?}, but timeout must not exceed {:?} ms, and chunk limit must not exceed {:?}", request.timeout, request.limit, self.config.max_timeout_ms, self.config.max_chunk_limit )); } let latest_ledger_info = self.executor_proxy.get_latest_ledger_info().await?; let target = LedgerInfo::from_proto(request.take_ledger_info_with_sigs()) .unwrap_or_else(|_| latest_ledger_info.clone()); debug!("[state sync] chunk request: peer_id: {:?}, known_version: {}, latest_ledger_info: {}, target: {}", peer_id, request.known_version, latest_ledger_info.ledger_info().version(), target.ledger_info().version()); // if upstream synchronizer doesn't have new data and request timeout is set // add peer request into subscription queue if self.known_version <= request.known_version && request.timeout > 0 { let expiration_time = SystemTime::now().checked_add(Duration::from_millis(request.timeout)); if let Some(time) = expiration_time { self.subscriptions .insert(peer_id, (time, request.known_version, request.limit)); } Ok(()) } else { match self.peer_manager.get_network_sender(&peer_id) { Some(sender) => { self.deliver_chunk( peer_id, request.known_version, request.limit, target, sender, ) .await } None => Err(format_err!( "[state sync] failed to find network for peer {}", peer_id )), } } } async fn deliver_chunk( &self, peer_id: PeerId, known_version: u64, limit: u64, target: LedgerInfo, mut network_sender: StateSynchronizerSender, ) -> Result<()> { let response = self .executor_proxy .get_chunk(known_version, limit, target) .await?; let mut msg = StateSynchronizerMsg::new(); msg.set_chunk_response(response); if network_sender.send_to(peer_id, msg).await.is_err() { error!("[state sync] failed to send p2p message"); } Ok(()) } /// processes batch of transactions downloaded from peer /// executes transactions, updates progress state, calls callback if some sync is finished async fn process_chunk_response( &mut self, peer_id: &PeerId, mut response: GetChunkResponse, ) -> Result<()> { let txn_list_with_proof = response.take_txn_list_with_proof(); if let Some(version) = txn_list_with_proof .first_transaction_version .clone() .map(|x| x.get_value()) .into_option() { let has_requested = self.peer_manager.has_requested(version, *peer_id); // node has received a response from peer, so remove peer entry from requests map self.peer_manager.process_response(version, *peer_id); if version != self.known_version + 1 { // version was not requested, or version was requested from a different peer, // so need to penalize peer for maliciously sending chunk if has_requested { self.peer_manager .update_score(&peer_id, PeerScoreUpdateType::InvalidChunk) } return Err(format_err!( "[state sync] non sequential chunk. Known version: {}, received: {}", self.known_version, version, )); } } let previous_version = self.known_version; let chunk_size = txn_list_with_proof.get_transactions().len(); let result = self .validate_and_store_chunk(txn_list_with_proof, response) .await; let latest_version = self.executor_proxy.get_latest_version().await?; if latest_version <= previous_version { self.peer_manager .update_score(peer_id, PeerScoreUpdateType::InvalidChunk); } else { self.commit(latest_version).await; } debug!( "[state sync] applied chunk. Previous version: {}, new version: {}, chunk size: {}", previous_version, self.known_version, chunk_size ); result } async fn validate_and_store_chunk( &mut self, txn_list_with_proof: TransactionListWithProof, mut response: GetChunkResponse, ) -> Result<()> { // optimistically fetch next chunk let chunk_size = txn_list_with_proof.get_transactions().len() as u64; self.request_next_chunk(chunk_size).await; debug!( "[state sync] process chunk response. chunk_size: {}", chunk_size ); let target = LedgerInfo::from_proto(response.take_ledger_info_with_sigs())?; self.executor_proxy.validate_ledger_info(&target)?; self.store_transactions(target, txn_list_with_proof).await?; counters::STATE_SYNC_TXN_REPLAYED.inc_by(chunk_size as i64); Ok(()) } /// ensures that StateSynchronizer makes progress /// if peer is not responding, issues new sync request async fn check_progress(&mut self) { if !self.peer_manager.is_empty() && (self.autosync || self.target.is_some()) { let last_commit = self.last_commit.unwrap_or(UNIX_EPOCH); let timeout = match self.target { Some(_) => 2 * self.config.tick_interval_ms, None => self.config.tick_interval_ms + self.config.long_poll_timeout_ms, }; let expected_next_sync = last_commit.checked_add(Duration::from_millis(timeout)); // if coordinator didn't make progress by expected time, issue new request if let Some(tst) = expected_next_sync { if SystemTime::now().duration_since(tst).is_ok() { self.peer_manager .process_timeout(self.known_version + 1, timeout); self.request_next_chunk(0).await; } } } } async fn request_next_chunk(&mut self, offset: u64) { if self.autosync || self.known_version + offset < self.target_version() { if let Some((peer_id, mut sender)) = self.peer_manager.pick_peer() { let mut req = GetChunkRequest::new(); req.set_known_version(self.known_version + offset); req.set_limit(self.config.chunk_limit); self.peer_manager .process_request(self.known_version + offset + 1, peer_id); let timeout = match &self.target { Some(target) => { req.set_ledger_info_with_sigs(target.clone().into_proto()); 0 } None => { req.set_timeout(self.config.long_poll_timeout_ms); self.config.long_poll_timeout_ms } }; debug!( "[state sync] request next chunk. peer_id: {:?}, known_version: {}, timeout: {}", peer_id, self.known_version + offset, timeout ); let mut msg = StateSynchronizerMsg::new(); msg.set_chunk_request(req); if sender.send_to(peer_id, msg).await.is_err() { error!("[state sync] failed to send p2p message"); } } } } async fn store_transactions( &self, ledger_info: LedgerInfoWithSignatures, txn_list_with_proof: TransactionListWithProof, ) -> Result<ExecuteChunkResponse> { let mut req = ExecuteChunkRequest::new(); req.set_txn_list_with_proof(txn_list_with_proof); req.set_ledger_info_with_sigs(ledger_info.into_proto()); self.executor_proxy.execute_chunk(req).await } async fn check_subscriptions(&mut self) -> Result<()> { let ledger_info = self.executor_proxy.get_latest_ledger_info().await?; let committed_version = self.known_version; let mut ready = vec![]; self.subscriptions .retain(|peer_id, (expiry, known_version, limit)| { // filter out expired peer requests if SystemTime::now().duration_since(expiry.clone()).is_ok() { return false; } if *known_version < committed_version { ready.push((*peer_id, *known_version, *limit)); false } else { true } }); let mut futures = FuturesUnordered::new(); for (peer_id, known_version, limit) in ready { if let Some(sender) = self.peer_manager.get_network_sender(&peer_id) { futures.push(self.deliver_chunk( peer_id, known_version, limit, ledger_info.clone(), sender, )); } } while let Some(res) = futures.next().await { if let Err(err) = res { error!("[state sync] failed to notify subscriber {:?}", err); } } Ok(()) } }
40.037255
223
0.54464
7a882a81945436207a95da010b48b04e45ba95f0
1,054
use songbird::input::{ error::{Error, Result}, Codec, Container, Input, Metadata, Reader, }; use std::process::{Child, Command, Stdio}; pub async fn ffmpeg(mut source: Child, metadata: Metadata, pre_args: &[&str]) -> Result<Input> { let ffmpeg_args = [ "-i", "-", // read from stdout "-f", "s16le", // use PCM signed 16-bit little-endian format "-ac", "2", // set two audio channels "-ar", "48000", // set audio sample rate of 48000Hz "-acodec", "pcm_f32le", "-", ]; let taken_stdout = source.stdout.take().ok_or(Error::Stdout)?; let ffmpeg = Command::new("ffmpeg") .args(pre_args) .args(&ffmpeg_args) .stdin(taken_stdout) .stderr(Stdio::null()) .stdout(Stdio::piped()) .spawn()?; let reader = Reader::from(vec![source, ffmpeg]); let input = Input::new( true, reader, Codec::FloatPcm, Container::Raw, Some(metadata), ); Ok(input) }
23.954545
96
0.531309
2fc3cd77ee19ef4ba8d74efc0482a2755584865a
35,567
// See https://raw.githubusercontent.com/paritytech/ink/v2.1.0/examples/multisig_plain/lib.rs // Copyright 2018-2020 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! # Plain Multisig Wallet //! //! This implements a plain multi owner wallet. //! //! ## Warning //! //! This contract is an *example*. It is neither audited nor endorsed for production use. //! Do **not** rely on it to keep anything of value secure. //! //! ## Overview //! //! Each instantiation of this contract has a set of `owners` and a `requirement` of //! how many of them need to agree on a `Transaction` for it to be able to be executed. //! Every owner can submit a transaction and when enough of the other owners confirm //! it will be able to be executed. The following invariant is enforced by the contract: //! //! ```ignore //! 0 < requirement && requirement <= owners && owners <= MAX_OWNERS //! ``` //! //! ## Error Handling //! //! With the exeception of `execute_transaction` no error conditions are signalled //! through return types. Any error or invariant violation triggers a panic and therefore //! rolls back the transaction. //! //! ## Interface //! //! The interface is modelled after the popular gnosis multisig wallet. However, there //! are subtle variations from the interface. For example the `confirm_transaction` //! will never trigger the execution of a `Transaction` even if the treshold is reached. //! A call of `execute_transaction` is always required. This can be called by anyone. //! //! All the messages that are declared as only callable by the wallet must go through //! the usual submit, confirm, execute cycle as any other transaction that should be //! called by the wallet. For example to add an owner you would submit a transaction //! that calls the wallets own `add_owner` message through `submit_transaction`. //! //! ### Owner Management //! //! The messages `add_owner`, `remove_owner`, and `replace_owner` can be used to manage //! the owner set after instantiation. //! //! ### Changing the Requirement //! //! `change_requirement` can be used to tighten or relax the `requirement` of how many //! owner signatures are needed to execute a `Transaction`. //! //! ### Transaction Management //! //! `submit_transaction`, `cancel_transaction`, `confirm_transaction`, //! `revoke_confirmation` and `execute_transaction` are the bread and butter messages //! of this contract. Use them to dispatch arbitrary messages to other contracts //! with the wallet as a sender. #![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract(version = "0.1.0")] mod multisig_plain { use ink_core::{ env::call::{ state::{Sealed, Unsealed}, CallBuilder, CallParams, }, storage, }; use ink_prelude::vec::Vec; use scale::Output; /// Tune this to your liking but be wary that allowing too many owners will not perform well. const MAX_OWNERS: u32 = 50; type TransactionId = u32; const WRONG_TRANSACTION_ID: &str = "The user specified an invalid transaction id. Abort."; /// A wrapper that allows us to encode a blob of bytes. /// /// We use this to pass the set of untyped (bytes) parameters to the `CallBuilder`. struct CallInput<'a>(&'a [u8]); impl<'a> scale::Encode for CallInput<'a> { fn encode_to<T: Output>(&self, dest: &mut T) { dest.write(self.0); } } /// Indicates whether a transaction is already confirmed or needs further confirmations. #[derive(scale::Encode, scale::Decode, Clone, Copy)] pub enum ConfirmationStatus { /// The transaction is already confirmed. Confirmed, /// Indicates how many confirmations are remaining. ConfirmationsNeeded(u32), } /// A Transaction is what every `owner` can submit for confirmation by other owners. /// If enough owners agree it will be executed by the contract. #[derive(scale::Encode, scale::Decode, storage::Flush)] #[cfg_attr(feature = "ink-generate-abi", derive(type_metadata::Metadata))] #[cfg_attr(feature = "std", derive(Debug, PartialEq, Eq))] pub struct Transaction { /// The AccountId of the contract that is called in this transaction. callee: AccountId, /// The selector bytes that identifies the function of the callee that should be called. selector: [u8; 4], /// The SCALE encoded parameters that are passed to the called function. input: Vec<u8>, /// The amount of chain balance that is transferred to the callee. transferred_value: Balance, /// Gas limit for the execution of the call. gas_limit: u64, } #[ink(storage)] struct MultisigPlain { /// Every entry in this map represents the confirmation of an owner for a /// transaction. This is effecively a set rather than a map. confirmations: storage::BTreeMap<(TransactionId, AccountId), ()>, /// The amount of confirmations for every transaction. This is a redundant /// information and is kept in order to prevent iterating through the /// confirmation set to check if a transaction is confirmed. confirmation_count: storage::BTreeMap<TransactionId, u32>, /// Just the list of transactions. It is a stash as stable ids are necessary /// for referencing them in confirmation calls. transactions: storage::Stash<Transaction>, /// The list is a vector because iterating over it is necessary when cleaning /// up the confirmation set. owners: storage::Vec<AccountId>, /// Redundant information to speed up the check whether a caller is an owner. is_owner: storage::BTreeMap<AccountId, ()>, /// Minimum number of owners that have to confirm a transaction to be executed. requirement: storage::Value<u32>, } /// Emitted when an owner confirms a transaction. #[ink(event)] struct Confirmation { /// The transaction that was confirmed. #[ink(topic)] transaction: TransactionId, /// The owner that sent the confirmation. #[ink(topic)] from: AccountId, /// The confirmation status after this confirmation was applied. #[ink(topic)] status: ConfirmationStatus, } /// Emitted when an owner revoked a confirmation. #[ink(event)] struct Revokation { /// The transaction that was revoked. #[ink(topic)] transaction: TransactionId, /// The owner that sent the revokation. #[ink(topic)] from: AccountId, } /// Emitted when an owner submits a transaction. #[ink(event)] struct Submission { /// The transaction that was submitted. #[ink(topic)] transaction: TransactionId, } /// Emitted when a transaction was canceled. #[ink(event)] struct Cancelation { /// The transaction that was canceled. #[ink(topic)] transaction: TransactionId, } /// Emitted when a transaction was executed. #[ink(event)] struct Execution { /// The transaction that was executed. #[ink(topic)] transaction: TransactionId, /// Indicates whether the transaction executed successfully. If so the `Ok` value holds /// the output in bytes. The Option is `None` when the transaction was executed through /// `invoke_transaction` rather than `evaluate_transaction`. #[ink(topic)] result: Result<Option<Vec<u8>>, ()>, } /// Emitted when an owner is added to the wallet. #[ink(event)] struct OwnerAddition { /// The owner that was added. #[ink(topic)] owner: AccountId, } /// Emitted when an owner is removed from the wallet. #[ink(event)] struct OwnerRemoval { /// The owner that was removed. #[ink(topic)] owner: AccountId, } /// Emitted when the requirement changed. #[ink(event)] struct RequirementChange { /// The new requirement value. new_requirement: u32, } impl MultisigPlain { /// The only constructor of the contract. /// /// A list of owners must be supplied and a number of how many of them must /// confirm a transaction. Duplicate owners are silently dropped. /// /// # Panics /// /// If `requirement` violates our invariant. #[ink(constructor)] fn new(&mut self, requirement: u32, owners: Vec<AccountId>) { for owner in &owners { self.is_owner.insert(*owner, ()); self.owners.push(*owner); } ensure_requirement_is_valid(self.owners.len(), requirement); assert!(self.is_owner.len() == self.owners.len()); self.requirement.set(requirement); } /// Add a new owner to the contract. /// /// Only callable by the wallet itself. /// /// # Panics /// /// If the owner already exists. /// /// # Examples /// /// Since this message must be send by the wallet itself it has to be build as a /// `Transaction` and dispatched through `submit_transaction` + `invoke_transaction`: /// ``` /// use ink_core::env::call{CallData, CallParams, Selector}; /// /// // address of an existing MultiSigPlain contract /// let wallet_id: AccountId = [7u8; 32].into(); /// /// // first create the transaction that adds `alice` through `add_owner` /// let alice: AccountId = [1u8; 32].into(); /// let mut call = CallData::new(Selector::from_str("add_owner")); /// call.push_arg(&alice); /// let transaction = Transaction { /// callee: wallet_id, /// selector: call.selector().to_bytes(), /// input: call.params().to_owned(), /// transferred_value: 0, /// gas_limit: 0 /// }; /// /// // submit the transaction for confirmation /// let mut submit = CallParams::eval(wallet_id, Selector::from_str("submit_transaction")); /// let (id, _) = submit.push_arg(&transaction) /// .fire() /// .expect("submit_transaction won't panic."); /// /// // wait until all required owners have confirmed and then execute the transaction /// let mut invoke = CallParams::eval(wallet_id, Selector::from_str("invoke_transaction")); /// invoke.push_arg(&id).fire(); /// ``` #[ink(message)] fn add_owner(&mut self, new_owner: AccountId) { self.ensure_from_wallet(); self.ensure_no_owner(&new_owner); ensure_requirement_is_valid(self.owners.len() + 1, *self.requirement); self.is_owner.insert(new_owner, ()); self.owners.push(new_owner); self.env().emit_event(OwnerAddition { owner: new_owner }); } /// Remove an owner from the contract. /// /// Only callable by the wallet itself. If by doing this the amount of owners /// would be smaller than the requirement it is adjusted to be exactly the /// number of owners. /// /// # Panics /// /// If `owner` is no owner of the wallet. #[ink(message)] fn remove_owner(&mut self, owner: AccountId) { self.ensure_from_wallet(); self.ensure_owner(&owner); let len = self.owners.len() - 1; let requirement = u32::min(len, *self.requirement); ensure_requirement_is_valid(len, requirement); self.owners.swap_remove(self.owner_index(&owner)); self.is_owner.remove(&owner); self.requirement.set(requirement); self.clean_owner_confirmations(&owner); self.env().emit_event(OwnerRemoval { owner }); } /// Replace an owner from the contract with a new one. /// /// Only callable by the wallet itself. /// /// # Panics /// /// If `old_owner` is no owner or if `new_owner` already is one. #[ink(message)] fn replace_owner(&mut self, old_owner: AccountId, new_owner: AccountId) { self.ensure_from_wallet(); self.ensure_owner(&old_owner); self.ensure_no_owner(&new_owner); self.owners .replace(self.owner_index(&old_owner), || new_owner); self.is_owner.remove(&old_owner); self.is_owner.insert(new_owner, ()); self.clean_owner_confirmations(&old_owner); self.env().emit_event(OwnerRemoval { owner: old_owner }); self.env().emit_event(OwnerAddition { owner: new_owner }); } /// Change the requirement to a new value. /// /// Only callable by the wallet itself. /// /// # Panics /// /// If the `new_requirement` violates our invariant. #[ink(message)] fn change_requirement(&mut self, new_requirement: u32) { self.ensure_from_wallet(); ensure_requirement_is_valid(self.owners.len(), new_requirement); self.requirement.set(new_requirement); self.env().emit_event(RequirementChange { new_requirement }); } /// Add a new transaction candiate to the contract. /// /// This also confirms the transaction for the caller. This can be called by any owner. #[ink(message)] fn submit_transaction( &mut self, transaction: Transaction, ) -> (TransactionId, ConfirmationStatus) { self.ensure_caller_is_owner(); let trans_id = self.transactions.put(transaction); self.env().emit_event(Submission { transaction: trans_id, }); ( trans_id, self.confirm_by_caller(self.env().caller(), trans_id), ) } /// Remove a transaction from the contract. /// Only callable by the wallet itself. /// /// # Panics /// /// If `trans_id` is no valid transaction id. #[ink(message)] fn cancel_transaction(&mut self, trans_id: TransactionId) { self.ensure_from_wallet(); if self.take_transaction(trans_id).is_some() { self.env().emit_event(Cancelation { transaction: trans_id, }); } } /// Confirm a transaction for the sender that was submitted by any owner. /// /// This can be called by any owner. /// /// # Panics /// /// If `trans_id` is no valid transaction id. #[ink(message)] fn confirm_transaction(&mut self, trans_id: TransactionId) -> ConfirmationStatus { self.ensure_caller_is_owner(); self.ensure_transaction_exists(trans_id); self.confirm_by_caller(self.env().caller(), trans_id) } /// Revoke the senders confirmation. /// /// This can be called by any owner. /// /// # Panics /// /// If `trans_id` is no valid transaction id. #[ink(message)] fn revoke_confirmation(&mut self, trans_id: TransactionId) { self.ensure_caller_is_owner(); let caller = self.env().caller(); if self.confirmations.remove(&(trans_id, caller)).is_some() { *self.confirmation_count.entry(trans_id).or_insert(1) -= 1; self.env().emit_event(Revokation { transaction: trans_id, from: caller, }); } } /// Invoke a confirmed execution without getting its output. /// /// Its return value indicates whether the called transaction was successful. /// This can be called by anyone. #[ink(message)] fn invoke_transaction(&mut self, trans_id: TransactionId) -> Result<(), ()> { self.ensure_confirmed(trans_id); let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID); let result = parameterize_call( &t, CallParams::<EnvTypes, ()>::invoke(t.callee, t.selector.into()), ) .fire() .map_err(|_| ()); self.env().emit_event(Execution { transaction: trans_id, result: result.map(|_| None), }); result } /// Evaluate a confirmed execution and return its output as bytes. /// /// Its return value indicates whether the called transaction was successful and contains /// its output when sucesful. /// This can be called by anyone. #[ink(message)] fn eval_transaction(&mut self, trans_id: TransactionId) -> Result<Vec<u8>, ()> { self.ensure_confirmed(trans_id); let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID); let result = parameterize_call( &t, CallParams::<EnvTypes, Vec<u8>>::eval(t.callee, t.selector.into()), ) .fire() .map_err(|_| ()); self.env().emit_event(Execution { transaction: trans_id, result: result.clone().map(Some), }); result } /// Set the `transaction` as confirmed by `confirmer`. /// Idempotent operation regarding an already confirmed `transaction` /// by `confirmer`. fn confirm_by_caller( &mut self, confirmer: AccountId, transaction: TransactionId, ) -> ConfirmationStatus { let count = self.confirmation_count.entry(transaction).or_insert(0); let new_confirmation = self .confirmations .insert((transaction, confirmer), ()) .is_none(); if new_confirmation { *count += 1; } let status = { if *count >= *self.requirement { ConfirmationStatus::Confirmed } else { ConfirmationStatus::ConfirmationsNeeded(*self.requirement - *count) } }; if new_confirmation { self.env().emit_event(Confirmation { transaction, from: confirmer, status, }); } status } /// Get the index of `owner` in `self.owners`. /// Panics if `owner` is not found in `self.owners`. fn owner_index(&self, owner: &AccountId) -> u32 { self.owners.iter().position(|x| *x == *owner).expect( "This is only called after it was already verified that the id is actually an owner.", ) as u32 } /// Remove the transaction identified by `trans_id` from `self.transactions`. /// Also removes all confirmation state associated with it. fn take_transaction(&mut self, trans_id: TransactionId) -> Option<Transaction> { let transaction = self.transactions.take(trans_id); if transaction.is_some() { self.clean_transaction_confirmations(trans_id); } transaction } /// Remove all confirmation state associated with `owner`. /// Also adjusts the `self.confirmation_count` variable. fn clean_owner_confirmations(&mut self, owner: &AccountId) { for (trans_id, _) in self.transactions.iter() { if self.confirmations.remove(&(trans_id, *owner)).is_some() { *self.confirmation_count.entry(trans_id).or_insert(0) += 1; } } } /// This removes all confirmation state associated with `transaction`. fn clean_transaction_confirmations(&mut self, transaction: TransactionId) { for owner in self.owners.iter() { self.confirmations.remove(&(transaction, *owner)); } self.confirmation_count.remove(&transaction); } /// Panic if transaction `trans_id` is not confirmed by at least /// `self.requirement` owners. fn ensure_confirmed(&self, trans_id: TransactionId) { assert!( self.confirmation_count .get(&trans_id) .expect(WRONG_TRANSACTION_ID) >= self.requirement.get() ); } /// Panic if the transaction `trans_id` does not exit. fn ensure_transaction_exists(&self, trans_id: TransactionId) { self.transactions.get(trans_id).expect(WRONG_TRANSACTION_ID); } /// Panic if the sender is no owner of the wallet. fn ensure_caller_is_owner(&self) { self.ensure_owner(&self.env().caller()); } /// Panic if the sender is not this wallet. fn ensure_from_wallet(&self) { assert_eq!(self.env().caller(), self.env().account_id()); } /// Panic if `owner` is not an owner, fn ensure_owner(&self, owner: &AccountId) { assert!(self.is_owner.contains_key(owner)); } /// Panic if `owner` is an owner. fn ensure_no_owner(&self, owner: &AccountId) { assert!(!self.is_owner.contains_key(owner)); } } /// Parameterize a call with the arguments stored inside a transaction. fn parameterize_call<R>( t: &Transaction, builder: CallBuilder<EnvTypes, R, Unsealed>, ) -> CallBuilder<EnvTypes, R, Sealed> { builder .gas_limit(t.gas_limit) .transferred_value(t.transferred_value) .push_arg(&CallInput(&t.input)) .seal() } /// Panic if the number of `owners` under a `requirement` violates our /// requirement invariant. fn ensure_requirement_is_valid(owners: u32, requirement: u32) { assert!(0 < requirement && requirement <= owners && owners <= MAX_OWNERS); } #[cfg(test)] mod tests { use super::*; use ink_core::env::{call, test}; type Accounts = test::DefaultAccounts<EnvTypes>; const WALLET: [u8; 32] = [7; 32]; impl Transaction { fn change_requirement(requirement: u32) -> Self { let mut call = call::CallData::new(call::Selector::from_str("change_requirement")); call.push_arg(&requirement); Self { callee: WALLET.into(), selector: call.selector().to_bytes(), input: call.params().to_owned(), transferred_value: 0, gas_limit: 1000000, } } } fn set_sender(sender: AccountId) { test::push_execution_context::<EnvTypes>( sender, WALLET.into(), 1000000, 1000000, call::CallData::new(call::Selector::from_str("dummy")), ); } fn set_from_wallet() { set_sender(WALLET.into()); } fn set_from_owner() { let accounts = default_accounts(); set_sender(accounts.alice); } fn set_from_noowner() { let accounts = default_accounts(); set_sender(accounts.django); } fn default_accounts() -> Accounts { test::default_accounts().expect("Test environment is expected to be initialized.") } fn build_contract() -> MultisigPlain { let accounts = default_accounts(); let owners = ink_prelude::vec![accounts.alice, accounts.bob, accounts.eve]; MultisigPlain::new(2, owners) } fn submit_transaction() -> MultisigPlain { let mut contract = build_contract(); let accounts = default_accounts(); set_from_owner(); contract.submit_transaction(Transaction::change_requirement(1)); assert_eq!(contract.transactions.len(), 1); assert_eq!(test::recorded_events().count(), 2); let transaction = contract.transactions.get(0).unwrap(); assert_eq!(*transaction, Transaction::change_requirement(1)); contract.confirmations.get(&(0, accounts.alice)).unwrap(); assert_eq!(contract.confirmations.len(), 1); assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1); contract } #[test] fn construction_works() { let accounts = default_accounts(); let owners = ink_prelude::vec![accounts.alice, accounts.bob, accounts.eve]; let contract = build_contract(); assert_eq!(contract.owners.len(), 3); assert_eq!(*contract.requirement.get(), 2); assert!(contract.owners.iter().eq(owners.iter())); assert!(contract.is_owner.get(&accounts.alice).is_some()); assert!(contract.is_owner.get(&accounts.bob).is_some()); assert!(contract.is_owner.get(&accounts.eve).is_some()); assert!(contract.is_owner.get(&accounts.charlie).is_none()); assert!(contract.is_owner.get(&accounts.django).is_none()); assert!(contract.is_owner.get(&accounts.frank).is_none()); assert_eq!(contract.confirmations.len(), 0); assert_eq!(contract.confirmation_count.len(), 0); assert_eq!(contract.transactions.len(), 0); } #[test] #[should_panic] fn empty_owner_construction_fails() { MultisigPlain::new(0, vec![]); } #[test] #[should_panic] fn zero_requirement_construction_fails() { let accounts = default_accounts(); MultisigPlain::new(0, vec![accounts.alice, accounts.bob]); } #[test] #[should_panic] fn too_large_requirement_construction_fails() { let accounts = default_accounts(); MultisigPlain::new(3, vec![accounts.alice, accounts.bob]); } #[test] fn add_owner_works() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); let owners = contract.owners.len(); contract.add_owner(accounts.frank); assert_eq!(contract.owners.len(), owners + 1); assert!(contract.is_owner.get(&accounts.frank).is_some()); assert_eq!(test::recorded_events().count(), 1); } #[test] #[should_panic] fn add_existing_owner_fails() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); contract.add_owner(accounts.bob); } #[test] #[should_panic] fn add_owner_permission_denied() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_owner(); contract.add_owner(accounts.frank); } #[test] fn remove_owner_works() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); let owners = contract.owners.len(); contract.remove_owner(accounts.alice); assert_eq!(contract.owners.len(), owners - 1); assert!(contract.is_owner.get(&accounts.alice).is_none()); assert_eq!(test::recorded_events().count(), 1); } #[test] #[should_panic] fn remove_owner_nonexisting_fails() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); contract.remove_owner(accounts.django); } #[test] #[should_panic] fn remove_owner_permission_denied() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_owner(); contract.remove_owner(accounts.alice); } #[test] fn replace_owner_works() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); let owners = contract.owners.len(); contract.replace_owner(accounts.alice, accounts.django); assert_eq!(contract.owners.len(), owners); assert!(contract.is_owner.get(&accounts.alice).is_none()); assert!(contract.is_owner.get(&accounts.django).is_some()); assert_eq!(test::recorded_events().count(), 2); } #[test] #[should_panic] fn replace_owner_existing_fails() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); contract.replace_owner(accounts.alice, accounts.bob); } #[test] #[should_panic] fn replace_owner_nonexisting_fails() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); contract.replace_owner(accounts.django, accounts.frank); } #[test] #[should_panic] fn replace_owner_permission_denied() { let accounts = default_accounts(); let mut contract = build_contract(); set_from_owner(); contract.replace_owner(accounts.alice, accounts.django); } #[test] fn change_requirement_works() { let mut contract = build_contract(); assert_eq!(*contract.requirement.get(), 2); set_from_wallet(); contract.change_requirement(3); assert_eq!(*contract.requirement.get(), 3); assert_eq!(test::recorded_events().count(), 1); } #[test] #[should_panic] fn change_requirement_too_high() { let mut contract = build_contract(); set_from_wallet(); contract.change_requirement(4); } #[test] #[should_panic] fn change_requirement_zero_fails() { let mut contract = build_contract(); set_from_wallet(); contract.change_requirement(0); } #[test] fn submit_transaction_works() { submit_transaction(); } #[test] #[should_panic] fn submit_transaction_noowner_fails() { let mut contract = build_contract(); set_from_noowner(); contract.submit_transaction(Transaction::change_requirement(1)); } #[test] #[should_panic] fn submit_transaction_wallet_fails() { let mut contract = build_contract(); set_from_wallet(); contract.submit_transaction(Transaction::change_requirement(1)); } #[test] fn cancel_transaction_works() { let mut contract = submit_transaction(); set_from_wallet(); contract.cancel_transaction(0); assert_eq!(contract.transactions.len(), 0); assert_eq!(test::recorded_events().count(), 3); } #[test] fn cancel_transaction_nonexisting() { let mut contract = submit_transaction(); set_from_wallet(); contract.cancel_transaction(1); assert_eq!(contract.transactions.len(), 1); assert_eq!(test::recorded_events().count(), 2); } #[test] #[should_panic] fn cancel_transaction_no_permission() { let mut contract = submit_transaction(); contract.cancel_transaction(0); } #[test] fn confirm_transaction_works() { let mut contract = submit_transaction(); let accounts = default_accounts(); set_sender(accounts.bob); contract.confirm_transaction(0); assert_eq!(test::recorded_events().count(), 3); contract.confirmations.get(&(0, accounts.bob)).unwrap(); assert_eq!(contract.confirmations.len(), 2); assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 2); } #[test] fn confirm_transaction_already_confirmed() { let mut contract = submit_transaction(); let accounts = default_accounts(); set_sender(accounts.alice); contract.confirm_transaction(0); assert_eq!(test::recorded_events().count(), 2); contract.confirmations.get(&(0, accounts.alice)).unwrap(); assert_eq!(contract.confirmations.len(), 1); assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1); } #[test] #[should_panic] fn confirm_transaction_noowner_fail() { let mut contract = submit_transaction(); set_from_noowner(); contract.confirm_transaction(0); } #[test] fn revoke_transaction_works() { let mut contract = submit_transaction(); let accounts = default_accounts(); set_sender(accounts.alice); contract.revoke_confirmation(0); assert_eq!(test::recorded_events().count(), 3); assert!(contract.confirmations.get(&(0, accounts.alice)).is_none()); assert_eq!(contract.confirmations.len(), 0); assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 0); } #[test] fn revoke_transaction_no_confirmer() { let mut contract = submit_transaction(); let accounts = default_accounts(); set_sender(accounts.bob); contract.revoke_confirmation(0); assert_eq!(test::recorded_events().count(), 2); assert!(contract.confirmations.get(&(0, accounts.alice)).is_some()); assert_eq!(contract.confirmations.len(), 1); assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1); } #[test] #[should_panic] fn revoke_transaction_noowner_fail() { let mut contract = submit_transaction(); let accounts = default_accounts(); set_sender(accounts.django); contract.revoke_confirmation(0); } #[test] fn execute_transaction_works() { // Execution of calls is currently unsupported in off-chain test. // Calling execute_transaction panics in any case. } } }
37.438947
99
0.578401
1de6723ea78cd1de07d7085670b39685b2106c61
45,137
use futures::Future; use serde_json; use serde_json::{map::Map, Value}; use indy::{anoncreds, blob_storage, ledger}; use time; use settings; use utils::constants::{LIBINDY_CRED_OFFER, REQUESTED_ATTRIBUTES, PROOF_REQUESTED_PREDICATES, ATTRS, REV_STATE_JSON}; use utils::libindy::{error_codes::map_rust_indy_sdk_error, mock_libindy_rc, wallet::get_wallet_handle}; use utils::libindy::payments::{pay_for_txn, PaymentTxn}; use utils::libindy::ledger::*; use utils::constants::{SCHEMA_ID, SCHEMA_JSON, SCHEMA_TXN_TYPE, CRED_DEF_ID, CRED_DEF_JSON, CRED_DEF_TXN_TYPE, REV_REG_DEF_TXN_TYPE, REV_REG_DELTA_TXN_TYPE, REVOC_REG_TYPE, rev_def_json, REV_REG_ID, REV_REG_DELTA_JSON, REV_REG_JSON}; use error::prelude::*; const BLOB_STORAGE_TYPE: &str = "default"; pub fn libindy_verifier_verify_proof(proof_req_json: &str, proof_json: &str, schemas_json: &str, credential_defs_json: &str, rev_reg_defs_json: &str, rev_regs_json: &str) -> VcxResult<bool> { //TODO there was timeout here (before future-based Rust wrapper) anoncreds::verifier_verify_proof(proof_req_json, proof_json, schemas_json, credential_defs_json, rev_reg_defs_json, rev_regs_json) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_create_and_store_revoc_reg(issuer_did: &str, cred_def_id: &str, tails_path: &str, max_creds: u32) -> VcxResult<(String, String, String)> { trace!("creating revocation: {}, {}, {}", cred_def_id, tails_path, max_creds); let tails_config = json!({"base_dir": tails_path,"uri_pattern": ""}).to_string(); let writer = blob_storage::open_writer(BLOB_STORAGE_TYPE, &tails_config) .wait() .map_err(map_rust_indy_sdk_error)?; let revoc_config = json!({"max_cred_num": max_creds,"issuance_type": "ISSUANCE_BY_DEFAULT"}).to_string(); anoncreds::issuer_create_and_store_revoc_reg(get_wallet_handle(), issuer_did, None, "tag1", cred_def_id, &revoc_config, writer) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_create_and_store_credential_def(issuer_did: &str, schema_json: &str, tag: &str, sig_type: Option<&str>, config_json: &str) -> VcxResult<(String, String)> { anoncreds::issuer_create_and_store_credential_def(get_wallet_handle(), issuer_did, schema_json, tag, sig_type, config_json) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_issuer_create_credential_offer(cred_def_id: &str) -> VcxResult<String> { if settings::test_indy_mode_enabled() { let rc = mock_libindy_rc(); if rc != 0 { return Err(VcxError::from(VcxErrorKind::InvalidState)); }; return Ok(LIBINDY_CRED_OFFER.to_string()); } anoncreds::issuer_create_credential_offer(get_wallet_handle(), cred_def_id) .wait() .map_err(map_rust_indy_sdk_error) } fn blob_storage_open_reader(base_dir: &str) -> VcxResult<i32> { let tails_config = json!({"base_dir": base_dir,"uri_pattern": ""}).to_string(); blob_storage::open_reader("default", &tails_config) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_issuer_create_credential(cred_offer_json: &str, cred_req_json: &str, cred_values_json: &str, rev_reg_id: Option<String>, tails_file: Option<String>) -> VcxResult<(String, Option<String>, Option<String>)> { let revocation = rev_reg_id.as_ref().map(String::as_str); let blob_handle = match tails_file { Some(x) => blob_storage_open_reader(&x)?, None => -1, }; anoncreds::issuer_create_credential(get_wallet_handle(), cred_offer_json, cred_req_json, cred_values_json, revocation, blob_handle) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_create_proof(proof_req_json: &str, requested_credentials_json: &str, master_secret_id: &str, schemas_json: &str, credential_defs_json: &str, revoc_states_json: Option<&str>) -> VcxResult<String> { let revoc_states_json = revoc_states_json.unwrap_or("{}"); anoncreds::prover_create_proof(get_wallet_handle(), proof_req_json, requested_credentials_json, master_secret_id, schemas_json, credential_defs_json, revoc_states_json) .wait() .map_err(map_rust_indy_sdk_error) } fn fetch_credentials(search_handle: i32, requested_attributes: Map<String, Value>) -> VcxResult<String> { let mut v: Value = json!({}); for item_referent in requested_attributes.keys().into_iter() { v[ATTRS][item_referent] = serde_json::from_str(&anoncreds::prover_fetch_credentials_for_proof_req(search_handle, item_referent, 100).wait() .map_err(map_rust_indy_sdk_error)?) .map_err(|_| { error!("Invalid Json Parsing of Object Returned from Libindy. Did Libindy change its structure?"); VcxError::from_msg(VcxErrorKind::InvalidConfiguration, "Invalid Json Parsing of Object Returned from Libindy. Did Libindy change its structure?") })? } Ok(v.to_string()) } fn close_search_handle(search_handle: i32) -> VcxResult<()> { anoncreds::prover_close_credentials_search_for_proof_req(search_handle) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_get_credentials_for_proof_req(proof_req: &str) -> VcxResult<String> { let wallet_handle = get_wallet_handle(); // this may be too redundant since Prover::search_credentials will validate the proof reqeuest already. let proof_request_json: Map<String, Value> = serde_json::from_str(proof_req) .map_err(|err| VcxError::from_msg(VcxErrorKind::InvalidProofRequest, format!("Cannot deserialize ProofRequest")))?; // since the search_credentials_for_proof request validates that the proof_req is properly structured, this get() // fn should never fail, unless libindy changes their formats. let requested_attributes: Option<Map<String, Value>> = proof_request_json.get(REQUESTED_ATTRIBUTES) .and_then(|v| { serde_json::from_value(v.clone()).map_err(|_| { error!("Invalid Json Parsing of Requested Attributes Retrieved From Libindy. Did Libindy change its structure?"); }).ok() }); let requested_predicates: Option<Map<String, Value>> = proof_request_json.get(PROOF_REQUESTED_PREDICATES).and_then(|v| { serde_json::from_value(v.clone()).map_err(|_| { error!("Invalid Json Parsing of Requested Predicates Retrieved From Libindy. Did Libindy change its structure?"); }).ok() }); // handle special case of "empty because json is bad" vs "empty because no attributes sepected" if requested_attributes == None && requested_predicates == None { return Err(VcxError::from_msg(VcxErrorKind::InvalidAttributesStructure, "Invalid Json Parsing of Requested Attributes Retrieved From Libindy")); } let mut fetch_attrs: Map<String, Value> = match requested_attributes { Some(attrs) => attrs.clone(), None => Map::new() }; match requested_predicates { Some(attrs) => fetch_attrs.extend(attrs), None => () } if 0 < fetch_attrs.len() { let search_handle = anoncreds::prover_search_credentials_for_proof_req(wallet_handle, proof_req, None) .wait() .map_err(|ec| { error!("Opening Indy Search for Credentials Failed"); map_rust_indy_sdk_error(ec) })?; let creds: String = fetch_credentials(search_handle, fetch_attrs)?; // should an error on closing a search handle throw an error, or just a warning? // for now we're are just outputting to the user that there is an issue, and continuing on. let _ = close_search_handle(search_handle); Ok(creds) } else { Ok("{}".to_string()) } } pub fn libindy_prover_create_credential_req(prover_did: &str, credential_offer_json: &str, credential_def_json: &str) -> VcxResult<(String, String)> { if settings::test_indy_mode_enabled() { return Ok((::utils::constants::CREDENTIAL_REQ_STRING.to_owned(), String::new())); } let master_secret_name = settings::DEFAULT_LINK_SECRET_ALIAS; anoncreds::prover_create_credential_req(get_wallet_handle(), prover_did, credential_offer_json, credential_def_json, master_secret_name) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_create_revocation_state(rev_reg_def_json: &str, rev_reg_delta_json: &str, cred_rev_id: &str, tails_file: &str) -> VcxResult<String> { if settings::test_indy_mode_enabled() { return Ok(REV_STATE_JSON.to_string()); } let blob_handle = blob_storage_open_reader(tails_file)?; anoncreds::create_revocation_state(blob_handle, rev_reg_def_json, rev_reg_delta_json, 100, cred_rev_id) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_update_revocation_state(rev_reg_def_json: &str, rev_state_json: &str, rev_reg_delta_json: &str, cred_rev_id: &str, tails_file: &str) -> VcxResult<String> { if settings::test_indy_mode_enabled() { return Ok(REV_STATE_JSON.to_string()); } let blob_handle = blob_storage_open_reader(tails_file)?; anoncreds::update_revocation_state(blob_handle, rev_state_json, rev_reg_def_json, rev_reg_delta_json, 100, cred_rev_id) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_store_credential(cred_id: Option<&str>, cred_req_meta: &str, cred_json: &str, cred_def_json: &str, rev_reg_def_json: Option<&str>) -> VcxResult<String> { if settings::test_indy_mode_enabled() { return Ok("cred_id".to_string()); } anoncreds::prover_store_credential(get_wallet_handle(), cred_id, cred_req_meta, cred_json, cred_def_json, rev_reg_def_json) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_prover_create_master_secret(master_secret_id: &str) -> VcxResult<String> { if settings::test_indy_mode_enabled() { return Ok(settings::DEFAULT_LINK_SECRET_ALIAS.to_string()); } anoncreds::prover_create_master_secret(get_wallet_handle(), Some(master_secret_id)) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_issuer_create_schema(issuer_did: &str, name: &str, version: &str, attrs: &str) -> VcxResult<(String, String)> { anoncreds::issuer_create_schema(issuer_did, name, version, attrs) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_issuer_revoke_credential(tails_file: &str, rev_reg_id: &str, cred_rev_id: &str) -> VcxResult<String> { let blob_handle = blob_storage_open_reader(tails_file)?; anoncreds::issuer_revoke_credential(get_wallet_handle(), blob_handle, rev_reg_id, cred_rev_id) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_build_revoc_reg_def_request(submitter_did: &str, rev_reg_def_json: &str) -> VcxResult<String> { ledger::build_revoc_reg_def_request(submitter_did, rev_reg_def_json) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_build_revoc_reg_entry_request(submitter_did: &str, rev_reg_id: &str, rev_def_type: &str, value: &str) -> VcxResult<String> { ledger::build_revoc_reg_entry_request(submitter_did, rev_reg_id, rev_def_type, value) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_build_get_revoc_reg_def_request(submitter_did: &str, rev_reg_id: &str) -> VcxResult<String> { ledger::build_get_revoc_reg_def_request(Some(submitter_did), rev_reg_id) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_parse_get_revoc_reg_def_response(rev_reg_def_json: &str) -> VcxResult<(String, String)> { ledger::parse_get_revoc_reg_def_response(rev_reg_def_json) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_build_get_revoc_reg_delta_request(submitter_did: &str, rev_reg_id: &str, from: i64, to: i64) -> VcxResult<String> { ledger::build_get_revoc_reg_delta_request(Some(submitter_did), rev_reg_id, from, to) .wait() .map_err(map_rust_indy_sdk_error) } fn libindy_build_get_revoc_reg_request(submitter_did: &str, rev_reg_id: &str, timestamp: u64) -> VcxResult<String> { ledger::build_get_revoc_reg_request(Some(submitter_did), rev_reg_id, timestamp as i64) .wait() .map_err(map_rust_indy_sdk_error) } fn libindy_parse_get_revoc_reg_response(get_rev_reg_resp: &str) -> VcxResult<(String, String, u64)> { ledger::parse_get_revoc_reg_response(get_rev_reg_resp) .wait() .map_err(map_rust_indy_sdk_error) } pub fn libindy_parse_get_revoc_reg_delta_response(get_rev_reg_delta_response: &str) -> VcxResult<(String, String, u64)> { ledger::parse_get_revoc_reg_delta_response(get_rev_reg_delta_response) .wait() .map_err(map_rust_indy_sdk_error) } pub fn create_schema(name: &str, version: &str, data: &str) -> VcxResult<(String, Option<PaymentTxn>)> { if settings::test_indy_mode_enabled() { let inputs = vec!["pay:null:9UFgyjuJxi1i1HD".to_string()]; let outputs = serde_json::from_str::<Vec<::utils::libindy::payments::Output>>(r#"[{"amount":4,"extra":null,"recipient":"pay:null:xkIsxem0YNtHrRO"}]"#).unwrap(); return Ok((SCHEMA_ID.to_string(), Some(PaymentTxn::from_parts(inputs, outputs, 1, false)))); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; let (id, create_schema) = libindy_issuer_create_schema(&submitter_did, name, version, data)?; let mut request = libindy_build_schema_request(&submitter_did, &create_schema)?; request = append_txn_author_agreement_to_request(&request)?; let (payment, response) = pay_for_txn(&request, SCHEMA_TXN_TYPE)?; _check_schema_response(&response)?; Ok((id, payment)) } pub fn get_schema_json(schema_id: &str) -> VcxResult<(String, String)> { if settings::test_indy_mode_enabled() { return Ok((SCHEMA_ID.to_string(), SCHEMA_JSON.to_string())); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; libindy_build_get_schema_request(&submitter_did, schema_id) .and_then(|req| libindy_submit_request(&req)) .and_then(|response| libindy_parse_get_schema_response(&response)) } pub fn create_cred_def(issuer_did: &str, schema_json: &str, tag: &str, sig_type: Option<&str>, support_revocation: Option<bool>) -> VcxResult<(String, Option<PaymentTxn>)> { if settings::test_indy_mode_enabled() { let inputs = vec!["pay:null:9UFgyjuJxi1i1HD".to_string()]; let outputs = serde_json::from_str::<Vec<::utils::libindy::payments::Output>>(r#"[{"amount":4,"extra":null,"recipient":"pay:null:xkIsxem0YNtHrRO"}]"#).unwrap(); return Ok((CRED_DEF_ID.to_string(), Some(PaymentTxn::from_parts(inputs, outputs, 1, false)))); } let config_json = json!({"support_revocation": support_revocation.unwrap_or(false)}).to_string(); let (id, cred_def_json) = libindy_create_and_store_credential_def(issuer_did, schema_json, tag, sig_type, &config_json)?; let mut cred_def_req = libindy_build_create_credential_def_txn(issuer_did, &cred_def_json)?; cred_def_req = append_txn_author_agreement_to_request(&cred_def_req)?; let (payment, response) = pay_for_txn(&cred_def_req, CRED_DEF_TXN_TYPE)?; Ok((id, payment)) } pub fn get_cred_def_json(cred_def_id: &str) -> VcxResult<(String, String)> { if settings::test_indy_mode_enabled() { return Ok((CRED_DEF_ID.to_string(), CRED_DEF_JSON.to_string())); } libindy_build_get_credential_def_txn(cred_def_id) .and_then(|req| libindy_submit_request(&req)) .and_then(|response| libindy_parse_get_cred_def_response(&response)) } pub fn create_rev_reg_def(issuer_did: &str, cred_def_id: &str, tails_file: &str, max_creds: u32) -> VcxResult<(String, String, String, Option<PaymentTxn>)> { debug!("creating revocation registry definition with issuer_did: {}, cred_def_id: {}, tails_file_path: {}, max_creds: {}", issuer_did, cred_def_id, tails_file, max_creds); if settings::test_indy_mode_enabled() { return Ok((REV_REG_ID.to_string(), rev_def_json(), "".to_string(), None)); } let (rev_reg_id, rev_reg_def_json, rev_reg_entry_json) = libindy_create_and_store_revoc_reg(issuer_did, cred_def_id, tails_file, max_creds)?; let mut rev_reg_def_req = libindy_build_revoc_reg_def_request(issuer_did, &rev_reg_def_json)?; rev_reg_def_req = append_txn_author_agreement_to_request(&rev_reg_def_req)?; let (payment, _) = pay_for_txn(&rev_reg_def_req, REV_REG_DEF_TXN_TYPE)?; Ok((rev_reg_id, rev_reg_def_json, rev_reg_entry_json, payment)) } pub fn get_rev_reg_def_json(rev_reg_id: &str) -> VcxResult<(String, String)> { if settings::test_indy_mode_enabled() { return Ok((REV_REG_ID.to_string(), rev_def_json())); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; libindy_build_get_revoc_reg_def_request(&submitter_did, rev_reg_id) .and_then(|req| libindy_submit_request(&req)) .and_then(|response| libindy_parse_get_revoc_reg_def_response(&response)) } pub fn post_rev_reg_delta(issuer_did: &str, rev_reg_id: &str, rev_reg_entry_json: &str) -> VcxResult<(Option<PaymentTxn>, String)> { let mut request = libindy_build_revoc_reg_entry_request(issuer_did, rev_reg_id, REVOC_REG_TYPE, rev_reg_entry_json)?; request = append_txn_author_agreement_to_request(&request)?; pay_for_txn(&request, REV_REG_DELTA_TXN_TYPE) } pub fn get_rev_reg_delta_json(rev_reg_id: &str, from: Option<u64>, to: Option<u64>) -> VcxResult<(String, String, u64)> { if settings::test_indy_mode_enabled() { return Ok((REV_REG_ID.to_string(), REV_REG_DELTA_JSON.to_string(), 1)); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; let from: i64 = if let Some(_from) = from { _from as i64 } else { -1 }; let to = if let Some(_to) = to { _to as i64 } else { time::get_time().sec }; libindy_build_get_revoc_reg_delta_request(&submitter_did, rev_reg_id, from, to) .and_then(|req| libindy_submit_request(&req)) .and_then(|response| libindy_parse_get_revoc_reg_delta_response(&response)) } pub fn get_rev_reg(rev_reg_id: &str, timestamp: u64) -> VcxResult<(String, String, u64)> { if settings::test_indy_mode_enabled() { return Ok((REV_REG_ID.to_string(), REV_REG_JSON.to_string(), 1)); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; libindy_build_get_revoc_reg_request(&submitter_did, rev_reg_id, timestamp) .and_then(|req| libindy_submit_request(&req)) .and_then(|response| libindy_parse_get_revoc_reg_response(&response)) } pub fn revoke_credential(tails_file: &str, rev_reg_id: &str, cred_rev_id: &str) -> VcxResult<(Option<PaymentTxn>, String)> { if settings::test_indy_mode_enabled() { let inputs = vec!["pay:null:9UFgyjuJxi1i1HD".to_string()]; let outputs = serde_json::from_str::<Vec<::utils::libindy::payments::Output>>(r#"[{"amount":4,"extra":null,"recipient":"pay:null:xkIsxem0YNtHrRO"}]"#).unwrap(); return Ok((Some(PaymentTxn::from_parts(inputs, outputs, 1, false)), REV_REG_DELTA_JSON.to_string())); } let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; let delta = libindy_issuer_revoke_credential(tails_file, rev_reg_id, cred_rev_id)?; let (payment, _) = post_rev_reg_delta(&submitter_did, rev_reg_id, &delta)?; Ok((payment, delta)) } fn _check_schema_response(response: &str) -> VcxResult<()> { // TODO: saved backwardcampatibilyty but actually we can better handle response match parse_response(response)? { Response::Reply(_) => Ok(()), Response::Reject(reject) => Err(VcxError::from_msg(VcxErrorKind::DuplicationSchema, format!("{:?}", reject))), Response::ReqNACK(reqnack) => Err(VcxError::from_msg(VcxErrorKind::UnknownSchemaRejection, "Unknown Rejection of Schema Creation, refer to libindy documentation")) } } #[cfg(test)] pub mod tests { use super::*; use utils::get_temp_dir_path; extern crate serde_json; extern crate rand; use rand::Rng; use settings; use utils::constants::*; use std::thread; use std::time::Duration; #[cfg(feature = "pool_tests")] use utils::constants::TEST_TAILS_FILE; pub fn create_schema(attr_list: &str) -> (String, String) { let data = attr_list.to_string(); let schema_name: String = rand::thread_rng().gen_ascii_chars().take(25).collect::<String>(); let schema_version: String = format!("{}.{}", rand::thread_rng().gen::<u32>().to_string(), rand::thread_rng().gen::<u32>().to_string()); let institution_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); libindy_issuer_create_schema(&institution_did, &schema_name, &schema_version, &data).unwrap() } pub fn create_schema_req(schema_json: &str) -> String { let institution_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let request = ::utils::libindy::ledger::libindy_build_schema_request(&institution_did, schema_json).unwrap(); append_txn_author_agreement_to_request(&request).unwrap() } pub fn write_schema(request: &str) { let (payment_info, response) = ::utils::libindy::payments::pay_for_txn(&request, SCHEMA_TXN_TYPE).unwrap(); } pub fn create_and_write_test_schema(attr_list: &str) -> (String, String) { let (schema_id, schema_json) = create_schema(attr_list); let req = create_schema_req(&schema_json); write_schema(&req); thread::sleep(Duration::from_millis(1000)); (schema_id, schema_json) } pub fn create_and_store_credential_def(attr_list: &str, support_rev: bool) -> (String, String, String, String, u32, Option<String>) { /* create schema */ let (schema_id, schema_json) = create_and_write_test_schema(attr_list); let name: String = rand::thread_rng().gen_ascii_chars().take(25).collect::<String>(); let institution_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); /* create cred-def */ let mut revocation_details = json!({"support_revocation":support_rev}); if support_rev { revocation_details["tails_file"] = json!(get_temp_dir_path(Some(TEST_TAILS_FILE)).to_str().unwrap().to_string()); revocation_details["max_creds"] = json!(10); } let handle = ::credential_def::create_new_credentialdef("1".to_string(), name, institution_did.clone(), schema_id.clone(), "tag1".to_string(), revocation_details.to_string()).unwrap(); thread::sleep(Duration::from_millis(1000)); let cred_def_id = ::credential_def::get_cred_def_id(handle).unwrap(); thread::sleep(Duration::from_millis(1000)); let (_, cred_def_json) = get_cred_def_json(&cred_def_id).unwrap(); let rev_reg_id = ::credential_def::get_rev_reg_id(handle).unwrap(); (schema_id, schema_json, cred_def_id, cred_def_json, handle, rev_reg_id) } pub fn create_credential_offer(attr_list: &str, revocation: bool) -> (String, String, String, String, String, Option<String>) { let (schema_id, schema_json, cred_def_id, cred_def_json, _, rev_reg_id) = create_and_store_credential_def(attr_list, revocation); let offer = ::utils::libindy::anoncreds::libindy_issuer_create_credential_offer(&cred_def_id).unwrap(); (schema_id, schema_json, cred_def_id, cred_def_json, offer, rev_reg_id) } pub fn create_credential_req(attr_list: &str, revocation: bool) -> (String, String, String, String, String, String, String, Option<String>) { let (schema_id, schema_json, cred_def_id, cred_def_json, offer, rev_reg_id) = create_credential_offer(attr_list, revocation); let institution_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let (req, req_meta) = ::utils::libindy::anoncreds::libindy_prover_create_credential_req(&institution_did, &offer, &cred_def_json).unwrap(); (schema_id, schema_json, cred_def_id, cred_def_json, offer, req, req_meta, rev_reg_id) } pub fn create_and_store_credential(attr_list: &str, revocation: bool) -> (String, String, String, String, String, String, String, String, Option<String>, Option<String>) { let (schema_id, schema_json, cred_def_id, cred_def_json, offer, req, req_meta, rev_reg_id) = create_credential_req(attr_list, revocation); /* create cred */ let credential_data = r#"{"address1": ["123 Main St"], "address2": ["Suite 3"], "city": ["Draper"], "state": ["UT"], "zip": ["84000"]}"#; let encoded_attributes = ::issuer_credential::encode_attributes(&credential_data).unwrap(); let (rev_def_json, tails_file) = if revocation { let (id, json) = get_rev_reg_def_json(&rev_reg_id.clone().unwrap()).unwrap(); (Some(json), Some(get_temp_dir_path(Some(TEST_TAILS_FILE)).to_str().unwrap().to_string().to_string())) } else { (None, None) }; let (cred, cred_rev_id, _) = ::utils::libindy::anoncreds::libindy_issuer_create_credential(&offer, &req, &encoded_attributes, rev_reg_id.clone(), tails_file).unwrap(); /* store cred */ let cred_id = ::utils::libindy::anoncreds::libindy_prover_store_credential(None, &req_meta, &cred, &cred_def_json, rev_def_json.as_ref().map(String::as_str)).unwrap(); (schema_id, schema_json, cred_def_id, cred_def_json, offer, req, req_meta, cred_id, rev_reg_id, cred_rev_id) } pub fn create_proof() -> (String, String, String, String) { let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let (schema_id, schema_json, cred_def_id, cred_def_json, offer, req, req_meta, cred_id, _, _) = create_and_store_credential(::utils::constants::DEFAULT_SCHEMA_ATTRS, false); let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"0.1", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", "restrictions": [json!({ "issuer_did": did })] }), "zip_2": json!({ "name":"zip", "restrictions": [json!({ "issuer_did": did })] }), "self_attest_3": json!({ "name":"self_attest", }), }), "requested_predicates": json!({}), }).to_string(); let requested_credentials_json = json!({ "self_attested_attributes":{ "self_attest_3": "my_self_attested_val" }, "requested_attributes":{ "address1_1": {"cred_id": cred_id, "revealed": true}, "zip_2": {"cred_id": cred_id, "revealed": true} }, "requested_predicates":{} }).to_string(); let schema_json: serde_json::Value = serde_json::from_str(&schema_json).unwrap(); let schemas = json!({ schema_id: schema_json, }).to_string(); let cred_def_json: serde_json::Value = serde_json::from_str(&cred_def_json).unwrap(); let cred_defs = json!({ cred_def_id: cred_def_json, }).to_string(); libindy_prover_get_credentials_for_proof_req(&proof_req).unwrap(); let proof = libindy_prover_create_proof( &proof_req, &requested_credentials_json, "main", &schemas, &cred_defs, None).unwrap(); (schemas, cred_defs, proof_req, proof) } pub fn create_self_attested_proof() -> (String, String) { let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"0.1", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", }), "zip_2": json!({ "name":"zip", }), }), "requested_predicates": json!({}), }).to_string(); let requested_credentials_json = json!({ "self_attested_attributes":{ "address1_1": "my_self_attested_address", "zip_2": "my_self_attested_zip" }, "requested_attributes":{}, "requested_predicates":{} }).to_string(); let schemas = json!({}).to_string(); let cred_defs = json!({}).to_string(); libindy_prover_get_credentials_for_proof_req(&proof_req).unwrap(); let proof = libindy_prover_create_proof( &proof_req, &requested_credentials_json, "main", &schemas, &cred_defs, None).unwrap(); (proof_req, proof) } pub fn create_proof_with_predicate(include_predicate_cred: bool) -> (String, String, String, String) { let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let (schema_id, schema_json, cred_def_id, cred_def_json, offer, req, req_meta, cred_id, _, _) = create_and_store_credential(::utils::constants::DEFAULT_SCHEMA_ATTRS, false); let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"0.1", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", "restrictions": [json!({ "issuer_did": did })] }), "self_attest_3": json!({ "name":"self_attest", }), }), "requested_predicates": json!({ "zip_3": {"name":"zip", "p_type":">=", "p_value":18} }), }).to_string(); let requested_credentials_json; if include_predicate_cred { requested_credentials_json = json!({ "self_attested_attributes":{ "self_attest_3": "my_self_attested_val" }, "requested_attributes":{ "address1_1": {"cred_id": cred_id, "revealed": true} }, "requested_predicates":{ "zip_3": {"cred_id": cred_id} } }).to_string(); } else { requested_credentials_json = json!({ "self_attested_attributes":{ "self_attest_3": "my_self_attested_val" }, "requested_attributes":{ "address1_1": {"cred_id": cred_id, "revealed": true} }, "requested_predicates":{ } }).to_string(); } let schema_json: serde_json::Value = serde_json::from_str(&schema_json).unwrap(); let schemas = json!({ schema_id: schema_json, }).to_string(); let cred_def_json: serde_json::Value = serde_json::from_str(&cred_def_json).unwrap(); let cred_defs = json!({ cred_def_id: cred_def_json, }).to_string(); libindy_prover_get_credentials_for_proof_req(&proof_req).unwrap(); let proof = libindy_prover_create_proof( &proof_req, &requested_credentials_json, "main", &schemas, &cred_defs, None).unwrap(); (schemas, cred_defs, proof_req, proof) } #[cfg(feature = "pool_tests")] #[test] fn test_prover_verify_proof() { init!("ledger"); let (schemas, cred_defs, proof_req, proof) = create_proof(); let result = libindy_verifier_verify_proof( &proof_req, &proof, &schemas, &cred_defs, "{}", "{}", ); assert!(result.is_ok()); let proof_validation = result.unwrap(); assert!(proof_validation, true); } #[cfg(feature = "pool_tests")] #[test] fn test_prover_verify_proof_with_predicate_success_case() { init!("ledger"); let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate(true); let result = libindy_verifier_verify_proof( &proof_req, &proof, &schemas, &cred_defs, "{}", "{}", ); assert!(result.is_ok()); let proof_validation = result.unwrap(); assert!(proof_validation, true); } #[cfg(feature = "pool_tests")] #[test] fn test_prover_verify_proof_with_predicate_fail_case() { init!("ledger"); let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate(false); let result = libindy_verifier_verify_proof( &proof_req, &proof, &schemas, &cred_defs, "{}", "{}", ); assert!(!result.is_ok()); } #[cfg(feature = "pool_tests")] #[test] fn tests_libindy_prover_get_credentials() { init!("ledger"); let proof_req = "{"; let result = libindy_prover_get_credentials_for_proof_req(&proof_req); assert_eq!(result.unwrap_err().kind(), VcxErrorKind::InvalidProofRequest); let proof_req = json!({ "nonce":"123432421212", "name":"proof_req_1", "version":"0.1", "requested_attributes": json!({ "address1_1": json!({ "name":"address1", }), "zip_2": json!({ "name":"zip", }), }), "requested_predicates": json!({}), }).to_string(); let result = libindy_prover_get_credentials_for_proof_req(&proof_req); let result_malformed_json = libindy_prover_get_credentials_for_proof_req("{}"); let wallet_handle = get_wallet_handle(); let proof_req_str: String = serde_json::to_string(&proof_req).unwrap(); assert!(result.is_ok()); assert_eq!(result_malformed_json.unwrap_err().kind(), VcxErrorKind::InvalidAttributesStructure); } #[cfg(feature = "pool_tests")] #[test] fn test_issuer_revoke_credential() { init!("ledger"); let rc = libindy_issuer_revoke_credential(get_temp_dir_path(Some(TEST_TAILS_FILE)).to_str().unwrap(), "", ""); assert!(rc.is_err()); let (_, _, cred_def_id, _, _, _, _, cred_id, rev_reg_id, cred_rev_id) = create_and_store_credential(::utils::constants::DEFAULT_SCHEMA_ATTRS, true); let rc = ::utils::libindy::anoncreds::libindy_issuer_revoke_credential(get_temp_dir_path(Some(TEST_TAILS_FILE)).to_str().unwrap(), &rev_reg_id.unwrap(), &cred_rev_id.unwrap()); assert!(rc.is_ok()); } #[test] fn test_create_cred_def() { init!("true"); let (id, _) = create_cred_def("did", SCHEMAS_JSON, "tag_1", None, Some(false)).unwrap(); assert_eq!(id, CRED_DEF_ID); } #[cfg(feature = "pool_tests")] #[test] fn test_create_cred_def_real() { init!("ledger"); let data = r#"["address1","address2","zip","city","state"]"#.to_string(); let (schema_id, _) = ::utils::libindy::anoncreds::tests::create_and_write_test_schema(::utils::constants::DEFAULT_SCHEMA_ATTRS); let (_, schema_json) = get_schema_json(&schema_id).unwrap(); let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let revocation_details = json!({ "support_revocation": true, "tails_file": get_temp_dir_path(Some("tails.txt")).to_str().unwrap(), "max_creds": 2 }).to_string(); create_cred_def(&did, &schema_json, "tag_1", None, Some(true)).unwrap(); } #[cfg(feature = "pool_tests")] #[test] fn test_rev_reg_def_fails_for_cred_def_created_without_revocation() { let wallet_name = "test_create_revocable_fails_with_no_tails_file"; init!("ledger"); let data = r#"["address1","address2","zip","city","state"]"#.to_string(); // Cred def is created with support_revocation=false, // revoc_reg_def will fail in libindy because cred_Def doesn't have revocation keys let (_, _, cred_def_id, _, _, _) = ::utils::libindy::anoncreds::tests::create_and_store_credential_def(::utils::constants::DEFAULT_SCHEMA_ATTRS, false); let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let rc = create_rev_reg_def(&did, &cred_def_id, get_temp_dir_path(Some("path.txt")).to_str().unwrap(), 2); assert_eq!(rc.unwrap_err().kind(), VcxErrorKind::LibindyInvalidStructure); } #[cfg(feature = "pool_tests")] #[test] fn test_create_rev_reg_def() { init!("ledger"); let data = r#"["address1","address2","zip","city","state"]"#.to_string(); let (schema_id, _) = ::utils::libindy::anoncreds::tests::create_and_write_test_schema(::utils::constants::DEFAULT_SCHEMA_ATTRS); let (_, schema_json) = get_schema_json(&schema_id).unwrap(); let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let revocation_details = json!({"support_revocation": true, "tails_file": get_temp_dir_path(Some("tails.txt")).to_str().unwrap(), "max_creds": 2}).to_string(); let (id, payment) = create_cred_def(&did, &schema_json, "tag_1", None, Some(true)).unwrap(); create_rev_reg_def(&did, &id, "tails.txt", 2).unwrap(); } #[cfg(feature = "pool_tests")] #[test] fn test_get_rev_reg_def_json() { init!("ledger"); let attrs = r#"["address1","address2","city","state","zip"]"#; let (_, _, _, _, _, rev_reg_id) = ::utils::libindy::anoncreds::tests::create_and_store_credential_def(attrs, true); let rev_reg_id = rev_reg_id.unwrap(); let (id, json) = get_rev_reg_def_json(&rev_reg_id).unwrap(); assert_eq!(id, rev_reg_id); } #[cfg(feature = "pool_tests")] #[test] fn test_get_rev_reg_delta_json() { init!("ledger"); let attrs = r#"["address1","address2","city","state","zip"]"#; let (_, _, _, _, _, rev_reg_id) = ::utils::libindy::anoncreds::tests::create_and_store_credential_def(attrs, true); let rev_reg_id = rev_reg_id.unwrap(); let (id, delta, timestamp) = get_rev_reg_delta_json(&rev_reg_id, None, None).unwrap(); assert_eq!(id, rev_reg_id); } #[cfg(feature = "pool_tests")] #[test] fn test_get_rev_reg() { init!("ledger"); let attrs = r#"["address1","address2","city","state","zip"]"#; let (_, _, _, _, _, rev_reg_id) = ::utils::libindy::anoncreds::tests::create_and_store_credential_def(attrs, true); let rev_reg_id = rev_reg_id.unwrap(); let (id, rev_reg, timestamp) = get_rev_reg(&rev_reg_id, time::get_time().sec as u64).unwrap(); assert_eq!(id, rev_reg_id); } #[cfg(feature = "pool_tests")] #[test] fn from_pool_ledger_with_id() { use settings; init!("ledger"); let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let (schema_id, schema_json) = ::utils::libindy::anoncreds::tests::create_and_write_test_schema(::utils::constants::DEFAULT_SCHEMA_ATTRS); let rc = get_schema_json(&schema_id); let (id, retrieved_schema) = rc.unwrap(); assert!(retrieved_schema.contains(&schema_id)); } #[test] fn from_ledger_schema_id() { init!("true"); let (id, retrieved_schema) = get_schema_json(SCHEMA_ID).unwrap(); assert_eq!(&retrieved_schema, SCHEMA_JSON); assert_eq!(&id, SCHEMA_ID); } #[cfg(feature = "pool_tests")] #[test] fn test_revoke_credential() { init!("ledger"); let (_, _, cred_def_id, _, _, _, _, cred_id, rev_reg_id, cred_rev_id) = ::utils::libindy::anoncreds::tests::create_and_store_credential(::utils::constants::DEFAULT_SCHEMA_ATTRS, true); let rev_reg_id = rev_reg_id.unwrap(); let (_, first_rev_reg_delta, first_timestamp) = get_rev_reg_delta_json(&rev_reg_id, None, None).unwrap(); let (_, test_same_delta, test_same_timestamp) = get_rev_reg_delta_json(&rev_reg_id, None, None).unwrap(); assert_eq!(first_rev_reg_delta, test_same_delta); assert_eq!(first_timestamp, test_same_timestamp); let (payment, revoked_rev_reg_delta) = revoke_credential(get_temp_dir_path(Some(TEST_TAILS_FILE)).to_str().unwrap(), &rev_reg_id, cred_rev_id.unwrap().as_str()).unwrap(); // Delta should change after revocation let (_, second_rev_reg_delta, _) = get_rev_reg_delta_json(&rev_reg_id, Some(first_timestamp + 1), None).unwrap(); assert!(payment.is_some()); assert_ne!(first_rev_reg_delta, second_rev_reg_delta); } }
44.690099
233
0.605446
6476d71fb31124267f7e17076257e9bce63cbd28
10,928
use crate::build::{build_internal, finalize}; use crate::cmd::{cfg_spinner, run_stage}; use crate::parse::{Integration, ServeOpts}; use crate::thread::{spawn_thread, ThreadHandle}; use crate::{errors::*, order_reload}; use console::{style, Emoji}; use indicatif::{MultiProgress, ProgressBar}; use std::env; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; // Emojis for stages static BUILDING_SERVER: Emoji<'_, '_> = Emoji("📡", ""); static SERVING: Emoji<'_, '_> = Emoji("🛰️ ", ""); /// Returns the exit code if it's non-zero. macro_rules! handle_exit_code { ($code:expr) => {{ let (stdout, stderr, code) = $code; if code != 0 { return ::std::result::Result::Ok(code); } (stdout, stderr) }}; } /// Builds the server for the app, program arguments having been interpreted. This needs to know if we've built as part of this process /// so it can show an accurate progress count. This also takes a `MultiProgress` so it can be used truly atomically (which will have /// build spinners already on it if necessary). This also takes a `Mutex<String>` to inform the caller of the path of the server /// executable. fn build_server( dir: PathBuf, spinners: &MultiProgress, did_build: bool, exec: Arc<Mutex<String>>, is_release: bool, is_standalone: bool, integration: Integration, ) -> Result< ThreadHandle<impl FnOnce() -> Result<i32, ExecutionError>, Result<i32, ExecutionError>>, ExecutionError, > { // If we're using the Actix Web integration, warn that it's unstable // A similar warning is emitted for snooping on it // TODO Remove this once Actix Web v4.0.0 goes stable if integration == Integration::ActixWeb { println!("WARNING: The Actix Web integration uses a beta version of Actix Web, and is considered unstable. It is not recommended for production usage.") } let num_steps = match did_build { true => 4, false => 2, }; let target = dir.join(".perseus/server"); // Server building message let sb_msg = format!( "{} {} Building server", style(format!("[{}/{}]", num_steps - 1, num_steps)) .bold() .dim(), BUILDING_SERVER ); // We'll parallelize the building of the server with any build commands that are currently running // We deliberately insert the spinner at the end of the list let sb_spinner = spinners.insert(num_steps - 1, ProgressBar::new_spinner()); let sb_spinner = cfg_spinner(sb_spinner, &sb_msg); let sb_target = target; let sb_thread = spawn_thread(move || { let (stdout, _stderr) = handle_exit_code!(run_stage( vec![&format!( // This sets Cargo to tell us everything, including the executable path to the server "{} build --message-format json --features integration-{} {} --no-default-features {}", env::var("PERSEUS_CARGO_PATH").unwrap_or_else(|_| "cargo".to_string()), // Enable the appropriate integration integration.to_string(), // We'll also handle whether or not it's standalone because that goes under the `--features` flag if is_standalone { "--features standalone" } else { "" }, if is_release { "--release" } else { "" }, )], &sb_target, &sb_spinner, &sb_msg )?); let msgs: Vec<&str> = stdout.trim().split('\n').collect(); // If we got to here, the exit code was 0 and everything should've worked // The last message will just tell us that the build finished, the second-last one will tell us the executable path let msg = msgs.get(msgs.len() - 2); let msg = match msg { // We'll parse it as a Serde `Value`, we don't need to know everything that's in there Some(msg) => serde_json::from_str::<serde_json::Value>(msg) .map_err(|err| ExecutionError::GetServerExecutableFailed { source: err })?, None => return Err(ExecutionError::ServerExectutableMsgNotFound), }; let server_exec_path = msg.get("executable"); let server_exec_path = match server_exec_path { // We'll parse it as a Serde `Value`, we don't need to know everything that's in there Some(server_exec_path) => match server_exec_path.as_str() { Some(server_exec_path) => server_exec_path, None => { return Err(ExecutionError::ParseServerExecutableFailed { err: "expected 'executable' field to be string".to_string(), }) } }, None => return Err(ExecutionError::ParseServerExecutableFailed { err: "expected 'executable' field in JSON map in second-last message, not present" .to_string(), }), }; // And now the main thread needs to know about this let mut exec_val = exec.lock().unwrap(); *exec_val = server_exec_path.to_string(); Ok(0) }); Ok(sb_thread) } /// Runs the server at the given path, handling any errors therewith. This will likely be a black hole until the user manually terminates /// the process. fn run_server( exec: Arc<Mutex<String>>, dir: PathBuf, did_build: bool, ) -> Result<i32, ExecutionError> { let target = dir.join(".perseus/server"); let num_steps = match did_build { true => 4, false => 2, }; // First off, handle any issues with the executable path let exec_val = exec.lock().unwrap(); if exec_val.is_empty() { return Err(ExecutionError::ParseServerExecutableFailed { err: "mutex value empty, implies uncaught thread termination (please report this as a bug)" .to_string() }); } let server_exec_path = (*exec_val).to_string(); // Manually run the generated binary (invoking in the right directory context for good measure if it ever needs it in future) let child = Command::new(&server_exec_path) .current_dir(target) // We should be able to access outputs in case there's an error .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|err| ExecutionError::CmdExecFailed { cmd: server_exec_path, source: err, })?; // Figure out what host/port the app will be live on (these have been set by the system) let host = env::var("PERSEUS_HOST").unwrap_or_else(|_| "localhost".to_string()); let port = env::var("PERSEUS_PORT") .unwrap_or_else(|_| "8080".to_string()) .parse::<u16>() .map_err(|err| ExecutionError::PortNotNumber { source: err })?; // Give the user a nice informational message println!( " {} {} Your app is now live on <http://{host}:{port}>! To change this, re-run this command with different settings for `--host` and `--port`.", style(format!("[{}/{}]", num_steps, num_steps)).bold().dim(), SERVING, host=host, port=port ); // Wait on the child process to finish (which it shouldn't unless there's an error), then perform error handling let output = child.wait_with_output().unwrap(); let exit_code = match output.status.code() { Some(exit_code) => exit_code, // If we have an exit code, use it None if output.status.success() => 0, // If we don't, but we know the command succeeded, return 0 (success code) None => 1, // If we don't know an exit code but we know that the command failed, return 1 (general error code) }; // Print `stderr` and stdout` only if there's something therein and the exit code is non-zero if !output.stderr.is_empty() && exit_code != 0 { // We don't print any failure message other than the actual error right now (see if people want something else?) std::io::stderr().write_all(&output.stdout).unwrap(); std::io::stderr().write_all(&output.stderr).unwrap(); return Ok(1); } Ok(0) } /// Builds the subcrates to get a directory that we can serve and then serves it. If possible, this will return the path to the server /// executable so that it can be used in deployment. pub fn serve(dir: PathBuf, opts: ServeOpts) -> Result<(i32, Option<String>), ExecutionError> { // Set the environment variables for the host and port env::set_var("PERSEUS_HOST", opts.host); env::set_var("PERSEUS_PORT", opts.port.to_string()); let spinners = MultiProgress::new(); let did_build = !opts.no_build; let should_run = !opts.no_run; // We need to have a way of knowing what the executable path to the server is let exec = Arc::new(Mutex::new(String::new())); // We can begin building the server in a thread without having to deal with the rest of the build stage yet let sb_thread = build_server( dir.clone(), &spinners, did_build, Arc::clone(&exec), opts.release, opts.standalone, opts.integration, )?; // Only build if the user hasn't set `--no-build`, handling non-zero exit codes if did_build { let (sg_thread, wb_thread) = build_internal(dir.clone(), &spinners, 4, opts.release)?; let sg_res = sg_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; let wb_res = wb_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; if sg_res != 0 { return Ok((sg_res, None)); } else if wb_res != 0 { return Ok((wb_res, None)); } } // Handle errors from the server building let sb_res = sb_thread .join() .map_err(|_| ExecutionError::ThreadWaitFailed)??; if sb_res != 0 { return Ok((sb_res, None)); } // And now we can run the finalization stage (only if `--no-build` wasn't specified) if did_build { finalize(&dir.join(".perseus"))?; } // Order any connected browsers to reload order_reload(); // Now actually run that executable path if we should if should_run { let exit_code = run_server(Arc::clone(&exec), dir, did_build)?; Ok((exit_code, None)) } else { // The user doesn't want to run the server, so we'll give them the executable path instead let exec_str = (*exec.lock().unwrap()).to_string(); println!("Not running server because `--no-run` was provided. You can run it manually by running the following executable in `.perseus/server/`.\n{}", &exec_str); Ok((0, Some(exec_str))) } }
41.869732
170
0.610725
146f7728ad1edea8d84c0b9bd64c49ef1b122b9f
1,315
//! 系统调用 use lib_redos; pub const STDIN: usize = 0; pub const STDOUT: usize = 1; /// 将参数放在对应寄存器中,并执行 `ecall` #[inline(always)] pub(crate) fn syscall(id: usize, arg0: usize, arg1: usize, arg2: usize, arg3: usize) -> isize { // 返回值 let mut ret = 0; unsafe { llvm_asm!("ecall" : "={x10}" (ret) : "{x10}" (arg0), "{x11}" (arg1), "{x12}" (arg2), "{x13}" (arg3), "{x17}" (id) : "memory" // 如果汇编可能改变内存,则需要加入 memory 选项 : "volatile"); // 防止编译器做激进的优化(如调换指令顺序等破坏 SBI 调用行为的优化) } ret } /// 读取字符 pub fn sys_read(fd: usize, buffer: &mut [u8]) -> isize { loop { let ret = syscall( lib_redos::SYS_READ, fd, buffer as *const [u8] as *const u8 as usize, buffer.len(), 0, ); if ret > 0 { return ret; } } } /// 打印字符串 pub fn sys_write(fd: usize, buffer: &[u8]) -> isize { syscall( lib_redos::SYS_WRITE, fd, buffer as *const [u8] as *const u8 as usize, buffer.len(), 0, ) } /// 退出并返回数值 pub fn sys_exit(code: isize) -> ! { syscall(lib_redos::SYS_EXIT, code as usize, 0, 0, 0); unreachable!() } fn sys_exit0() -> ! { syscall(lib_redos::SYS_EXIT, 0, 0, 0, 0); unreachable!() }
21.916667
95
0.501901
e56c139f84e3472fbe66c31293abd4c7758d2de8
1,991
#![feature(intrinsics, lang_items, no_core, fundamental)] #![no_core] #![allow(unused_variables)] fn fibonacci_iterative(n: i32) -> i32 { let mut current = 0; let mut next = 1; let mut iterator = 0; loop { if iterator == n { break; } let tmp = current + next; current = next; next = tmp; iterator += 1; } current } #[lang = "panic"] fn panic() -> ! { loop {} } macro_rules! panic { () => ( panic!("explicit panic") ); ($msg:expr) => ({ $crate::panic() }); } macro_rules! assert { ($cond:expr) => ( if !$cond { panic!(concat!("assertion failed: ", stringify!($cond))) } ); } fn main() { let result = fibonacci_iterative(25); assert!(result == 75025); } #[lang = "sized"] #[fundamental] pub trait Sized {} #[lang = "copy"] pub trait Copy: Clone {} pub trait Clone: Sized {} #[lang = "eq"] pub trait PartialEq<Rhs: ?Sized = Self> { fn eq(&self, other: &Rhs) -> bool; #[inline] fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } } impl PartialEq for i32 { #[inline] fn eq(&self, other: &i32) -> bool { (*self) == (*other) } #[inline] fn ne(&self, other: &i32) -> bool { (*self) != (*other) } } #[lang = "add"] pub trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for i32 { type Output = i32; fn add(self, rhs: i32) -> Self::Output { self + rhs } } #[lang = "sub"] pub trait Sub<RHS = Self> { type Output; fn sub(self, rhs: RHS) -> Self::Output; } impl Sub for i32 { type Output = i32; fn sub(self, rhs: i32) -> Self::Output { self - rhs } } #[lang = "add_assign"] pub trait AddAssign<Rhs = Self> { fn add_assign(&mut self, Rhs); } impl AddAssign for i32 { #[inline] fn add_assign(&mut self, other: i32) { *self += other } }
16.731092
68
0.512305
e2707f5dfe234bee372313703ebd545ec6fb94ba
1,004
pub trait Area { fn area(&self) -> f64; } pub struct Triangle { pub h: f64, pub d: f64, } impl Triangle { pub fn new(h: f64, d: f64) -> Self { Triangle { h, d } } } impl Area for Triangle { fn area(&self) -> f64 { return (self.h * self.d) / 2 as f64; } } pub struct Circle { pub r: f64 } impl Circle { pub fn new(r: f64) -> Self { return Circle { r }; } } impl Area for Circle { fn area(&self) -> f64 { return std::f64::consts::PI * self.r * self.r; } } pub fn get_area<T: Area>(value: &T) -> f64 { return value.area(); } #[cfg(test)] mod test { use crate::graphic_area::{Triangle, get_area, Circle}; #[test] fn test() { let triangle = Triangle::new(2.0, 3.0); let tr_area = get_area(&triangle); println!("tr area: {}", tr_area); let circle = Circle::new(2 as f64); let cir_area = get_area(&circle); println!("circle area: {}", cir_area) } }
16.459016
58
0.5249
1649035079af2f70da9d4506ad63de262dc8a1d0
2,182
//Imports use std::fmt; // Tuples can be used a function arguements and aas return values fn reverse(pair: (i32, bool)) -> (bool, i32) { // `let` can be used to bind the members of a tupel to varialbes let (integer, boolean) = pair; (boolean, integer) } // The following struct is for the activity. #[derive(Debug)] struct Matrix(f32, f32, f32, f32); fn transpose(matrix: Matrix) -> Matrix { Matrix(matrix.0, matrix.2, matrix.1, matrix.3) } impl fmt::Display for Matrix { // This trait requires `fmt` with this exact signature fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\n{} {}\n{} {}", self.0, self.1, self.2, self.3) } } fn main() { // A tuple with a bunch of different types let long_tuple = (1u8, 2u16, 3u32, 4u64, -1i8, -2i16, -3i32, -4i64, 0.1f32, 0.2f64, 'a', true); // Values can be extracted from the tuple using tuple indexing println!("long tuple first value: {}", long_tuple.0); println!("long tuple second value: {}", long_tuple.1); // Tuples can be tuple members let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); // Tuples are printable println!("tuple of tuples: {:?}", tuple_of_tuples); // But long Tuples cannot be printed // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); // println!("too long tuple: {:?}", too_long_tuple); // TODO ^ Uncomment the above 2 lines to see the compiler error let pair = (1, true); println!("pair is {:?}", pair); println!("the reversed pair is {:?}", reverse(pair)); // To create one element tuples, the comma is required to tell them apart // from a literal surrounded by parentheses println!("one element tuple: {:?}", (5u32,)); println!("just and integer: {:?}", (5u32)); //tuples can be destructed to create bindings let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:{}", matrix); println!("Transpose:{}", transpose(matrix)); }
31.171429
77
0.584785
de9a6a66e1a18d57f1dca5e50fa807c537c5aea7
163
//! OS-specific extension for crate types. #[cfg(unix)] pub mod unix; #[cfg(target_os = "macos")] pub mod macos; #[cfg(target_os = "windows")] pub mod windows;
14.818182
42
0.668712
761d8faf6ead0eaec0217aa3237c5fcdd6e25126
8,720
// Copyright 2017 Serde Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use std::ops; use super::Value; use map::Map; /// A type that can be used to index into a `serde_json::Value`. See the `get` /// and `get_mut` methods of `Value`. /// /// This trait is sealed and cannot be implemented for types outside of /// `serde_json`. pub trait Index: private::Sealed { /// Return None if the key is not already in the array or object. #[doc(hidden)] fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; /// Return None if the key is not already in the array or object. #[doc(hidden)] fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; /// Panic if array index out of bounds. If key is not already in the object, /// insert it with a value of null. Panic if Value is a type that cannot be /// indexed into, except if Value is null then it can be treated as an empty /// object. #[doc(hidden)] fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; } impl Index for usize { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { match *v { Value::Array(ref vec) => vec.get(*self), _ => None, } } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { match *v { Value::Array(ref mut vec) => vec.get_mut(*self), _ => None, } } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { match *v { Value::Array(ref mut vec) => { let len = vec.len(); vec.get_mut(*self) .unwrap_or_else( || { panic!( "cannot access index {} of JSON array of length {}", self, len ) }, ) } _ => panic!("cannot access index {} of JSON {}", self, Type(v)), } } } impl Index for str { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { match *v { Value::Object(ref map) => map.get(self), _ => None, } } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { match *v { Value::Object(ref mut map) => map.get_mut(self), _ => None, } } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { if let Value::Null = *v { let mut map = Map::new(); map.insert(self.to_owned(), Value::Null); *v = Value::Object(map); } match *v { Value::Object(ref mut map) => { map.entry(self.to_owned()).or_insert(Value::Null) } _ => panic!("cannot access key {:?} in JSON {}", self, Type(v)), } } } impl Index for String { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { self[..].index_into(v) } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { self[..].index_into_mut(v) } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { self[..].index_or_insert(v) } } impl<'a, T: ?Sized> Index for &'a T where T: Index, { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { (**self).index_into(v) } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { (**self).index_into_mut(v) } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { (**self).index_or_insert(v) } } // Prevent users from implementing the Index trait. mod private { pub trait Sealed {} impl Sealed for usize {} impl Sealed for str {} impl Sealed for String {} impl<'a, T: ?Sized> Sealed for &'a T where T: Sealed, { } } /// Used in panic messages. struct Type<'a>(&'a Value); impl<'a> fmt::Display for Type<'a> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match *self.0 { Value::Null => formatter.write_str("null"), Value::Bool(_) => formatter.write_str("boolean"), Value::Number(_) => formatter.write_str("number"), Value::String(_) => formatter.write_str("string"), Value::Array(_) => formatter.write_str("array"), Value::Object(_) => formatter.write_str("object"), } } } // The usual semantics of Index is to panic on invalid indexing. // // That said, the usual semantics are for things like Vec and BTreeMap which // have different use cases than Value. If you are working with a Vec, you know // that you are working with a Vec and you can get the len of the Vec and make // sure your indices are within bounds. The Value use cases are more // loosey-goosey. You got some JSON from an endpoint and you want to pull values // out of it. Outside of this Index impl, you already have the option of using // value.as_array() and working with the Vec directly, or matching on // Value::Array and getting the Vec directly. The Index impl means you can skip // that and index directly into the thing using a concise syntax. You don't have // to check the type, you don't have to check the len, it is all about what you // expect the Value to look like. // // Basically the use cases that would be well served by panicking here are // better served by using one of the other approaches: get and get_mut, // as_array, or match. The value of this impl is that it adds a way of working // with Value that is not well served by the existing approaches: concise and // careless and sometimes that is exactly what you want. impl<I> ops::Index<I> for Value where I: Index, { type Output = Value; /// Index into a `serde_json::Value` using the syntax `value[0]` or /// `value["k"]`. /// /// Returns `Value::Null` if the type of `self` does not match the type of /// the index, for example if the index is a string and `self` is an array /// or a number. Also returns `Value::Null` if the given key does not exist /// in the map or the given index is not within the bounds of the array. /// /// For retrieving deeply nested values, you should have a look at the /// `Value::pointer` method. /// /// # Examples /// /// ```rust /// # #[macro_use] /// # extern crate serde_json; /// # /// # fn main() { /// let data = json!({ /// "x": { /// "y": ["z", "zz"] /// } /// }); /// /// assert_eq!(data["x"]["y"], json!(["z", "zz"])); /// assert_eq!(data["x"]["y"][0], json!("z")); /// /// assert_eq!(data["a"], json!(null)); // returns null for undefined values /// assert_eq!(data["a"]["b"], json!(null)); // does not panic /// # } /// ``` fn index(&self, index: I) -> &Value { static NULL: Value = Value::Null; index.index_into(self).unwrap_or(&NULL) } } impl<I> ops::IndexMut<I> for Value where I: Index, { /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or /// `value["k"] = ...`. /// /// If the index is a number, the value must be an array of length bigger /// than the index. Indexing into a value that is not an array or an array /// that is too small will panic. /// /// If the index is a string, the value must be an object or null which is /// treated like an empty object. If the key is not already present in the /// object, it will be inserted with a value of null. Indexing into a value /// that is neither an object nor null will panic. /// /// # Examples /// /// ```rust /// # #[macro_use] /// # extern crate serde_json; /// # /// # fn main() { /// let mut data = json!({ "x": 0 }); /// /// // replace an existing key /// data["x"] = json!(1); /// /// // insert a new key /// data["y"] = json!([false, false, false]); /// /// // replace an array value /// data["y"][0] = json!(true); /// /// // inserted a deeply nested key /// data["a"]["b"]["c"]["d"] = json!(true); /// /// println!("{}", data); /// # } /// ``` fn index_mut(&mut self, index: I) -> &mut Value { index.index_or_insert(self) } }
33.538462
84
0.55172
ef1877cdd83b7bbe84ab389de54bafb92a4600b5
301
#[macro_export] macro_rules! bail { ($err:expr $(,)?) => { return std::result::Result::Err($err.into()); }; } #[macro_export] macro_rules! ensure { ($cond:expr, $err:expr $(,)?) => { if !$cond { return std::result::Result::Err($err.into()); } }; }
18.8125
57
0.48505
90d6707f766bc7afb86fb5c7440fd01415302212
152,025
use num_traits::One; use casper_engine_test_support::{ internal::{ ExecuteRequestBuilder, InMemoryWasmTestBuilder, WasmTestBuilder, DEFAULT_RUN_GENESIS_REQUEST, }, DEFAULT_ACCOUNT_ADDR, }; use casper_execution_engine::{ shared::{account::Account, stored_value::StoredValue}, storage::global_state::in_memory::InMemoryGlobalState, }; use casper_types::{ runtime_args, system::CallStackElement, CLValue, ContractHash, ContractPackageHash, EntryPointType, HashAddr, Key, RuntimeArgs, }; use get_call_stack_recursive_subcall::{ Call, ContractAddress, ARG_CALLS, ARG_CURRENT_DEPTH, METHOD_FORWARDER_CONTRACT_NAME, METHOD_FORWARDER_SESSION_NAME, }; const CONTRACT_RECURSIVE_SUBCALL: &str = "get_call_stack_recursive_subcall.wasm"; const CONTRACT_CALL_RECURSIVE_SUBCALL: &str = "get_call_stack_call_recursive_subcall.wasm"; const CONTRACT_PACKAGE_NAME: &str = "forwarder"; const CONTRACT_NAME: &str = "our_contract_name"; const CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT: &str = METHOD_FORWARDER_CONTRACT_NAME; const CONTRACT_FORWARDER_ENTRYPOINT_SESSION: &str = METHOD_FORWARDER_SESSION_NAME; fn stored_session(contract_hash: ContractHash) -> Call { Call { contract_address: ContractAddress::ContractHash(contract_hash), target_method: CONTRACT_FORWARDER_ENTRYPOINT_SESSION.to_string(), entry_point_type: EntryPointType::Session, } } fn stored_versioned_session(contract_package_hash: ContractPackageHash) -> Call { Call { contract_address: ContractAddress::ContractPackageHash(contract_package_hash), target_method: CONTRACT_FORWARDER_ENTRYPOINT_SESSION.to_string(), entry_point_type: EntryPointType::Session, } } fn stored_contract(contract_hash: ContractHash) -> Call { Call { contract_address: ContractAddress::ContractHash(contract_hash), target_method: CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT.to_string(), entry_point_type: EntryPointType::Contract, } } fn stored_versioned_contract(contract_package_hash: ContractPackageHash) -> Call { Call { contract_address: ContractAddress::ContractPackageHash(contract_package_hash), target_method: CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT.to_string(), entry_point_type: EntryPointType::Contract, } } fn store_contract(builder: &mut WasmTestBuilder<InMemoryGlobalState>, session_filename: &str) { let store_contract_request = ExecuteRequestBuilder::standard(*DEFAULT_ACCOUNT_ADDR, session_filename, runtime_args! {}) .build(); builder .exec(store_contract_request) .commit() .expect_success(); } trait AccountExt { fn get_hash(&self, key: &str) -> HashAddr; } impl AccountExt for Account { fn get_hash(&self, key: &str) -> HashAddr { self.named_keys() .get(key) .cloned() .and_then(Key::into_hash) .unwrap() } } trait BuilderExt { fn get_call_stack_from_session_context( &mut self, stored_call_stack_key: &str, ) -> Vec<CallStackElement>; fn get_call_stack_from_contract_context( &mut self, stored_call_stack_key: &str, contract_package_hash: HashAddr, ) -> Vec<CallStackElement>; } impl BuilderExt for WasmTestBuilder<InMemoryGlobalState> { fn get_call_stack_from_session_context( &mut self, stored_call_stack_key: &str, ) -> Vec<CallStackElement> { let cl_value = self .query( None, (*DEFAULT_ACCOUNT_ADDR).into(), &[stored_call_stack_key.to_string()], ) .unwrap(); cl_value .as_cl_value() .cloned() .map(CLValue::into_t::<Vec<CallStackElement>>) .unwrap() .unwrap() } fn get_call_stack_from_contract_context( &mut self, stored_call_stack_key: &str, contract_package_hash: HashAddr, ) -> Vec<CallStackElement> { let value = self .query(None, Key::Hash(contract_package_hash), &[]) .unwrap(); let contract_package = match value { StoredValue::ContractPackage(package) => package, _ => panic!("unreachable"), }; let current_contract_hash = contract_package.current_contract_hash().unwrap(); let cl_value = self .query( None, current_contract_hash.into(), &[stored_call_stack_key.to_string()], ) .unwrap(); cl_value .as_cl_value() .cloned() .map(CLValue::into_t::<Vec<CallStackElement>>) .unwrap() .unwrap() } } fn setup() -> WasmTestBuilder<InMemoryGlobalState> { let mut builder = InMemoryWasmTestBuilder::default(); builder.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST); store_contract(&mut builder, CONTRACT_RECURSIVE_SUBCALL); builder } fn assert_each_context_has_correct_call_stack_info( builder: &mut InMemoryWasmTestBuilder, top_level_call: Call, mut subcalls: Vec<Call>, current_contract_package_hash: HashAddr, ) { let mut calls = vec![top_level_call]; calls.append(&mut subcalls); // query for and verify that all the elements in the call stack match their // pre-defined Call element for (i, call) in calls.iter().enumerate() { let stored_call_stack_key = format!("call_stack-{}", i); // we need to know where to look for the call stack information let call_stack = match call.entry_point_type { EntryPointType::Contract => builder.get_call_stack_from_contract_context( &stored_call_stack_key, current_contract_package_hash, ), EntryPointType::Session => { builder.get_call_stack_from_session_context(&stored_call_stack_key) } }; assert_eq!( call_stack.len(), i + 2, "call stack len was an unexpected size {}, should be {} {:#?}", call_stack.len(), i + 2, call_stack, ); let (head, rest) = call_stack.split_at(usize::one()); assert_eq!( head, [CallStackElement::Session { account_hash: *DEFAULT_ACCOUNT_ADDR, }], ); assert_call_stack_matches_calls(rest.to_vec(), &calls); } } fn assert_invalid_context(builder: &mut InMemoryWasmTestBuilder, depth: usize) { if depth == 0 { builder.expect_success(); } else { let error = builder.get_error().unwrap(); assert!(matches!( error, casper_execution_engine::core::engine_state::Error::Exec( casper_execution_engine::core::execution::Error::InvalidContext ) )); } } fn assert_each_context_has_correct_call_stack_info_module_bytes( builder: &mut InMemoryWasmTestBuilder, subcalls: Vec<Call>, current_contract_package_hash: HashAddr, ) { let stored_call_stack_key = format!("call_stack-{}", 0); let call_stack = builder.get_call_stack_from_session_context(&stored_call_stack_key); let (head, _) = call_stack.split_at(usize::one()); assert_eq!( head, [CallStackElement::Session { account_hash: *DEFAULT_ACCOUNT_ADDR, }], ); for (i, call) in (1..=subcalls.len()).zip(subcalls.iter()) { let stored_call_stack_key = format!("call_stack-{}", i); // we need to know where to look for the call stack information let call_stack = match call.entry_point_type { EntryPointType::Contract => builder.get_call_stack_from_contract_context( &stored_call_stack_key, current_contract_package_hash, ), EntryPointType::Session => { builder.get_call_stack_from_session_context(&stored_call_stack_key) } }; let (head, rest) = call_stack.split_at(usize::one()); assert_eq!( head, [CallStackElement::Session { account_hash: *DEFAULT_ACCOUNT_ADDR, }], ); assert_call_stack_matches_calls(rest.to_vec(), &subcalls); } } fn assert_call_stack_matches_calls(call_stack: Vec<CallStackElement>, calls: &[Call]) { for (index, expected_call_stack_element) in call_stack.iter().enumerate() { let maybe_call = calls.get(index); match (maybe_call, expected_call_stack_element) { // Versioned Call with EntryPointType::Contract ( Some(Call { entry_point_type, contract_address: ContractAddress::ContractPackageHash(current_contract_package_hash), .. }), CallStackElement::StoredContract { contract_package_hash, .. }, ) if *entry_point_type == EntryPointType::Contract && *contract_package_hash == *current_contract_package_hash => {} // Unversioned Call with EntryPointType::Contract ( Some(Call { entry_point_type, contract_address: ContractAddress::ContractHash(current_contract_hash), .. }), CallStackElement::StoredContract { contract_hash, .. }, ) if *entry_point_type == EntryPointType::Contract && *contract_hash == *current_contract_hash => {} // Versioned Call with EntryPointType::Session ( Some(Call { entry_point_type, contract_address: ContractAddress::ContractPackageHash(current_contract_package_hash), .. }), CallStackElement::StoredSession { account_hash, contract_package_hash, .. }, ) if *entry_point_type == EntryPointType::Session && *account_hash == *DEFAULT_ACCOUNT_ADDR && *contract_package_hash == *current_contract_package_hash => {} // Unversioned Call with EntryPointType::Session ( Some(Call { entry_point_type, contract_address: ContractAddress::ContractHash(current_contract_hash), .. }), CallStackElement::StoredSession { account_hash, contract_hash, .. }, ) if *entry_point_type == EntryPointType::Session && *account_hash == *DEFAULT_ACCOUNT_ADDR && *contract_hash == *current_contract_hash => {} _ => panic!( "call stack element {:#?} didn't match expected call {:#?} at index {}, {:#?}", expected_call_stack_element, maybe_call, index, call_stack, ), } } } mod session { use casper_engine_test_support::{internal::ExecuteRequestBuilder, DEFAULT_ACCOUNT_ADDR}; use casper_types::{runtime_args, RuntimeArgs}; use super::{ AccountExt, ARG_CALLS, ARG_CURRENT_DEPTH, CONTRACT_CALL_RECURSIVE_SUBCALL, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, CONTRACT_NAME, CONTRACT_PACKAGE_NAME, }; // DEPTHS should not contain 1, as it will eliminate the initial element from the subcalls // vector const DEPTHS: &[usize] = &[0, 2, 5, 10]; // Session + recursive subcall #[ignore] #[test] fn session_bytes_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_contract_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_contract(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_contract( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_session_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_session(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_contract( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_session_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_session(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_contract(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_session_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_session(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_contract( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_session_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_session(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_contract(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_session_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_session(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_session_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_session(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } // Session + recursive subcall failure cases #[ignore] #[test] fn session_bytes_to_stored_versioned_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())); } let execute_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_CALL_RECURSIVE_SUBCALL, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } // Stored contract + recursive subcall #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_contract(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_contract(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_contract(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_contract(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_contract(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_contract(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_contract(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_contract(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } // Stored contract + recursive subcall failure cases #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_versioned_contract_to_stored_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_name_to_stored_contract_to_stored_versioned_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_contract_by_hash_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_name_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_contract_by_hash_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_CONTRACT, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } // Stored session + recursive subcall #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } // Stored session + recursive subcall failure cases #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::versioned_contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_package_hash.into(), None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_name_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = ExecuteRequestBuilder::contract_call_by_name( *DEFAULT_ACCOUNT_ADDR, CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = ExecuteRequestBuilder::contract_call_by_hash( *DEFAULT_ACCOUNT_ADDR, current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }, ) .build(); builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } } mod payment { use rand::Rng; use casper_engine_test_support::{ internal::{DeployItemBuilder, ExecuteRequestBuilder}, DEFAULT_ACCOUNT_ADDR, }; use casper_execution_engine::shared::wasm; use casper_types::{runtime_args, RuntimeArgs}; use super::{ AccountExt, ARG_CALLS, ARG_CURRENT_DEPTH, CONTRACT_CALL_RECURSIVE_SUBCALL, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, CONTRACT_NAME, CONTRACT_PACKAGE_NAME, }; // DEPTHS should not contain 1, as it will eliminate the initial element from the subcalls // vector. Going further than 5 will git the gas limit. const DEPTHS: &[usize] = &[0, 2, 5]; // Session + recursive subcall #[ignore] #[test] fn session_bytes_to_stored_versioned_session_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_session(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_contract( current_contract_package_hash.into(), )); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_session_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_session(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_contract(current_contract_hash.into())); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_session_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_session(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_contract( current_contract_package_hash.into(), )); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_session(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_contract(current_contract_hash.into())); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info_module_bytes( &mut builder, subcalls, current_contract_package_hash, ); } } // Session + recursive subcall failure cases #[ignore] #[test] fn session_bytes_to_stored_versioned_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn session_bytes_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())); } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_payment_code(CONTRACT_CALL_RECURSIVE_SUBCALL, args) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } // Stored session + recursive subcall #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_contract_by_name( CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_contract_by_hash( current_contract_package_hash, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_contract_by_name( CONTRACT_PACKAGE_NAME, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_contract_by_hash( current_contract_package_hash, None, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_session(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_hash( current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_session() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_session(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_hash( current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_named_key( CONTRACT_PACKAGE_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_hash( current_contract_package_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_named_key( CONTRACT_PACKAGE_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_hash( current_contract_package_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_versioned_session(current_contract_package_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_versioned_contract(current_contract_package_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_hash( current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_name_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_contract() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let subcalls = vec![super::stored_contract(current_contract_hash.into()); *len]; let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_hash( current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit().expect_success(); super::assert_each_context_has_correct_call_stack_info( &mut builder, super::stored_session(current_contract_hash.into()), subcalls, current_contract_package_hash, ); } } // Stored session + recursive subcall failure cases #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail( ) { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_named_key( CONTRACT_PACKAGE_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_hash( current_contract_package_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_name_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_named_key( CONTRACT_PACKAGE_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_versioned_session_by_hash_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_versioned_payment_hash( current_contract_package_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_name_to_stored_versioned_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_hash_to_stored_versioned_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![ super::stored_versioned_contract(current_contract_package_hash.into()); len.saturating_sub(1) ]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_hash( current_contract_hash.into(), CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_name_to_stored_contract_to_stored_versioned_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_package_hash = default_account.get_hash(CONTRACT_PACKAGE_NAME); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_versioned_session( current_contract_package_hash.into(), )) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } #[ignore] #[test] fn stored_session_by_name_to_stored_contract_to_stored_session_should_fail() { for len in DEPTHS { let mut builder = super::setup(); let default_account = builder.get_account(*DEFAULT_ACCOUNT_ADDR).unwrap(); let current_contract_hash = default_account.get_hash(CONTRACT_NAME); let mut subcalls = vec![super::stored_contract(current_contract_hash.into()); len.saturating_sub(1)]; if *len > 0 { subcalls.push(super::stored_session(current_contract_hash.into())) } let execute_request = { let mut rng = rand::thread_rng(); let deploy_hash = rng.gen(); let sender = *DEFAULT_ACCOUNT_ADDR; let args = runtime_args! { ARG_CALLS => subcalls.clone(), ARG_CURRENT_DEPTH => 0u8, }; let deploy = DeployItemBuilder::new() .with_address(sender) .with_stored_payment_named_key( CONTRACT_NAME, CONTRACT_FORWARDER_ENTRYPOINT_SESSION, args, ) .with_session_bytes(wasm::do_nothing_bytes(), RuntimeArgs::default()) .with_authorization_keys(&[sender]) .with_deploy_hash(deploy_hash) .build(); ExecuteRequestBuilder::new().push_deploy(deploy).build() }; builder.exec(execute_request).commit(); super::assert_invalid_context(&mut builder, *len); } } }
38.448407
110
0.568768
7a461397210b8f4d6f6c493f5f23bed2df4b07d0
19,991
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ block_storage::BlockStore, counters, event_processor::{EventProcessor, SyncProcessor, UnverifiedEvent, VerifiedEvent}, liveness::{ leader_reputation::{ActiveInactiveHeuristic, LeaderReputation, LibraDBBackend}, multi_proposer_election::MultiProposer, pacemaker::{ExponentialTimeInterval, Pacemaker}, proposal_generator::ProposalGenerator, proposer_election::ProposerElection, rotating_proposer_election::{choose_leader, RotatingProposer}, }, network::{IncomingBlockRetrievalRequest, NetworkReceivers, NetworkSender}, network_interface::{ConsensusMsg, ConsensusNetworkSender}, persistent_liveness_storage::{LedgerRecoveryData, PersistentLivenessStorage, RecoveryData}, state_replication::{StateComputer, TxnManager}, util::time_service::TimeService, }; use anyhow::anyhow; use channel::libra_channel; use consensus_types::{ common::{Author, Payload, Round}, epoch_retrieval::EpochRetrievalRequest, }; use futures::{select, StreamExt}; use libra_config::config::{ConsensusConfig, ConsensusProposerType, NodeConfig}; use libra_logger::prelude::*; use libra_types::{ account_address::AccountAddress, epoch_change::EpochChangeProof, epoch_info::EpochInfo, on_chain_config::{OnChainConfigPayload, ValidatorSet}, }; use network::protocols::network::Event; use safety_rules::SafetyRulesManager; use std::{ cmp::Ordering, sync::Arc, time::{Duration, Instant}, }; /// The enum contains two processor /// SyncProcessor is used to process events in order to sync up with peer if we can't recover from local consensusdb /// EventProcessor is used for normal event handling. /// We suppress clippy warning here because we expect most of the time we will have EventProcessor #[allow(clippy::large_enum_variant)] pub enum Processor<T> { SyncProcessor(SyncProcessor<T>), EventProcessor(EventProcessor<T>), } #[allow(clippy::large_enum_variant)] pub enum LivenessStorageData<T> { RecoveryData(RecoveryData<T>), LedgerRecoveryData(LedgerRecoveryData), } impl<T: Payload> LivenessStorageData<T> { pub fn expect_recovery_data(self, msg: &str) -> RecoveryData<T> { match self { LivenessStorageData::RecoveryData(data) => data, LivenessStorageData::LedgerRecoveryData(_) => panic!("{}", msg), } } } // Manager the components that shared across epoch and spawn per-epoch EventProcessor with // epoch-specific input. pub struct EpochManager<T> { author: Author, config: ConsensusConfig, time_service: Arc<dyn TimeService>, self_sender: channel::Sender<anyhow::Result<Event<ConsensusMsg<T>>>>, network_sender: ConsensusNetworkSender<T>, timeout_sender: channel::Sender<Round>, txn_manager: Box<dyn TxnManager<Payload = T>>, state_computer: Arc<dyn StateComputer<Payload = T>>, storage: Arc<dyn PersistentLivenessStorage<T>>, safety_rules_manager: SafetyRulesManager<T>, processor: Option<Processor<T>>, } impl<T: Payload> EpochManager<T> { pub fn new( node_config: &mut NodeConfig, time_service: Arc<dyn TimeService>, self_sender: channel::Sender<anyhow::Result<Event<ConsensusMsg<T>>>>, network_sender: ConsensusNetworkSender<T>, timeout_sender: channel::Sender<Round>, txn_manager: Box<dyn TxnManager<Payload = T>>, state_computer: Arc<dyn StateComputer<Payload = T>>, storage: Arc<dyn PersistentLivenessStorage<T>>, ) -> Self { let author = node_config.validator_network.as_ref().unwrap().peer_id; let config = node_config.consensus.clone(); let safety_rules_manager = SafetyRulesManager::new(node_config); Self { author, config, time_service, self_sender, network_sender, timeout_sender, txn_manager, state_computer, storage, safety_rules_manager, processor: None, } } fn epoch_info(&self) -> &EpochInfo { match self .processor .as_ref() .expect("EpochManager not started yet") { Processor::EventProcessor(p) => p.epoch_info(), Processor::SyncProcessor(p) => p.epoch_info(), } } fn epoch(&self) -> u64 { self.epoch_info().epoch } fn create_pacemaker( &self, time_service: Arc<dyn TimeService>, timeout_sender: channel::Sender<Round>, ) -> Pacemaker { // 1.5^6 ~= 11 // Timeout goes from initial_timeout to initial_timeout*11 in 6 steps let time_interval = Box::new(ExponentialTimeInterval::new( Duration::from_millis(self.config.pacemaker_initial_timeout_ms), 1.5, 6, )); Pacemaker::new(time_interval, time_service, timeout_sender) } /// Create a proposer election handler based on proposers fn create_proposer_election( &self, epoch_info: &EpochInfo, ) -> Box<dyn ProposerElection<T> + Send + Sync> { let proposers = epoch_info .verifier .get_ordered_account_addresses_iter() .collect::<Vec<_>>(); match self.config.proposer_type { ConsensusProposerType::MultipleOrderedProposers => { Box::new(MultiProposer::new(epoch_info.epoch, proposers, 2)) } ConsensusProposerType::RotatingProposer => Box::new(RotatingProposer::new( proposers, self.config.contiguous_rounds, )), // We don't really have a fixed proposer! ConsensusProposerType::FixedProposer => { let proposer = choose_leader(proposers); Box::new(RotatingProposer::new( vec![proposer], self.config.contiguous_rounds, )) } ConsensusProposerType::LeaderReputation(heuristic_config) => { let backend = Box::new(LibraDBBackend::new( proposers.len(), self.storage.libra_db(), )); let heuristic = Box::new(ActiveInactiveHeuristic::new( heuristic_config.active_weights, heuristic_config.inactive_weights, )); Box::new(LeaderReputation::new(proposers, backend, heuristic)) } } } async fn process_epoch_retrieval( &mut self, request: EpochRetrievalRequest, peer_id: AccountAddress, ) { let proof = match self .storage .libra_db() .get_epoch_change_ledger_infos(request.start_epoch, request.end_epoch) { Ok(proof) => proof, Err(e) => { warn!("Failed to get epoch proof from storage: {:?}", e); return; } }; let msg = ConsensusMsg::EpochChangeProof::<T>(Box::new(proof)); if let Err(e) = self.network_sender.send_to(peer_id, msg) { warn!( "Failed to send a epoch retrieval to peer {}: {:?}", peer_id, e ); }; } async fn process_different_epoch(&mut self, different_epoch: u64, peer_id: AccountAddress) { match different_epoch.cmp(&self.epoch()) { // We try to help nodes that have lower epoch than us Ordering::Less => { self.process_epoch_retrieval( EpochRetrievalRequest { start_epoch: different_epoch, end_epoch: self.epoch(), }, peer_id, ) .await } // We request proof to join higher epoch Ordering::Greater => { let request = EpochRetrievalRequest { start_epoch: self.epoch(), end_epoch: different_epoch, }; let msg = ConsensusMsg::EpochRetrievalRequest::<T>(Box::new(request)); if let Err(e) = self.network_sender.send_to(peer_id, msg) { warn!( "Failed to send a epoch retrieval to peer {}: {:?}", peer_id, e ); } } Ordering::Equal => { warn!("Same epoch should not come to process_different_epoch"); } } } async fn start_new_epoch(&mut self, proof: EpochChangeProof) { let ledger_info = match proof.verify(self.epoch_info()) { Ok(ledger_info) => ledger_info, Err(e) => { error!("Invalid EpochChangeProof: {:?}", e); return; } }; debug!( "Received epoch change to {}", ledger_info.ledger_info().epoch() + 1 ); // make sure storage is on this ledger_info too, it should be no-op if it's already committed if let Err(e) = self.state_computer.sync_to(ledger_info.clone()).await { error!("State sync to new epoch {} failed with {:?}, we'll try to start from current libradb", ledger_info, e); } // state_computer notifies reconfiguration in another channel } async fn start_event_processor( &mut self, recovery_data: RecoveryData<T>, epoch_info: EpochInfo, ) { // Release the previous EventProcessor, especially the SafetyRule client self.processor = None; counters::EPOCH.set(epoch_info.epoch as i64); counters::CURRENT_EPOCH_VALIDATORS.set(epoch_info.verifier.len() as i64); counters::CURRENT_EPOCH_QUORUM_SIZE.set(epoch_info.verifier.quorum_voting_power() as i64); info!( "Starting {} with genesis {}", epoch_info, recovery_data.root_block(), ); let last_vote = recovery_data.last_vote(); info!("Create BlockStore"); let block_store = Arc::new(BlockStore::new( Arc::clone(&self.storage), recovery_data, Arc::clone(&self.state_computer), self.config.max_pruned_blocks_in_mem, )); info!("Update SafetyRules"); let mut safety_rules = self.safety_rules_manager.client(); let consensus_state = safety_rules .consensus_state() .expect("Unable to retrieve ConsensusState from SafetyRules"); let sr_waypoint = consensus_state.waypoint(); let proofs = self .storage .retrieve_epoch_change_proof(sr_waypoint.version()) .expect("Unable to retrieve Waypoint state from Storage"); safety_rules .initialize(&proofs) .expect("Unable to initialize SafetyRules"); info!("Create ProposalGenerator"); // txn manager is required both by proposal generator (to pull the proposers) // and by event processor (to update their status). let proposal_generator = ProposalGenerator::new( self.author, block_store.clone(), self.txn_manager.clone(), self.time_service.clone(), self.config.max_block_size, ); info!("Create Pacemaker"); let pacemaker = self.create_pacemaker(self.time_service.clone(), self.timeout_sender.clone()); info!("Create ProposerElection"); let proposer_election = self.create_proposer_election(&epoch_info); let network_sender = NetworkSender::new( self.author, self.network_sender.clone(), self.self_sender.clone(), epoch_info.verifier.clone(), ); let mut processor = EventProcessor::new( epoch_info, block_store, last_vote, pacemaker, proposer_election, proposal_generator, safety_rules, network_sender, self.txn_manager.clone(), self.storage.clone(), self.time_service.clone(), ); processor.start().await; self.processor = Some(Processor::EventProcessor(processor)); info!("EventProcessor started"); } // Depending on what data we can extract from consensusdb, we may or may not have an // event processor at startup. If we need to sync up with peers for blocks to construct // a valid block store, which is required to construct an event processor, we will take // care of the sync up here. async fn start_sync_processor( &mut self, ledger_recovery_data: LedgerRecoveryData, epoch_info: EpochInfo, ) { let network_sender = NetworkSender::new( self.author, self.network_sender.clone(), self.self_sender.clone(), epoch_info.verifier.clone(), ); self.processor = Some(Processor::SyncProcessor(SyncProcessor::new( epoch_info, network_sender, self.storage.clone(), self.state_computer.clone(), ledger_recovery_data, ))); info!("SyncProcessor started"); } pub async fn start_processor(&mut self, payload: OnChainConfigPayload) { let validator_set: ValidatorSet = payload .get() .expect("failed to get ValidatorSet from payload"); let epoch_info = EpochInfo { epoch: payload.epoch(), verifier: (&validator_set).into(), }; let validator_keys = validator_set.payload().to_vec(); info!("Update Network about new validators"); self.network_sender .update_eligible_nodes(validator_keys) .await .expect("Unable to update network's eligible peers"); match self.storage.start() { LivenessStorageData::RecoveryData(initial_data) => { self.start_event_processor(initial_data, epoch_info).await } LivenessStorageData::LedgerRecoveryData(ledger_recovery_data) => { self.start_sync_processor(ledger_recovery_data, epoch_info) .await } } } pub async fn process_message( &mut self, peer_id: AccountAddress, consensus_msg: ConsensusMsg<T>, ) { if let Some(event) = self.process_epoch(peer_id, consensus_msg).await { match event.verify(&self.epoch_info().verifier) { Ok(event) => self.process_event(peer_id, event).await, Err(err) => warn!("Message failed verification: {:?}", err), } } } async fn process_epoch( &mut self, peer_id: AccountAddress, msg: ConsensusMsg<T>, ) -> Option<UnverifiedEvent<T>> { match msg { ConsensusMsg::ProposalMsg(_) | ConsensusMsg::SyncInfo(_) | ConsensusMsg::VoteMsg(_) => { let event: UnverifiedEvent<T> = msg.into(); if event.epoch() == self.epoch() { return Some(event); } else { self.process_different_epoch(event.epoch(), peer_id).await; } } ConsensusMsg::EpochChangeProof(proof) => { let msg_epoch = proof.epoch().map_err(|e| warn!("{:?}", e)).ok()?; if msg_epoch == self.epoch() { self.start_new_epoch(*proof).await } else { self.process_different_epoch(msg_epoch, peer_id).await } } ConsensusMsg::EpochRetrievalRequest(request) => { if request.end_epoch <= self.epoch() { self.process_epoch_retrieval(*request, peer_id).await } else { warn!("Received EpochRetrievalRequest beyond what we have locally"); } } _ => { warn!("Unexpected messages: {:?}", msg); } } None } async fn process_event(&mut self, peer_id: AccountAddress, event: VerifiedEvent<T>) { match self.processor_mut() { Processor::SyncProcessor(p) => { let result = match event { VerifiedEvent::ProposalMsg(proposal) => p.process_proposal_msg(*proposal).await, VerifiedEvent::VoteMsg(vote) => p.process_vote(*vote).await, _ => Err(anyhow!("Unexpected VerifiedEvent during startup")), }; let epoch_info = p.epoch_info().clone(); match result { Ok(data) => { info!("Recovered from SyncProcessor"); self.start_event_processor(data, epoch_info).await } Err(e) => error!("{:?}", e), } } Processor::EventProcessor(p) => match event { VerifiedEvent::ProposalMsg(proposal) => p.process_proposal_msg(*proposal).await, VerifiedEvent::VoteMsg(vote) => p.process_vote(*vote).await, VerifiedEvent::SyncInfo(sync_info) => { p.process_sync_info_msg(*sync_info, peer_id).await } }, } } fn processor_mut(&mut self) -> &mut Processor<T> { self.processor .as_mut() .expect("EpochManager not started yet") } pub async fn process_block_retrieval(&mut self, request: IncomingBlockRetrievalRequest) { match self.processor_mut() { Processor::EventProcessor(p) => p.process_block_retrieval(request).await, _ => warn!("EventProcessor not started yet"), } } pub async fn process_local_timeout(&mut self, round: u64) { match self.processor_mut() { Processor::EventProcessor(p) => p.process_local_timeout(round).await, _ => unreachable!("EventProcessor not started yet"), } } pub async fn start( mut self, mut pacemaker_timeout_sender_rx: channel::Receiver<Round>, mut network_receivers: NetworkReceivers<T>, mut reconfig_events: libra_channel::Receiver<(), OnChainConfigPayload>, ) { // initial start of the processor if let Some(payload) = reconfig_events.next().await { self.start_processor(payload).await; } loop { let pre_select_instant = Instant::now(); let idle_duration; select! { payload = reconfig_events.select_next_some() => { idle_duration = pre_select_instant.elapsed(); self.start_processor(payload).await } msg = network_receivers.consensus_messages.select_next_some() => { idle_duration = pre_select_instant.elapsed(); self.process_message(msg.0, msg.1).await } block_retrieval = network_receivers.block_retrieval.select_next_some() => { idle_duration = pre_select_instant.elapsed(); self.process_block_retrieval(block_retrieval).await } round = pacemaker_timeout_sender_rx.select_next_some() => { idle_duration = pre_select_instant.elapsed(); self.process_local_timeout(round).await } } counters::EVENT_PROCESSING_LOOP_BUSY_DURATION_S .observe_duration(pre_select_instant.elapsed() - idle_duration); counters::EVENT_PROCESSING_LOOP_IDLE_DURATION_S.observe_duration(idle_duration); } } }
37.79017
123
0.581662
d64522a22ee6ae8c8425e7460b30b069bf7e0d9f
2,279
use super::element::*; use super::path_element::*; use super::brush_element::*; use super::group_element::*; use super::motion_element::*; use super::transformed_vector::*; use super::brush_properties_element::*; use super::brush_definition_element::*; use super::super::edit::ElementId; use std::ops::Deref; /// /// Possible types of vector element /// #[derive(Clone, Debug)] pub enum Vector { /// Vector that has been transformed from a source vector (eg, by applying a motion) Transformed(TransformedVector), /// Sets the brush to use for future brush strokes BrushDefinition(BrushDefinitionElement), /// Brush properties for future brush strokes BrushProperties(BrushPropertiesElement), /// Brush stroke vector BrushStroke(BrushElement), /// Path vector Path(PathElement), /// Element describing a motion Motion(MotionElement), /// Element describing a group (with optional cache and path combining operation) Group(GroupElement) } impl Vector { /// /// Creates a new vector from an element /// #[inline] pub fn new<IntoVec: Into<Vector>>(from: IntoVec) -> Vector { from.into() } /// /// The ID for this vector /// #[inline] pub fn id(&self) -> ElementId { self.deref().id() } /// /// If this element was transformed from an original element, returns that original element /// pub fn original_without_transformations(&self) -> Vector { use self::Vector::*; match self { Transformed(transformed) => (*transformed.without_transformations()).clone(), not_transformed => not_transformed.clone() } } } impl Deref for Vector { type Target = dyn VectorElement; #[inline] fn deref(&self) -> &dyn VectorElement { use Vector::*; match self { Transformed(transform) => transform, BrushDefinition(defn) => defn, BrushProperties(props) => props, BrushStroke(elem) => elem, Path(elem) => elem, Motion(elem) => elem, Group(elem) => elem } } }
25.322222
95
0.586222
bf77f8ad970c59e0f26c855ef92e095453e1fce9
13,618
extern crate chrono; extern crate elf; extern crate tar; #[macro_use] extern crate structopt; use std::cmp; use std::fmt::Write as fmtwrite; use std::fs; use std::io; use std::io::{Seek, Write}; use std::mem; #[macro_use] mod util; mod cmdline; mod header; use structopt::StructOpt; fn main() { let opt = cmdline::Opt::from_args(); // Create the metadata.toml file needed for the TAB file. let mut metadata_toml = String::new(); write!( &mut metadata_toml, "tab-version = 1 name = \"{}\" only-for-boards = \"\" build-date = {}", opt.package_name.as_ref().map_or("", |package_name| package_name.as_str()), chrono::prelude::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) ).unwrap(); // Start creating a tar archive which will be the .tab file. let tab_name = fs::File::create(&opt.output).expect("Could not create the output file."); let mut tab = tar::Builder::new(tab_name); // Add the metadata file without creating a real file on the filesystem. let mut header = tar::Header::new_gnu(); header.set_size(metadata_toml.as_bytes().len() as u64); header.set_mode(0o644); header.set_cksum(); tab.append_data(&mut header, "metadata.toml", metadata_toml.as_bytes()) .unwrap(); // Iterate all input elfs. Convert them to Tock friendly binaries and then // add them to the TAB file. for elf_path in opt.input { let tbf_path = elf_path.with_extension("tbf"); let elffile = elf::File::open_path(&elf_path).expect("Could not open the .elf file."); if opt.output.clone() == tbf_path.clone() { panic!("tab file {} and output file {} cannot be the same file", opt.output.clone().to_str().unwrap(), tbf_path.clone().to_str().unwrap()); } // Get output file as both read/write for creating the binary and // adding it to the TAB tar file. let mut outfile: fs::File = fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(tbf_path.clone()) .unwrap(); // Do the conversion to a tock binary. elf_to_tbf( &elffile, &mut outfile, opt.package_name.clone(), opt.verbose, opt.stack_size, opt.app_heap_size, opt.kernel_heap_size, opt.protected_region_size, ).unwrap(); // Add the file to the TAB tar file. outfile.seek(io::SeekFrom::Start(0)).unwrap(); tab.append_file(tbf_path.file_name().unwrap(), &mut outfile) .unwrap(); outfile.seek(io::SeekFrom::Start(0)).unwrap(); tab.append_file( tbf_path.with_extension("bin").file_name().unwrap(), &mut outfile, ).unwrap(); } } /// Convert an ELF file to a TBF (Tock Binary Format) binary file. /// /// This will place all writeable and executable sections from the ELF file /// into a binary and prepend a TBF header to it. For all writeable sections, /// if there is a .rel.X section it will be included at the end with a 32 bit /// length parameter first. /// /// Assumptions: /// - Sections in a segment that is RW and set to be loaded will be in RAM and /// should count towards minimum required RAM. /// - Sections that are writeable flash regions include .wfr in their name. fn elf_to_tbf( input: &elf::File, output: &mut Write, package_name: Option<String>, verbose: bool, stack_len: u32, app_heap_len: u32, kernel_heap_len: u32, protected_region_size_arg: Option<u32>, ) -> io::Result<()> { let package_name = package_name.unwrap_or_default(); // Get an array of the sections sorted so we place them in the proper order // in the binary. let mut sections_sort: Vec<(usize, usize)> = Vec::new(); for (i, section) in input.sections.iter().enumerate() { sections_sort.push((i, section.shdr.offset as usize)); } sections_sort.sort_by_key(|s| s.1); // Keep track of how much RAM this app will need. let mut minimum_ram_size: u32 = 0; // Find the ELF segment for the RAM segment. That will tell us how much // RAM we need to reserve for when those are copied into memory. for segment in &input.phdrs { if segment.progtype == elf::types::PT_LOAD && segment.flags.0 == elf::types::PF_W.0 + elf::types::PF_R.0 { minimum_ram_size = segment.memsz as u32; break; } } if verbose { println!( "Min RAM size from sections in ELF: {} bytes", minimum_ram_size ); } // Add in room the app is asking us to reserve for the stack and heaps to // the minimum required RAM size. minimum_ram_size += align8!(stack_len) + align4!(app_heap_len) + align4!(kernel_heap_len); // Need an array of sections to look for relocation data to include. let mut rel_sections: Vec<String> = Vec::new(); // Iterate the sections in the ELF file to find properties of the app that // are required to go in the TBF header. let mut writeable_flash_regions_count = 0; for s in &sections_sort { let section = &input.sections[s.0]; // Count write only sections as writeable flash regions. if section.shdr.name.contains(".wfr") && section.shdr.size > 0 { writeable_flash_regions_count += 1; } // Check write+alloc sections for possible .rel.X sections. if section.shdr.flags.0 == elf::types::SHF_WRITE.0 + elf::types::SHF_ALLOC.0 { // This section is also one we might need to include relocation // data for. rel_sections.push(section.shdr.name.clone()); } } if verbose { println!( "Number of writeable flash regions: {}", writeable_flash_regions_count ); } // Keep track of an index of where we are in creating the app binary. let mut binary_index = 0; // Now we can create the first pass TBF header. This is mostly to get the // size of the header since we have to fill in some of the offsets later. let mut tbfheader = header::TbfHeader::new(); let header_length = tbfheader.create( minimum_ram_size, writeable_flash_regions_count, package_name, ); // If a protected region size was passed, confirm the header will fit. // Otherwise, use the header size as the protected region size. let protected_region_size = if let Some(fixed_protected_region_size) = protected_region_size_arg { if fixed_protected_region_size < header_length as u32 { // The header doesn't fit in the provided protected region size; // throw an error. return Err(io::Error::new( io::ErrorKind::InvalidInput, format!( "protected_region_size = {} is too small for the TBF headers. Header size: {}", fixed_protected_region_size, header_length), )); } // Update the header's protected size, as the protected region may // be larger than the header size. tbfheader.set_protected_size(fixed_protected_region_size - header_length as u32); fixed_protected_region_size } else { header_length as u32 }; binary_index += protected_region_size as usize; // The init function is where the app will start executing, defined as an // offset from the end of protected region at the beginning of the app in // flash. Typically the protected region only includes the TBF header. To // calculate the offset we need to find which section includes the entry // function and then determine its offset relative to the end of the // protected region. let mut init_fn_offset: u32 = 0; // Need a place to put the app sections before we know the true TBF header. let mut binary: Vec<u8> = vec![0; protected_region_size as usize - header_length]; let mut entry_point_found = false; // Iterate the sections in the ELF file and add them to the binary as needed for s in &sections_sort { let section = &input.sections[s.0]; // Determine if this is the section where the entry point is in. If it // is, then we need to calculate the correct init_fn_offset. if input.ehdr.entry >= section.shdr.addr && input.ehdr.entry < (section.shdr.addr + section.shdr.size) && (section.shdr.name.find("debug")).is_none() { // panic in case we detect entry point in multiple sections. if entry_point_found { panic!("Duplicate entry point in {} section", section.shdr.name); } entry_point_found = true; if verbose { println!("Entry point is in {} section", section.shdr.name); } // init_fn_offset is specified relative to the end of the TBF // header. init_fn_offset = (input.ehdr.entry - section.shdr.addr) as u32 + (binary_index - header_length) as u32 } // If this is writeable, executable, or allocated, is nonzero length, // and is type `PROGBITS` we want to add it to the binary. if (section.shdr.flags.0 & (elf::types::SHF_WRITE.0 + elf::types::SHF_EXECINSTR.0 + elf::types::SHF_ALLOC.0) != 0) && section.shdr.shtype == elf::types::SHT_PROGBITS && section.shdr.size > 0 { if verbose { println!( "Including the {} section at offset {} (0x{:x})", section.shdr.name, binary_index, binary_index ); } if align4needed!(binary_index) != 0 { println!( "Warning! Placing section {} at 0x{:x}, which is not 4-byte aligned.", section.shdr.name, binary_index ); } binary.extend(&section.data); // Check if this is a writeable flash region. If so, we need to // set the offset and size in the header. if section.shdr.name.contains(".wfr") && section.shdr.size > 0 { tbfheader.set_writeable_flash_region_values( binary_index as u32, section.shdr.size as u32, ); } // Now increment where we are in the binary. binary_index += section.shdr.size as usize; } } // Now that we have checked all of the sections, we can set the // init_fn_offset. tbfheader.set_init_fn_offset(init_fn_offset); // Next we have to add in any relocation data. let mut relocation_binary: Vec<u8> = Vec::new(); // For each section that might have relocation data, check if a .rel.X // section exists and if so include it. if verbose { println!("Searching for .rel.X sections to add."); } for relocation_section_name in &rel_sections { let mut name: String = ".rel".to_owned(); name.push_str(relocation_section_name); let rel_data = input .sections .iter() .find(|section| section.shdr.name == name) .map_or(&[] as &[u8], |section| section.data.as_ref()); relocation_binary.extend(rel_data); if verbose && !rel_data.is_empty() { println!( " Adding {} section. Length: {} bytes at {} (0x{:x})", name, rel_data.len(), binary_index + mem::size_of::<u32>() + rel_data.len(), binary_index + mem::size_of::<u32>() + rel_data.len() ); } if !rel_data.is_empty() && align4needed!(binary_index) != 0 { println!( "Warning! Placing section {} at 0x{:x}, which is not 4-byte aligned.", name, binary_index ); } } // Add the relocation data to our total length. Also include the 4 bytes for // the relocation data length. binary_index += relocation_binary.len() + mem::size_of::<u32>(); // That is everything that we are going to include in our app binary. Now // we need to pad the binary to a power of 2 in size, and make sure it is // at least 512 bytes in size. let post_content_pad = if binary_index.count_ones() > 1 { let power2len = cmp::max(1 << (32 - (binary_index as u32).leading_zeros()), 512); power2len - binary_index } else { 0 }; binary_index += post_content_pad; let total_size = binary_index; // Now set the total size of the app in the header. tbfheader.set_total_size(total_size as u32); if verbose { print!("{}", tbfheader); } // Write the header and actual app to a binary file. output.write_all(tbfheader.generate().unwrap().get_ref())?; output.write_all(binary.as_ref())?; let rel_data_len: [u8; 4] = [ (relocation_binary.len() & 0xff) as u8, (relocation_binary.len() >> 8 & 0xff) as u8, (relocation_binary.len() >> 16 & 0xff) as u8, (relocation_binary.len() >> 24 & 0xff) as u8, ]; output.write_all(&rel_data_len)?; output.write_all(relocation_binary.as_ref())?; // Pad to get a power of 2 sized flash app. util::do_pad(output, post_content_pad as usize)?; Ok(()) }
37.106267
99
0.600602
f8f00317395fa292141fce4a827005f58a54bd36
8,865
use super::parser::{Int, E}; const CHARS: &'static [(&'static str, &'static str)] = &[ ("galaxy", r#" ..###.. .....#. .###..# #.#.#.# #..###. .#..... ..###.. "#), /* ("equal", r#" ### #.. ### "#)*/ ]; type Bitmap2D = Vec<Vec<bool>>; #[derive(Debug, Clone)] pub enum RecognizedChar { Num(Int), Char(String), } impl RecognizedChar { pub fn starts_with(&self, prefix: &str) -> bool { match self { RecognizedChar::Num(n) => false, // TODO やる RecognizedChar::Char(name) => name.starts_with(prefix), } } } impl std::fmt::Display for RecognizedChar { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { RecognizedChar::Num(n) => write!(f, "{}", n), RecognizedChar::Char(name) => write!(f, "{}", name), } } } //////////////////////////////////////////////////////////////////////////////////////////////////// pub struct Recognizer { char_templates: Vec<(&'static str, Bitmap2D)>, } pub fn prepare_char_templates() -> Vec<(&'static str, Bitmap2D)> { let mut v = vec![]; for (name, template) in CHARS.iter() { let template: Vec<Vec<_>> = template.lines().filter(|line| !line.is_empty()).map(|line| line.chars().map(|c| c == '#').collect()).collect(); // 横幅が統一されてることチェック let w = template[0].len(); assert!(template.iter().all(|t| t.len() == w)); v.push((*name, template)); } v } impl Recognizer { pub fn new() -> Self { Self { char_templates: prepare_char_templates() } } // [((channel, x, y), result), ...] pub fn recognize(&self, e: &E) -> RecognitionResult { let list_of_list_of_coords = super::visualize::collect_list_of_list_of_coords(e); let mut results = vec![]; for (channel, list_of_coords) in list_of_list_of_coords.iter().enumerate() { let (bmp, (min_x, min_y)) = super::visualize::create_bitmap_with_offset(list_of_coords); let match_results = self.match_all(&bmp); results.append(&mut match_results.into_iter().map(|((x, y), rr)| ((channel, min_x.clone() + x as Int, min_y.clone() + y as Int), rr)).collect()); } RecognitionResult { chars: results } } //////////////////////////////////////////////////////////////////////////////////////////////// fn does_match_char_at(&self, bmp: &Bitmap2D, template: &Bitmap2D, x: usize, y: usize) -> bool { // TODO: 周囲が空いていることをチェックする let tw = template[0].len(); let th = template.len(); if x + tw > bmp[0].len() { return false; } if y + th > bmp.len() { return false; } for dy in 0..th { for dx in 0..tw { if bmp[y + dy][x + dx] != template[dy][dx] { return false; } } } true } /// 空白であることをチェックする。OKならtrue。 /// /// xとyは左上なので、余白をチェックするのはそのさらに外だよ fn check_margin(&self, bmp: &Bitmap2D, x: usize, y: usize, w: usize, h: usize) -> bool { // クソだるいのでここだけsignedで処理するよー let x = x as i64; let y = y as i64; for dx in -1..=(w as i64) { for &dy in &[-1, h as i64] { let tx = x + dx; let ty = y + dy; if tx < 0 || tx >= (bmp[0].len() as i64) { continue; } if ty < 0 || ty >= (bmp.len() as i64) { continue; } if bmp[ty as usize][tx as usize] { return false } } } for dy in -1..=(h as i64) { for &dx in &[-1, w as i64] { let tx = x + dx; let ty = y + dy; if tx < 0 || tx >= (bmp[0].len() as i64) { continue; } if ty < 0 || ty >= (bmp.len() as i64) { continue; } if bmp[ty as usize][tx as usize] { return false } } } true } //////////////////////////////////////////////////////////////////////////////////////////////// // 注意:返してる座標は中央!(クリックしたいのでは的な気持ち) fn match_chars_at(&self, bmp: &Vec<Vec<bool>>, x: usize, y: usize) -> Option<((usize, usize), RecognizedChar)> { for (name, template) in self.char_templates.iter() { if self.does_match_char_at(bmp, template, x, y) { let center_x = x + template[0].len() / 2; let center_y = y + template[0].len() / 2; return Some(((center_x, center_y), RecognizedChar::Char(name.to_string()))); } } None } fn match_num_at(&self, bmp: &Vec<Vec<bool>>, x: usize, y: usize) -> Option<((usize, usize), RecognizedChar)> { let h = bmp.len(); let w = bmp[0].len(); if bmp[y][x] { return None; } let mut k = 1; loop { if y + k >= h || !bmp[y + k][x] { break; } if x + k >= w || !bmp[y][x + k] { break; } k += 1; } k -= 1; if k <= 0 { return None } let mut sgn; let center_x = x + (k + 1) / 2; let center_y; if y + k + 1 < h && bmp[y + k + 1][x] { sgn = -1; center_y = y + (k + 2) / 2; if !self.check_margin(bmp, x, y, k + 1, k + 2) { return None; } } else { sgn = 1; center_y = y + (k + 1) / 2; if !self.check_margin(bmp, x, y, k + 1, k + 1) { return None; } } // dbg!(x, y, k); let mut n = Int::from(0); let mut b = Int::from(1 as i32); for i in 0..k * k { if bmp[y + 1 + i / k][x + 1 + i % k] { n += &b; } b *= 2; } n *= sgn; //println!("found number: (x={}, y={}) -> {}", x, y, n); Some(((center_x, center_y), RecognizedChar::Num(n))) } fn match_at(&self, bmp: &Vec<Vec<bool>>, x: usize, y: usize) -> Option<((usize, usize), RecognizedChar)> { self.match_num_at(bmp, x, y).or_else(|| self.match_chars_at(bmp, x, y)) } fn match_all(&self, bmp: &Vec<Vec<bool>>) -> Vec<((usize, usize), RecognizedChar)> { let h = bmp.len(); let w = bmp[0].len(); let mut results = vec![]; for y in 0..h { for x in 0..w { if let Some(((cx, cy), rr)) = self.match_at(bmp, x, y) { results.push(((cx, cy), rr)); } } } results } fn detect_chars(&self, bmp: &Vec<Vec<bool>>) { let h = bmp.len(); let w = bmp[0].len(); let mut usd = vec![vec![false; w]; h]; for y in 0..h { for x in 0..w { if usd[y][x] { continue; } if bmp[y][x] { continue; } // println!("YHO"); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// #[derive(Debug)] pub struct RecognitionResult { chars: Vec<((usize, Int, Int), RecognizedChar)>, } impl RecognitionResult { pub fn new_empty() -> Self { Self { chars: vec![] } } pub fn pretty_print(&self) { println!("{}", "-".repeat(80)); println!("{:>5} {:>5} {:>5} | Value", "c", "x", "y"); println!("{}", "-".repeat(80)); for row in self.chars.iter() { println!("{:>5} {:>5} {:>5} | {}", (row.0).0, (row.0).1, (row.0).2, row.1); } println!("{}", "-".repeat(80)); } pub fn filter_command(&self, original_command: &str) -> String { if original_command.is_empty() { return original_command.to_string(); } let mut matches = vec![]; for ((c, x, y), rc) in self.chars.iter() { if rc.starts_with(original_command) { matches.push((*c, x.clone(), y.clone())); } } if matches.len() == 0 { return original_command.to_string(); } if matches.len() >= 2 { eprintln!("Recognizer: multiple matches: {:?}", matches); return original_command.to_string(); } // unique match let m = &matches[0]; let command = format!("{} {}", m.1, m.2); eprintln!("Recognizer: {} -> {}", original_command, &command); command } }
27.616822
157
0.415116
e29f8f3363e48f3d84d515015150ef6073bdd200
8,678
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[cfg(not(test))] use flexi_logger::{Cleanup, Criterion, Duplicate, Logger, Naming}; // Test naming occasionally uses camelCase with underscores to separate sections of // the test name. #[cfg_attr(test, allow(non_snake_case))] #[macro_use] extern crate neovide_derive; #[macro_use] extern crate clap; mod bridge; mod channel_utils; mod cmd_line; mod editor; mod error_handling; mod redraw_scheduler; mod renderer; mod running_tracker; mod settings; mod utils; mod window; mod windows_utils; #[macro_use] extern crate derive_new; #[macro_use] extern crate lazy_static; use std::env::args; use std::sync::mpsc::channel; use log::trace; use tokio::sync::mpsc::unbounded_channel; use bridge::start_bridge; use cmd_line::CmdLineSettings; use editor::start_editor; use renderer::{cursor_renderer::CursorSettings, RendererSettings}; use settings::SETTINGS; use window::{create_window, KeyboardSettings, WindowSettings}; pub use channel_utils::*; pub use running_tracker::*; pub use windows_utils::*; fn main() { // ----------- // | DATA FLOW | // ----------- // // Data flows in a circular motion via channels. This allows each component to handle and // process data on their own thread while not blocking the other components from processing. // // This way Neovim continues to produce events, the window doesn't freeze and queues up ui // commands, and the editor can do the processing necessary to handle the UI events // effectively. // // BRIDGE // V REDRAW EVENT // EDITOR // V DRAW COMMAND // WINDOW // V UI COMMAND // BRIDGE // // BRIDGE: // The bridge is responsible for the connection to the neovim process itself. It is in charge // of starting and communicating to and from the process. // // REDRAW EVENT: // Redraw events are direct events from the neovim process meant to specify how the editor // should be drawn to the screen. They also include other things such as whether the mouse is // enabled. The bridge takes these events, filters out some of them meant only for // filtering, and forwards them to the editor. // // EDITOR: // The editor is responsible for processing and transforming redraw events into something // more readily renderable. Ligature support and multi window management requires some // significant preprocessing of the redraw events in order to capture what exactly should get // drawn where. Futher this step takes a bit of processing power to accomplish, so it is done // on it's own thread. Ideally heavily computationally expensive tasks should be done in the // editor. // // DRAW COMMAND: // The draw commands are distilled render information describing actions to be done at the // window by window level. // // WINDOW: // The window is responsible for rendering and gathering input events from the user. This // inncludes taking the draw commands from the editor and turning them into pixels on the // screen. The ui commands are then forwarded back to the BRIDGE to convert them into // commands for neovim to handle properly. // // UI COMMAND: // The ui commands are things like text input/key bindings, outer window resizes, and mouse // inputs. // // ------------------ // | Other Components | // ------------------ // // Neovide also includes some other systems which are globally available via lazy static // instantiations. // // SETTINGS: // The settings system is live updated from global variables in neovim with the prefix // "neovide". They allow us to configure and manage the functionality of neovide from neovim // init scripts and variables. // // REDRAW SCHEDULER: // The redraw scheduler is a simple system in charge of deciding if the renderer should draw // another frame next frame, or if it can safely skip drawing to save battery and cpu power. // Multiple other parts of the app "queue_next_frame" function to ensure animations continue // properly or updates to the graphics are pushed to the screen. #[cfg(target_os = "windows")] windows_attach_to_console(); //Will exit if -h or -v if let Err(err) = cmd_line::handle_command_line_arguments(args().collect()) { eprintln!("{}", err); return; } #[cfg(not(test))] init_logger(); trace!("Neovide version: {}", crate_version!()); maybe_disown(); #[cfg(target_os = "windows")] windows_fix_dpi(); #[cfg(target_os = "macos")] handle_macos(); WindowSettings::register(); RendererSettings::register(); CursorSettings::register(); KeyboardSettings::register(); let (redraw_event_sender, redraw_event_receiver) = unbounded_channel(); let logging_redraw_event_sender = LoggingTx::attach(redraw_event_sender, "redraw_event".to_owned()); let (batched_draw_command_sender, batched_draw_command_receiver) = channel(); let logging_batched_draw_command_sender = LoggingSender::attach( batched_draw_command_sender, "batched_draw_command".to_owned(), ); let (ui_command_sender, ui_command_receiver) = unbounded_channel(); let logging_ui_command_sender = LoggingTx::attach(ui_command_sender, "ui_command".to_owned()); let (window_command_sender, window_command_receiver) = channel(); let logging_window_command_sender = LoggingSender::attach(window_command_sender, "window_command".to_owned()); // We need to keep the bridge reference around to prevent the tokio runtime from getting freed let _bridge = start_bridge( #[cfg(windows)] logging_ui_command_sender.clone(), ui_command_receiver, logging_redraw_event_sender, ); start_editor( redraw_event_receiver, logging_batched_draw_command_sender, logging_window_command_sender, ); create_window( batched_draw_command_receiver, window_command_receiver, logging_ui_command_sender, ); } #[cfg(not(test))] pub fn init_logger() { let settings = SETTINGS.get::<CmdLineSettings>(); let logger = if settings.log_to_file { Logger::with_env_or_str("neovide") .log_to_file() .rotate( Criterion::Size(10_000_000), Naming::Timestamps, Cleanup::KeepLogFiles(1), ) .duplicate_to_stderr(Duplicate::Error) } else { Logger::with_env_or_str("neovide = error") }; logger.start().expect("Could not start logger"); } fn maybe_disown() { use std::{env, process}; let settings = SETTINGS.get::<CmdLineSettings>(); if cfg!(debug_assertions) || settings.no_fork { return; } if let Ok(current_exe) = env::current_exe() { assert!(process::Command::new(current_exe) .stdin(process::Stdio::null()) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .arg("--nofork") .args(env::args().skip(1)) .spawn() .is_ok()); process::exit(0); } else { eprintln!("error in disowning process, cannot obtain the path for the current executable, continuing without disowning..."); } } #[cfg(target_os = "windows")] fn windows_fix_dpi() { use winapi::shared::windef::DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2; use winapi::um::winuser::SetProcessDpiAwarenessContext; unsafe { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); } } #[cfg(target_os = "macos")] fn handle_macos() { use std::env; if env::var_os("TERM").is_none() { let shell = env::var("SHELL").unwrap(); // printenv is the proper way to print env variables. using echo $PATH would break Fish. let cmd = "printenv PATH"; if let Ok(path) = std::process::Command::new(shell) .arg("-lic") // interactive login shell, this simulates opening a real terminal emulator .arg(cmd) .output() { env::set_var("PATH", std::str::from_utf8(&path.stdout).unwrap()); } } } #[cfg(target_os = "windows")] fn windows_attach_to_console() { // Attach to parent console tip found here: https://github.com/rust-lang/rust/issues/67159#issuecomment-987882771 use winapi::um::wincon::{AttachConsole, ATTACH_PARENT_PROCESS}; unsafe { AttachConsole(ATTACH_PARENT_PROCESS); } }
33.122137
132
0.664785
4843c449ebdeb788267755be5d8745e9325067ee
4,000
extern crate nannou; use nannou::prelude::*; use nannou::ui::prelude::*; fn main() { nannou::run(model, event, view); } struct Model { ui: Ui, ids: Ids, resolution: usize, scale: f32, rotation: f32, color: Rgb, position: Point2, } struct Ids { resolution: widget::Id, scale: widget::Id, rotation: widget::Id, random_color: widget::Id, position: widget::Id, } fn model(app: &App) -> Model { // Set the loop mode to wait for events, an energy-efficient option for pure-GUI apps. app.set_loop_mode(LoopMode::wait(3)); // Create the UI. let mut ui = app.new_ui().build().unwrap(); // Generate some ids for our widgets. let ids = Ids { resolution: ui.generate_widget_id(), scale: ui.generate_widget_id(), rotation: ui.generate_widget_id(), random_color: ui.generate_widget_id(), position: ui.generate_widget_id(), }; // Init our variables let resolution = 6; let scale = 200.0; let rotation = 0.0; let position = pt2(0.0, 0.0); let color = Rgb::new(1.0, 0.0, 1.0); Model { ui, ids, resolution, scale, rotation, position, color, } } fn event(_app: &App, mut model: Model, event: Event) -> Model { if let Event::Update(_update) = event { // Calling `set_widgets` allows us to instantiate some widgets. let ui = &mut model.ui.set_widgets(); fn slider(val: f32, min: f32, max: f32) -> widget::Slider<'static, f32> { widget::Slider::new(val, min, max) .w_h(200.0, 30.0) .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) } for value in slider(model.resolution as f32, 3.0, 15.0) .top_left_with_margin(20.0) .label("Resolution") .set(model.ids.resolution, ui) { model.resolution = value as usize; } for value in slider(model.scale, 10.0, 500.0) .down(10.0) .label("Scale") .set(model.ids.scale, ui) { model.scale = value; } for value in slider(model.rotation, -PI, PI) .down(10.0) .label("Rotation") .set(model.ids.rotation, ui) { model.rotation = value; } for _click in widget::Button::new() .down(10.0) .w_h(200.0, 60.0) .label("Random Color") .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) .set(model.ids.random_color, ui) { model.color = Rgb::new(random(), random(), random()); } for (x, y) in widget::XYPad::new( model.position.x, -200.0, 200.0, model.position.y, -200.0, 200.0, ).down(10.0) .w_h(200.0, 200.0) .label("Position") .label_font_size(15) .rgb(0.3, 0.3, 0.3) .label_rgb(1.0, 1.0, 1.0) .border(0.0) .set(model.ids.position, ui) { model.position = Point2::new(x, y); } } model } // Draw the state of your `Model` into the given `Frame` here. fn view(app: &App, model: &Model, frame: Frame) -> Frame { // Begin drawing let draw = app.draw(); draw.background().rgb(0.02, 0.02, 0.02); draw.ellipse() .xy(model.position) .radius(model.scale) .resolution(model.resolution) .rotate(model.rotation) .color(model.color); // Write the result of our drawing to the window's OpenGL frame. draw.to_frame(app, &frame).unwrap(); // Draw the state of the `Ui` to the frame. model.ui.draw_to_frame(app, &frame).unwrap(); // Return the drawn frame. frame }
25.316456
90
0.5145
cc2a936437b4f5ffce7adcf0defabdae4170cec0
6,835
use std::io; use std::io::Write; use common::{intersect_bitsets, BitSet, ReadOnlyBitSet}; use ownedbytes::OwnedBytes; use crate::space_usage::ByteCount; use crate::DocId; /// Write an alive `BitSet` /// /// where `alive_bitset` is the set of alive `DocId`. /// Warning: this function does not call terminate. The caller is in charge of /// closing the writer properly. pub fn write_alive_bitset<T: Write>(alive_bitset: &BitSet, writer: &mut T) -> io::Result<()> { alive_bitset.serialize(writer)?; Ok(()) } /// Set of alive `DocId`s. #[derive(Clone)] pub struct AliveBitSet { num_alive_docs: usize, bitset: ReadOnlyBitSet, } /// Intersects two AliveBitSets in a new one. /// The two bitsets need to have the same max_value. pub fn intersect_alive_bitsets(left: AliveBitSet, right: AliveBitSet) -> AliveBitSet { assert_eq!(left.bitset().max_value(), right.bitset().max_value()); let bitset = intersect_bitsets(left.bitset(), right.bitset()); let num_alive_docs = bitset.len(); AliveBitSet { num_alive_docs, bitset, } } impl AliveBitSet { #[cfg(test)] pub(crate) fn for_test_from_deleted_docs(deleted_docs: &[DocId], max_doc: u32) -> AliveBitSet { assert!(deleted_docs.iter().all(|&doc| doc < max_doc)); let mut bitset = BitSet::with_max_value_and_full(max_doc); for &doc in deleted_docs { bitset.remove(doc); } let mut alive_bitset_buffer = Vec::new(); write_alive_bitset(&bitset, &mut alive_bitset_buffer).unwrap(); let alive_bitset_bytes = OwnedBytes::new(alive_bitset_buffer); Self::open(alive_bitset_bytes) } pub(crate) fn from_bitset(bitset: &BitSet) -> AliveBitSet { let readonly_bitset = ReadOnlyBitSet::from(bitset); AliveBitSet::from(readonly_bitset) } /// Opens an alive bitset given its file. pub fn open(bytes: OwnedBytes) -> AliveBitSet { let bitset = ReadOnlyBitSet::open(bytes); AliveBitSet::from(bitset) } /// Returns true if the document is still "alive". In other words, if it has not been deleted. #[inline] pub fn is_alive(&self, doc: DocId) -> bool { self.bitset.contains(doc) } /// Returns true if the document has been marked as deleted. #[inline] pub fn is_deleted(&self, doc: DocId) -> bool { !self.is_alive(doc) } /// Iterate over the alive doc_ids. #[inline] pub fn iter_alive(&self) -> impl Iterator<Item = DocId> + '_ { self.bitset.iter() } /// Get underlying bitset. #[inline] pub fn bitset(&self) -> &ReadOnlyBitSet { &self.bitset } /// The number of alive documents. pub fn num_alive_docs(&self) -> usize { self.num_alive_docs } /// Summarize total space usage of this bitset. pub fn space_usage(&self) -> ByteCount { self.bitset().num_bytes() } } impl From<ReadOnlyBitSet> for AliveBitSet { fn from(bitset: ReadOnlyBitSet) -> AliveBitSet { let num_alive_docs = bitset.len(); AliveBitSet { num_alive_docs, bitset, } } } #[cfg(test)] mod tests { use super::AliveBitSet; #[test] fn test_alive_bitset_empty() { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[], 10); for doc in 0..10 { assert_eq!(alive_bitset.is_deleted(doc), !alive_bitset.is_alive(doc)); assert!(!alive_bitset.is_deleted(doc)); } assert_eq!(alive_bitset.num_alive_docs(), 10); } #[test] fn test_alive_bitset() { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[1, 9], 10); assert!(alive_bitset.is_alive(0)); assert!(alive_bitset.is_deleted(1)); assert!(alive_bitset.is_alive(2)); assert!(alive_bitset.is_alive(3)); assert!(alive_bitset.is_alive(4)); assert!(alive_bitset.is_alive(5)); assert!(alive_bitset.is_alive(6)); assert!(alive_bitset.is_alive(6)); assert!(alive_bitset.is_alive(7)); assert!(alive_bitset.is_alive(8)); assert!(alive_bitset.is_deleted(9)); for doc in 0..10 { assert_eq!(alive_bitset.is_deleted(doc), !alive_bitset.is_alive(doc)); } assert_eq!(alive_bitset.num_alive_docs(), 8); } #[test] fn test_alive_bitset_iter_minimal() { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[7], 8); let data: Vec<_> = alive_bitset.iter_alive().collect(); assert_eq!(data, vec![0, 1, 2, 3, 4, 5, 6]); } #[test] fn test_alive_bitset_iter_small() { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[0, 2, 3, 6], 7); let data: Vec<_> = alive_bitset.iter_alive().collect(); assert_eq!(data, vec![1, 4, 5]); } #[test] fn test_alive_bitset_iter() { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[0, 1, 1000], 1001); let data: Vec<_> = alive_bitset.iter_alive().collect(); assert_eq!(data, (2..=999).collect::<Vec<_>>()); } } #[cfg(all(test, feature = "unstable"))] mod bench { use rand::prelude::IteratorRandom; use rand::thread_rng; use test::Bencher; use super::AliveBitSet; fn get_alive() -> Vec<u32> { let mut data = (0..1_000_000_u32).collect::<Vec<u32>>(); for _ in 0..(1_000_000) * 1 / 8 { remove_rand(&mut data); } data } fn remove_rand(raw: &mut Vec<u32>) { let i = (0..raw.len()).choose(&mut thread_rng()).unwrap(); raw.remove(i); } #[bench] fn bench_deletebitset_iter_deser_on_fly(bench: &mut Bencher) { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[0, 1, 1000, 10000], 1_000_000); bench.iter(|| alive_bitset.iter_alive().collect::<Vec<_>>()); } #[bench] fn bench_deletebitset_access(bench: &mut Bencher) { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&[0, 1, 1000, 10000], 1_000_000); bench.iter(|| { (0..1_000_000_u32) .filter(|doc| alive_bitset.is_alive(*doc)) .collect::<Vec<_>>() }); } #[bench] fn bench_deletebitset_iter_deser_on_fly_1_8_alive(bench: &mut Bencher) { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&get_alive(), 1_000_000); bench.iter(|| alive_bitset.iter_alive().collect::<Vec<_>>()); } #[bench] fn bench_deletebitset_access_1_8_alive(bench: &mut Bencher) { let alive_bitset = AliveBitSet::for_test_from_deleted_docs(&get_alive(), 1_000_000); bench.iter(|| { (0..1_000_000_u32) .filter(|doc| alive_bitset.is_alive(*doc)) .collect::<Vec<_>>() }); } }
30.243363
100
0.617557
907052c0f3b90b7229eebdbc227bd922512e7b41
3,125
use algebra::mnt4_753::Fr as MNT4Fr; use algebra::mnt6_753::{FqParameters, Fr, G1Projective, G2Projective}; use algebra_core::fields::Field; use algebra_core::{test_rng, ProjectiveCurve}; use r1cs_core::ConstraintSystem; use r1cs_std::bits::boolean::Boolean; use r1cs_std::mnt6_753::{G1Gadget, G2Gadget}; use r1cs_std::prelude::AllocGadget; use r1cs_std::test_constraint_system::TestConstraintSystem; use r1cs_std::ToBitsGadget; use rand::RngCore; use nimiq_nano_sync::gadgets::mnt4::YToBitGadget; use nimiq_nano_sync::utils::{bytes_to_bits, pad_point_bits, serialize_g1_mnt6, serialize_g2_mnt6}; // When running tests you are advised to run only one test at a time or you might run out of RAM. // Also they take a long time to run. This is why they have the ignore flag. #[test] #[ignore] fn serialization_mnt6_works() { // Initialize the constraint system. let mut cs = TestConstraintSystem::<MNT4Fr>::new(); // Create random integer. let rng = &mut test_rng(); let mut bytes = [0u8; 96]; rng.fill_bytes(&mut bytes[2..]); let x = Fr::from_random_bytes(&bytes).unwrap(); // Create random points. let g2_point = G2Projective::prime_subgroup_generator().mul(x); let g1_point = G1Projective::prime_subgroup_generator().mul(x); // Allocate the random inputs in the circuit. let g2_point_var = G2Gadget::alloc(cs.ns(|| "alloc g1 point"), || Ok(&g2_point)).unwrap(); let g1_point_var = G1Gadget::alloc(cs.ns(|| "alloc g2 point"), || Ok(&g1_point)).unwrap(); // ----------- G2 ----------- // Serialize using the primitive version. let bytes = serialize_g2_mnt6(g2_point); let bits = bytes_to_bits(&bytes); // Allocate the primitive result for easier comparison. let mut primitive_var: Vec<Boolean> = Vec::new(); for i in 0..bits.len() { primitive_var.push(Boolean::alloc(cs.ns(|| format!("allocate primitive result g2: bit {}", i)), || Ok(bits[i])).unwrap()); } // Serialize using the gadget version. let mut gadget_var = vec![]; let x_bits = g2_point_var.x.to_bits(cs.ns(|| "g2 x to bits")).unwrap(); let y_bit = YToBitGadget::y_to_bit_g2(cs.ns(|| "g2 y to bit"), &g2_point_var).unwrap(); gadget_var.extend(pad_point_bits::<FqParameters>(x_bits, y_bit)); assert_eq!(primitive_var, gadget_var); // ----------- G1 ----------- // Serialize using the primitive version. let bytes = serialize_g1_mnt6(g1_point); let bits = bytes_to_bits(&bytes); // Allocate the primitive result for easier comparison. let mut primitive_var: Vec<Boolean> = Vec::new(); for i in 0..bits.len() { primitive_var.push(Boolean::alloc(cs.ns(|| format!("allocate primitive result g1: bit {}", i)), || Ok(bits[i])).unwrap()); } // Serialize using the gadget version. let mut gadget_var = vec![]; let x_bits = g1_point_var.x.to_bits(cs.ns(|| "g1 x to bits")).unwrap(); let y_bit = YToBitGadget::y_to_bit_g1(cs.ns(|| "g1 y to bit"), &g1_point_var).unwrap(); gadget_var.extend(pad_point_bits::<FqParameters>(x_bits, y_bit)); assert_eq!(primitive_var, gadget_var); }
40.584416
130
0.6784
280ebf3f447ee71a5205c5605468f4ff62b1aaa7
3,999
/* * Copyright (c) 2020 TensorBase, and its contributors * All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #[macro_export] macro_rules! with_timer { ($timer_name:ident, $($s:stmt);+ $(;)?) => { let $timer_name = ::std::time::Instant::now(); $($s)* }; } #[macro_export] macro_rules! with_timer_print { ($timer_name:ident, $($s:stmt);+ $(;)?) => { let $timer_name = ::std::time::Instant::now(); $($s)* println!("{:?}", $timer_name.elapsed()); }; } #[macro_export] #[cfg(debug_assertions)] macro_rules! debug { ($x:expr) => { dbg!($x) }; } #[macro_export] macro_rules! bytes_cat { ($($arg:expr),*) => {{ let mut v = Vec::new(); $( v.extend_from_slice($arg); )* v }} } #[macro_export] #[cfg(not(debug_assertions))] macro_rules! debug { ($x:expr) => { std::convert::identity($x) }; } #[macro_export] macro_rules! seq { // Sequences ($($v:expr,)*) => { std::array::IntoIter::new([$($v,)*]).collect() }; ($($v:expr),*) => { std::array::IntoIter::new([$($v,)*]).collect() }; // Maps ($($k:expr => $v:expr,)*) => { std::array::IntoIter::new([$(($k, $v),)*]).collect() }; ($($k:expr => $v:expr),*) => { std::array::IntoIter::new([$(($k, $v),)*]).collect() }; } #[macro_export] macro_rules! show_option_size { (header) => { println!("{:<22} {:>4} {}", "Type", "T", "Option<T>"); }; ($t:ty) => { println!( "{:<22} {:4} {:4}", stringify!($t), std::mem::size_of::<$t>(), std::mem::size_of::<Option<$t>>() ) }; } //REF from dtolnay's https://github.com/dtolnay/reduce pub trait Reduce<T> { fn reduce<F>(self, f: F) -> Option<T> where Self: Sized, F: FnMut(T, T) -> T; } impl<T, I> Reduce<T> for I where I: Iterator<Item = T>, { #[inline] fn reduce<F>(mut self, f: F) -> Option<T> where Self: Sized, F: FnMut(T, T) -> T, { self.next().map(|first| self.fold(first, f)) } } #[cfg(test)] mod unit_tests { #[test] fn basic_check() { let x = 4; debug!(x); if debug!(x == 5) { println!("x == 5"); } else { println!("x != 5"); } } #[test] fn test_matches() { let foo = 'f'; assert!(matches!(foo, 'A'..='Z' | 'a'..='z')); let bar = Some(4); assert!(matches!(bar, Some(x) if x > 2)); } #[test] fn test_bytes_cat() { assert_eq!(bytes_cat!(b"a", b"B"), b"aB"); let v = vec![1, 2, 3u8]; assert_eq!(bytes_cat!(&v, &[4u8, 5, 6]), &[1, 2, 3, 4, 5, 6]); } #[test] fn test_reduce() { let v = vec![1usize, 2, 3, 4, 5]; let sum = v.into_iter().reduce(|a, b| a + b); assert_eq!(Some(15), sum); // Reduce an empty iterator into None let v = Vec::<usize>::new(); let sum = v.into_iter().reduce(|a, b| a + b); assert_eq!(None, sum); } #[test] fn test_next_power_of_two() { assert_eq!(0usize.next_power_of_two(), 1); assert_eq!(1u64.next_power_of_two(), 1); assert_eq!(2u64.next_power_of_two(), 2); assert_eq!(3u64.next_power_of_two(), 4); assert_eq!(8u64.next_power_of_two(), 8); assert_eq!(9u64.next_power_of_two(), 16); } }
23.803571
76
0.507877
d570294b0aa90814498f6159ffcf21a8a3b67c61
353
use std::{io, thread}; fn main() -> io::Result<()> { // https://twitter.com/yoshuawuyts/status/1479776297115136000 let count = thread::available_parallelism()?.get(); assert!(count >= 1_usize); // https://blog.rust-lang.org/2022/01/13/Rust-1.58.0.html#captured-identifiers-in-format-strings println!("cores: {count}"); Ok(()) }
32.090909
100
0.645892
ed7a081337ece9c3934de932a718df1b02b51e49
8,849
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-BSD-3-Clause file. // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // //! Helper for creating valid kernel command line strings. use std::fmt; use std::result; /// The error type for command line building operations. #[derive(Debug, PartialEq)] pub enum Error { /// Operation would have resulted in a non-printable ASCII character. InvalidAscii, /// Key/Value Operation would have had a space in it. HasSpace, /// Key/Value Operation would have had an equals sign in it. HasEquals, /// Operation would have made the command line too large. TooLarge, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match *self { Error::InvalidAscii => "String contains a non-printable ASCII character.", Error::HasSpace => "String contains a space.", Error::HasEquals => "String contains an equals sign.", Error::TooLarge => "Inserting string would make command line too long.", } ) } } impl std::error::Error for Error {} /// Specialized [`Result`] type for command line operations. /// /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html pub type Result<T> = result::Result<T, Error>; fn valid_char(c: char) -> bool { match c { ' '..='~' => true, _ => false, } } fn valid_str(s: &str) -> Result<()> { if s.chars().all(valid_char) { Ok(()) } else { Err(Error::InvalidAscii) } } fn valid_element(s: &str) -> Result<()> { if !s.chars().all(valid_char) { Err(Error::InvalidAscii) } else if s.contains(' ') { Err(Error::HasSpace) } else if s.contains('=') { Err(Error::HasEquals) } else { Ok(()) } } /// A builder for a kernel command line string that validates the string as it's being built. /// A `CString` can be constructed from this directly using `CString::new`. /// /// # Examples /// /// ```rust /// # use linux_loader::cmdline::*; /// # use std::ffi::CString; /// let cl = Cmdline::new(100); /// let cl_cstring = CString::new(cl).unwrap(); /// assert_eq!(cl_cstring.to_str().unwrap(), ""); /// ``` pub struct Cmdline { line: String, capacity: usize, } impl Cmdline { /// Constructs an empty [`Cmdline`] with the given capacity, including the nul terminator. /// /// # Arguments /// /// * `capacity` - Command line capacity. Must be greater than 0. /// /// # Examples /// /// ```rust /// # use linux_loader::cmdline::*; /// let cl = Cmdline::new(100); /// ``` /// [`Cmdline`]: struct.Cmdline.html pub fn new(capacity: usize) -> Cmdline { assert_ne!(capacity, 0); Cmdline { line: String::with_capacity(capacity), capacity, } } fn has_capacity(&self, more: usize) -> Result<()> { let needs_space = if self.line.is_empty() { 0 } else { 1 }; if self.line.len() + more + needs_space < self.capacity { Ok(()) } else { Err(Error::TooLarge) } } fn start_push(&mut self) { if !self.line.is_empty() { self.line.push(' '); } } fn end_push(&mut self) { // This assert is always true because of the `has_capacity` check that each insert method // uses. assert!(self.line.len() < self.capacity); } /// Validates and inserts a key-value pair into this command line. /// /// # Arguments /// /// * `key` - Key to be inserted in the command line string. /// * `val` - Value corresponding to `key`. /// /// # Examples /// /// ```rust /// # use linux_loader::cmdline::*; /// # use std::ffi::CString; /// let mut cl = Cmdline::new(100); /// cl.insert("foo", "bar"); /// let cl_cstring = CString::new(cl).unwrap(); /// assert_eq!(cl_cstring.to_str().unwrap(), "foo=bar"); /// ``` pub fn insert<T: AsRef<str>>(&mut self, key: T, val: T) -> Result<()> { let k = key.as_ref(); let v = val.as_ref(); valid_element(k)?; valid_element(v)?; self.has_capacity(k.len() + v.len() + 1)?; self.start_push(); self.line.push_str(k); self.line.push('='); self.line.push_str(v); self.end_push(); Ok(()) } /// Validates and inserts a string to the end of the current command line. /// /// # Arguments /// /// * `slug` - String to be appended to the command line. /// /// # Examples /// /// ```rust /// # use linux_loader::cmdline::*; /// # use std::ffi::CString; /// let mut cl = Cmdline::new(100); /// cl.insert_str("foobar"); /// let cl_cstring = CString::new(cl).unwrap(); /// assert_eq!(cl_cstring.to_str().unwrap(), "foobar"); /// ``` pub fn insert_str<T: AsRef<str>>(&mut self, slug: T) -> Result<()> { let s = slug.as_ref(); valid_str(s)?; self.has_capacity(s.len())?; self.start_push(); self.line.push_str(s); self.end_push(); Ok(()) } /// Returns the string representation of the command line without the nul terminator. /// /// # Examples /// /// ```rust /// # use linux_loader::cmdline::*; /// let mut cl = Cmdline::new(10); /// cl.insert_str("foobar"); /// assert_eq!(cl.as_str(), "foobar"); /// ``` pub fn as_str(&self) -> &str { self.line.as_str() } } impl Into<Vec<u8>> for Cmdline { fn into(self) -> Vec<u8> { self.line.into_bytes() } } #[cfg(test)] mod tests { use super::*; use std::ffi::CString; #[test] fn test_insert_hello_world() { let mut cl = Cmdline::new(100); assert_eq!(cl.as_str(), ""); assert!(cl.insert("hello", "world").is_ok()); assert_eq!(cl.as_str(), "hello=world"); let s = CString::new(cl).expect("failed to create CString from Cmdline"); assert_eq!(s, CString::new("hello=world").unwrap()); } #[test] fn test_insert_multi() { let mut cl = Cmdline::new(100); assert!(cl.insert("hello", "world").is_ok()); assert!(cl.insert("foo", "bar").is_ok()); assert_eq!(cl.as_str(), "hello=world foo=bar"); } #[test] fn test_insert_space() { let mut cl = Cmdline::new(100); assert_eq!(cl.insert("a ", "b"), Err(Error::HasSpace)); assert_eq!(cl.insert("a", "b "), Err(Error::HasSpace)); assert_eq!(cl.insert("a ", "b "), Err(Error::HasSpace)); assert_eq!(cl.insert(" a", "b"), Err(Error::HasSpace)); assert_eq!(cl.as_str(), ""); } #[test] fn test_insert_equals() { let mut cl = Cmdline::new(100); assert_eq!(cl.insert("a=", "b"), Err(Error::HasEquals)); assert_eq!(cl.insert("a", "b="), Err(Error::HasEquals)); assert_eq!(cl.insert("a=", "b "), Err(Error::HasEquals)); assert_eq!(cl.insert("=a", "b"), Err(Error::HasEquals)); assert_eq!(cl.insert("a", "=b"), Err(Error::HasEquals)); assert_eq!(cl.as_str(), ""); } #[test] fn test_insert_emoji() { let mut cl = Cmdline::new(100); assert_eq!(cl.insert("heart", "💖"), Err(Error::InvalidAscii)); assert_eq!(cl.insert("💖", "love"), Err(Error::InvalidAscii)); assert_eq!(cl.as_str(), ""); } #[test] fn test_insert_string() { let mut cl = Cmdline::new(13); assert_eq!(cl.as_str(), ""); assert!(cl.insert_str("noapic").is_ok()); assert_eq!(cl.as_str(), "noapic"); assert!(cl.insert_str("nopci").is_ok()); assert_eq!(cl.as_str(), "noapic nopci"); } #[test] fn test_insert_too_large() { let mut cl = Cmdline::new(4); assert_eq!(cl.insert("hello", "world"), Err(Error::TooLarge)); assert_eq!(cl.insert("a", "world"), Err(Error::TooLarge)); assert_eq!(cl.insert("hello", "b"), Err(Error::TooLarge)); assert!(cl.insert("a", "b").is_ok()); assert_eq!(cl.insert("a", "b"), Err(Error::TooLarge)); assert_eq!(cl.insert_str("a"), Err(Error::TooLarge)); assert_eq!(cl.as_str(), "a=b"); let mut cl = Cmdline::new(10); assert!(cl.insert("ab", "ba").is_ok()); // adds 5 length assert_eq!(cl.insert("c", "da"), Err(Error::TooLarge)); // adds 5 (including space) length assert!(cl.insert("c", "d").is_ok()); // adds 4 (including space) length } }
29.496667
98
0.548311
b98ec0d17b43a4a30ab11f8126d7479fd1431c18
1,322
use tokio::{io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, net::TcpListener, sync::broadcast}; #[tokio::main] async fn main() { let listener = TcpListener::bind("localhost:4567").await.unwrap(); let (tx,_rx) = broadcast::channel(10); loop { let (mut socket,addr) = listener.accept().await.unwrap(); let tx = tx.clone(); let mut rx = tx.subscribe(); tokio::spawn(async move { let (reader,mut writer) = socket.split(); let mut reader = BufReader::new(reader); let mut line = String::new(); loop{ tokio::select! { result = reader.read_line(&mut line) => { if result.unwrap() ==0 { break; } tx.send((line.clone(),addr)).unwrap(); line.clear(); } result = rx.recv()=> { let (msg,other_addr) = result.unwrap(); if addr != other_addr { writer.write_all(msg.as_bytes()).await.unwrap(); } } } } }); } }
30.045455
96
0.403177
5d98c92037f52e5a0db8135bc4a0b3155edfc337
2,039
//! EDN export use super::table::{AsKey, FromPairs, FromPrimitive, FromVec, TableAccumulator}; use crate::eval::emit::{Emitter, Event, RenderMetadata}; use crate::eval::primitive::Primitive; use edn_format::{emit_str, Keyword, Value}; use ordered_float::OrderedFloat; use std::io::Write; impl AsKey<Value> for Value { fn as_key(&self) -> Value { self.clone() } } impl FromPrimitive for Value { fn from_primitive(_metadata: RenderMetadata, primitive: &Primitive) -> Self { match primitive { Primitive::Null => Value::Nil, Primitive::Bool(b) => Value::Boolean(*b), Primitive::Sym(s) => Value::Keyword(Keyword::from_name(s)), Primitive::Str(s) => Value::String(s.clone()), Primitive::Num(n) => { if let Some(i) = n.as_i64() { Value::Integer(i) } else if let Some(f) = n.as_f64() { Value::Float(OrderedFloat(f)) } else { panic!("unrepresentable number") } } Primitive::ZonedDateTime(dt) => Value::Inst(*dt), } } } impl FromVec<Value> for Value { fn from_vec(_metadata: RenderMetadata, slice: Vec<Value>) -> Self { Value::Vector(slice) } } impl FromPairs<Value, Value> for Value { fn from_pairs(_metadata: RenderMetadata, pairs: Vec<(Value, Value)>) -> Self { Value::Map(pairs.into_iter().collect()) } } /// Emitter for EDN pub struct EdnEmitter<'a> { accum: TableAccumulator<Value, Value>, out: &'a mut (dyn Write + 'a), } impl<'a> EdnEmitter<'a> { pub fn new(out: &'a mut (dyn Write + 'a)) -> Self { EdnEmitter { accum: Default::default(), out, } } } impl<'a> Emitter for EdnEmitter<'a> { fn emit(&mut self, event: Event) { self.accum.consume(event); if let Some(result) = self.accum.result() { writeln!(self.out, "{}", emit_str(result)).unwrap(); } } }
28.319444
82
0.556645
de1937cea5c86e00ba2639a84d01a841513d717f
5,308
#![recursion_limit="128"] use futures::{Poll, pending, pin_mut, poll, join, try_join, select}; use futures::channel::{mpsc, oneshot}; use futures::executor::block_on; use futures::future::{self, FutureExt}; use futures::stream::StreamExt; use futures::sink::SinkExt; #[test] fn poll_and_pending() { let pending_once = async { pending!() }; block_on(async { pin_mut!(pending_once); assert_eq!(Poll::Pending, poll!(&mut pending_once)); assert_eq!(Poll::Ready(()), poll!(&mut pending_once)); }); } #[test] fn join() { let (tx1, rx1) = oneshot::channel::<i32>(); let (tx2, rx2) = oneshot::channel::<i32>(); let fut = async { let res = join!(rx1, rx2); assert_eq!((Ok(1), Ok(2)), res); }; block_on(async { pin_mut!(fut); assert_eq!(Poll::Pending, poll!(&mut fut)); tx1.send(1).unwrap(); assert_eq!(Poll::Pending, poll!(&mut fut)); tx2.send(2).unwrap(); assert_eq!(Poll::Ready(()), poll!(&mut fut)); }); } #[test] fn select() { let (tx1, rx1) = oneshot::channel::<i32>(); let (_tx2, rx2) = oneshot::channel::<i32>(); tx1.send(1).unwrap(); let mut ran = false; block_on(async { select! { res = rx1.fuse() => { assert_eq!(Ok(1), res); ran = true; }, _ = rx2.fuse() => unreachable!(), } }); assert!(ran); } #[test] fn select_streams() { let (mut tx1, rx1) = mpsc::channel::<i32>(1); let (mut tx2, rx2) = mpsc::channel::<i32>(1); let mut rx1 = rx1.fuse(); let mut rx2 = rx2.fuse(); let mut ran = false; let mut total = 0; block_on(async { let mut tx1_opt; let mut tx2_opt; select! { _ = rx1.next() => panic!(), _ = rx2.next() => panic!(), default => { tx1.send(2).await.unwrap(); tx2.send(3).await.unwrap(); tx1_opt = Some(tx1); tx2_opt = Some(tx2); } complete => panic!(), } loop { select! { // runs first and again after default x = rx1.next() => if let Some(x) = x { total += x; }, // runs second and again after default x = rx2.next() => if let Some(x) = x { total += x; }, // runs third default => { assert_eq!(total, 5); ran = true; drop(tx1_opt.take().unwrap()); drop(tx2_opt.take().unwrap()); }, // runs last complete => break, }; } }); assert!(ran); } #[test] fn select_can_move_uncompleted_futures() { let (tx1, rx1) = oneshot::channel::<i32>(); let (tx2, rx2) = oneshot::channel::<i32>(); tx1.send(1).unwrap(); tx2.send(2).unwrap(); let mut ran = false; let mut rx1 = rx1.fuse(); let mut rx2 = rx2.fuse(); block_on(async { select! { res = rx1 => { assert_eq!(Ok(1), res); assert_eq!(Ok(2), rx2.await); ran = true; }, res = rx2 => { assert_eq!(Ok(2), res); assert_eq!(Ok(1), rx1.await); ran = true; }, } }); assert!(ran); } #[test] fn select_nested() { let mut outer_fut = future::ready(1); let mut inner_fut = future::ready(2); let res = block_on(async { select! { x = outer_fut => { select! { y = inner_fut => x + y, } } } }); assert_eq!(res, 3); } #[test] fn select_size() { let fut = async { let mut ready = future::ready(0i32); select! { _ = ready => {}, } }; assert_eq!(::std::mem::size_of_val(&fut), 24); let fut = async { let mut ready1 = future::ready(0i32); let mut ready2 = future::ready(0i32); select! { _ = ready1 => {}, _ = ready2 => {}, } }; assert_eq!(::std::mem::size_of_val(&fut), 40); } #[test] fn join_size() { let fut = async { let ready = future::ready(0i32); join!(ready) }; assert_eq!(::std::mem::size_of_val(&fut), 16); let fut = async { let ready1 = future::ready(0i32); let ready2 = future::ready(0i32); join!(ready1, ready2) }; assert_eq!(::std::mem::size_of_val(&fut), 28); } #[test] fn try_join_size() { let fut = async { let ready = future::ready(Ok::<i32, i32>(0)); try_join!(ready) }; assert_eq!(::std::mem::size_of_val(&fut), 16); let fut = async { let ready1 = future::ready(Ok::<i32, i32>(0)); let ready2 = future::ready(Ok::<i32, i32>(0)); try_join!(ready1, ready2) }; assert_eq!(::std::mem::size_of_val(&fut), 28); } #[test] fn join_doesnt_require_unpin() { let _ = async { join!(async {}, async {}) }; } #[test] fn try_join_doesnt_require_unpin() { let _ = async { try_join!( async { Ok::<(), ()>(()) }, async { Ok::<(), ()>(()) }, ) }; }
25.037736
70
0.465335
87208dd4beb7bf388d2c99e012e2a1b80739a150
31,509
//! A group of attributes that can be attached to Rust code in order //! to generate a clippy lint detecting said code automatically. use crate::utils::{get_attr, higher}; use rustc::hir; use rustc::hir::intravisit::{NestedVisitorMap, Visitor}; use rustc::hir::{BindingAnnotation, Block, Expr, ExprKind, Pat, PatKind, QPath, Stmt, StmtKind, TyKind}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass}; use rustc::session::Session; use rustc::{declare_lint_pass, declare_tool_lint}; use rustc_data_structures::fx::FxHashMap; use syntax::ast::{Attribute, LitKind}; declare_clippy_lint! { /// **What it does:** Generates clippy code that detects the offending pattern /// /// **Example:** /// ```rust,ignore /// // ./tests/ui/my_lint.rs /// fn foo() { /// // detect the following pattern /// #[clippy::author] /// if x == 42 { /// // but ignore everything from here on /// #![clippy::author = "ignore"] /// } /// () /// } /// ``` /// /// Running `TESTNAME=ui/my_lint cargo uitest` will produce /// a `./tests/ui/new_lint.stdout` file with the generated code: /// /// ```rust,ignore /// // ./tests/ui/new_lint.stdout /// if_chain! { /// if let ExprKind::If(ref cond, ref then, None) = item.node, /// if let ExprKind::Binary(BinOp::Eq, ref left, ref right) = cond.node, /// if let ExprKind::Path(ref path) = left.node, /// if let ExprKind::Lit(ref lit) = right.node, /// if let LitKind::Int(42, _) = lit.node, /// then { /// // report your lint here /// } /// } /// ``` pub LINT_AUTHOR, internal_warn, "helper for writing lints" } declare_lint_pass!(Author => [LINT_AUTHOR]); fn prelude() { println!("if_chain! {{"); } fn done() { println!(" then {{"); println!(" // report your lint here"); println!(" }}"); println!("}}"); } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Author { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { if !has_attr(cx.sess(), &item.attrs) { return; } prelude(); PrintVisitor::new("item").visit_item(item); done(); } fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) { if !has_attr(cx.sess(), &item.attrs) { return; } prelude(); PrintVisitor::new("item").visit_impl_item(item); done(); } fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) { if !has_attr(cx.sess(), &item.attrs) { return; } prelude(); PrintVisitor::new("item").visit_trait_item(item); done(); } fn check_variant(&mut self, cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant) { if !has_attr(cx.sess(), &var.attrs) { return; } prelude(); PrintVisitor::new("var").visit_variant(var, &hir::Generics::empty(), hir::DUMMY_HIR_ID); done(); } fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) { if !has_attr(cx.sess(), &field.attrs) { return; } prelude(); PrintVisitor::new("field").visit_struct_field(field); done(); } fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) { if !has_attr(cx.sess(), &expr.attrs) { return; } prelude(); PrintVisitor::new("expr").visit_expr(expr); done(); } fn check_arm(&mut self, cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) { if !has_attr(cx.sess(), &arm.attrs) { return; } prelude(); PrintVisitor::new("arm").visit_arm(arm); done(); } fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) { if !has_attr(cx.sess(), stmt.node.attrs()) { return; } prelude(); PrintVisitor::new("stmt").visit_stmt(stmt); done(); } fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) { if !has_attr(cx.sess(), &item.attrs) { return; } prelude(); PrintVisitor::new("item").visit_foreign_item(item); done(); } } impl PrintVisitor { fn new(s: &'static str) -> Self { Self { ids: FxHashMap::default(), current: s.to_owned(), } } fn next(&mut self, s: &'static str) -> String { use std::collections::hash_map::Entry::*; match self.ids.entry(s) { // already there: start numbering from `1` Occupied(mut occ) => { let val = occ.get_mut(); *val += 1; format!("{}{}", s, *val) }, // not there: insert and return name as given Vacant(vac) => { vac.insert(0); s.to_owned() }, } } fn print_qpath(&mut self, path: &QPath) { print!(" if match_qpath({}, &[", self.current); print_path(path, &mut true); println!("]);"); } } struct PrintVisitor { /// Fields are the current index that needs to be appended to pattern /// binding names ids: FxHashMap<&'static str, usize>, /// the name that needs to be destructured current: String, } impl<'tcx> Visitor<'tcx> for PrintVisitor { #[allow(clippy::too_many_lines)] fn visit_expr(&mut self, expr: &Expr) { // handle if desugarings // TODO add more desugarings here if let Some((cond, then, opt_else)) = higher::if_block(&expr) { let cond_pat = self.next("cond"); let then_pat = self.next("then"); if let Some(else_) = opt_else { let else_pat = self.next("else_"); println!( " if let Some((ref {}, ref {}, Some({}))) = higher::if_block(&{});", cond_pat, then_pat, else_pat, self.current ); self.current = else_pat; self.visit_expr(else_); } else { println!( " if let Some((ref {}, ref {}, None)) = higher::if_block(&{});", cond_pat, then_pat, self.current ); } self.current = cond_pat; self.visit_expr(cond); self.current = then_pat; self.visit_expr(then); return; } print!(" if let ExprKind::"); let current = format!("{}.node", self.current); match expr.node { ExprKind::Box(ref inner) => { let inner_pat = self.next("inner"); println!("Box(ref {}) = {};", inner_pat, current); self.current = inner_pat; self.visit_expr(inner); }, ExprKind::Array(ref elements) => { let elements_pat = self.next("elements"); println!("Array(ref {}) = {};", elements_pat, current); println!(" if {}.len() == {};", elements_pat, elements.len()); for (i, element) in elements.iter().enumerate() { self.current = format!("{}[{}]", elements_pat, i); self.visit_expr(element); } }, ExprKind::Call(ref func, ref args) => { let func_pat = self.next("func"); let args_pat = self.next("args"); println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current); self.current = func_pat; self.visit_expr(func); println!(" if {}.len() == {};", args_pat, args.len()); for (i, arg) in args.iter().enumerate() { self.current = format!("{}[{}]", args_pat, i); self.visit_expr(arg); } }, ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => { println!("MethodCall(ref method_name, ref generics, ref args) = {};", current); println!(" // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment"); }, ExprKind::Tup(ref elements) => { let elements_pat = self.next("elements"); println!("Tup(ref {}) = {};", elements_pat, current); println!(" if {}.len() == {};", elements_pat, elements.len()); for (i, element) in elements.iter().enumerate() { self.current = format!("{}[{}]", elements_pat, i); self.visit_expr(element); } }, ExprKind::Binary(ref op, ref left, ref right) => { let op_pat = self.next("op"); let left_pat = self.next("left"); let right_pat = self.next("right"); println!( "Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current ); println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat); self.current = left_pat; self.visit_expr(left); self.current = right_pat; self.visit_expr(right); }, ExprKind::Unary(ref op, ref inner) => { let inner_pat = self.next("inner"); println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current); self.current = inner_pat; self.visit_expr(inner); }, ExprKind::Lit(ref lit) => { let lit_pat = self.next("lit"); println!("Lit(ref {}) = {};", lit_pat, current); match lit.node { LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat), LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat), LitKind::Err(val) => println!(" if let LitKind::Err({}) = {}.node;", val, lit_pat), LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat), // FIXME: also check int type LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat), LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat), LitKind::FloatUnsuffixed(_) => { println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat) }, LitKind::ByteStr(ref vec) => { let vec_pat = self.next("vec"); println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat); println!(" if let [{:?}] = **{};", vec, vec_pat); }, LitKind::Str(ref text, _) => { let str_pat = self.next("s"); println!(" if let LitKind::Str(ref {}, _) = {}.node;", str_pat, lit_pat); println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str()) }, } }, ExprKind::Cast(ref expr, ref ty) => { let cast_pat = self.next("expr"); let cast_ty = self.next("cast_ty"); let qp_label = self.next("qp"); println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current); if let TyKind::Path(ref qp) = ty.node { println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty); self.current = qp_label; self.print_qpath(qp); } self.current = cast_pat; self.visit_expr(expr); }, ExprKind::Type(ref expr, ref _ty) => { let cast_pat = self.next("expr"); println!("Type(ref {}, _) = {};", cast_pat, current); self.current = cast_pat; self.visit_expr(expr); }, ExprKind::Loop(ref body, _, desugaring) => { let body_pat = self.next("body"); let des = loop_desugaring_name(desugaring); let label_pat = self.next("label"); println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current); self.current = body_pat; self.visit_block(body); }, ExprKind::Match(ref expr, ref arms, desugaring) => { let des = desugaring_name(desugaring); let expr_pat = self.next("expr"); let arms_pat = self.next("arms"); println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current); self.current = expr_pat; self.visit_expr(expr); println!(" if {}.len() == {};", arms_pat, arms.len()); for (i, arm) in arms.iter().enumerate() { self.current = format!("{}[{}].body", arms_pat, i); self.visit_expr(&arm.body); if let Some(ref guard) = arm.guard { let guard_pat = self.next("guard"); println!(" if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i); match guard { hir::Guard::If(ref if_expr) => { let if_expr_pat = self.next("expr"); println!(" if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat); self.current = if_expr_pat; self.visit_expr(if_expr); }, } } println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len()); for (j, pat) in arm.pats.iter().enumerate() { self.current = format!("{}[{}].pats[{}]", arms_pat, i, j); self.visit_pat(pat); } } }, ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => { println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current); println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment"); }, ExprKind::Yield(ref sub, _) => { let sub_pat = self.next("sub"); println!("Yield(ref sub) = {};", current); self.current = sub_pat; self.visit_expr(sub); }, ExprKind::Block(ref block, _) => { let block_pat = self.next("block"); println!("Block(ref {}) = {};", block_pat, current); self.current = block_pat; self.visit_block(block); }, ExprKind::Assign(ref target, ref value) => { let target_pat = self.next("target"); let value_pat = self.next("value"); println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current); self.current = target_pat; self.visit_expr(target); self.current = value_pat; self.visit_expr(value); }, ExprKind::AssignOp(ref op, ref target, ref value) => { let op_pat = self.next("op"); let target_pat = self.next("target"); let value_pat = self.next("value"); println!( "AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current ); println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat); self.current = target_pat; self.visit_expr(target); self.current = value_pat; self.visit_expr(value); }, ExprKind::Field(ref object, ref field_ident) => { let obj_pat = self.next("object"); let field_name_pat = self.next("field_name"); println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current); println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str()); self.current = obj_pat; self.visit_expr(object); }, ExprKind::Index(ref object, ref index) => { let object_pat = self.next("object"); let index_pat = self.next("index"); println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current); self.current = object_pat; self.visit_expr(object); self.current = index_pat; self.visit_expr(index); }, ExprKind::Path(ref path) => { let path_pat = self.next("path"); println!("Path(ref {}) = {};", path_pat, current); self.current = path_pat; self.print_qpath(path); }, ExprKind::AddrOf(mutability, ref inner) => { let inner_pat = self.next("inner"); println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current); self.current = inner_pat; self.visit_expr(inner); }, ExprKind::Break(ref _destination, ref opt_value) => { let destination_pat = self.next("destination"); if let Some(ref value) = *opt_value { let value_pat = self.next("value"); println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current); self.current = value_pat; self.visit_expr(value); } else { println!("Break(ref {}, None) = {};", destination_pat, current); } // FIXME: implement label printing }, ExprKind::Continue(ref _destination) => { let destination_pat = self.next("destination"); println!("Again(ref {}) = {};", destination_pat, current); // FIXME: implement label printing }, ExprKind::Ret(ref opt_value) => { if let Some(ref value) = *opt_value { let value_pat = self.next("value"); println!("Ret(Some(ref {})) = {};", value_pat, current); self.current = value_pat; self.visit_expr(value); } else { println!("Ret(None) = {};", current); } }, ExprKind::InlineAsm(_, ref _input, ref _output) => { println!("InlineAsm(_, ref input, ref output) = {};", current); println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment"); }, ExprKind::Struct(ref path, ref fields, ref opt_base) => { let path_pat = self.next("path"); let fields_pat = self.next("fields"); if let Some(ref base) = *opt_base { let base_pat = self.next("base"); println!( "Struct(ref {}, ref {}, Some(ref {})) = {};", path_pat, fields_pat, base_pat, current ); self.current = base_pat; self.visit_expr(base); } else { println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current); } self.current = path_pat; self.print_qpath(path); println!(" if {}.len() == {};", fields_pat, fields.len()); println!(" // unimplemented: field checks"); }, // FIXME: compute length (needs type info) ExprKind::Repeat(ref value, _) => { let value_pat = self.next("value"); println!("Repeat(ref {}, _) = {};", value_pat, current); println!("// unimplemented: repeat count check"); self.current = value_pat; self.visit_expr(value); }, ExprKind::Err => { println!("Err = {}", current); }, ExprKind::DropTemps(ref expr) => { let expr_pat = self.next("expr"); println!("DropTemps(ref {}) = {};", expr_pat, current); self.current = expr_pat; self.visit_expr(expr); }, } } fn visit_block(&mut self, block: &Block) { let trailing_pat = self.next("trailing_expr"); println!(" if let Some({}) = &{}.expr;", trailing_pat, self.current); println!(" if {}.stmts.len() == {};", self.current, block.stmts.len()); let current = self.current.clone(); for (i, stmt) in block.stmts.iter().enumerate() { self.current = format!("{}.stmts[{}]", current, i); self.visit_stmt(stmt); } } #[allow(clippy::too_many_lines)] fn visit_pat(&mut self, pat: &Pat) { print!(" if let PatKind::"); let current = format!("{}.node", self.current); match pat.node { PatKind::Wild => println!("Wild = {};", current), PatKind::Binding(anno, .., ident, ref sub) => { let anno_pat = match anno { BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated", BindingAnnotation::Mutable => "BindingAnnotation::Mutable", BindingAnnotation::Ref => "BindingAnnotation::Ref", BindingAnnotation::RefMut => "BindingAnnotation::RefMut", }; let name_pat = self.next("name"); if let Some(ref sub) = *sub { let sub_pat = self.next("sub"); println!( "Binding({}, _, {}, Some(ref {})) = {};", anno_pat, name_pat, sub_pat, current ); self.current = sub_pat; self.visit_pat(sub); } else { println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current); } println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str()); }, PatKind::Struct(ref path, ref fields, ignore) => { let path_pat = self.next("path"); let fields_pat = self.next("fields"); println!( "Struct(ref {}, ref {}, {}) = {};", path_pat, fields_pat, ignore, current ); self.current = path_pat; self.print_qpath(path); println!(" if {}.len() == {};", fields_pat, fields.len()); println!(" // unimplemented: field checks"); }, PatKind::Or(ref fields) => { let fields_pat = self.next("fields"); println!("Or(ref {}) = {};", fields_pat, current); println!(" if {}.len() == {};", fields_pat, fields.len()); println!(" // unimplemented: field checks"); }, PatKind::TupleStruct(ref path, ref fields, skip_pos) => { let path_pat = self.next("path"); let fields_pat = self.next("fields"); println!( "TupleStruct(ref {}, ref {}, {:?}) = {};", path_pat, fields_pat, skip_pos, current ); self.current = path_pat; self.print_qpath(path); println!(" if {}.len() == {};", fields_pat, fields.len()); println!(" // unimplemented: field checks"); }, PatKind::Path(ref path) => { let path_pat = self.next("path"); println!("Path(ref {}) = {};", path_pat, current); self.current = path_pat; self.print_qpath(path); }, PatKind::Tuple(ref fields, skip_pos) => { let fields_pat = self.next("fields"); println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current); println!(" if {}.len() == {};", fields_pat, fields.len()); println!(" // unimplemented: field checks"); }, PatKind::Box(ref pat) => { let pat_pat = self.next("pat"); println!("Box(ref {}) = {};", pat_pat, current); self.current = pat_pat; self.visit_pat(pat); }, PatKind::Ref(ref pat, muta) => { let pat_pat = self.next("pat"); println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current); self.current = pat_pat; self.visit_pat(pat); }, PatKind::Lit(ref lit_expr) => { let lit_expr_pat = self.next("lit_expr"); println!("Lit(ref {}) = {}", lit_expr_pat, current); self.current = lit_expr_pat; self.visit_expr(lit_expr); }, PatKind::Range(ref start, ref end, end_kind) => { let start_pat = self.next("start"); let end_pat = self.next("end"); println!( "Range(ref {}, ref {}, RangeEnd::{:?}) = {};", start_pat, end_pat, end_kind, current ); self.current = start_pat; self.visit_expr(start); self.current = end_pat; self.visit_expr(end); }, PatKind::Slice(ref start, ref middle, ref end) => { let start_pat = self.next("start"); let end_pat = self.next("end"); if let Some(ref middle) = middle { let middle_pat = self.next("middle"); println!( "Slice(ref {}, Some(ref {}), ref {}) = {};", start_pat, middle_pat, end_pat, current ); self.current = middle_pat; self.visit_pat(middle); } else { println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current); } println!(" if {}.len() == {};", start_pat, start.len()); for (i, pat) in start.iter().enumerate() { self.current = format!("{}[{}]", start_pat, i); self.visit_pat(pat); } println!(" if {}.len() == {};", end_pat, end.len()); for (i, pat) in end.iter().enumerate() { self.current = format!("{}[{}]", end_pat, i); self.visit_pat(pat); } }, } } fn visit_stmt(&mut self, s: &Stmt) { print!(" if let StmtKind::"); let current = format!("{}.node", self.current); match s.node { // A local (let) binding: StmtKind::Local(ref local) => { let local_pat = self.next("local"); println!("Local(ref {}) = {};", local_pat, current); if let Some(ref init) = local.init { let init_pat = self.next("init"); println!(" if let Some(ref {}) = {}.init;", init_pat, local_pat); self.current = init_pat; self.visit_expr(init); } self.current = format!("{}.pat", local_pat); self.visit_pat(&local.pat); }, // An item binding: StmtKind::Item(_) => { println!("Item(item_id) = {};", current); }, // Expr without trailing semi-colon (must have unit type): StmtKind::Expr(ref e) => { let e_pat = self.next("e"); println!("Expr(ref {}, _) = {}", e_pat, current); self.current = e_pat; self.visit_expr(e); }, // Expr with trailing semi-colon (may have any type): StmtKind::Semi(ref e) => { let e_pat = self.next("e"); println!("Semi(ref {}, _) = {}", e_pat, current); self.current = e_pat; self.visit_expr(e); }, } } fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::None } } fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool { get_attr(sess, attrs, "author").count() > 0 } fn desugaring_name(des: hir::MatchSource) -> String { match des { hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(), hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(), hir::MatchSource::WhileDesugar => "MatchSource::WhileDesugar".to_string(), hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(), hir::MatchSource::Normal => "MatchSource::Normal".to_string(), hir::MatchSource::IfLetDesugar { contains_else_clause } => format!( "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause ), hir::MatchSource::IfDesugar { contains_else_clause } => format!( "MatchSource::IfDesugar {{ contains_else_clause: {} }}", contains_else_clause ), hir::MatchSource::AwaitDesugar => "MatchSource::AwaitDesugar".to_string(), } } fn loop_desugaring_name(des: hir::LoopSource) -> &'static str { match des { hir::LoopSource::ForLoop => "LoopSource::ForLoop", hir::LoopSource::Loop => "LoopSource::Loop", hir::LoopSource::While => "LoopSource::While", hir::LoopSource::WhileLet => "LoopSource::WhileLet", } } fn print_path(path: &QPath, first: &mut bool) { match *path { QPath::Resolved(_, ref path) => { for segment in &path.segments { if *first { *first = false; } else { print!(", "); } print!("{:?}", segment.ident.as_str()); } }, QPath::TypeRelative(ref ty, ref segment) => match ty.node { hir::TyKind::Path(ref inner_path) => { print_path(inner_path, first); if *first { *first = false; } else { print!(", "); } print!("{:?}", segment.ident.as_str()); }, ref other => print!("/* unimplemented: {:?}*/", other), }, } }
42.407806
115
0.460535
714ba50814cc02ad94700b38c323846e51e6e7ba
90
//! Cargo Command Implementation use crate::command; pub struct Cargo; command!(Cargo);
12.857143
32
0.744444
5631e4cf0c8491818737e84db3ba038b5e013338
15,566
use serde_json::Value as jsonValue; use std::env; use std::fmt; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use structopt::StructOpt; use toml::Value; use walkdir::{DirEntry, WalkDir}; mod book; use book::Chapter; use book::Format; #[derive(Debug, PartialEq)] enum SummaryError {} impl fmt::Display for SummaryError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "There is an error: {}", self) } } type Result<T> = std::result::Result<T, Box<SummaryError>>; #[derive(StructOpt, Debug)] #[structopt()] struct Opt { /// Activate debug mode #[structopt(name = "debug", short, long)] debug: bool, // The number of occurrences of the `v/verbose` flag /// Verbose mode (-v, -vv, -vvv) #[structopt(short = "v", long = "verbose", parse(from_occurrences))] verbose: u8, /// Title from md file header? #[structopt(name = "mdheader", short, long)] mdheader: bool, /// Format md/git book #[structopt(name = "format", short, long, default_value = "md")] format: Format, /// Title for summary #[structopt(name = "title", short, long, default_value = "Summary")] title: String, /// Start with following chapters (space seperate) #[structopt(name = "sort", short, long)] sort: Option<Vec<String>>, /// Output file #[structopt(name = "outputfile", short, long, default_value = "SUMMARY.md")] outputfile: String, /// Notes dir where to parse all your notes from #[structopt(name = "notesdir", short, long, default_value = ".")] dir: PathBuf, /// Overwrite existing SUMMARY.md file #[structopt(name = "yes", short, long = "overwrite")] yes: bool, } fn main() { let mut opt = Opt::from_args(); // print opt in verbose level 3 if opt.verbose > 2 { println!("{:?}", opt); println!("{:?}", env::current_dir().unwrap().display()); } // parse book.js OR book.toml match opt.format { Format::Md(_) => parse_config_file(&format!("{}{}", opt.dir.display(), "/book.toml"), &mut opt), Format::Git(_) => { parse_config_file(&format!("{}{}", opt.dir.display(), "/book.json"), &mut opt); parse_config_file(&format!("{}{}", opt.dir.display(), "/book.js"), &mut opt); }, } if opt.dir == PathBuf::from("./") { opt.dir = env::current_dir().unwrap(); } if !opt.dir.is_dir() { eprintln!("Error: Path {} not found!", opt.dir.display()); std::process::exit(1) } let entries = match get_dir(&opt.dir, &opt.outputfile) { Ok(e) => e, Err(err) => { eprintln!("Error: {:?}", err); std::process::exit(1) } }; // SUMMARY.md file check if exists if Path::new(&format!("{}/{}", &opt.dir.display(), &opt.outputfile)).exists() && !opt.yes { loop { println!( "File {} already exists, do you want to overwrite it? [Y/n]", &opt.outputfile ); let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(_) if &input == "y\n" || &input == "Y\n" || &input == "\n" => break, Ok(_) if &input == "n\n" || &input == "N\n" => return, _ => {} } } } if opt.verbose > 2 { dbg!(&entries); } let book = Chapter::new(opt.title, &entries); create_file( &opt.dir.to_str().unwrap(), &opt.outputfile, // &book.get_summary_file(&opt.format), &book.get_summary_file(&opt.format, &opt.sort), ); if opt.verbose > 2 { dbg!(&book); } } fn is_hidden(entry: &DirEntry) -> bool { entry .file_name() .to_str() .map(|s| s.starts_with('.')) .unwrap_or(false) } fn get_dir(dir: &PathBuf, outputfile: &str) -> Result<Vec<String>> { let mut entries: Vec<String> = vec![]; for direntry in WalkDir::new(dir) .sort_by(|a, b| a.file_name().cmp(b.file_name())) .into_iter() .filter_entry(|e| !is_hidden(e)) .filter_map(|e| e.ok()) { // entry without: // - given root folder // - plain dirnames // - not md files // - not SUMMARY.md file let entry = direntry.path().strip_prefix(dir).unwrap().to_str().unwrap(); if !entry.is_empty() && !entry.eq(outputfile) && !entry.to_lowercase().eq("readme.md") && entry.contains(".md") { entries.push(entry.to_owned()); } } Ok(entries) } fn parse_config_file(path: &str, opt: &mut Opt) { let path = Path::new(path); if !path.exists() { if opt.verbose > 2 { eprintln!("Book config file {} not found.", path.display()); } return; } let mut file = match File::open(&path) { Err(why) => panic!( "Error: Couldn't open {}: {}", path.display(), why.to_string() ), Ok(file) => file, }; let mut content = String::new(); if let Err(why) = file.read_to_string(&mut content) { panic!( "Error: Couldn't read {}: {}", path.display(), why.to_string() ) } if opt.verbose > 2 { println!("Found book config file: {}", path.display()); } let ext: &str = path.extension().unwrap().to_str().unwrap(); match ext { "toml" => { let values = content.parse::<Value>().unwrap(); if opt.dir.to_str().eq(&Some(".")) { if let Some(src) = values["book"]["src"].as_str() { if opt.verbose > 2 { println!("Found `src` in book.toml: {}", src); } opt.dir = PathBuf::from(src); } } if opt.title.eq("Summary") { if let Some(title) = values["book"]["title"].as_str() { if opt.verbose > 2 { println!("Found `title` in book.toml: {}", title); } opt.title = title.to_string(); } } } "js" | "json" => { let values: jsonValue = serde_json::from_str(&content).unwrap(); if opt.dir.to_str().eq(&Some(".")) { if let Some(src) = values["root"].as_str() { if opt.verbose > 2 { println!("Found `root` in book.{}: {}", ext, src); } opt.dir = PathBuf::from(src); } } if opt.title.eq("Summary") { if let Some(title) = values["title"].as_str() { if opt.verbose > 2 { println!("Found `title` in book.{}: {}", ext, title); } opt.title = title.to_string(); } } } _ => {} } } fn create_file(path: &str, filename: &str, content: &str) { let filepath = format!("{}/{}", path, filename); let path = Path::new(&filepath); let display = path.display(); // Open a file in write-only mode, returns `io::Result<File>` let mut file = match File::create(&path) { Err(why) => panic!("Couldn't create {}: {}", display, why.to_string()), Ok(file) => file, }; // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>` match file.write_all(content.as_bytes()) { Err(why) => panic!("Couldn't write to {}: {}", display, why.to_string()), Ok(_) => println!("Successfully create {}", display), } } /* ------------------------- TEST --------------------------------- */ #[cfg(test)] mod tests { use super::*; const TITLE: &str = "Summary"; const FORMAT: Format = Format::Git('*'); // # get file list: no hidden files, filepaths from given folder as root #[test] fn get_file_list_test() { let expected = Ok(vec![ "about.md".to_string(), "chapter1/FILE.md".to_string(), "chapter1/file1.md".to_string(), "chapter2/FILE1.md".to_string(), "chapter2/README.md".to_string(), "chapter2/file2.md".to_string(), "chapter2/subchap/info.md".to_string(), "chapter3/file1.md".to_string(), "chapter3/file2.md".to_string(), "chapter3/file3.md".to_string(), ]); assert_eq!( expected, get_dir(&PathBuf::from(r"./examples/gitbook/book"), &"SUMMARY.md") ); } #[test] fn create_struct_empty_test() { // # empty list let input: Vec<String> = vec![]; let expected: Chapter = Chapter { name: TITLE.to_string(), files: vec![], chapter: vec![], }; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book); } #[test] fn create_struct_onefile_test() { // # only one file let input: Vec<String> = vec!["file.md".to_string()]; let expected: Chapter = Chapter { name: TITLE.to_string(), files: vec!["file.md".to_string()], chapter: vec![], }; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book); } #[test] fn create_struct_onechapter_test() { // # only one chapter let input: Vec<String> = vec!["chapter1/file1.md".to_string()]; let expected: Chapter = Chapter { name: TITLE.to_string(), files: vec![], chapter: vec![Chapter { name: "chapter1".to_string(), files: vec!["chapter1/file1.md".to_string()], chapter: vec![], }], }; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book); } #[test] fn create_struct_subchapter_test() { // # chapter with subchapters let input: Vec<String> = vec![ "chapter1/file1.md".to_string(), "chapter1/subchap/file1.md".to_string(), ]; let expected: Chapter = Chapter { name: TITLE.to_string(), files: vec![], chapter: vec![Chapter { name: "chapter1".to_string(), files: vec!["chapter1/file1.md".to_string()], chapter: vec![Chapter { name: "subchap".to_string(), files: vec!["chapter1/subchap/file1.md".to_string()], chapter: vec![], }], }], }; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book); } // 2. Markdown output for entry in chapter // - format (md/git) // - titlecase for entry // - remove pre numbers in entry #[test] fn md_output_onefile_test() { let list_char: char = match FORMAT { Format::Md(c) => c, Format::Git(c) => c, }; // only one file let input: Vec<String> = vec!["file1.md".to_string()]; let expected: &str = &format!("# {}\n\n{} [File1](file1.md)\n", TITLE, list_char); let book = Chapter::new(TITLE.to_string(), &input); dbg!(&book); assert_eq!(expected, book.get_summary_file(&FORMAT, &None)); } #[test] fn md_output_onechapter_test() { let list_char: char = match FORMAT { Format::Md(c) => c, Format::Git(c) => c, }; // only one file let input: Vec<String> = vec!["file1.md".to_string(), "chapter1/file1.md".to_string()]; let expected: &str = &format!( "# {0}\n\n{1} [File1](file1.md)\n{1} Chapter1\n {1} [File1](chapter1/file1.md)\n", TITLE, list_char ); let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book.get_summary_file(&FORMAT, &None)); } #[test] fn md_output_subchapter_test() { let list_char: char = match FORMAT { Format::Md(c) => c, Format::Git(c) => c, }; // only one file let input: Vec<String> = vec![ "chapter1/file1.md".to_string(), "chapter1/subchap/file1.md".to_string(), ]; let expected: &str = &format!( "# {0}\n\n{1} Chapter1\n {1} [File1](chapter1/file1.md)\n {1} Subchap\n {1} [File1](chapter1/subchap/file1.md)\n", TITLE, list_char ); let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book.get_summary_file(&FORMAT, &None)); } #[test] fn md_simple_structure_test() { let input = vec![ "part1/README.md".to_string(), "part1/WritingIsGood.md".to_string(), "part1/GitbookIsNice.md".to_string(), "part2/README.md".to_string(), "part2/First_part_of_part_2.md".to_string(), "part2/Second_part_of_part_2.md".to_string(), ]; let expected = r#"# Summary * [Part1](part1/README.md) * [WritingIsGood](part1/WritingIsGood.md) * [GitbookIsNice](part1/GitbookIsNice.md) * [Part2](part2/README.md) * [First Part of Part 2](part2/First_part_of_part_2.md) * [Second Part of Part 2](part2/Second_part_of_part_2.md) "#; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!(expected, book.get_summary_file(&FORMAT, &None)); } #[test] fn parse_config_test() { let bookjson = "./examples/gitbook/book.json"; let booktoml = "./examples/mdbook/book.toml"; // opt with default values let mut opt = Opt { debug: false, verbose: 3, mdheader: false, format: FORMAT, title: "Summary".to_string(), sort: None, outputfile: "SUMMARY.md".to_string(), dir: PathBuf::from("."), yes: true, }; parse_config_file(booktoml, &mut opt); assert_eq!("src", format!("{}", opt.dir.display())); assert_eq!("MyMDBook", opt.title); opt.dir = PathBuf::from("."); opt.title = "Summary".to_string(); parse_config_file(bookjson, &mut opt); assert_eq!("book", format!("{}", opt.dir.display())); assert_eq!("My title", opt.title); } #[test] fn sort_chapter_test() { let input = vec![ "part1/README.md".to_string(), "part1/WritingIsGood.md".to_string(), "part2/GitbookIsNice.md".to_string(), "part2/README.md".to_string(), "part3/file.md".to_string(), "part4/file.md".to_string(), ]; let expected = r#"# Summary * Part4 * [File](part4/file.md) * Part3 * [File](part3/file.md) * [Part1](part1/README.md) * [WritingIsGood](part1/WritingIsGood.md) * [Part2](part2/README.md) * [GitbookIsNice](part2/GitbookIsNice.md) "#; let book = Chapter::new(TITLE.to_string(), &input); assert_eq!( expected, book.get_summary_file( &FORMAT, &Some(vec![ "PART4".to_string(), "part5".to_string(), "part3".to_string() ]) ) ); } }
29.095327
139
0.504882
f7082b96788133090222471cc65db1d77e75c1be
5,890
use makepad_render::*; #[derive(Clone, DrawQuad)] #[repr(C)] struct ButtonQuad { #[default_shader(self::shader_quad)] some: f32, base: DrawQuad, counter: f32, } #[derive(Clone, DrawText)] #[repr(C)] struct ButtonText { #[default_shader(self::shader_text)] base: DrawText, counter: f32, } pub struct BareExampleApp { window: Window, pass: Pass, color_texture: Texture, main_view: View, quad: ButtonQuad, text: ButtonText, count: f32 } impl BareExampleApp { pub fn new(cx: &mut Cx) -> Self { Self { window: Window::new(cx), pass: Pass::default(), color_texture: Texture::new(cx), quad: ButtonQuad::new(cx, default_shader!()), text: ButtonText::new(cx, default_shader!()), main_view: View::new(), count: 0. } } pub fn style(cx: &mut Cx) { ButtonQuad::register_draw_input(cx); ButtonText::register_draw_input(cx); live_body!(cx, r#" self::shader_quad: Shader { use makepad_render::drawquad::shader::*; draw_input: self::ButtonQuad; fn pixel() -> vec4 { return mix(#f00, #0f0, abs(sin(counter + some))); } } self::shader_text: Shader { use makepad_render::drawtext::shader::*; draw_input: self::ButtonText; fn get_color() -> vec4 { //return #f; return mix(#f00, #0f0, abs(sin(counter + char_offset * 0.2))); } } "#); } pub fn handle_app(&mut self, _cx: &mut Cx, event: &mut Event) { match event { Event::Construct => { }, Event::FingerMove(fm) => { self.count = fm.abs.x * 0.01; }, _ => () } } pub fn draw_app(&mut self, cx: &mut Cx) { self.window.begin_window(cx); self.pass.begin_pass(cx); self.pass.add_color_texture(cx, self.color_texture, ClearColor::ClearWith(Vec4::color("300"))); if self.main_view.begin_view(cx, Layout::default()).is_ok() { cx.profile_start(1); //let x = 1.0f32; //let y = x.sin(); self.quad.counter = 0.; self.quad.begin_many(cx); //self.quad.base.shader = live_shader!(cx, self::bg_shader); //println!("{}", self.quad.base.slots); self.text.counter += 0.01; //self.text.begin_many(cx); self.quad.counter = 0.; self.quad.some += 1.1; let msg = format!("HELLO WORLD"); for i in 0..1000000 { let v = 0.5 * (i as f32); self.quad.counter += 0.01; //= (i as f32).sin(); let x = 0.0;//400. + (v + self.count).sin() * 400.; let y = 0.0;//400. + (v * 1.12 + self.count * 18.).cos() * 400.; self.quad.draw_quad_abs(cx, Rect {pos: vec2(x, y), size: vec2(10., 10.0)}); //self.text.draw_text_abs(cx, vec2(x, y), &msg); } //self.text.end_many(cx); self.quad.end_many(cx); self.count += 0.001; cx.profile_end(1); /* cx.profile_start(2); for i in 0..2500000 { let v = 0.3 * (i as f32); self.quad.draw_quad_scratch(Rect { x: 300. + (v + self.count).sin() * 100., y: 300. + (v + self.count * 8.).cos() * 100., w: 10., h: 10. }); self.quad.scratch[9] = v * 2. + self.count * 10.; self.quad.draw_quad_scratch_final(cx, 10); } self.count += 0.001; cx.profile_end(2); cx.profile_start(3); let inst = cx.new_instance(self.quad.shader, None, 1); let mut data = Vec::new(); for i in 0..2500000 { let inst_array = inst.get_instance_array(cx); std::mem::swap(&mut data, inst_array); let v = 0.3 * (i as f32); self.quad.draw_quad_scratch(Rect { x: 300. + (v + self.count).sin() * 100., y: 300. + (v + self.count * 8.).cos() * 100., w: 10., h: 10. }); self.quad.scratch[9] = v * 2. + self.count * 10.; data.extend_from_slice(&self.quad.scratch[0..10]); std::mem::swap(inst_array, &mut data); } self.count += 0.001; cx.profile_end(3); */ /* cx.profile_start(4); let inst = cx.new_instance(self.quad3.shader, None, 1); let inst_array = inst.get_instance_array(cx); for i in 0..2500000 { let v = 0.3 * (i as f32); self.quad3.rect = Rect { x: 300. + (v + self.count).sin() * 100., y: 300. + (v + self.count * 8.).cos() * 100., w: 10., h: 10. }; self.quad3.count = v * 2. + self.count * 10.; self.quad3.draw_quad_direct(inst_array); //inst_array.push(); } self.count += 0.001; cx.profile_end(4); */ self.main_view.redraw_view(cx); self.main_view.end_view(cx); } self.pass.end_pass(cx); self.window.end_window(cx); } }
32.362637
103
0.436503
e82fd57de84d4721ba63f6e5ed4698d793122f74
3,950
//! Driver for rust-analyzer. //! //! Based on cli flags, either spawns an LSP server, or runs a batch analysis mod args; use lsp_server::Connection; use rust_analyzer::{cli, config::Config, from_json, Result}; use crate::args::HelpPrinted; fn main() -> Result<()> { setup_logging()?; let args = match args::Args::parse()? { Ok(it) => it, Err(HelpPrinted) => return Ok(()), }; match args.command { args::Command::Parse { no_dump } => cli::parse(no_dump)?, args::Command::Symbols => cli::symbols()?, args::Command::Highlight { rainbow } => cli::highlight(rainbow)?, args::Command::Stats { randomize, memory_usage, only, with_deps, path, load_output_dirs, with_proc_macro, } => cli::analysis_stats( args.verbosity, memory_usage, path.as_ref(), only.as_ref().map(String::as_ref), with_deps, randomize, load_output_dirs, with_proc_macro, )?, args::Command::Bench { path, what, load_output_dirs, with_proc_macro } => { cli::analysis_bench( args.verbosity, path.as_ref(), what, load_output_dirs, with_proc_macro, )? } args::Command::Diagnostics { path, load_output_dirs, with_proc_macro, all } => { cli::diagnostics(path.as_ref(), load_output_dirs, with_proc_macro, all)? } args::Command::ProcMacro => run_proc_macro_srv()?, args::Command::RunServer => run_server()?, args::Command::Version => println!("rust-analyzer {}", env!("REV")), } Ok(()) } fn setup_logging() -> Result<()> { std::env::set_var("RUST_BACKTRACE", "short"); env_logger::try_init_from_env("RA_LOG")?; ra_prof::init(); Ok(()) } fn run_proc_macro_srv() -> Result<()> { ra_proc_macro_srv::cli::run()?; Ok(()) } fn run_server() -> Result<()> { log::info!("lifecycle: server started"); let (connection, io_threads) = Connection::stdio(); let (initialize_id, initialize_params) = connection.initialize_start()?; let initialize_params = from_json::<lsp_types::InitializeParams>("InitializeParams", initialize_params)?; let server_capabilities = rust_analyzer::server_capabilities(&initialize_params.capabilities); let initialize_result = lsp_types::InitializeResult { capabilities: server_capabilities, server_info: Some(lsp_types::ServerInfo { name: String::from("rust-analyzer"), version: Some(String::from(env!("REV"))), }), }; let initialize_result = serde_json::to_value(initialize_result).unwrap(); connection.initialize_finish(initialize_id, initialize_result)?; if let Some(client_info) = initialize_params.client_info { log::info!("Client '{}' {}", client_info.name, client_info.version.unwrap_or_default()); } let cwd = std::env::current_dir()?; let root = initialize_params.root_uri.and_then(|it| it.to_file_path().ok()).unwrap_or(cwd); let workspace_roots = initialize_params .workspace_folders .map(|workspaces| { workspaces.into_iter().filter_map(|it| it.uri.to_file_path().ok()).collect::<Vec<_>>() }) .filter(|workspaces| !workspaces.is_empty()) .unwrap_or_else(|| vec![root]); let config = { let mut config = Config::default(); if let Some(value) = &initialize_params.initialization_options { config.update(value); } config.update_caps(&initialize_params.capabilities); config }; rust_analyzer::main_loop(workspace_roots, config, connection)?; log::info!("shutting down IO..."); io_threads.join()?; log::info!("... IO is down"); Ok(()) }
30.859375
98
0.594177
5bd12542853fcf79945ba32a8883f2f85cc5a6c9
161,564
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>The metadata that you apply to a resource to help you categorize and organize them. /// Each tag consists of a key and an optional value, both of which you define. /// Tag keys can have a maximum character length of 128 characters, and tag values can have /// a maximum length of 256 characters.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Tag { /// <p>One part of a key-value pair that make up a tag. A <code>key</code> is a general label /// that acts like a category for more specific tag values.</p> pub key: std::option::Option<std::string::String>, /// <p>The optional part of a key-value pair that make up a tag. A <code>value</code> acts as /// a descriptor within a tag category (key).</p> pub value: std::option::Option<std::string::String>, } impl Tag { /// <p>One part of a key-value pair that make up a tag. A <code>key</code> is a general label /// that acts like a category for more specific tag values.</p> pub fn key(&self) -> std::option::Option<&str> { self.key.as_deref() } /// <p>The optional part of a key-value pair that make up a tag. A <code>value</code> acts as /// a descriptor within a tag category (key).</p> pub fn value(&self) -> std::option::Option<&str> { self.value.as_deref() } } impl std::fmt::Debug for Tag { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Tag"); formatter.field("key", &self.key); formatter.field("value", &self.value); formatter.finish() } } /// See [`Tag`](crate::model::Tag) pub mod tag { /// A builder for [`Tag`](crate::model::Tag) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) key: std::option::Option<std::string::String>, pub(crate) value: std::option::Option<std::string::String>, } impl Builder { /// <p>One part of a key-value pair that make up a tag. A <code>key</code> is a general label /// that acts like a category for more specific tag values.</p> pub fn key(mut self, input: impl Into<std::string::String>) -> Self { self.key = Some(input.into()); self } /// <p>One part of a key-value pair that make up a tag. A <code>key</code> is a general label /// that acts like a category for more specific tag values.</p> pub fn set_key(mut self, input: std::option::Option<std::string::String>) -> Self { self.key = input; self } /// <p>The optional part of a key-value pair that make up a tag. A <code>value</code> acts as /// a descriptor within a tag category (key).</p> pub fn value(mut self, input: impl Into<std::string::String>) -> Self { self.value = Some(input.into()); self } /// <p>The optional part of a key-value pair that make up a tag. A <code>value</code> acts as /// a descriptor within a tag category (key).</p> pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self { self.value = input; self } /// Consumes the builder and constructs a [`Tag`](crate::model::Tag) pub fn build(self) -> crate::model::Tag { crate::model::Tag { key: self.key, value: self.value, } } } } impl Tag { /// Creates a new builder-style object to manufacture [`Tag`](crate::model::Tag) pub fn builder() -> crate::model::tag::Builder { crate::model::tag::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum LifecyclePolicyPreviewStatus { #[allow(missing_docs)] // documentation missing in model Complete, #[allow(missing_docs)] // documentation missing in model Expired, #[allow(missing_docs)] // documentation missing in model Failed, #[allow(missing_docs)] // documentation missing in model InProgress, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for LifecyclePolicyPreviewStatus { fn from(s: &str) -> Self { match s { "COMPLETE" => LifecyclePolicyPreviewStatus::Complete, "EXPIRED" => LifecyclePolicyPreviewStatus::Expired, "FAILED" => LifecyclePolicyPreviewStatus::Failed, "IN_PROGRESS" => LifecyclePolicyPreviewStatus::InProgress, other => LifecyclePolicyPreviewStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for LifecyclePolicyPreviewStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(LifecyclePolicyPreviewStatus::from(s)) } } impl LifecyclePolicyPreviewStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { LifecyclePolicyPreviewStatus::Complete => "COMPLETE", LifecyclePolicyPreviewStatus::Expired => "EXPIRED", LifecyclePolicyPreviewStatus::Failed => "FAILED", LifecyclePolicyPreviewStatus::InProgress => "IN_PROGRESS", LifecyclePolicyPreviewStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["COMPLETE", "EXPIRED", "FAILED", "IN_PROGRESS"] } } impl AsRef<str> for LifecyclePolicyPreviewStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>The current status of an image scan.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageScanStatus { /// <p>The current state of an image scan.</p> pub status: std::option::Option<crate::model::ScanStatus>, /// <p>The description of the image scan status.</p> pub description: std::option::Option<std::string::String>, } impl ImageScanStatus { /// <p>The current state of an image scan.</p> pub fn status(&self) -> std::option::Option<&crate::model::ScanStatus> { self.status.as_ref() } /// <p>The description of the image scan status.</p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } } impl std::fmt::Debug for ImageScanStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageScanStatus"); formatter.field("status", &self.status); formatter.field("description", &self.description); formatter.finish() } } /// See [`ImageScanStatus`](crate::model::ImageScanStatus) pub mod image_scan_status { /// A builder for [`ImageScanStatus`](crate::model::ImageScanStatus) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) status: std::option::Option<crate::model::ScanStatus>, pub(crate) description: std::option::Option<std::string::String>, } impl Builder { /// <p>The current state of an image scan.</p> pub fn status(mut self, input: crate::model::ScanStatus) -> Self { self.status = Some(input); self } /// <p>The current state of an image scan.</p> pub fn set_status(mut self, input: std::option::Option<crate::model::ScanStatus>) -> Self { self.status = input; self } /// <p>The description of the image scan status.</p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p>The description of the image scan status.</p> pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self { self.description = input; self } /// Consumes the builder and constructs a [`ImageScanStatus`](crate::model::ImageScanStatus) pub fn build(self) -> crate::model::ImageScanStatus { crate::model::ImageScanStatus { status: self.status, description: self.description, } } } } impl ImageScanStatus { /// Creates a new builder-style object to manufacture [`ImageScanStatus`](crate::model::ImageScanStatus) pub fn builder() -> crate::model::image_scan_status::Builder { crate::model::image_scan_status::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ScanStatus { #[allow(missing_docs)] // documentation missing in model Complete, #[allow(missing_docs)] // documentation missing in model Failed, #[allow(missing_docs)] // documentation missing in model InProgress, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ScanStatus { fn from(s: &str) -> Self { match s { "COMPLETE" => ScanStatus::Complete, "FAILED" => ScanStatus::Failed, "IN_PROGRESS" => ScanStatus::InProgress, other => ScanStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for ScanStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ScanStatus::from(s)) } } impl ScanStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ScanStatus::Complete => "COMPLETE", ScanStatus::Failed => "FAILED", ScanStatus::InProgress => "IN_PROGRESS", ScanStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["COMPLETE", "FAILED", "IN_PROGRESS"] } } impl AsRef<str> for ScanStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An object with identifying information for an image in an Amazon ECR repository.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageIdentifier { /// <p>The <code>sha256</code> digest of the image manifest.</p> pub image_digest: std::option::Option<std::string::String>, /// <p>The tag used for the image.</p> pub image_tag: std::option::Option<std::string::String>, } impl ImageIdentifier { /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(&self) -> std::option::Option<&str> { self.image_digest.as_deref() } /// <p>The tag used for the image.</p> pub fn image_tag(&self) -> std::option::Option<&str> { self.image_tag.as_deref() } } impl std::fmt::Debug for ImageIdentifier { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageIdentifier"); formatter.field("image_digest", &self.image_digest); formatter.field("image_tag", &self.image_tag); formatter.finish() } } /// See [`ImageIdentifier`](crate::model::ImageIdentifier) pub mod image_identifier { /// A builder for [`ImageIdentifier`](crate::model::ImageIdentifier) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) image_digest: std::option::Option<std::string::String>, pub(crate) image_tag: std::option::Option<std::string::String>, } impl Builder { /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(mut self, input: impl Into<std::string::String>) -> Self { self.image_digest = Some(input.into()); self } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn set_image_digest(mut self, input: std::option::Option<std::string::String>) -> Self { self.image_digest = input; self } /// <p>The tag used for the image.</p> pub fn image_tag(mut self, input: impl Into<std::string::String>) -> Self { self.image_tag = Some(input.into()); self } /// <p>The tag used for the image.</p> pub fn set_image_tag(mut self, input: std::option::Option<std::string::String>) -> Self { self.image_tag = input; self } /// Consumes the builder and constructs a [`ImageIdentifier`](crate::model::ImageIdentifier) pub fn build(self) -> crate::model::ImageIdentifier { crate::model::ImageIdentifier { image_digest: self.image_digest, image_tag: self.image_tag, } } } } impl ImageIdentifier { /// Creates a new builder-style object to manufacture [`ImageIdentifier`](crate::model::ImageIdentifier) pub fn builder() -> crate::model::image_identifier::Builder { crate::model::image_identifier::Builder::default() } } /// <p>The replication configuration for a registry.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ReplicationConfiguration { /// <p>An array of objects representing the replication destinations and repository filters /// for a replication configuration.</p> pub rules: std::option::Option<std::vec::Vec<crate::model::ReplicationRule>>, } impl ReplicationConfiguration { /// <p>An array of objects representing the replication destinations and repository filters /// for a replication configuration.</p> pub fn rules(&self) -> std::option::Option<&[crate::model::ReplicationRule]> { self.rules.as_deref() } } impl std::fmt::Debug for ReplicationConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ReplicationConfiguration"); formatter.field("rules", &self.rules); formatter.finish() } } /// See [`ReplicationConfiguration`](crate::model::ReplicationConfiguration) pub mod replication_configuration { /// A builder for [`ReplicationConfiguration`](crate::model::ReplicationConfiguration) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) rules: std::option::Option<std::vec::Vec<crate::model::ReplicationRule>>, } impl Builder { /// Appends an item to `rules`. /// /// To override the contents of this collection use [`set_rules`](Self::set_rules). /// /// <p>An array of objects representing the replication destinations and repository filters /// for a replication configuration.</p> pub fn rules(mut self, input: impl Into<crate::model::ReplicationRule>) -> Self { let mut v = self.rules.unwrap_or_default(); v.push(input.into()); self.rules = Some(v); self } /// <p>An array of objects representing the replication destinations and repository filters /// for a replication configuration.</p> pub fn set_rules( mut self, input: std::option::Option<std::vec::Vec<crate::model::ReplicationRule>>, ) -> Self { self.rules = input; self } /// Consumes the builder and constructs a [`ReplicationConfiguration`](crate::model::ReplicationConfiguration) pub fn build(self) -> crate::model::ReplicationConfiguration { crate::model::ReplicationConfiguration { rules: self.rules } } } } impl ReplicationConfiguration { /// Creates a new builder-style object to manufacture [`ReplicationConfiguration`](crate::model::ReplicationConfiguration) pub fn builder() -> crate::model::replication_configuration::Builder { crate::model::replication_configuration::Builder::default() } } /// <p>An array of objects representing the replication destinations and repository filters /// for a replication configuration.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ReplicationRule { /// <p>An array of objects representing the destination for a replication rule.</p> pub destinations: std::option::Option<std::vec::Vec<crate::model::ReplicationDestination>>, /// <p>An array of objects representing the filters for a replication rule. Specifying a /// repository filter for a replication rule provides a method for controlling which /// repositories in a private registry are replicated.</p> pub repository_filters: std::option::Option<std::vec::Vec<crate::model::RepositoryFilter>>, } impl ReplicationRule { /// <p>An array of objects representing the destination for a replication rule.</p> pub fn destinations(&self) -> std::option::Option<&[crate::model::ReplicationDestination]> { self.destinations.as_deref() } /// <p>An array of objects representing the filters for a replication rule. Specifying a /// repository filter for a replication rule provides a method for controlling which /// repositories in a private registry are replicated.</p> pub fn repository_filters(&self) -> std::option::Option<&[crate::model::RepositoryFilter]> { self.repository_filters.as_deref() } } impl std::fmt::Debug for ReplicationRule { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ReplicationRule"); formatter.field("destinations", &self.destinations); formatter.field("repository_filters", &self.repository_filters); formatter.finish() } } /// See [`ReplicationRule`](crate::model::ReplicationRule) pub mod replication_rule { /// A builder for [`ReplicationRule`](crate::model::ReplicationRule) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) destinations: std::option::Option<std::vec::Vec<crate::model::ReplicationDestination>>, pub(crate) repository_filters: std::option::Option<std::vec::Vec<crate::model::RepositoryFilter>>, } impl Builder { /// Appends an item to `destinations`. /// /// To override the contents of this collection use [`set_destinations`](Self::set_destinations). /// /// <p>An array of objects representing the destination for a replication rule.</p> pub fn destinations( mut self, input: impl Into<crate::model::ReplicationDestination>, ) -> Self { let mut v = self.destinations.unwrap_or_default(); v.push(input.into()); self.destinations = Some(v); self } /// <p>An array of objects representing the destination for a replication rule.</p> pub fn set_destinations( mut self, input: std::option::Option<std::vec::Vec<crate::model::ReplicationDestination>>, ) -> Self { self.destinations = input; self } /// Appends an item to `repository_filters`. /// /// To override the contents of this collection use [`set_repository_filters`](Self::set_repository_filters). /// /// <p>An array of objects representing the filters for a replication rule. Specifying a /// repository filter for a replication rule provides a method for controlling which /// repositories in a private registry are replicated.</p> pub fn repository_filters( mut self, input: impl Into<crate::model::RepositoryFilter>, ) -> Self { let mut v = self.repository_filters.unwrap_or_default(); v.push(input.into()); self.repository_filters = Some(v); self } /// <p>An array of objects representing the filters for a replication rule. Specifying a /// repository filter for a replication rule provides a method for controlling which /// repositories in a private registry are replicated.</p> pub fn set_repository_filters( mut self, input: std::option::Option<std::vec::Vec<crate::model::RepositoryFilter>>, ) -> Self { self.repository_filters = input; self } /// Consumes the builder and constructs a [`ReplicationRule`](crate::model::ReplicationRule) pub fn build(self) -> crate::model::ReplicationRule { crate::model::ReplicationRule { destinations: self.destinations, repository_filters: self.repository_filters, } } } } impl ReplicationRule { /// Creates a new builder-style object to manufacture [`ReplicationRule`](crate::model::ReplicationRule) pub fn builder() -> crate::model::replication_rule::Builder { crate::model::replication_rule::Builder::default() } } /// <p>The filter settings used with image replication. Specifying a repository filter to a /// replication rule provides a method for controlling which repositories in a private /// registry are replicated. If no repository filter is specified, all images in the /// repository are replicated.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RepositoryFilter { /// <p>The repository filter details. When the <code>PREFIX_MATCH</code> filter type is /// specified, this value is required and should be the repository name prefix to configure /// replication for.</p> pub filter: std::option::Option<std::string::String>, /// <p>The repository filter type. The only supported value is <code>PREFIX_MATCH</code>, /// which is a repository name prefix specified with the <code>filter</code> /// parameter.</p> pub filter_type: std::option::Option<crate::model::RepositoryFilterType>, } impl RepositoryFilter { /// <p>The repository filter details. When the <code>PREFIX_MATCH</code> filter type is /// specified, this value is required and should be the repository name prefix to configure /// replication for.</p> pub fn filter(&self) -> std::option::Option<&str> { self.filter.as_deref() } /// <p>The repository filter type. The only supported value is <code>PREFIX_MATCH</code>, /// which is a repository name prefix specified with the <code>filter</code> /// parameter.</p> pub fn filter_type(&self) -> std::option::Option<&crate::model::RepositoryFilterType> { self.filter_type.as_ref() } } impl std::fmt::Debug for RepositoryFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RepositoryFilter"); formatter.field("filter", &self.filter); formatter.field("filter_type", &self.filter_type); formatter.finish() } } /// See [`RepositoryFilter`](crate::model::RepositoryFilter) pub mod repository_filter { /// A builder for [`RepositoryFilter`](crate::model::RepositoryFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) filter: std::option::Option<std::string::String>, pub(crate) filter_type: std::option::Option<crate::model::RepositoryFilterType>, } impl Builder { /// <p>The repository filter details. When the <code>PREFIX_MATCH</code> filter type is /// specified, this value is required and should be the repository name prefix to configure /// replication for.</p> pub fn filter(mut self, input: impl Into<std::string::String>) -> Self { self.filter = Some(input.into()); self } /// <p>The repository filter details. When the <code>PREFIX_MATCH</code> filter type is /// specified, this value is required and should be the repository name prefix to configure /// replication for.</p> pub fn set_filter(mut self, input: std::option::Option<std::string::String>) -> Self { self.filter = input; self } /// <p>The repository filter type. The only supported value is <code>PREFIX_MATCH</code>, /// which is a repository name prefix specified with the <code>filter</code> /// parameter.</p> pub fn filter_type(mut self, input: crate::model::RepositoryFilterType) -> Self { self.filter_type = Some(input); self } /// <p>The repository filter type. The only supported value is <code>PREFIX_MATCH</code>, /// which is a repository name prefix specified with the <code>filter</code> /// parameter.</p> pub fn set_filter_type( mut self, input: std::option::Option<crate::model::RepositoryFilterType>, ) -> Self { self.filter_type = input; self } /// Consumes the builder and constructs a [`RepositoryFilter`](crate::model::RepositoryFilter) pub fn build(self) -> crate::model::RepositoryFilter { crate::model::RepositoryFilter { filter: self.filter, filter_type: self.filter_type, } } } } impl RepositoryFilter { /// Creates a new builder-style object to manufacture [`RepositoryFilter`](crate::model::RepositoryFilter) pub fn builder() -> crate::model::repository_filter::Builder { crate::model::repository_filter::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum RepositoryFilterType { #[allow(missing_docs)] // documentation missing in model PrefixMatch, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for RepositoryFilterType { fn from(s: &str) -> Self { match s { "PREFIX_MATCH" => RepositoryFilterType::PrefixMatch, other => RepositoryFilterType::Unknown(other.to_owned()), } } } impl std::str::FromStr for RepositoryFilterType { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(RepositoryFilterType::from(s)) } } impl RepositoryFilterType { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { RepositoryFilterType::PrefixMatch => "PREFIX_MATCH", RepositoryFilterType::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["PREFIX_MATCH"] } } impl AsRef<str> for RepositoryFilterType { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An array of objects representing the destination for a replication rule.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ReplicationDestination { /// <p>The Region to replicate to.</p> pub region: std::option::Option<std::string::String>, /// <p>The Amazon Web Services account ID of the Amazon ECR private registry to replicate to. When configuring /// cross-Region replication within your own registry, specify your own account ID.</p> pub registry_id: std::option::Option<std::string::String>, } impl ReplicationDestination { /// <p>The Region to replicate to.</p> pub fn region(&self) -> std::option::Option<&str> { self.region.as_deref() } /// <p>The Amazon Web Services account ID of the Amazon ECR private registry to replicate to. When configuring /// cross-Region replication within your own registry, specify your own account ID.</p> pub fn registry_id(&self) -> std::option::Option<&str> { self.registry_id.as_deref() } } impl std::fmt::Debug for ReplicationDestination { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ReplicationDestination"); formatter.field("region", &self.region); formatter.field("registry_id", &self.registry_id); formatter.finish() } } /// See [`ReplicationDestination`](crate::model::ReplicationDestination) pub mod replication_destination { /// A builder for [`ReplicationDestination`](crate::model::ReplicationDestination) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) region: std::option::Option<std::string::String>, pub(crate) registry_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The Region to replicate to.</p> pub fn region(mut self, input: impl Into<std::string::String>) -> Self { self.region = Some(input.into()); self } /// <p>The Region to replicate to.</p> pub fn set_region(mut self, input: std::option::Option<std::string::String>) -> Self { self.region = input; self } /// <p>The Amazon Web Services account ID of the Amazon ECR private registry to replicate to. When configuring /// cross-Region replication within your own registry, specify your own account ID.</p> pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_id = Some(input.into()); self } /// <p>The Amazon Web Services account ID of the Amazon ECR private registry to replicate to. When configuring /// cross-Region replication within your own registry, specify your own account ID.</p> pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.registry_id = input; self } /// Consumes the builder and constructs a [`ReplicationDestination`](crate::model::ReplicationDestination) pub fn build(self) -> crate::model::ReplicationDestination { crate::model::ReplicationDestination { region: self.region, registry_id: self.registry_id, } } } } impl ReplicationDestination { /// Creates a new builder-style object to manufacture [`ReplicationDestination`](crate::model::ReplicationDestination) pub fn builder() -> crate::model::replication_destination::Builder { crate::model::replication_destination::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ImageTagMutability { #[allow(missing_docs)] // documentation missing in model Immutable, #[allow(missing_docs)] // documentation missing in model Mutable, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ImageTagMutability { fn from(s: &str) -> Self { match s { "IMMUTABLE" => ImageTagMutability::Immutable, "MUTABLE" => ImageTagMutability::Mutable, other => ImageTagMutability::Unknown(other.to_owned()), } } } impl std::str::FromStr for ImageTagMutability { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ImageTagMutability::from(s)) } } impl ImageTagMutability { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ImageTagMutability::Immutable => "IMMUTABLE", ImageTagMutability::Mutable => "MUTABLE", ImageTagMutability::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["IMMUTABLE", "MUTABLE"] } } impl AsRef<str> for ImageTagMutability { fn as_ref(&self) -> &str { self.as_str() } } /// <p>The image scanning configuration for a repository.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageScanningConfiguration { /// <p>The setting that determines whether images are scanned after being pushed to a /// repository. If set to <code>true</code>, images will be scanned after being pushed. If /// this parameter is not specified, it will default to <code>false</code> and images will /// not be scanned unless a scan is manually started with the <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html">API_StartImageScan</a> API.</p> pub scan_on_push: bool, } impl ImageScanningConfiguration { /// <p>The setting that determines whether images are scanned after being pushed to a /// repository. If set to <code>true</code>, images will be scanned after being pushed. If /// this parameter is not specified, it will default to <code>false</code> and images will /// not be scanned unless a scan is manually started with the <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html">API_StartImageScan</a> API.</p> pub fn scan_on_push(&self) -> bool { self.scan_on_push } } impl std::fmt::Debug for ImageScanningConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageScanningConfiguration"); formatter.field("scan_on_push", &self.scan_on_push); formatter.finish() } } /// See [`ImageScanningConfiguration`](crate::model::ImageScanningConfiguration) pub mod image_scanning_configuration { /// A builder for [`ImageScanningConfiguration`](crate::model::ImageScanningConfiguration) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) scan_on_push: std::option::Option<bool>, } impl Builder { /// <p>The setting that determines whether images are scanned after being pushed to a /// repository. If set to <code>true</code>, images will be scanned after being pushed. If /// this parameter is not specified, it will default to <code>false</code> and images will /// not be scanned unless a scan is manually started with the <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html">API_StartImageScan</a> API.</p> pub fn scan_on_push(mut self, input: bool) -> Self { self.scan_on_push = Some(input); self } /// <p>The setting that determines whether images are scanned after being pushed to a /// repository. If set to <code>true</code>, images will be scanned after being pushed. If /// this parameter is not specified, it will default to <code>false</code> and images will /// not be scanned unless a scan is manually started with the <a href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_StartImageScan.html">API_StartImageScan</a> API.</p> pub fn set_scan_on_push(mut self, input: std::option::Option<bool>) -> Self { self.scan_on_push = input; self } /// Consumes the builder and constructs a [`ImageScanningConfiguration`](crate::model::ImageScanningConfiguration) pub fn build(self) -> crate::model::ImageScanningConfiguration { crate::model::ImageScanningConfiguration { scan_on_push: self.scan_on_push.unwrap_or_default(), } } } } impl ImageScanningConfiguration { /// Creates a new builder-style object to manufacture [`ImageScanningConfiguration`](crate::model::ImageScanningConfiguration) pub fn builder() -> crate::model::image_scanning_configuration::Builder { crate::model::image_scanning_configuration::Builder::default() } } /// <p>An object representing an Amazon ECR image.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Image { /// <p>The Amazon Web Services account ID associated with the registry containing the image.</p> pub registry_id: std::option::Option<std::string::String>, /// <p>The name of the repository associated with the image.</p> pub repository_name: std::option::Option<std::string::String>, /// <p>An object containing the image tag and image digest associated with an image.</p> pub image_id: std::option::Option<crate::model::ImageIdentifier>, /// <p>The image manifest associated with the image.</p> pub image_manifest: std::option::Option<std::string::String>, /// <p>The manifest media type of the image.</p> pub image_manifest_media_type: std::option::Option<std::string::String>, } impl Image { /// <p>The Amazon Web Services account ID associated with the registry containing the image.</p> pub fn registry_id(&self) -> std::option::Option<&str> { self.registry_id.as_deref() } /// <p>The name of the repository associated with the image.</p> pub fn repository_name(&self) -> std::option::Option<&str> { self.repository_name.as_deref() } /// <p>An object containing the image tag and image digest associated with an image.</p> pub fn image_id(&self) -> std::option::Option<&crate::model::ImageIdentifier> { self.image_id.as_ref() } /// <p>The image manifest associated with the image.</p> pub fn image_manifest(&self) -> std::option::Option<&str> { self.image_manifest.as_deref() } /// <p>The manifest media type of the image.</p> pub fn image_manifest_media_type(&self) -> std::option::Option<&str> { self.image_manifest_media_type.as_deref() } } impl std::fmt::Debug for Image { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Image"); formatter.field("registry_id", &self.registry_id); formatter.field("repository_name", &self.repository_name); formatter.field("image_id", &self.image_id); formatter.field("image_manifest", &self.image_manifest); formatter.field("image_manifest_media_type", &self.image_manifest_media_type); formatter.finish() } } /// See [`Image`](crate::model::Image) pub mod image { /// A builder for [`Image`](crate::model::Image) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) registry_id: std::option::Option<std::string::String>, pub(crate) repository_name: std::option::Option<std::string::String>, pub(crate) image_id: std::option::Option<crate::model::ImageIdentifier>, pub(crate) image_manifest: std::option::Option<std::string::String>, pub(crate) image_manifest_media_type: std::option::Option<std::string::String>, } impl Builder { /// <p>The Amazon Web Services account ID associated with the registry containing the image.</p> pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_id = Some(input.into()); self } /// <p>The Amazon Web Services account ID associated with the registry containing the image.</p> pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.registry_id = input; self } /// <p>The name of the repository associated with the image.</p> pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self { self.repository_name = Some(input.into()); self } /// <p>The name of the repository associated with the image.</p> pub fn set_repository_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_name = input; self } /// <p>An object containing the image tag and image digest associated with an image.</p> pub fn image_id(mut self, input: crate::model::ImageIdentifier) -> Self { self.image_id = Some(input); self } /// <p>An object containing the image tag and image digest associated with an image.</p> pub fn set_image_id( mut self, input: std::option::Option<crate::model::ImageIdentifier>, ) -> Self { self.image_id = input; self } /// <p>The image manifest associated with the image.</p> pub fn image_manifest(mut self, input: impl Into<std::string::String>) -> Self { self.image_manifest = Some(input.into()); self } /// <p>The image manifest associated with the image.</p> pub fn set_image_manifest( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.image_manifest = input; self } /// <p>The manifest media type of the image.</p> pub fn image_manifest_media_type(mut self, input: impl Into<std::string::String>) -> Self { self.image_manifest_media_type = Some(input.into()); self } /// <p>The manifest media type of the image.</p> pub fn set_image_manifest_media_type( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.image_manifest_media_type = input; self } /// Consumes the builder and constructs a [`Image`](crate::model::Image) pub fn build(self) -> crate::model::Image { crate::model::Image { registry_id: self.registry_id, repository_name: self.repository_name, image_id: self.image_id, image_manifest: self.image_manifest, image_manifest_media_type: self.image_manifest_media_type, } } } } impl Image { /// Creates a new builder-style object to manufacture [`Image`](crate::model::Image) pub fn builder() -> crate::model::image::Builder { crate::model::image::Builder::default() } } /// <p>An object representing a filter on a <a>ListImages</a> operation.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListImagesFilter { /// <p>The tag status with which to filter your <a>ListImages</a> results. You can /// filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub tag_status: std::option::Option<crate::model::TagStatus>, } impl ListImagesFilter { /// <p>The tag status with which to filter your <a>ListImages</a> results. You can /// filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn tag_status(&self) -> std::option::Option<&crate::model::TagStatus> { self.tag_status.as_ref() } } impl std::fmt::Debug for ListImagesFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListImagesFilter"); formatter.field("tag_status", &self.tag_status); formatter.finish() } } /// See [`ListImagesFilter`](crate::model::ListImagesFilter) pub mod list_images_filter { /// A builder for [`ListImagesFilter`](crate::model::ListImagesFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) tag_status: std::option::Option<crate::model::TagStatus>, } impl Builder { /// <p>The tag status with which to filter your <a>ListImages</a> results. You can /// filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn tag_status(mut self, input: crate::model::TagStatus) -> Self { self.tag_status = Some(input); self } /// <p>The tag status with which to filter your <a>ListImages</a> results. You can /// filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn set_tag_status( mut self, input: std::option::Option<crate::model::TagStatus>, ) -> Self { self.tag_status = input; self } /// Consumes the builder and constructs a [`ListImagesFilter`](crate::model::ListImagesFilter) pub fn build(self) -> crate::model::ListImagesFilter { crate::model::ListImagesFilter { tag_status: self.tag_status, } } } } impl ListImagesFilter { /// Creates a new builder-style object to manufacture [`ListImagesFilter`](crate::model::ListImagesFilter) pub fn builder() -> crate::model::list_images_filter::Builder { crate::model::list_images_filter::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum TagStatus { #[allow(missing_docs)] // documentation missing in model Any, #[allow(missing_docs)] // documentation missing in model Tagged, #[allow(missing_docs)] // documentation missing in model Untagged, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for TagStatus { fn from(s: &str) -> Self { match s { "ANY" => TagStatus::Any, "TAGGED" => TagStatus::Tagged, "UNTAGGED" => TagStatus::Untagged, other => TagStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for TagStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(TagStatus::from(s)) } } impl TagStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { TagStatus::Any => "ANY", TagStatus::Tagged => "TAGGED", TagStatus::Untagged => "UNTAGGED", TagStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["ANY", "TAGGED", "UNTAGGED"] } } impl AsRef<str> for TagStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>The summary of the lifecycle policy preview request.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LifecyclePolicyPreviewSummary { /// <p>The number of expiring images.</p> pub expiring_image_total_count: std::option::Option<i32>, } impl LifecyclePolicyPreviewSummary { /// <p>The number of expiring images.</p> pub fn expiring_image_total_count(&self) -> std::option::Option<i32> { self.expiring_image_total_count } } impl std::fmt::Debug for LifecyclePolicyPreviewSummary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LifecyclePolicyPreviewSummary"); formatter.field( "expiring_image_total_count", &self.expiring_image_total_count, ); formatter.finish() } } /// See [`LifecyclePolicyPreviewSummary`](crate::model::LifecyclePolicyPreviewSummary) pub mod lifecycle_policy_preview_summary { /// A builder for [`LifecyclePolicyPreviewSummary`](crate::model::LifecyclePolicyPreviewSummary) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) expiring_image_total_count: std::option::Option<i32>, } impl Builder { /// <p>The number of expiring images.</p> pub fn expiring_image_total_count(mut self, input: i32) -> Self { self.expiring_image_total_count = Some(input); self } /// <p>The number of expiring images.</p> pub fn set_expiring_image_total_count(mut self, input: std::option::Option<i32>) -> Self { self.expiring_image_total_count = input; self } /// Consumes the builder and constructs a [`LifecyclePolicyPreviewSummary`](crate::model::LifecyclePolicyPreviewSummary) pub fn build(self) -> crate::model::LifecyclePolicyPreviewSummary { crate::model::LifecyclePolicyPreviewSummary { expiring_image_total_count: self.expiring_image_total_count, } } } } impl LifecyclePolicyPreviewSummary { /// Creates a new builder-style object to manufacture [`LifecyclePolicyPreviewSummary`](crate::model::LifecyclePolicyPreviewSummary) pub fn builder() -> crate::model::lifecycle_policy_preview_summary::Builder { crate::model::lifecycle_policy_preview_summary::Builder::default() } } /// <p>The result of the lifecycle policy preview.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LifecyclePolicyPreviewResult { /// <p>The list of tags associated with this image.</p> pub image_tags: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The <code>sha256</code> digest of the image manifest.</p> pub image_digest: std::option::Option<std::string::String>, /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository.</p> pub image_pushed_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The type of action to be taken.</p> pub action: std::option::Option<crate::model::LifecyclePolicyRuleAction>, /// <p>The priority of the applied rule.</p> pub applied_rule_priority: std::option::Option<i32>, } impl LifecyclePolicyPreviewResult { /// <p>The list of tags associated with this image.</p> pub fn image_tags(&self) -> std::option::Option<&[std::string::String]> { self.image_tags.as_deref() } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(&self) -> std::option::Option<&str> { self.image_digest.as_deref() } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository.</p> pub fn image_pushed_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.image_pushed_at.as_ref() } /// <p>The type of action to be taken.</p> pub fn action(&self) -> std::option::Option<&crate::model::LifecyclePolicyRuleAction> { self.action.as_ref() } /// <p>The priority of the applied rule.</p> pub fn applied_rule_priority(&self) -> std::option::Option<i32> { self.applied_rule_priority } } impl std::fmt::Debug for LifecyclePolicyPreviewResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LifecyclePolicyPreviewResult"); formatter.field("image_tags", &self.image_tags); formatter.field("image_digest", &self.image_digest); formatter.field("image_pushed_at", &self.image_pushed_at); formatter.field("action", &self.action); formatter.field("applied_rule_priority", &self.applied_rule_priority); formatter.finish() } } /// See [`LifecyclePolicyPreviewResult`](crate::model::LifecyclePolicyPreviewResult) pub mod lifecycle_policy_preview_result { /// A builder for [`LifecyclePolicyPreviewResult`](crate::model::LifecyclePolicyPreviewResult) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) image_tags: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) image_digest: std::option::Option<std::string::String>, pub(crate) image_pushed_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) action: std::option::Option<crate::model::LifecyclePolicyRuleAction>, pub(crate) applied_rule_priority: std::option::Option<i32>, } impl Builder { /// Appends an item to `image_tags`. /// /// To override the contents of this collection use [`set_image_tags`](Self::set_image_tags). /// /// <p>The list of tags associated with this image.</p> pub fn image_tags(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.image_tags.unwrap_or_default(); v.push(input.into()); self.image_tags = Some(v); self } /// <p>The list of tags associated with this image.</p> pub fn set_image_tags( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.image_tags = input; self } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(mut self, input: impl Into<std::string::String>) -> Self { self.image_digest = Some(input.into()); self } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn set_image_digest(mut self, input: std::option::Option<std::string::String>) -> Self { self.image_digest = input; self } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository.</p> pub fn image_pushed_at(mut self, input: aws_smithy_types::Instant) -> Self { self.image_pushed_at = Some(input); self } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository.</p> pub fn set_image_pushed_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.image_pushed_at = input; self } /// <p>The type of action to be taken.</p> pub fn action(mut self, input: crate::model::LifecyclePolicyRuleAction) -> Self { self.action = Some(input); self } /// <p>The type of action to be taken.</p> pub fn set_action( mut self, input: std::option::Option<crate::model::LifecyclePolicyRuleAction>, ) -> Self { self.action = input; self } /// <p>The priority of the applied rule.</p> pub fn applied_rule_priority(mut self, input: i32) -> Self { self.applied_rule_priority = Some(input); self } /// <p>The priority of the applied rule.</p> pub fn set_applied_rule_priority(mut self, input: std::option::Option<i32>) -> Self { self.applied_rule_priority = input; self } /// Consumes the builder and constructs a [`LifecyclePolicyPreviewResult`](crate::model::LifecyclePolicyPreviewResult) pub fn build(self) -> crate::model::LifecyclePolicyPreviewResult { crate::model::LifecyclePolicyPreviewResult { image_tags: self.image_tags, image_digest: self.image_digest, image_pushed_at: self.image_pushed_at, action: self.action, applied_rule_priority: self.applied_rule_priority, } } } } impl LifecyclePolicyPreviewResult { /// Creates a new builder-style object to manufacture [`LifecyclePolicyPreviewResult`](crate::model::LifecyclePolicyPreviewResult) pub fn builder() -> crate::model::lifecycle_policy_preview_result::Builder { crate::model::lifecycle_policy_preview_result::Builder::default() } } /// <p>The type of action to be taken.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LifecyclePolicyRuleAction { /// <p>The type of action to be taken.</p> pub r#type: std::option::Option<crate::model::ImageActionType>, } impl LifecyclePolicyRuleAction { /// <p>The type of action to be taken.</p> pub fn r#type(&self) -> std::option::Option<&crate::model::ImageActionType> { self.r#type.as_ref() } } impl std::fmt::Debug for LifecyclePolicyRuleAction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LifecyclePolicyRuleAction"); formatter.field("r#type", &self.r#type); formatter.finish() } } /// See [`LifecyclePolicyRuleAction`](crate::model::LifecyclePolicyRuleAction) pub mod lifecycle_policy_rule_action { /// A builder for [`LifecyclePolicyRuleAction`](crate::model::LifecyclePolicyRuleAction) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) r#type: std::option::Option<crate::model::ImageActionType>, } impl Builder { /// <p>The type of action to be taken.</p> pub fn r#type(mut self, input: crate::model::ImageActionType) -> Self { self.r#type = Some(input); self } /// <p>The type of action to be taken.</p> pub fn set_type( mut self, input: std::option::Option<crate::model::ImageActionType>, ) -> Self { self.r#type = input; self } /// Consumes the builder and constructs a [`LifecyclePolicyRuleAction`](crate::model::LifecyclePolicyRuleAction) pub fn build(self) -> crate::model::LifecyclePolicyRuleAction { crate::model::LifecyclePolicyRuleAction { r#type: self.r#type, } } } } impl LifecyclePolicyRuleAction { /// Creates a new builder-style object to manufacture [`LifecyclePolicyRuleAction`](crate::model::LifecyclePolicyRuleAction) pub fn builder() -> crate::model::lifecycle_policy_rule_action::Builder { crate::model::lifecycle_policy_rule_action::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ImageActionType { #[allow(missing_docs)] // documentation missing in model Expire, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ImageActionType { fn from(s: &str) -> Self { match s { "EXPIRE" => ImageActionType::Expire, other => ImageActionType::Unknown(other.to_owned()), } } } impl std::str::FromStr for ImageActionType { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ImageActionType::from(s)) } } impl ImageActionType { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ImageActionType::Expire => "EXPIRE", ImageActionType::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["EXPIRE"] } } impl AsRef<str> for ImageActionType { fn as_ref(&self) -> &str { self.as_str() } } /// <p>The filter for the lifecycle policy preview.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LifecyclePolicyPreviewFilter { /// <p>The tag status of the image.</p> pub tag_status: std::option::Option<crate::model::TagStatus>, } impl LifecyclePolicyPreviewFilter { /// <p>The tag status of the image.</p> pub fn tag_status(&self) -> std::option::Option<&crate::model::TagStatus> { self.tag_status.as_ref() } } impl std::fmt::Debug for LifecyclePolicyPreviewFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LifecyclePolicyPreviewFilter"); formatter.field("tag_status", &self.tag_status); formatter.finish() } } /// See [`LifecyclePolicyPreviewFilter`](crate::model::LifecyclePolicyPreviewFilter) pub mod lifecycle_policy_preview_filter { /// A builder for [`LifecyclePolicyPreviewFilter`](crate::model::LifecyclePolicyPreviewFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) tag_status: std::option::Option<crate::model::TagStatus>, } impl Builder { /// <p>The tag status of the image.</p> pub fn tag_status(mut self, input: crate::model::TagStatus) -> Self { self.tag_status = Some(input); self } /// <p>The tag status of the image.</p> pub fn set_tag_status( mut self, input: std::option::Option<crate::model::TagStatus>, ) -> Self { self.tag_status = input; self } /// Consumes the builder and constructs a [`LifecyclePolicyPreviewFilter`](crate::model::LifecyclePolicyPreviewFilter) pub fn build(self) -> crate::model::LifecyclePolicyPreviewFilter { crate::model::LifecyclePolicyPreviewFilter { tag_status: self.tag_status, } } } } impl LifecyclePolicyPreviewFilter { /// Creates a new builder-style object to manufacture [`LifecyclePolicyPreviewFilter`](crate::model::LifecyclePolicyPreviewFilter) pub fn builder() -> crate::model::lifecycle_policy_preview_filter::Builder { crate::model::lifecycle_policy_preview_filter::Builder::default() } } /// <p>An object representing authorization data for an Amazon ECR registry.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AuthorizationData { /// <p>A base64-encoded string that contains authorization data for the specified Amazon ECR /// registry. When the string is decoded, it is presented in the format /// <code>user:password</code> for private registry authentication using <code>docker /// login</code>.</p> pub authorization_token: std::option::Option<std::string::String>, /// <p>The Unix time in seconds and milliseconds when the authorization token expires. /// Authorization tokens are valid for 12 hours.</p> pub expires_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The registry URL to use for this authorization token in a <code>docker login</code> /// command. The Amazon ECR registry URL format is /// <code>https://aws_account_id.dkr.ecr.region.amazonaws.com</code>. For example, /// <code>https://012345678910.dkr.ecr.us-east-1.amazonaws.com</code>.. </p> pub proxy_endpoint: std::option::Option<std::string::String>, } impl AuthorizationData { /// <p>A base64-encoded string that contains authorization data for the specified Amazon ECR /// registry. When the string is decoded, it is presented in the format /// <code>user:password</code> for private registry authentication using <code>docker /// login</code>.</p> pub fn authorization_token(&self) -> std::option::Option<&str> { self.authorization_token.as_deref() } /// <p>The Unix time in seconds and milliseconds when the authorization token expires. /// Authorization tokens are valid for 12 hours.</p> pub fn expires_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.expires_at.as_ref() } /// <p>The registry URL to use for this authorization token in a <code>docker login</code> /// command. The Amazon ECR registry URL format is /// <code>https://aws_account_id.dkr.ecr.region.amazonaws.com</code>. For example, /// <code>https://012345678910.dkr.ecr.us-east-1.amazonaws.com</code>.. </p> pub fn proxy_endpoint(&self) -> std::option::Option<&str> { self.proxy_endpoint.as_deref() } } impl std::fmt::Debug for AuthorizationData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AuthorizationData"); formatter.field("authorization_token", &self.authorization_token); formatter.field("expires_at", &self.expires_at); formatter.field("proxy_endpoint", &self.proxy_endpoint); formatter.finish() } } /// See [`AuthorizationData`](crate::model::AuthorizationData) pub mod authorization_data { /// A builder for [`AuthorizationData`](crate::model::AuthorizationData) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) authorization_token: std::option::Option<std::string::String>, pub(crate) expires_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) proxy_endpoint: std::option::Option<std::string::String>, } impl Builder { /// <p>A base64-encoded string that contains authorization data for the specified Amazon ECR /// registry. When the string is decoded, it is presented in the format /// <code>user:password</code> for private registry authentication using <code>docker /// login</code>.</p> pub fn authorization_token(mut self, input: impl Into<std::string::String>) -> Self { self.authorization_token = Some(input.into()); self } /// <p>A base64-encoded string that contains authorization data for the specified Amazon ECR /// registry. When the string is decoded, it is presented in the format /// <code>user:password</code> for private registry authentication using <code>docker /// login</code>.</p> pub fn set_authorization_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.authorization_token = input; self } /// <p>The Unix time in seconds and milliseconds when the authorization token expires. /// Authorization tokens are valid for 12 hours.</p> pub fn expires_at(mut self, input: aws_smithy_types::Instant) -> Self { self.expires_at = Some(input); self } /// <p>The Unix time in seconds and milliseconds when the authorization token expires. /// Authorization tokens are valid for 12 hours.</p> pub fn set_expires_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.expires_at = input; self } /// <p>The registry URL to use for this authorization token in a <code>docker login</code> /// command. The Amazon ECR registry URL format is /// <code>https://aws_account_id.dkr.ecr.region.amazonaws.com</code>. For example, /// <code>https://012345678910.dkr.ecr.us-east-1.amazonaws.com</code>.. </p> pub fn proxy_endpoint(mut self, input: impl Into<std::string::String>) -> Self { self.proxy_endpoint = Some(input.into()); self } /// <p>The registry URL to use for this authorization token in a <code>docker login</code> /// command. The Amazon ECR registry URL format is /// <code>https://aws_account_id.dkr.ecr.region.amazonaws.com</code>. For example, /// <code>https://012345678910.dkr.ecr.us-east-1.amazonaws.com</code>.. </p> pub fn set_proxy_endpoint( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.proxy_endpoint = input; self } /// Consumes the builder and constructs a [`AuthorizationData`](crate::model::AuthorizationData) pub fn build(self) -> crate::model::AuthorizationData { crate::model::AuthorizationData { authorization_token: self.authorization_token, expires_at: self.expires_at, proxy_endpoint: self.proxy_endpoint, } } } } impl AuthorizationData { /// Creates a new builder-style object to manufacture [`AuthorizationData`](crate::model::AuthorizationData) pub fn builder() -> crate::model::authorization_data::Builder { crate::model::authorization_data::Builder::default() } } /// <p>An object representing a repository.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Repository { /// <p>The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the <code>arn:aws:ecr</code> namespace, followed by the region of the /// repository, Amazon Web Services account ID of the repository owner, repository namespace, and repository name. /// For example, <code>arn:aws:ecr:region:012345678910:repository/test</code>.</p> pub repository_arn: std::option::Option<std::string::String>, /// <p>The Amazon Web Services account ID associated with the registry that contains the repository.</p> pub registry_id: std::option::Option<std::string::String>, /// <p>The name of the repository.</p> pub repository_name: std::option::Option<std::string::String>, /// <p>The URI for the repository. You can use this URI for container image <code>push</code> /// and <code>pull</code> operations.</p> pub repository_uri: std::option::Option<std::string::String>, /// <p>The date and time, in JavaScript date format, when the repository was created.</p> pub created_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The tag mutability setting for the repository.</p> pub image_tag_mutability: std::option::Option<crate::model::ImageTagMutability>, /// <p>The image scanning configuration for a repository.</p> pub image_scanning_configuration: std::option::Option<crate::model::ImageScanningConfiguration>, /// <p>The encryption configuration for the repository. This determines how the contents of /// your repository are encrypted at rest.</p> pub encryption_configuration: std::option::Option<crate::model::EncryptionConfiguration>, } impl Repository { /// <p>The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the <code>arn:aws:ecr</code> namespace, followed by the region of the /// repository, Amazon Web Services account ID of the repository owner, repository namespace, and repository name. /// For example, <code>arn:aws:ecr:region:012345678910:repository/test</code>.</p> pub fn repository_arn(&self) -> std::option::Option<&str> { self.repository_arn.as_deref() } /// <p>The Amazon Web Services account ID associated with the registry that contains the repository.</p> pub fn registry_id(&self) -> std::option::Option<&str> { self.registry_id.as_deref() } /// <p>The name of the repository.</p> pub fn repository_name(&self) -> std::option::Option<&str> { self.repository_name.as_deref() } /// <p>The URI for the repository. You can use this URI for container image <code>push</code> /// and <code>pull</code> operations.</p> pub fn repository_uri(&self) -> std::option::Option<&str> { self.repository_uri.as_deref() } /// <p>The date and time, in JavaScript date format, when the repository was created.</p> pub fn created_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.created_at.as_ref() } /// <p>The tag mutability setting for the repository.</p> pub fn image_tag_mutability(&self) -> std::option::Option<&crate::model::ImageTagMutability> { self.image_tag_mutability.as_ref() } /// <p>The image scanning configuration for a repository.</p> pub fn image_scanning_configuration( &self, ) -> std::option::Option<&crate::model::ImageScanningConfiguration> { self.image_scanning_configuration.as_ref() } /// <p>The encryption configuration for the repository. This determines how the contents of /// your repository are encrypted at rest.</p> pub fn encryption_configuration( &self, ) -> std::option::Option<&crate::model::EncryptionConfiguration> { self.encryption_configuration.as_ref() } } impl std::fmt::Debug for Repository { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Repository"); formatter.field("repository_arn", &self.repository_arn); formatter.field("registry_id", &self.registry_id); formatter.field("repository_name", &self.repository_name); formatter.field("repository_uri", &self.repository_uri); formatter.field("created_at", &self.created_at); formatter.field("image_tag_mutability", &self.image_tag_mutability); formatter.field( "image_scanning_configuration", &self.image_scanning_configuration, ); formatter.field("encryption_configuration", &self.encryption_configuration); formatter.finish() } } /// See [`Repository`](crate::model::Repository) pub mod repository { /// A builder for [`Repository`](crate::model::Repository) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) repository_arn: std::option::Option<std::string::String>, pub(crate) registry_id: std::option::Option<std::string::String>, pub(crate) repository_name: std::option::Option<std::string::String>, pub(crate) repository_uri: std::option::Option<std::string::String>, pub(crate) created_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) image_tag_mutability: std::option::Option<crate::model::ImageTagMutability>, pub(crate) image_scanning_configuration: std::option::Option<crate::model::ImageScanningConfiguration>, pub(crate) encryption_configuration: std::option::Option<crate::model::EncryptionConfiguration>, } impl Builder { /// <p>The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the <code>arn:aws:ecr</code> namespace, followed by the region of the /// repository, Amazon Web Services account ID of the repository owner, repository namespace, and repository name. /// For example, <code>arn:aws:ecr:region:012345678910:repository/test</code>.</p> pub fn repository_arn(mut self, input: impl Into<std::string::String>) -> Self { self.repository_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the <code>arn:aws:ecr</code> namespace, followed by the region of the /// repository, Amazon Web Services account ID of the repository owner, repository namespace, and repository name. /// For example, <code>arn:aws:ecr:region:012345678910:repository/test</code>.</p> pub fn set_repository_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_arn = input; self } /// <p>The Amazon Web Services account ID associated with the registry that contains the repository.</p> pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_id = Some(input.into()); self } /// <p>The Amazon Web Services account ID associated with the registry that contains the repository.</p> pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.registry_id = input; self } /// <p>The name of the repository.</p> pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self { self.repository_name = Some(input.into()); self } /// <p>The name of the repository.</p> pub fn set_repository_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_name = input; self } /// <p>The URI for the repository. You can use this URI for container image <code>push</code> /// and <code>pull</code> operations.</p> pub fn repository_uri(mut self, input: impl Into<std::string::String>) -> Self { self.repository_uri = Some(input.into()); self } /// <p>The URI for the repository. You can use this URI for container image <code>push</code> /// and <code>pull</code> operations.</p> pub fn set_repository_uri( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_uri = input; self } /// <p>The date and time, in JavaScript date format, when the repository was created.</p> pub fn created_at(mut self, input: aws_smithy_types::Instant) -> Self { self.created_at = Some(input); self } /// <p>The date and time, in JavaScript date format, when the repository was created.</p> pub fn set_created_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.created_at = input; self } /// <p>The tag mutability setting for the repository.</p> pub fn image_tag_mutability(mut self, input: crate::model::ImageTagMutability) -> Self { self.image_tag_mutability = Some(input); self } /// <p>The tag mutability setting for the repository.</p> pub fn set_image_tag_mutability( mut self, input: std::option::Option<crate::model::ImageTagMutability>, ) -> Self { self.image_tag_mutability = input; self } /// <p>The image scanning configuration for a repository.</p> pub fn image_scanning_configuration( mut self, input: crate::model::ImageScanningConfiguration, ) -> Self { self.image_scanning_configuration = Some(input); self } /// <p>The image scanning configuration for a repository.</p> pub fn set_image_scanning_configuration( mut self, input: std::option::Option<crate::model::ImageScanningConfiguration>, ) -> Self { self.image_scanning_configuration = input; self } /// <p>The encryption configuration for the repository. This determines how the contents of /// your repository are encrypted at rest.</p> pub fn encryption_configuration( mut self, input: crate::model::EncryptionConfiguration, ) -> Self { self.encryption_configuration = Some(input); self } /// <p>The encryption configuration for the repository. This determines how the contents of /// your repository are encrypted at rest.</p> pub fn set_encryption_configuration( mut self, input: std::option::Option<crate::model::EncryptionConfiguration>, ) -> Self { self.encryption_configuration = input; self } /// Consumes the builder and constructs a [`Repository`](crate::model::Repository) pub fn build(self) -> crate::model::Repository { crate::model::Repository { repository_arn: self.repository_arn, registry_id: self.registry_id, repository_name: self.repository_name, repository_uri: self.repository_uri, created_at: self.created_at, image_tag_mutability: self.image_tag_mutability, image_scanning_configuration: self.image_scanning_configuration, encryption_configuration: self.encryption_configuration, } } } } impl Repository { /// Creates a new builder-style object to manufacture [`Repository`](crate::model::Repository) pub fn builder() -> crate::model::repository::Builder { crate::model::repository::Builder::default() } } /// <p>The encryption configuration for the repository. This determines how the contents of /// your repository are encrypted at rest.</p> /// <p>By default, when no encryption configuration is set or the <code>AES256</code> /// encryption type is used, Amazon ECR uses server-side encryption with Amazon S3-managed encryption /// keys which encrypts your data at rest using an AES-256 encryption algorithm. This does /// not require any action on your part.</p> /// <p>For more control over the encryption of the contents of your repository, you can use /// server-side encryption with Key Management Service key stored in Key Management Service (KMS) to encrypt your /// images. For more information, see <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html">Amazon ECR encryption at /// rest</a> in the <i>Amazon Elastic Container Registry User Guide</i>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct EncryptionConfiguration { /// <p>The encryption type to use.</p> /// <p>If you use the <code>KMS</code> encryption type, the contents of the repository will /// be encrypted using server-side encryption with Key Management Service key stored in KMS. When you /// use KMS to encrypt your data, you can either use the default Amazon Web Services managed KMS key /// for Amazon ECR, or specify your own KMS key, which you already created. For more /// information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html">Protecting data using server-side /// encryption with an KMS key stored in Key Management Service (SSE-KMS)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> /// <p>If you use the <code>AES256</code> encryption type, Amazon ECR uses server-side encryption /// with Amazon S3-managed encryption keys which encrypts the images in the repository using an /// AES-256 encryption algorithm. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html">Protecting data using /// server-side encryption with Amazon S3-managed encryption keys (SSE-S3)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> pub encryption_type: std::option::Option<crate::model::EncryptionType>, /// <p>If you use the <code>KMS</code> encryption type, specify the KMS key to use for /// encryption. The alias, key ID, or full ARN of the KMS key can be specified. The key /// must exist in the same Region as the repository. If no key is specified, the default /// Amazon Web Services managed KMS key for Amazon ECR will be used.</p> pub kms_key: std::option::Option<std::string::String>, } impl EncryptionConfiguration { /// <p>The encryption type to use.</p> /// <p>If you use the <code>KMS</code> encryption type, the contents of the repository will /// be encrypted using server-side encryption with Key Management Service key stored in KMS. When you /// use KMS to encrypt your data, you can either use the default Amazon Web Services managed KMS key /// for Amazon ECR, or specify your own KMS key, which you already created. For more /// information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html">Protecting data using server-side /// encryption with an KMS key stored in Key Management Service (SSE-KMS)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> /// <p>If you use the <code>AES256</code> encryption type, Amazon ECR uses server-side encryption /// with Amazon S3-managed encryption keys which encrypts the images in the repository using an /// AES-256 encryption algorithm. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html">Protecting data using /// server-side encryption with Amazon S3-managed encryption keys (SSE-S3)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> pub fn encryption_type(&self) -> std::option::Option<&crate::model::EncryptionType> { self.encryption_type.as_ref() } /// <p>If you use the <code>KMS</code> encryption type, specify the KMS key to use for /// encryption. The alias, key ID, or full ARN of the KMS key can be specified. The key /// must exist in the same Region as the repository. If no key is specified, the default /// Amazon Web Services managed KMS key for Amazon ECR will be used.</p> pub fn kms_key(&self) -> std::option::Option<&str> { self.kms_key.as_deref() } } impl std::fmt::Debug for EncryptionConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("EncryptionConfiguration"); formatter.field("encryption_type", &self.encryption_type); formatter.field("kms_key", &self.kms_key); formatter.finish() } } /// See [`EncryptionConfiguration`](crate::model::EncryptionConfiguration) pub mod encryption_configuration { /// A builder for [`EncryptionConfiguration`](crate::model::EncryptionConfiguration) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) encryption_type: std::option::Option<crate::model::EncryptionType>, pub(crate) kms_key: std::option::Option<std::string::String>, } impl Builder { /// <p>The encryption type to use.</p> /// <p>If you use the <code>KMS</code> encryption type, the contents of the repository will /// be encrypted using server-side encryption with Key Management Service key stored in KMS. When you /// use KMS to encrypt your data, you can either use the default Amazon Web Services managed KMS key /// for Amazon ECR, or specify your own KMS key, which you already created. For more /// information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html">Protecting data using server-side /// encryption with an KMS key stored in Key Management Service (SSE-KMS)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> /// <p>If you use the <code>AES256</code> encryption type, Amazon ECR uses server-side encryption /// with Amazon S3-managed encryption keys which encrypts the images in the repository using an /// AES-256 encryption algorithm. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html">Protecting data using /// server-side encryption with Amazon S3-managed encryption keys (SSE-S3)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> pub fn encryption_type(mut self, input: crate::model::EncryptionType) -> Self { self.encryption_type = Some(input); self } /// <p>The encryption type to use.</p> /// <p>If you use the <code>KMS</code> encryption type, the contents of the repository will /// be encrypted using server-side encryption with Key Management Service key stored in KMS. When you /// use KMS to encrypt your data, you can either use the default Amazon Web Services managed KMS key /// for Amazon ECR, or specify your own KMS key, which you already created. For more /// information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html">Protecting data using server-side /// encryption with an KMS key stored in Key Management Service (SSE-KMS)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> /// <p>If you use the <code>AES256</code> encryption type, Amazon ECR uses server-side encryption /// with Amazon S3-managed encryption keys which encrypts the images in the repository using an /// AES-256 encryption algorithm. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html">Protecting data using /// server-side encryption with Amazon S3-managed encryption keys (SSE-S3)</a> in the /// <i>Amazon Simple Storage Service Console Developer Guide.</i>.</p> pub fn set_encryption_type( mut self, input: std::option::Option<crate::model::EncryptionType>, ) -> Self { self.encryption_type = input; self } /// <p>If you use the <code>KMS</code> encryption type, specify the KMS key to use for /// encryption. The alias, key ID, or full ARN of the KMS key can be specified. The key /// must exist in the same Region as the repository. If no key is specified, the default /// Amazon Web Services managed KMS key for Amazon ECR will be used.</p> pub fn kms_key(mut self, input: impl Into<std::string::String>) -> Self { self.kms_key = Some(input.into()); self } /// <p>If you use the <code>KMS</code> encryption type, specify the KMS key to use for /// encryption. The alias, key ID, or full ARN of the KMS key can be specified. The key /// must exist in the same Region as the repository. If no key is specified, the default /// Amazon Web Services managed KMS key for Amazon ECR will be used.</p> pub fn set_kms_key(mut self, input: std::option::Option<std::string::String>) -> Self { self.kms_key = input; self } /// Consumes the builder and constructs a [`EncryptionConfiguration`](crate::model::EncryptionConfiguration) pub fn build(self) -> crate::model::EncryptionConfiguration { crate::model::EncryptionConfiguration { encryption_type: self.encryption_type, kms_key: self.kms_key, } } } } impl EncryptionConfiguration { /// Creates a new builder-style object to manufacture [`EncryptionConfiguration`](crate::model::EncryptionConfiguration) pub fn builder() -> crate::model::encryption_configuration::Builder { crate::model::encryption_configuration::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum EncryptionType { #[allow(missing_docs)] // documentation missing in model Aes256, #[allow(missing_docs)] // documentation missing in model Kms, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for EncryptionType { fn from(s: &str) -> Self { match s { "AES256" => EncryptionType::Aes256, "KMS" => EncryptionType::Kms, other => EncryptionType::Unknown(other.to_owned()), } } } impl std::str::FromStr for EncryptionType { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(EncryptionType::from(s)) } } impl EncryptionType { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { EncryptionType::Aes256 => "AES256", EncryptionType::Kms => "KMS", EncryptionType::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["AES256", "KMS"] } } impl AsRef<str> for EncryptionType { fn as_ref(&self) -> &str { self.as_str() } } /// <p>The details of an image scan.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageScanFindings { /// <p>The time of the last completed image scan.</p> pub image_scan_completed_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The time when the vulnerability data was last scanned.</p> pub vulnerability_source_updated_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The findings from the image scan.</p> pub findings: std::option::Option<std::vec::Vec<crate::model::ImageScanFinding>>, /// <p>The image vulnerability counts, sorted by severity.</p> pub finding_severity_counts: std::option::Option<std::collections::HashMap<crate::model::FindingSeverity, i32>>, } impl ImageScanFindings { /// <p>The time of the last completed image scan.</p> pub fn image_scan_completed_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.image_scan_completed_at.as_ref() } /// <p>The time when the vulnerability data was last scanned.</p> pub fn vulnerability_source_updated_at( &self, ) -> std::option::Option<&aws_smithy_types::Instant> { self.vulnerability_source_updated_at.as_ref() } /// <p>The findings from the image scan.</p> pub fn findings(&self) -> std::option::Option<&[crate::model::ImageScanFinding]> { self.findings.as_deref() } /// <p>The image vulnerability counts, sorted by severity.</p> pub fn finding_severity_counts( &self, ) -> std::option::Option<&std::collections::HashMap<crate::model::FindingSeverity, i32>> { self.finding_severity_counts.as_ref() } } impl std::fmt::Debug for ImageScanFindings { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageScanFindings"); formatter.field("image_scan_completed_at", &self.image_scan_completed_at); formatter.field( "vulnerability_source_updated_at", &self.vulnerability_source_updated_at, ); formatter.field("findings", &self.findings); formatter.field("finding_severity_counts", &self.finding_severity_counts); formatter.finish() } } /// See [`ImageScanFindings`](crate::model::ImageScanFindings) pub mod image_scan_findings { /// A builder for [`ImageScanFindings`](crate::model::ImageScanFindings) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) image_scan_completed_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) vulnerability_source_updated_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) findings: std::option::Option<std::vec::Vec<crate::model::ImageScanFinding>>, pub(crate) finding_severity_counts: std::option::Option<std::collections::HashMap<crate::model::FindingSeverity, i32>>, } impl Builder { /// <p>The time of the last completed image scan.</p> pub fn image_scan_completed_at(mut self, input: aws_smithy_types::Instant) -> Self { self.image_scan_completed_at = Some(input); self } /// <p>The time of the last completed image scan.</p> pub fn set_image_scan_completed_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.image_scan_completed_at = input; self } /// <p>The time when the vulnerability data was last scanned.</p> pub fn vulnerability_source_updated_at(mut self, input: aws_smithy_types::Instant) -> Self { self.vulnerability_source_updated_at = Some(input); self } /// <p>The time when the vulnerability data was last scanned.</p> pub fn set_vulnerability_source_updated_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.vulnerability_source_updated_at = input; self } /// Appends an item to `findings`. /// /// To override the contents of this collection use [`set_findings`](Self::set_findings). /// /// <p>The findings from the image scan.</p> pub fn findings(mut self, input: impl Into<crate::model::ImageScanFinding>) -> Self { let mut v = self.findings.unwrap_or_default(); v.push(input.into()); self.findings = Some(v); self } /// <p>The findings from the image scan.</p> pub fn set_findings( mut self, input: std::option::Option<std::vec::Vec<crate::model::ImageScanFinding>>, ) -> Self { self.findings = input; self } /// Adds a key-value pair to `finding_severity_counts`. /// /// To override the contents of this collection use [`set_finding_severity_counts`](Self::set_finding_severity_counts). /// /// <p>The image vulnerability counts, sorted by severity.</p> pub fn finding_severity_counts( mut self, k: impl Into<crate::model::FindingSeverity>, v: impl Into<i32>, ) -> Self { let mut hash_map = self.finding_severity_counts.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.finding_severity_counts = Some(hash_map); self } /// <p>The image vulnerability counts, sorted by severity.</p> pub fn set_finding_severity_counts( mut self, input: std::option::Option< std::collections::HashMap<crate::model::FindingSeverity, i32>, >, ) -> Self { self.finding_severity_counts = input; self } /// Consumes the builder and constructs a [`ImageScanFindings`](crate::model::ImageScanFindings) pub fn build(self) -> crate::model::ImageScanFindings { crate::model::ImageScanFindings { image_scan_completed_at: self.image_scan_completed_at, vulnerability_source_updated_at: self.vulnerability_source_updated_at, findings: self.findings, finding_severity_counts: self.finding_severity_counts, } } } } impl ImageScanFindings { /// Creates a new builder-style object to manufacture [`ImageScanFindings`](crate::model::ImageScanFindings) pub fn builder() -> crate::model::image_scan_findings::Builder { crate::model::image_scan_findings::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum FindingSeverity { #[allow(missing_docs)] // documentation missing in model Critical, #[allow(missing_docs)] // documentation missing in model High, #[allow(missing_docs)] // documentation missing in model Informational, #[allow(missing_docs)] // documentation missing in model Low, #[allow(missing_docs)] // documentation missing in model Medium, #[allow(missing_docs)] // documentation missing in model Undefined, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for FindingSeverity { fn from(s: &str) -> Self { match s { "CRITICAL" => FindingSeverity::Critical, "HIGH" => FindingSeverity::High, "INFORMATIONAL" => FindingSeverity::Informational, "LOW" => FindingSeverity::Low, "MEDIUM" => FindingSeverity::Medium, "UNDEFINED" => FindingSeverity::Undefined, other => FindingSeverity::Unknown(other.to_owned()), } } } impl std::str::FromStr for FindingSeverity { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(FindingSeverity::from(s)) } } impl FindingSeverity { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { FindingSeverity::Critical => "CRITICAL", FindingSeverity::High => "HIGH", FindingSeverity::Informational => "INFORMATIONAL", FindingSeverity::Low => "LOW", FindingSeverity::Medium => "MEDIUM", FindingSeverity::Undefined => "UNDEFINED", FindingSeverity::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "CRITICAL", "HIGH", "INFORMATIONAL", "LOW", "MEDIUM", "UNDEFINED", ] } } impl AsRef<str> for FindingSeverity { fn as_ref(&self) -> &str { self.as_str() } } /// <p>Contains information about an image scan finding.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageScanFinding { /// <p>The name associated with the finding, usually a CVE number.</p> pub name: std::option::Option<std::string::String>, /// <p>The description of the finding.</p> pub description: std::option::Option<std::string::String>, /// <p>A link containing additional details about the security vulnerability.</p> pub uri: std::option::Option<std::string::String>, /// <p>The finding severity.</p> pub severity: std::option::Option<crate::model::FindingSeverity>, /// <p>A collection of attributes of the host from which the finding is generated.</p> pub attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>, } impl ImageScanFinding { /// <p>The name associated with the finding, usually a CVE number.</p> pub fn name(&self) -> std::option::Option<&str> { self.name.as_deref() } /// <p>The description of the finding.</p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } /// <p>A link containing additional details about the security vulnerability.</p> pub fn uri(&self) -> std::option::Option<&str> { self.uri.as_deref() } /// <p>The finding severity.</p> pub fn severity(&self) -> std::option::Option<&crate::model::FindingSeverity> { self.severity.as_ref() } /// <p>A collection of attributes of the host from which the finding is generated.</p> pub fn attributes(&self) -> std::option::Option<&[crate::model::Attribute]> { self.attributes.as_deref() } } impl std::fmt::Debug for ImageScanFinding { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageScanFinding"); formatter.field("name", &self.name); formatter.field("description", &self.description); formatter.field("uri", &self.uri); formatter.field("severity", &self.severity); formatter.field("attributes", &self.attributes); formatter.finish() } } /// See [`ImageScanFinding`](crate::model::ImageScanFinding) pub mod image_scan_finding { /// A builder for [`ImageScanFinding`](crate::model::ImageScanFinding) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) name: std::option::Option<std::string::String>, pub(crate) description: std::option::Option<std::string::String>, pub(crate) uri: std::option::Option<std::string::String>, pub(crate) severity: std::option::Option<crate::model::FindingSeverity>, pub(crate) attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>, } impl Builder { /// <p>The name associated with the finding, usually a CVE number.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } /// <p>The name associated with the finding, usually a CVE number.</p> pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The description of the finding.</p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p>The description of the finding.</p> pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self { self.description = input; self } /// <p>A link containing additional details about the security vulnerability.</p> pub fn uri(mut self, input: impl Into<std::string::String>) -> Self { self.uri = Some(input.into()); self } /// <p>A link containing additional details about the security vulnerability.</p> pub fn set_uri(mut self, input: std::option::Option<std::string::String>) -> Self { self.uri = input; self } /// <p>The finding severity.</p> pub fn severity(mut self, input: crate::model::FindingSeverity) -> Self { self.severity = Some(input); self } /// <p>The finding severity.</p> pub fn set_severity( mut self, input: std::option::Option<crate::model::FindingSeverity>, ) -> Self { self.severity = input; self } /// Appends an item to `attributes`. /// /// To override the contents of this collection use [`set_attributes`](Self::set_attributes). /// /// <p>A collection of attributes of the host from which the finding is generated.</p> pub fn attributes(mut self, input: impl Into<crate::model::Attribute>) -> Self { let mut v = self.attributes.unwrap_or_default(); v.push(input.into()); self.attributes = Some(v); self } /// <p>A collection of attributes of the host from which the finding is generated.</p> pub fn set_attributes( mut self, input: std::option::Option<std::vec::Vec<crate::model::Attribute>>, ) -> Self { self.attributes = input; self } /// Consumes the builder and constructs a [`ImageScanFinding`](crate::model::ImageScanFinding) pub fn build(self) -> crate::model::ImageScanFinding { crate::model::ImageScanFinding { name: self.name, description: self.description, uri: self.uri, severity: self.severity, attributes: self.attributes, } } } } impl ImageScanFinding { /// Creates a new builder-style object to manufacture [`ImageScanFinding`](crate::model::ImageScanFinding) pub fn builder() -> crate::model::image_scan_finding::Builder { crate::model::image_scan_finding::Builder::default() } } /// <p>This data type is used in the <a>ImageScanFinding</a> data type.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Attribute { /// <p>The attribute key.</p> pub key: std::option::Option<std::string::String>, /// <p>The value assigned to the attribute key.</p> pub value: std::option::Option<std::string::String>, } impl Attribute { /// <p>The attribute key.</p> pub fn key(&self) -> std::option::Option<&str> { self.key.as_deref() } /// <p>The value assigned to the attribute key.</p> pub fn value(&self) -> std::option::Option<&str> { self.value.as_deref() } } impl std::fmt::Debug for Attribute { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Attribute"); formatter.field("key", &self.key); formatter.field("value", &self.value); formatter.finish() } } /// See [`Attribute`](crate::model::Attribute) pub mod attribute { /// A builder for [`Attribute`](crate::model::Attribute) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) key: std::option::Option<std::string::String>, pub(crate) value: std::option::Option<std::string::String>, } impl Builder { /// <p>The attribute key.</p> pub fn key(mut self, input: impl Into<std::string::String>) -> Self { self.key = Some(input.into()); self } /// <p>The attribute key.</p> pub fn set_key(mut self, input: std::option::Option<std::string::String>) -> Self { self.key = input; self } /// <p>The value assigned to the attribute key.</p> pub fn value(mut self, input: impl Into<std::string::String>) -> Self { self.value = Some(input.into()); self } /// <p>The value assigned to the attribute key.</p> pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self { self.value = input; self } /// Consumes the builder and constructs a [`Attribute`](crate::model::Attribute) pub fn build(self) -> crate::model::Attribute { crate::model::Attribute { key: self.key, value: self.value, } } } } impl Attribute { /// Creates a new builder-style object to manufacture [`Attribute`](crate::model::Attribute) pub fn builder() -> crate::model::attribute::Builder { crate::model::attribute::Builder::default() } } /// <p>An object that describes an image returned by a <a>DescribeImages</a> /// operation.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageDetail { /// <p>The Amazon Web Services account ID associated with the registry to which this image belongs.</p> pub registry_id: std::option::Option<std::string::String>, /// <p>The name of the repository to which this image belongs.</p> pub repository_name: std::option::Option<std::string::String>, /// <p>The <code>sha256</code> digest of the image manifest.</p> pub image_digest: std::option::Option<std::string::String>, /// <p>The list of tags associated with this image.</p> pub image_tags: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The size, in bytes, of the image in the repository.</p> /// <p>If the image is a manifest list, this will be the max size of all manifests in the /// list.</p> /// <note> /// <p>Beginning with Docker version 1.9, the Docker client compresses image layers /// before pushing them to a V2 Docker registry. The output of the <code>docker /// images</code> command shows the uncompressed image size, so it may return a /// larger image size than the image sizes returned by <a>DescribeImages</a>.</p> /// </note> pub image_size_in_bytes: std::option::Option<i64>, /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository. </p> pub image_pushed_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The current state of the scan.</p> pub image_scan_status: std::option::Option<crate::model::ImageScanStatus>, /// <p>A summary of the last completed image scan.</p> pub image_scan_findings_summary: std::option::Option<crate::model::ImageScanFindingsSummary>, /// <p>The media type of the image manifest.</p> pub image_manifest_media_type: std::option::Option<std::string::String>, /// <p>The artifact media type of the image.</p> pub artifact_media_type: std::option::Option<std::string::String>, } impl ImageDetail { /// <p>The Amazon Web Services account ID associated with the registry to which this image belongs.</p> pub fn registry_id(&self) -> std::option::Option<&str> { self.registry_id.as_deref() } /// <p>The name of the repository to which this image belongs.</p> pub fn repository_name(&self) -> std::option::Option<&str> { self.repository_name.as_deref() } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(&self) -> std::option::Option<&str> { self.image_digest.as_deref() } /// <p>The list of tags associated with this image.</p> pub fn image_tags(&self) -> std::option::Option<&[std::string::String]> { self.image_tags.as_deref() } /// <p>The size, in bytes, of the image in the repository.</p> /// <p>If the image is a manifest list, this will be the max size of all manifests in the /// list.</p> /// <note> /// <p>Beginning with Docker version 1.9, the Docker client compresses image layers /// before pushing them to a V2 Docker registry. The output of the <code>docker /// images</code> command shows the uncompressed image size, so it may return a /// larger image size than the image sizes returned by <a>DescribeImages</a>.</p> /// </note> pub fn image_size_in_bytes(&self) -> std::option::Option<i64> { self.image_size_in_bytes } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository. </p> pub fn image_pushed_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.image_pushed_at.as_ref() } /// <p>The current state of the scan.</p> pub fn image_scan_status(&self) -> std::option::Option<&crate::model::ImageScanStatus> { self.image_scan_status.as_ref() } /// <p>A summary of the last completed image scan.</p> pub fn image_scan_findings_summary( &self, ) -> std::option::Option<&crate::model::ImageScanFindingsSummary> { self.image_scan_findings_summary.as_ref() } /// <p>The media type of the image manifest.</p> pub fn image_manifest_media_type(&self) -> std::option::Option<&str> { self.image_manifest_media_type.as_deref() } /// <p>The artifact media type of the image.</p> pub fn artifact_media_type(&self) -> std::option::Option<&str> { self.artifact_media_type.as_deref() } } impl std::fmt::Debug for ImageDetail { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageDetail"); formatter.field("registry_id", &self.registry_id); formatter.field("repository_name", &self.repository_name); formatter.field("image_digest", &self.image_digest); formatter.field("image_tags", &self.image_tags); formatter.field("image_size_in_bytes", &self.image_size_in_bytes); formatter.field("image_pushed_at", &self.image_pushed_at); formatter.field("image_scan_status", &self.image_scan_status); formatter.field( "image_scan_findings_summary", &self.image_scan_findings_summary, ); formatter.field("image_manifest_media_type", &self.image_manifest_media_type); formatter.field("artifact_media_type", &self.artifact_media_type); formatter.finish() } } /// See [`ImageDetail`](crate::model::ImageDetail) pub mod image_detail { /// A builder for [`ImageDetail`](crate::model::ImageDetail) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) registry_id: std::option::Option<std::string::String>, pub(crate) repository_name: std::option::Option<std::string::String>, pub(crate) image_digest: std::option::Option<std::string::String>, pub(crate) image_tags: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) image_size_in_bytes: std::option::Option<i64>, pub(crate) image_pushed_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) image_scan_status: std::option::Option<crate::model::ImageScanStatus>, pub(crate) image_scan_findings_summary: std::option::Option<crate::model::ImageScanFindingsSummary>, pub(crate) image_manifest_media_type: std::option::Option<std::string::String>, pub(crate) artifact_media_type: std::option::Option<std::string::String>, } impl Builder { /// <p>The Amazon Web Services account ID associated with the registry to which this image belongs.</p> pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_id = Some(input.into()); self } /// <p>The Amazon Web Services account ID associated with the registry to which this image belongs.</p> pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.registry_id = input; self } /// <p>The name of the repository to which this image belongs.</p> pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self { self.repository_name = Some(input.into()); self } /// <p>The name of the repository to which this image belongs.</p> pub fn set_repository_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_name = input; self } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn image_digest(mut self, input: impl Into<std::string::String>) -> Self { self.image_digest = Some(input.into()); self } /// <p>The <code>sha256</code> digest of the image manifest.</p> pub fn set_image_digest(mut self, input: std::option::Option<std::string::String>) -> Self { self.image_digest = input; self } /// Appends an item to `image_tags`. /// /// To override the contents of this collection use [`set_image_tags`](Self::set_image_tags). /// /// <p>The list of tags associated with this image.</p> pub fn image_tags(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.image_tags.unwrap_or_default(); v.push(input.into()); self.image_tags = Some(v); self } /// <p>The list of tags associated with this image.</p> pub fn set_image_tags( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.image_tags = input; self } /// <p>The size, in bytes, of the image in the repository.</p> /// <p>If the image is a manifest list, this will be the max size of all manifests in the /// list.</p> /// <note> /// <p>Beginning with Docker version 1.9, the Docker client compresses image layers /// before pushing them to a V2 Docker registry. The output of the <code>docker /// images</code> command shows the uncompressed image size, so it may return a /// larger image size than the image sizes returned by <a>DescribeImages</a>.</p> /// </note> pub fn image_size_in_bytes(mut self, input: i64) -> Self { self.image_size_in_bytes = Some(input); self } /// <p>The size, in bytes, of the image in the repository.</p> /// <p>If the image is a manifest list, this will be the max size of all manifests in the /// list.</p> /// <note> /// <p>Beginning with Docker version 1.9, the Docker client compresses image layers /// before pushing them to a V2 Docker registry. The output of the <code>docker /// images</code> command shows the uncompressed image size, so it may return a /// larger image size than the image sizes returned by <a>DescribeImages</a>.</p> /// </note> pub fn set_image_size_in_bytes(mut self, input: std::option::Option<i64>) -> Self { self.image_size_in_bytes = input; self } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository. </p> pub fn image_pushed_at(mut self, input: aws_smithy_types::Instant) -> Self { self.image_pushed_at = Some(input); self } /// <p>The date and time, expressed in standard JavaScript date format, at which the current /// image was pushed to the repository. </p> pub fn set_image_pushed_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.image_pushed_at = input; self } /// <p>The current state of the scan.</p> pub fn image_scan_status(mut self, input: crate::model::ImageScanStatus) -> Self { self.image_scan_status = Some(input); self } /// <p>The current state of the scan.</p> pub fn set_image_scan_status( mut self, input: std::option::Option<crate::model::ImageScanStatus>, ) -> Self { self.image_scan_status = input; self } /// <p>A summary of the last completed image scan.</p> pub fn image_scan_findings_summary( mut self, input: crate::model::ImageScanFindingsSummary, ) -> Self { self.image_scan_findings_summary = Some(input); self } /// <p>A summary of the last completed image scan.</p> pub fn set_image_scan_findings_summary( mut self, input: std::option::Option<crate::model::ImageScanFindingsSummary>, ) -> Self { self.image_scan_findings_summary = input; self } /// <p>The media type of the image manifest.</p> pub fn image_manifest_media_type(mut self, input: impl Into<std::string::String>) -> Self { self.image_manifest_media_type = Some(input.into()); self } /// <p>The media type of the image manifest.</p> pub fn set_image_manifest_media_type( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.image_manifest_media_type = input; self } /// <p>The artifact media type of the image.</p> pub fn artifact_media_type(mut self, input: impl Into<std::string::String>) -> Self { self.artifact_media_type = Some(input.into()); self } /// <p>The artifact media type of the image.</p> pub fn set_artifact_media_type( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.artifact_media_type = input; self } /// Consumes the builder and constructs a [`ImageDetail`](crate::model::ImageDetail) pub fn build(self) -> crate::model::ImageDetail { crate::model::ImageDetail { registry_id: self.registry_id, repository_name: self.repository_name, image_digest: self.image_digest, image_tags: self.image_tags, image_size_in_bytes: self.image_size_in_bytes, image_pushed_at: self.image_pushed_at, image_scan_status: self.image_scan_status, image_scan_findings_summary: self.image_scan_findings_summary, image_manifest_media_type: self.image_manifest_media_type, artifact_media_type: self.artifact_media_type, } } } } impl ImageDetail { /// Creates a new builder-style object to manufacture [`ImageDetail`](crate::model::ImageDetail) pub fn builder() -> crate::model::image_detail::Builder { crate::model::image_detail::Builder::default() } } /// <p>A summary of the last completed image scan.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageScanFindingsSummary { /// <p>The time of the last completed image scan.</p> pub image_scan_completed_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The time when the vulnerability data was last scanned.</p> pub vulnerability_source_updated_at: std::option::Option<aws_smithy_types::Instant>, /// <p>The image vulnerability counts, sorted by severity.</p> pub finding_severity_counts: std::option::Option<std::collections::HashMap<crate::model::FindingSeverity, i32>>, } impl ImageScanFindingsSummary { /// <p>The time of the last completed image scan.</p> pub fn image_scan_completed_at(&self) -> std::option::Option<&aws_smithy_types::Instant> { self.image_scan_completed_at.as_ref() } /// <p>The time when the vulnerability data was last scanned.</p> pub fn vulnerability_source_updated_at( &self, ) -> std::option::Option<&aws_smithy_types::Instant> { self.vulnerability_source_updated_at.as_ref() } /// <p>The image vulnerability counts, sorted by severity.</p> pub fn finding_severity_counts( &self, ) -> std::option::Option<&std::collections::HashMap<crate::model::FindingSeverity, i32>> { self.finding_severity_counts.as_ref() } } impl std::fmt::Debug for ImageScanFindingsSummary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageScanFindingsSummary"); formatter.field("image_scan_completed_at", &self.image_scan_completed_at); formatter.field( "vulnerability_source_updated_at", &self.vulnerability_source_updated_at, ); formatter.field("finding_severity_counts", &self.finding_severity_counts); formatter.finish() } } /// See [`ImageScanFindingsSummary`](crate::model::ImageScanFindingsSummary) pub mod image_scan_findings_summary { /// A builder for [`ImageScanFindingsSummary`](crate::model::ImageScanFindingsSummary) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) image_scan_completed_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) vulnerability_source_updated_at: std::option::Option<aws_smithy_types::Instant>, pub(crate) finding_severity_counts: std::option::Option<std::collections::HashMap<crate::model::FindingSeverity, i32>>, } impl Builder { /// <p>The time of the last completed image scan.</p> pub fn image_scan_completed_at(mut self, input: aws_smithy_types::Instant) -> Self { self.image_scan_completed_at = Some(input); self } /// <p>The time of the last completed image scan.</p> pub fn set_image_scan_completed_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.image_scan_completed_at = input; self } /// <p>The time when the vulnerability data was last scanned.</p> pub fn vulnerability_source_updated_at(mut self, input: aws_smithy_types::Instant) -> Self { self.vulnerability_source_updated_at = Some(input); self } /// <p>The time when the vulnerability data was last scanned.</p> pub fn set_vulnerability_source_updated_at( mut self, input: std::option::Option<aws_smithy_types::Instant>, ) -> Self { self.vulnerability_source_updated_at = input; self } /// Adds a key-value pair to `finding_severity_counts`. /// /// To override the contents of this collection use [`set_finding_severity_counts`](Self::set_finding_severity_counts). /// /// <p>The image vulnerability counts, sorted by severity.</p> pub fn finding_severity_counts( mut self, k: impl Into<crate::model::FindingSeverity>, v: impl Into<i32>, ) -> Self { let mut hash_map = self.finding_severity_counts.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.finding_severity_counts = Some(hash_map); self } /// <p>The image vulnerability counts, sorted by severity.</p> pub fn set_finding_severity_counts( mut self, input: std::option::Option< std::collections::HashMap<crate::model::FindingSeverity, i32>, >, ) -> Self { self.finding_severity_counts = input; self } /// Consumes the builder and constructs a [`ImageScanFindingsSummary`](crate::model::ImageScanFindingsSummary) pub fn build(self) -> crate::model::ImageScanFindingsSummary { crate::model::ImageScanFindingsSummary { image_scan_completed_at: self.image_scan_completed_at, vulnerability_source_updated_at: self.vulnerability_source_updated_at, finding_severity_counts: self.finding_severity_counts, } } } } impl ImageScanFindingsSummary { /// Creates a new builder-style object to manufacture [`ImageScanFindingsSummary`](crate::model::ImageScanFindingsSummary) pub fn builder() -> crate::model::image_scan_findings_summary::Builder { crate::model::image_scan_findings_summary::Builder::default() } } /// <p>An object representing a filter on a <a>DescribeImages</a> /// operation.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeImagesFilter { /// <p>The tag status with which to filter your <a>DescribeImages</a> results. You /// can filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub tag_status: std::option::Option<crate::model::TagStatus>, } impl DescribeImagesFilter { /// <p>The tag status with which to filter your <a>DescribeImages</a> results. You /// can filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn tag_status(&self) -> std::option::Option<&crate::model::TagStatus> { self.tag_status.as_ref() } } impl std::fmt::Debug for DescribeImagesFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeImagesFilter"); formatter.field("tag_status", &self.tag_status); formatter.finish() } } /// See [`DescribeImagesFilter`](crate::model::DescribeImagesFilter) pub mod describe_images_filter { /// A builder for [`DescribeImagesFilter`](crate::model::DescribeImagesFilter) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) tag_status: std::option::Option<crate::model::TagStatus>, } impl Builder { /// <p>The tag status with which to filter your <a>DescribeImages</a> results. You /// can filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn tag_status(mut self, input: crate::model::TagStatus) -> Self { self.tag_status = Some(input); self } /// <p>The tag status with which to filter your <a>DescribeImages</a> results. You /// can filter results based on whether they are <code>TAGGED</code> or /// <code>UNTAGGED</code>.</p> pub fn set_tag_status( mut self, input: std::option::Option<crate::model::TagStatus>, ) -> Self { self.tag_status = input; self } /// Consumes the builder and constructs a [`DescribeImagesFilter`](crate::model::DescribeImagesFilter) pub fn build(self) -> crate::model::DescribeImagesFilter { crate::model::DescribeImagesFilter { tag_status: self.tag_status, } } } } impl DescribeImagesFilter { /// Creates a new builder-style object to manufacture [`DescribeImagesFilter`](crate::model::DescribeImagesFilter) pub fn builder() -> crate::model::describe_images_filter::Builder { crate::model::describe_images_filter::Builder::default() } } /// <p>The status of the replication process for an image.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageReplicationStatus { /// <p>The destination Region for the image replication.</p> pub region: std::option::Option<std::string::String>, /// <p>The AWS account ID associated with the registry to which the image belongs.</p> pub registry_id: std::option::Option<std::string::String>, /// <p>The image replication status.</p> pub status: std::option::Option<crate::model::ReplicationStatus>, /// <p>The failure code for a replication that has failed.</p> pub failure_code: std::option::Option<std::string::String>, } impl ImageReplicationStatus { /// <p>The destination Region for the image replication.</p> pub fn region(&self) -> std::option::Option<&str> { self.region.as_deref() } /// <p>The AWS account ID associated with the registry to which the image belongs.</p> pub fn registry_id(&self) -> std::option::Option<&str> { self.registry_id.as_deref() } /// <p>The image replication status.</p> pub fn status(&self) -> std::option::Option<&crate::model::ReplicationStatus> { self.status.as_ref() } /// <p>The failure code for a replication that has failed.</p> pub fn failure_code(&self) -> std::option::Option<&str> { self.failure_code.as_deref() } } impl std::fmt::Debug for ImageReplicationStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageReplicationStatus"); formatter.field("region", &self.region); formatter.field("registry_id", &self.registry_id); formatter.field("status", &self.status); formatter.field("failure_code", &self.failure_code); formatter.finish() } } /// See [`ImageReplicationStatus`](crate::model::ImageReplicationStatus) pub mod image_replication_status { /// A builder for [`ImageReplicationStatus`](crate::model::ImageReplicationStatus) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) region: std::option::Option<std::string::String>, pub(crate) registry_id: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::ReplicationStatus>, pub(crate) failure_code: std::option::Option<std::string::String>, } impl Builder { /// <p>The destination Region for the image replication.</p> pub fn region(mut self, input: impl Into<std::string::String>) -> Self { self.region = Some(input.into()); self } /// <p>The destination Region for the image replication.</p> pub fn set_region(mut self, input: std::option::Option<std::string::String>) -> Self { self.region = input; self } /// <p>The AWS account ID associated with the registry to which the image belongs.</p> pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_id = Some(input.into()); self } /// <p>The AWS account ID associated with the registry to which the image belongs.</p> pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.registry_id = input; self } /// <p>The image replication status.</p> pub fn status(mut self, input: crate::model::ReplicationStatus) -> Self { self.status = Some(input); self } /// <p>The image replication status.</p> pub fn set_status( mut self, input: std::option::Option<crate::model::ReplicationStatus>, ) -> Self { self.status = input; self } /// <p>The failure code for a replication that has failed.</p> pub fn failure_code(mut self, input: impl Into<std::string::String>) -> Self { self.failure_code = Some(input.into()); self } /// <p>The failure code for a replication that has failed.</p> pub fn set_failure_code(mut self, input: std::option::Option<std::string::String>) -> Self { self.failure_code = input; self } /// Consumes the builder and constructs a [`ImageReplicationStatus`](crate::model::ImageReplicationStatus) pub fn build(self) -> crate::model::ImageReplicationStatus { crate::model::ImageReplicationStatus { region: self.region, registry_id: self.registry_id, status: self.status, failure_code: self.failure_code, } } } } impl ImageReplicationStatus { /// Creates a new builder-style object to manufacture [`ImageReplicationStatus`](crate::model::ImageReplicationStatus) pub fn builder() -> crate::model::image_replication_status::Builder { crate::model::image_replication_status::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ReplicationStatus { #[allow(missing_docs)] // documentation missing in model Complete, #[allow(missing_docs)] // documentation missing in model Failed, #[allow(missing_docs)] // documentation missing in model InProgress, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ReplicationStatus { fn from(s: &str) -> Self { match s { "COMPLETE" => ReplicationStatus::Complete, "FAILED" => ReplicationStatus::Failed, "IN_PROGRESS" => ReplicationStatus::InProgress, other => ReplicationStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for ReplicationStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ReplicationStatus::from(s)) } } impl ReplicationStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ReplicationStatus::Complete => "COMPLETE", ReplicationStatus::Failed => "FAILED", ReplicationStatus::InProgress => "IN_PROGRESS", ReplicationStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["COMPLETE", "FAILED", "IN_PROGRESS"] } } impl AsRef<str> for ReplicationStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An object representing an Amazon ECR image failure.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ImageFailure { /// <p>The image ID associated with the failure.</p> pub image_id: std::option::Option<crate::model::ImageIdentifier>, /// <p>The code associated with the failure.</p> pub failure_code: std::option::Option<crate::model::ImageFailureCode>, /// <p>The reason for the failure.</p> pub failure_reason: std::option::Option<std::string::String>, } impl ImageFailure { /// <p>The image ID associated with the failure.</p> pub fn image_id(&self) -> std::option::Option<&crate::model::ImageIdentifier> { self.image_id.as_ref() } /// <p>The code associated with the failure.</p> pub fn failure_code(&self) -> std::option::Option<&crate::model::ImageFailureCode> { self.failure_code.as_ref() } /// <p>The reason for the failure.</p> pub fn failure_reason(&self) -> std::option::Option<&str> { self.failure_reason.as_deref() } } impl std::fmt::Debug for ImageFailure { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ImageFailure"); formatter.field("image_id", &self.image_id); formatter.field("failure_code", &self.failure_code); formatter.field("failure_reason", &self.failure_reason); formatter.finish() } } /// See [`ImageFailure`](crate::model::ImageFailure) pub mod image_failure { /// A builder for [`ImageFailure`](crate::model::ImageFailure) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) image_id: std::option::Option<crate::model::ImageIdentifier>, pub(crate) failure_code: std::option::Option<crate::model::ImageFailureCode>, pub(crate) failure_reason: std::option::Option<std::string::String>, } impl Builder { /// <p>The image ID associated with the failure.</p> pub fn image_id(mut self, input: crate::model::ImageIdentifier) -> Self { self.image_id = Some(input); self } /// <p>The image ID associated with the failure.</p> pub fn set_image_id( mut self, input: std::option::Option<crate::model::ImageIdentifier>, ) -> Self { self.image_id = input; self } /// <p>The code associated with the failure.</p> pub fn failure_code(mut self, input: crate::model::ImageFailureCode) -> Self { self.failure_code = Some(input); self } /// <p>The code associated with the failure.</p> pub fn set_failure_code( mut self, input: std::option::Option<crate::model::ImageFailureCode>, ) -> Self { self.failure_code = input; self } /// <p>The reason for the failure.</p> pub fn failure_reason(mut self, input: impl Into<std::string::String>) -> Self { self.failure_reason = Some(input.into()); self } /// <p>The reason for the failure.</p> pub fn set_failure_reason( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.failure_reason = input; self } /// Consumes the builder and constructs a [`ImageFailure`](crate::model::ImageFailure) pub fn build(self) -> crate::model::ImageFailure { crate::model::ImageFailure { image_id: self.image_id, failure_code: self.failure_code, failure_reason: self.failure_reason, } } } } impl ImageFailure { /// Creates a new builder-style object to manufacture [`ImageFailure`](crate::model::ImageFailure) pub fn builder() -> crate::model::image_failure::Builder { crate::model::image_failure::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ImageFailureCode { #[allow(missing_docs)] // documentation missing in model ImageNotFound, #[allow(missing_docs)] // documentation missing in model ImageReferencedByManifestList, #[allow(missing_docs)] // documentation missing in model ImageTagDoesNotMatchDigest, #[allow(missing_docs)] // documentation missing in model InvalidImageDigest, #[allow(missing_docs)] // documentation missing in model InvalidImageTag, #[allow(missing_docs)] // documentation missing in model KmsError, #[allow(missing_docs)] // documentation missing in model MissingDigestAndTag, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ImageFailureCode { fn from(s: &str) -> Self { match s { "ImageNotFound" => ImageFailureCode::ImageNotFound, "ImageReferencedByManifestList" => ImageFailureCode::ImageReferencedByManifestList, "ImageTagDoesNotMatchDigest" => ImageFailureCode::ImageTagDoesNotMatchDigest, "InvalidImageDigest" => ImageFailureCode::InvalidImageDigest, "InvalidImageTag" => ImageFailureCode::InvalidImageTag, "KmsError" => ImageFailureCode::KmsError, "MissingDigestAndTag" => ImageFailureCode::MissingDigestAndTag, other => ImageFailureCode::Unknown(other.to_owned()), } } } impl std::str::FromStr for ImageFailureCode { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ImageFailureCode::from(s)) } } impl ImageFailureCode { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ImageFailureCode::ImageNotFound => "ImageNotFound", ImageFailureCode::ImageReferencedByManifestList => "ImageReferencedByManifestList", ImageFailureCode::ImageTagDoesNotMatchDigest => "ImageTagDoesNotMatchDigest", ImageFailureCode::InvalidImageDigest => "InvalidImageDigest", ImageFailureCode::InvalidImageTag => "InvalidImageTag", ImageFailureCode::KmsError => "KmsError", ImageFailureCode::MissingDigestAndTag => "MissingDigestAndTag", ImageFailureCode::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "ImageNotFound", "ImageReferencedByManifestList", "ImageTagDoesNotMatchDigest", "InvalidImageDigest", "InvalidImageTag", "KmsError", "MissingDigestAndTag", ] } } impl AsRef<str> for ImageFailureCode { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An object representing an Amazon ECR image layer failure.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LayerFailure { /// <p>The layer digest associated with the failure.</p> pub layer_digest: std::option::Option<std::string::String>, /// <p>The failure code associated with the failure.</p> pub failure_code: std::option::Option<crate::model::LayerFailureCode>, /// <p>The reason for the failure.</p> pub failure_reason: std::option::Option<std::string::String>, } impl LayerFailure { /// <p>The layer digest associated with the failure.</p> pub fn layer_digest(&self) -> std::option::Option<&str> { self.layer_digest.as_deref() } /// <p>The failure code associated with the failure.</p> pub fn failure_code(&self) -> std::option::Option<&crate::model::LayerFailureCode> { self.failure_code.as_ref() } /// <p>The reason for the failure.</p> pub fn failure_reason(&self) -> std::option::Option<&str> { self.failure_reason.as_deref() } } impl std::fmt::Debug for LayerFailure { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LayerFailure"); formatter.field("layer_digest", &self.layer_digest); formatter.field("failure_code", &self.failure_code); formatter.field("failure_reason", &self.failure_reason); formatter.finish() } } /// See [`LayerFailure`](crate::model::LayerFailure) pub mod layer_failure { /// A builder for [`LayerFailure`](crate::model::LayerFailure) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) layer_digest: std::option::Option<std::string::String>, pub(crate) failure_code: std::option::Option<crate::model::LayerFailureCode>, pub(crate) failure_reason: std::option::Option<std::string::String>, } impl Builder { /// <p>The layer digest associated with the failure.</p> pub fn layer_digest(mut self, input: impl Into<std::string::String>) -> Self { self.layer_digest = Some(input.into()); self } /// <p>The layer digest associated with the failure.</p> pub fn set_layer_digest(mut self, input: std::option::Option<std::string::String>) -> Self { self.layer_digest = input; self } /// <p>The failure code associated with the failure.</p> pub fn failure_code(mut self, input: crate::model::LayerFailureCode) -> Self { self.failure_code = Some(input); self } /// <p>The failure code associated with the failure.</p> pub fn set_failure_code( mut self, input: std::option::Option<crate::model::LayerFailureCode>, ) -> Self { self.failure_code = input; self } /// <p>The reason for the failure.</p> pub fn failure_reason(mut self, input: impl Into<std::string::String>) -> Self { self.failure_reason = Some(input.into()); self } /// <p>The reason for the failure.</p> pub fn set_failure_reason( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.failure_reason = input; self } /// Consumes the builder and constructs a [`LayerFailure`](crate::model::LayerFailure) pub fn build(self) -> crate::model::LayerFailure { crate::model::LayerFailure { layer_digest: self.layer_digest, failure_code: self.failure_code, failure_reason: self.failure_reason, } } } } impl LayerFailure { /// Creates a new builder-style object to manufacture [`LayerFailure`](crate::model::LayerFailure) pub fn builder() -> crate::model::layer_failure::Builder { crate::model::layer_failure::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum LayerFailureCode { #[allow(missing_docs)] // documentation missing in model InvalidLayerDigest, #[allow(missing_docs)] // documentation missing in model MissingLayerDigest, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for LayerFailureCode { fn from(s: &str) -> Self { match s { "InvalidLayerDigest" => LayerFailureCode::InvalidLayerDigest, "MissingLayerDigest" => LayerFailureCode::MissingLayerDigest, other => LayerFailureCode::Unknown(other.to_owned()), } } } impl std::str::FromStr for LayerFailureCode { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(LayerFailureCode::from(s)) } } impl LayerFailureCode { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { LayerFailureCode::InvalidLayerDigest => "InvalidLayerDigest", LayerFailureCode::MissingLayerDigest => "MissingLayerDigest", LayerFailureCode::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["InvalidLayerDigest", "MissingLayerDigest"] } } impl AsRef<str> for LayerFailureCode { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An object representing an Amazon ECR image layer.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct Layer { /// <p>The <code>sha256</code> digest of the image layer.</p> pub layer_digest: std::option::Option<std::string::String>, /// <p>The availability status of the image layer.</p> pub layer_availability: std::option::Option<crate::model::LayerAvailability>, /// <p>The size, in bytes, of the image layer.</p> pub layer_size: std::option::Option<i64>, /// <p>The media type of the layer, such as /// <code>application/vnd.docker.image.rootfs.diff.tar.gzip</code> or /// <code>application/vnd.oci.image.layer.v1.tar+gzip</code>.</p> pub media_type: std::option::Option<std::string::String>, } impl Layer { /// <p>The <code>sha256</code> digest of the image layer.</p> pub fn layer_digest(&self) -> std::option::Option<&str> { self.layer_digest.as_deref() } /// <p>The availability status of the image layer.</p> pub fn layer_availability(&self) -> std::option::Option<&crate::model::LayerAvailability> { self.layer_availability.as_ref() } /// <p>The size, in bytes, of the image layer.</p> pub fn layer_size(&self) -> std::option::Option<i64> { self.layer_size } /// <p>The media type of the layer, such as /// <code>application/vnd.docker.image.rootfs.diff.tar.gzip</code> or /// <code>application/vnd.oci.image.layer.v1.tar+gzip</code>.</p> pub fn media_type(&self) -> std::option::Option<&str> { self.media_type.as_deref() } } impl std::fmt::Debug for Layer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("Layer"); formatter.field("layer_digest", &self.layer_digest); formatter.field("layer_availability", &self.layer_availability); formatter.field("layer_size", &self.layer_size); formatter.field("media_type", &self.media_type); formatter.finish() } } /// See [`Layer`](crate::model::Layer) pub mod layer { /// A builder for [`Layer`](crate::model::Layer) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) layer_digest: std::option::Option<std::string::String>, pub(crate) layer_availability: std::option::Option<crate::model::LayerAvailability>, pub(crate) layer_size: std::option::Option<i64>, pub(crate) media_type: std::option::Option<std::string::String>, } impl Builder { /// <p>The <code>sha256</code> digest of the image layer.</p> pub fn layer_digest(mut self, input: impl Into<std::string::String>) -> Self { self.layer_digest = Some(input.into()); self } /// <p>The <code>sha256</code> digest of the image layer.</p> pub fn set_layer_digest(mut self, input: std::option::Option<std::string::String>) -> Self { self.layer_digest = input; self } /// <p>The availability status of the image layer.</p> pub fn layer_availability(mut self, input: crate::model::LayerAvailability) -> Self { self.layer_availability = Some(input); self } /// <p>The availability status of the image layer.</p> pub fn set_layer_availability( mut self, input: std::option::Option<crate::model::LayerAvailability>, ) -> Self { self.layer_availability = input; self } /// <p>The size, in bytes, of the image layer.</p> pub fn layer_size(mut self, input: i64) -> Self { self.layer_size = Some(input); self } /// <p>The size, in bytes, of the image layer.</p> pub fn set_layer_size(mut self, input: std::option::Option<i64>) -> Self { self.layer_size = input; self } /// <p>The media type of the layer, such as /// <code>application/vnd.docker.image.rootfs.diff.tar.gzip</code> or /// <code>application/vnd.oci.image.layer.v1.tar+gzip</code>.</p> pub fn media_type(mut self, input: impl Into<std::string::String>) -> Self { self.media_type = Some(input.into()); self } /// <p>The media type of the layer, such as /// <code>application/vnd.docker.image.rootfs.diff.tar.gzip</code> or /// <code>application/vnd.oci.image.layer.v1.tar+gzip</code>.</p> pub fn set_media_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.media_type = input; self } /// Consumes the builder and constructs a [`Layer`](crate::model::Layer) pub fn build(self) -> crate::model::Layer { crate::model::Layer { layer_digest: self.layer_digest, layer_availability: self.layer_availability, layer_size: self.layer_size, media_type: self.media_type, } } } } impl Layer { /// Creates a new builder-style object to manufacture [`Layer`](crate::model::Layer) pub fn builder() -> crate::model::layer::Builder { crate::model::layer::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum LayerAvailability { #[allow(missing_docs)] // documentation missing in model Available, #[allow(missing_docs)] // documentation missing in model Unavailable, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for LayerAvailability { fn from(s: &str) -> Self { match s { "AVAILABLE" => LayerAvailability::Available, "UNAVAILABLE" => LayerAvailability::Unavailable, other => LayerAvailability::Unknown(other.to_owned()), } } } impl std::str::FromStr for LayerAvailability { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(LayerAvailability::from(s)) } } impl LayerAvailability { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { LayerAvailability::Available => "AVAILABLE", LayerAvailability::Unavailable => "UNAVAILABLE", LayerAvailability::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["AVAILABLE", "UNAVAILABLE"] } } impl AsRef<str> for LayerAvailability { fn as_ref(&self) -> &str { self.as_str() } }
43.772419
193
0.630085
48f53ba0e11a5797940d88955ceb685c2ae0c2f8
18,128
/* Copyright [2019] [Kieran White] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{copyable, stm}; use log::trace; use std::collections::VecDeque; use unicode_segmentation::UnicodeSegmentation; use FormattingMachine::*; #[derive(Debug, PartialEq)] pub enum Error { InvalidGraphemeLength(ByteWidth), TokenTooLong, IllegalState, } #[derive(Debug)] pub struct Dims(pub GlyphXCnt, pub GlyphYCnt); impl Dims { pub fn width(&self) -> usize { (self.0).0 } } const BREAKABLE: &str = "-_"; const SPACES: &str = " \t"; copyable!(ByteWidth, usize); const ZERO_BYTES: ByteWidth = ByteWidth(0); copyable!(GlyphXCnt, usize); const ZERO_GLYPHS: GlyphXCnt = GlyphXCnt(0); copyable!(GlyphYCnt, usize); impl GlyphXCnt { pub fn is_none(&self) -> bool { self.0 == 0 } } struct GlyphLayout { screen_widths: VecDeque<ByteWidth>, line_length: GlyphXCnt, last_line_offset: GlyphXCnt, last_line_bytes: ByteWidth, } impl GlyphLayout { pub fn new(line_length: GlyphXCnt) -> GlyphLayout { GlyphLayout { screen_widths: VecDeque::<ByteWidth>::new(), line_length, last_line_offset: ZERO_GLYPHS, last_line_bytes: ZERO_BYTES, } } pub fn partial_width(&self) -> GlyphXCnt { GlyphXCnt(self.last_line_offset.0) } pub fn width(&self) -> GlyphXCnt { self.line_length } pub fn reset(&mut self) { self.screen_widths.clear(); self.last_line_offset = ZERO_GLYPHS; self.last_line_bytes = ZERO_BYTES; } pub fn add(&mut self, added_bytes: ByteWidth) -> Result<(), Error> { if added_bytes.0 == 0 { return Err(Error::InvalidGraphemeLength(added_bytes)); } let new_bytes = ByteWidth(self.last_line_bytes.0 + added_bytes.0); let new_offset = GlyphXCnt(self.last_line_offset.0 + 1); if new_offset.0 % self.line_length.0 == 0 { self.screen_widths.push_back(new_bytes); self.last_line_bytes = ZERO_BYTES; self.last_line_offset = ZERO_GLYPHS; } else { self.last_line_bytes = new_bytes; self.last_line_offset = new_offset; } Ok(()) } pub fn unshift_screen(&mut self) -> Option<ByteWidth> { self.screen_widths.pop_front() } pub fn is_multirow(&self) -> bool { self.screen_widths.len() > 0 } pub fn next_length(&self) -> GlyphXCnt { if self.is_multirow() { self.line_length } else { GlyphXCnt(self.last_line_offset.0) } } pub fn fits(&self, c: GlyphXCnt) -> bool { if c.is_none() { true } else if self.is_multirow() { false } else { return self.last_line_offset.0 + c.0 as usize <= self.width().0; } } } struct SizedString { val: String, len: GlyphXCnt, } impl SizedString { pub fn new(val: String, len: GlyphXCnt) -> SizedString { SizedString { val, len } } } struct Pending { value: String, starting_spaces: String, layout: GlyphLayout, } enum ConsumptionState { Consumed(SizedString), Empty, TooLarge, } enum Placement { Assigned(ConsumptionState, GlyphXCnt), Invalid, } impl Pending { pub fn new(line_length: GlyphXCnt) -> Pending { Pending { value: String::new(), starting_spaces: String::with_capacity(10), layout: GlyphLayout::new(line_length), } } pub fn consume(&mut self, c: GlyphXCnt) -> ConsumptionState { //returns none when the token won't fit if c.is_none() { self.unshift_to_row_start() } else if self.layout.is_multirow() { //We've not at the start of a line and the current token is part of a multi-row token sequence so it won't fit ConsumptionState::TooLarge } else { let num_spaces: usize = self.starting_spaces.len(); let total_len = GlyphXCnt(self.layout.next_length().0 + num_spaces); if ZERO_GLYPHS == total_len { return ConsumptionState::Empty; } else if self.layout.fits(GlyphXCnt(c.0 + num_spaces)) { let result = ConsumptionState::Consumed(SizedString { val: self.starting_spaces.to_string() + &self.value, len: GlyphXCnt(self.layout.partial_width().0 + num_spaces), }); self.reset(); result } else { //The current token won't fit. It's not part of multi-row token sequence and we're not at the start of a line. ConsumptionState::TooLarge } } } pub fn add_glyph(&mut self, new_glyph: &str) -> Result<(), Error> { if SPACES.contains(new_glyph) && self.value.len() == 0 { self.starting_spaces += " "; } else { self.value += new_glyph; self.layout.add(ByteWidth(new_glyph.len()))?; } Ok(()) } fn reset(&mut self) { self.value.clear(); self.starting_spaces.clear(); self.layout.reset(); } fn unshift_to_row_start(&mut self) -> ConsumptionState { if let Some(ByteWidth(next_screen_width_in_bytes)) = self.layout.unshift_screen() { let (screen_glyphs, new_value) = { let (screen_glyphs, new_value) = self.value.split_at_mut(next_screen_width_in_bytes); (screen_glyphs.to_string(), new_value) }; self.value = new_value.to_string(); self.starting_spaces.clear(); ConsumptionState::Consumed(SizedString::new( screen_glyphs.to_string(), self.layout.width(), )) } else { let result = self.value.clone(); if result.len() == 0 { ConsumptionState::Empty } else { let length = self.layout.partial_width(); self.reset(); ConsumptionState::Consumed(SizedString::new(result, length)) } } } } stm!(machine tok_stm, FormattingMachine, FormattingAtEnd, FormattingTerminals, []=> Empty() |end|, { [TokenComplete] => BuildingBreakable() |end|; [TokenComplete] => NotStartedBuildingNonBreakable() |end|; [Empty, NotStartedBuildingNonBreakable, TokenComplete] => StartedBuildingNonBreakable() |end|; [Empty, BuildingBreakable, StartedBuildingNonBreakable] => TokenComplete() }); pub struct LeftFormatter { size: Dims, all_splitters: String, } impl LeftFormatter { pub fn new(size: Dims) -> LeftFormatter { LeftFormatter { size, all_splitters: BREAKABLE.to_string() + SPACES, } } fn build_out( pending: &mut Pending, output: &mut Option<String>, col: &mut GlyphXCnt, ) -> Result<(), Error> { let mut new_col = *col; while let Placement::Assigned( ConsumptionState::Consumed(SizedString { val: tok, len: width, }), placement_col, ) = match pending.consume(new_col) { consumed @ ConsumptionState::Consumed(_) => Placement::Assigned(consumed, new_col), ConsumptionState::TooLarge => { if new_col != ZERO_GLYPHS { let start_line_token = pending.consume(ZERO_GLYPHS); match start_line_token { ConsumptionState::Consumed(SizedString { val: tok, len: width, }) => Placement::Assigned( ConsumptionState::Consumed(SizedString { val: "\n".to_owned() + &tok, len: width, }), ZERO_GLYPHS, ), ConsumptionState::Empty => Placement::Invalid, ConsumptionState::TooLarge => Err(Error::TokenTooLong)?, } } else { Err(Error::TokenTooLong)? } } ConsumptionState::Empty => Placement::Invalid, } { *output = if let Some(ref orig) = *output { Some(orig.to_owned() + &tok) } else { Some(tok) }; new_col = GlyphXCnt(placement_col.0 + width.0); } *col = new_col; Ok(()) } pub fn just_lines(&self, unformatted: &str) -> Result<Vec<String>, Error> { Ok(unformatted .lines() .map(|l| { let mut mach = FormattingMachine::new( (), Box::new(|mach| { trace!("dropping FormattingMachine: {:?}", mach); match mach { FormattingAtEnd::Empty(st) => FormattingTerminals::Empty(st), FormattingAtEnd::BuildingBreakable(st) => { FormattingTerminals::BuildingBreakable(st) } FormattingAtEnd::NotStartedBuildingNonBreakable(st) => { FormattingTerminals::NotStartedBuildingNonBreakable(st) } FormattingAtEnd::StartedBuildingNonBreakable(st) => { FormattingTerminals::StartedBuildingNonBreakable(st) } FormattingAtEnd::TokenComplete(_st) => panic!( "Dropping when state is not accepting: {:?}", stringify!(mach) ), } }), ); let mut col = GlyphXCnt(0); let mut output = None; let mut pending = Pending::new(GlyphXCnt(self.size.width())); let graphemes = l.graphemes(true).collect::<Vec<&str>>(); for grapheme in graphemes { loop { mach = match mach { Empty(st) => { col = GlyphXCnt(0); if self.all_splitters.contains(grapheme) { TokenComplete(st.into()) } else { pending.add_glyph(grapheme)?; //pending start StartedBuildingNonBreakable(st.into()) } } BuildingBreakable(st) => TokenComplete(st.into()), StartedBuildingNonBreakable(st) => { if self.all_splitters.contains(grapheme) { TokenComplete(st.into()) } else { pending.add_glyph(grapheme)?; //pending start StartedBuildingNonBreakable(st.into()) } } NotStartedBuildingNonBreakable(st) => { pending.add_glyph(grapheme)?; //pending start if grapheme is not a space if SPACES.contains(grapheme) { NotStartedBuildingNonBreakable(st.into()) } else { StartedBuildingNonBreakable(st.into()) } } TokenComplete(st) => { LeftFormatter::build_out(&mut pending, &mut output, &mut col)?; pending.add_glyph(grapheme)?; //pending start if BREAKABLE.contains(grapheme) { BuildingBreakable(st.into()) } else if SPACES.contains(grapheme) { NotStartedBuildingNonBreakable(st.into()) //pending start if grapheme is not a space } else { StartedBuildingNonBreakable(st.into()) //pending start if grapheme is not a space } } }; if let &TokenComplete(_) = &mach { } else { break; } } } LeftFormatter::build_out(&mut pending, &mut output, &mut col)?; if let Some(inner) = output { Ok(inner) } else { Ok(String::new()) } }) .collect::<Result<Vec<String>, Error>>()? .iter() .map(|string_ref| string_ref.to_string()) .collect::<Vec<String>>()) } pub fn just(&self, unformatted: &str) -> Result<String, Error> { Ok(self.just_lines(unformatted)?.join("\n")) } } #[cfg(test)] mod tests { use crate::formatter::{Dims, GlyphXCnt, GlyphYCnt, LeftFormatter}; #[test] fn just() { let f = LeftFormatter::new(Dims(GlyphXCnt(5), GlyphYCnt(15))); assert_eq!(f.just("foo blah"), Ok("foo\nblah".to_string())); assert_eq!(f.just("foo bla-h"), Ok("foo\nbla-h".to_string())); assert_eq!(f.just("foo bla h"), Ok("foo\nbla h".to_string())); assert_eq!(f.just("foo bl--h"), Ok("foo\nbl--h".to_string())); assert_eq!(f.just("foo bl h"), Ok("foo\nbl h".to_string())); assert_eq!(f.just("fo bl123456h"), Ok("fo\nbl123\n456h".to_string())); assert_eq!(f.just("fo bl123456h"), Ok("fo\nbl123\n456h".to_string())); assert_eq!(f.just("fo-bl123456h"), Ok("fo-\nbl123\n456h".to_string())); assert_eq!(f.just("fo--bl123456h"), Ok("fo--\nbl123\n456h".to_string())); assert_eq!(f.just(" bl123456h"), Ok("bl123\n456h".to_string())); assert_eq!( f.just("fo----bl123456h"), Ok("fo---\n-\nbl123\n456h".to_string()) ); assert_eq!( f.just("fo-bl123456hfar"), Ok("fo-\nbl123\n456hf\nar".to_string()) ); assert_eq!(f.just(" bl123456h"), Ok("bl123\n456h".to_string())); assert_eq!( f.just("abc -52 123456"), Ok("abc\n-52\n12345\n6".to_string()) ); assert_eq!( f.just(" -52456 123456"), Ok("-5245\n6\n12345\n6".to_string()) ); assert_eq!(f.just(""), Ok("".to_string())); assert_eq!(f.just(" "), Ok("".to_string())); assert_eq!(f.just(" "), Ok("".to_string())); assert_eq!(f.just(" "), Ok("".to_string())); assert_eq!(f.just(" "), Ok("".to_string())); assert_eq!(f.just(" a"), Ok("a".to_string())); assert_eq!(f.just(" a"), Ok("a".to_string())); assert_eq!(f.just("ab a"), Ok("ab\na".to_string())); assert_eq!(f.just("ab a"), Ok("ab\na".to_string())); assert_eq!(f.just(" abcdef"), Ok("abcde\nf".to_string())); assert_eq!(f.just(" abcdef"), Ok("abcde\nf".to_string())); assert_eq!(f.just("ab abcdef"), Ok("ab\nabcde\nf".to_string())); assert_eq!(f.just("ab abcdef"), Ok("ab\nabcde\nf".to_string())); assert_eq!(f.just(" a"), Ok("a".to_string())); assert_eq!(f.just(" a"), Ok("a".to_string())); assert_eq!(f.just("abcdef a"), Ok("abcde\nf\na".to_string())); assert_eq!(f.just("abcdef a"), Ok("abcde\nf\na".to_string())); assert_eq!(f.just("-"), Ok("-".to_string())); assert_eq!(f.just("--"), Ok("--".to_string())); assert_eq!(f.just("-----"), Ok("-----".to_string())); assert_eq!(f.just("------"), Ok("-----\n-".to_string())); assert_eq!(f.just("-----a"), Ok("-----\na".to_string())); assert_eq!(f.just("------a"), Ok("-----\n-a".to_string())); assert_eq!(f.just("ab-----a"), Ok("ab---\n--a".to_string())); assert_eq!(f.just("ab------a"), Ok("ab---\n---a".to_string())); assert_eq!(f.just("-----abcdef"), Ok("-----\nabcde\nf".to_string())); assert_eq!(f.just("------abcdef"), Ok("-----\n-\nabcde\nf".to_string())); assert_eq!( f.just("ab-----abcdef"), Ok("ab---\n--\nabcde\nf".to_string()) ); assert_eq!( f.just("ab------abcdef"), Ok("ab---\n---\nabcde\nf".to_string()) ); assert_eq!(f.just("-----a"), Ok("-----\na".to_string())); assert_eq!(f.just("------a"), Ok("-----\n-a".to_string())); assert_eq!(f.just("abcdef-----a"), Ok("abcde\nf----\n-a".to_string())); assert_eq!(f.just("abcdef------a"), Ok("abcde\nf----\n--a".to_string())); assert_eq!( f.just( "foo blah foo bla-h foo bla h foo bl--h foo bl h fo bl123456h fo bl123456h fo-bl123456h fo--bl123456h bl123456h " ), Ok("foo blah foo bla-h foo bla h foo bl--h foo bl h fo bl123 456h fo bl123 456h fo- bl123 456h fo-- bl123 456h bl123 456h " .to_string()) ); } }
34.59542
126
0.500221
8ff6a25e39f95c9861f6d261234a83577c3dd39d
2,195
use core::fmt; use core::pin::Pin; use futures_core::future::{FusedFuture, Future}; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Future for the [`for_each`](super::StreamExt::for_each) method. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct ForEach<St, Fut, F> { stream: St, f: F, future: Option<Fut>, } impl<St, Fut, F> Unpin for ForEach<St, Fut, F> where St: Unpin, Fut: Unpin, {} impl<St, Fut, F> fmt::Debug for ForEach<St, Fut, F> where St: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ForEach") .field("stream", &self.stream) .field("future", &self.future) .finish() } } impl<St, Fut, F> ForEach<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future<Output = ()>, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); unsafe_pinned!(future: Option<Fut>); pub(super) fn new(stream: St, f: F) -> ForEach<St, Fut, F> { ForEach { stream, f, future: None, } } } impl<St: FusedStream, Fut, F> FusedFuture for ForEach<St, Fut, F> { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() } } impl<St, Fut, F> Future for ForEach<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future<Output = ()>, { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { loop { if let Some(future) = self.as_mut().future().as_pin_mut() { ready!(future.poll(cx)); } self.as_mut().future().set(None); match ready!(self.as_mut().stream().poll_next(cx)) { Some(e) => { let future = (self.as_mut().f())(e); self.as_mut().future().set(Some(future)); } None => { return Poll::Ready(()); } } } } }
25.823529
73
0.523918
72a9d65e31087ace519217cfa20ab96fc0835bf3
4,284
// // Copyright (C) 2019 Kubos Corporation // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use comms_service::*; use std::cell::RefCell; use std::str; use std::sync::{Arc, Barrier, Mutex}; use std::thread; use warp::{self, Buf, Filter}; // This MockComms structure allows for easy integration testing // of the comms_service crate by giving direct access to the // "radio" buffers that ground/flight read and write to. #[derive(Debug)] pub struct MockComms { pub read_buff: RefCell<Vec<Vec<u8>>>, pub write_buff: RefCell<Vec<Vec<u8>>>, } impl MockComms { pub fn new() -> Self { MockComms { read_buff: RefCell::new(Vec::<Vec<u8>>::with_capacity(50)), write_buff: RefCell::new(Vec::<Vec<u8>>::with_capacity(50)), } } // Used by comms service to read from radio pub fn read(&self) -> CommsResult<Vec<u8>> { let mut buffer = self.read_buff.borrow_mut(); if let Some(data) = buffer.pop() { return Ok(data); } bail!("Failed to get data"); } // Used by comms service to write to radio pub fn write(&self, data: &[u8]) -> CommsResult<()> { let mut buffer = self.write_buff.borrow_mut(); buffer.push(data.to_vec()); Ok(()) } // Push data into the radio's read buffer // "Ground has sent a packet to be read" pub fn push_read(&self, data: &[u8]) { let mut buffer = self.read_buff.borrow_mut(); buffer.push(data.to_vec()); } // Remove a packet from the radio's write buffer // "Ground is reading a packet from the radio" pub fn pop_write(&self) -> Option<Vec<u8>> { let mut buffer = self.write_buff.borrow_mut(); let ret_data = buffer.pop(); ret_data } } // Read fn for CommsControlBlock pub fn read(socket: &Arc<Mutex<MockComms>>) -> CommsResult<Vec<u8>> { if let Ok(socket) = socket.lock() { socket.read() } else { bail!("Failed to lock socket"); } } // Write fn for CommsControlBlock pub fn write(socket: &Arc<Mutex<MockComms>>, data: &[u8]) -> CommsResult<()> { if let Ok(socket) = socket.lock() { socket.write(data).unwrap(); Ok(()) } else { bail!("Failed to lock socket"); } } // Convenience config generator pub fn comms_config( sat_ip: &str, ground_ip: &str, ground_port: u16, downlink_port: u16, ) -> CommsConfig { CommsConfig { max_num_handlers: Some(10), downlink_ports: Some(vec![downlink_port]), timeout: Some(1000), ground_ip: ground_ip.to_owned(), ground_port: Some(ground_port), satellite_ip: sat_ip.to_owned(), } } pub fn spawn_http_server( payload: Vec<u8>, thread_data: Arc<Mutex<Vec<u8>>>, service_ip: &str, barrier: Arc<Barrier>, ) { let routes = warp::post2() .and(warp::any()) .and(warp::body::concat()) .map(move |mut body: warp::body::FullBody| { let mut data = vec![]; let mut remaining = body.remaining(); while remaining != 0 { let cnt = body.bytes().len(); let mut body_bytes = body.bytes().to_vec(); data.append(&mut body_bytes); body.advance(cnt); remaining -= cnt; } if let Ok(mut thread_data_handle) = thread_data.lock() { thread_data_handle.append(&mut data); } barrier.wait(); // Send a response back to the ground via the handler port str::from_utf8(&payload).unwrap().to_owned() }); let service_ip: std::net::SocketAddrV4 = service_ip.parse().unwrap(); thread::spawn(move || warp::serve(routes).run(service_ip)); }
30.169014
78
0.603641
e40e09eadc8d48179f4e5350be1e0d64ea5f8427
15,714
// This file is generated. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] const METHOD_DEBUG_GET: ::grpcio::Method<super::debugpb::GetRequest, super::debugpb::GetResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/Get", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_RAFT_LOG: ::grpcio::Method<super::debugpb::RaftLogRequest, super::debugpb::RaftLogResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/RaftLog", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_REGION_INFO: ::grpcio::Method<super::debugpb::RegionInfoRequest, super::debugpb::RegionInfoResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/RegionInfo", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_REGION_SIZE: ::grpcio::Method<super::debugpb::RegionSizeRequest, super::debugpb::RegionSizeResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/RegionSize", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_SCAN_MVCC: ::grpcio::Method<super::debugpb::ScanMvccRequest, super::debugpb::ScanMvccResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::ServerStreaming, name: "/debugpb.Debug/ScanMvcc", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_COMPACT: ::grpcio::Method<super::debugpb::CompactRequest, super::debugpb::CompactResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/Compact", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_INJECT_FAIL_POINT: ::grpcio::Method<super::debugpb::InjectFailPointRequest, super::debugpb::InjectFailPointResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/InjectFailPoint", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_RECOVER_FAIL_POINT: ::grpcio::Method<super::debugpb::RecoverFailPointRequest, super::debugpb::RecoverFailPointResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/RecoverFailPoint", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; const METHOD_DEBUG_LIST_FAIL_POINTS: ::grpcio::Method<super::debugpb::ListFailPointsRequest, super::debugpb::ListFailPointsResponse> = ::grpcio::Method { ty: ::grpcio::MethodType::Unary, name: "/debugpb.Debug/ListFailPoints", req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de }, }; pub struct DebugClient { client: ::grpcio::Client, } impl DebugClient { pub fn new(channel: ::grpcio::Channel) -> Self { DebugClient { client: ::grpcio::Client::new(channel), } } pub fn get_opt(&self, req: &super::debugpb::GetRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::GetResponse> { self.client.unary_call(&METHOD_DEBUG_GET, req, opt) } pub fn get(&self, req: &super::debugpb::GetRequest) -> ::grpcio::Result<super::debugpb::GetResponse> { self.get_opt(req, ::grpcio::CallOption::default()) } pub fn get_async_opt(&self, req: &super::debugpb::GetRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::GetResponse>> { self.client.unary_call_async(&METHOD_DEBUG_GET, req, opt) } pub fn get_async(&self, req: &super::debugpb::GetRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::GetResponse>> { self.get_async_opt(req, ::grpcio::CallOption::default()) } pub fn raft_log_opt(&self, req: &super::debugpb::RaftLogRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::RaftLogResponse> { self.client.unary_call(&METHOD_DEBUG_RAFT_LOG, req, opt) } pub fn raft_log(&self, req: &super::debugpb::RaftLogRequest) -> ::grpcio::Result<super::debugpb::RaftLogResponse> { self.raft_log_opt(req, ::grpcio::CallOption::default()) } pub fn raft_log_async_opt(&self, req: &super::debugpb::RaftLogRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RaftLogResponse>> { self.client.unary_call_async(&METHOD_DEBUG_RAFT_LOG, req, opt) } pub fn raft_log_async(&self, req: &super::debugpb::RaftLogRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RaftLogResponse>> { self.raft_log_async_opt(req, ::grpcio::CallOption::default()) } pub fn region_info_opt(&self, req: &super::debugpb::RegionInfoRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::RegionInfoResponse> { self.client.unary_call(&METHOD_DEBUG_REGION_INFO, req, opt) } pub fn region_info(&self, req: &super::debugpb::RegionInfoRequest) -> ::grpcio::Result<super::debugpb::RegionInfoResponse> { self.region_info_opt(req, ::grpcio::CallOption::default()) } pub fn region_info_async_opt(&self, req: &super::debugpb::RegionInfoRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RegionInfoResponse>> { self.client.unary_call_async(&METHOD_DEBUG_REGION_INFO, req, opt) } pub fn region_info_async(&self, req: &super::debugpb::RegionInfoRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RegionInfoResponse>> { self.region_info_async_opt(req, ::grpcio::CallOption::default()) } pub fn region_size_opt(&self, req: &super::debugpb::RegionSizeRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::RegionSizeResponse> { self.client.unary_call(&METHOD_DEBUG_REGION_SIZE, req, opt) } pub fn region_size(&self, req: &super::debugpb::RegionSizeRequest) -> ::grpcio::Result<super::debugpb::RegionSizeResponse> { self.region_size_opt(req, ::grpcio::CallOption::default()) } pub fn region_size_async_opt(&self, req: &super::debugpb::RegionSizeRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RegionSizeResponse>> { self.client.unary_call_async(&METHOD_DEBUG_REGION_SIZE, req, opt) } pub fn region_size_async(&self, req: &super::debugpb::RegionSizeRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RegionSizeResponse>> { self.region_size_async_opt(req, ::grpcio::CallOption::default()) } pub fn scan_mvcc_opt(&self, req: &super::debugpb::ScanMvccRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientSStreamReceiver<super::debugpb::ScanMvccResponse>> { self.client.server_streaming(&METHOD_DEBUG_SCAN_MVCC, req, opt) } pub fn scan_mvcc(&self, req: &super::debugpb::ScanMvccRequest) -> ::grpcio::Result<::grpcio::ClientSStreamReceiver<super::debugpb::ScanMvccResponse>> { self.scan_mvcc_opt(req, ::grpcio::CallOption::default()) } pub fn compact_opt(&self, req: &super::debugpb::CompactRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::CompactResponse> { self.client.unary_call(&METHOD_DEBUG_COMPACT, req, opt) } pub fn compact(&self, req: &super::debugpb::CompactRequest) -> ::grpcio::Result<super::debugpb::CompactResponse> { self.compact_opt(req, ::grpcio::CallOption::default()) } pub fn compact_async_opt(&self, req: &super::debugpb::CompactRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::CompactResponse>> { self.client.unary_call_async(&METHOD_DEBUG_COMPACT, req, opt) } pub fn compact_async(&self, req: &super::debugpb::CompactRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::CompactResponse>> { self.compact_async_opt(req, ::grpcio::CallOption::default()) } pub fn inject_fail_point_opt(&self, req: &super::debugpb::InjectFailPointRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::InjectFailPointResponse> { self.client.unary_call(&METHOD_DEBUG_INJECT_FAIL_POINT, req, opt) } pub fn inject_fail_point(&self, req: &super::debugpb::InjectFailPointRequest) -> ::grpcio::Result<super::debugpb::InjectFailPointResponse> { self.inject_fail_point_opt(req, ::grpcio::CallOption::default()) } pub fn inject_fail_point_async_opt(&self, req: &super::debugpb::InjectFailPointRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::InjectFailPointResponse>> { self.client.unary_call_async(&METHOD_DEBUG_INJECT_FAIL_POINT, req, opt) } pub fn inject_fail_point_async(&self, req: &super::debugpb::InjectFailPointRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::InjectFailPointResponse>> { self.inject_fail_point_async_opt(req, ::grpcio::CallOption::default()) } pub fn recover_fail_point_opt(&self, req: &super::debugpb::RecoverFailPointRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::RecoverFailPointResponse> { self.client.unary_call(&METHOD_DEBUG_RECOVER_FAIL_POINT, req, opt) } pub fn recover_fail_point(&self, req: &super::debugpb::RecoverFailPointRequest) -> ::grpcio::Result<super::debugpb::RecoverFailPointResponse> { self.recover_fail_point_opt(req, ::grpcio::CallOption::default()) } pub fn recover_fail_point_async_opt(&self, req: &super::debugpb::RecoverFailPointRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RecoverFailPointResponse>> { self.client.unary_call_async(&METHOD_DEBUG_RECOVER_FAIL_POINT, req, opt) } pub fn recover_fail_point_async(&self, req: &super::debugpb::RecoverFailPointRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::RecoverFailPointResponse>> { self.recover_fail_point_async_opt(req, ::grpcio::CallOption::default()) } pub fn list_fail_points_opt(&self, req: &super::debugpb::ListFailPointsRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::debugpb::ListFailPointsResponse> { self.client.unary_call(&METHOD_DEBUG_LIST_FAIL_POINTS, req, opt) } pub fn list_fail_points(&self, req: &super::debugpb::ListFailPointsRequest) -> ::grpcio::Result<super::debugpb::ListFailPointsResponse> { self.list_fail_points_opt(req, ::grpcio::CallOption::default()) } pub fn list_fail_points_async_opt(&self, req: &super::debugpb::ListFailPointsRequest, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::ListFailPointsResponse>> { self.client.unary_call_async(&METHOD_DEBUG_LIST_FAIL_POINTS, req, opt) } pub fn list_fail_points_async(&self, req: &super::debugpb::ListFailPointsRequest) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::debugpb::ListFailPointsResponse>> { self.list_fail_points_async_opt(req, ::grpcio::CallOption::default()) } pub fn spawn<F>(&self, f: F) where F: ::futures::Future<Item = (), Error = ()> + Send + 'static { self.client.spawn(f) } } pub trait Debug { fn get(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::GetRequest, sink: ::grpcio::UnarySink<super::debugpb::GetResponse>); fn raft_log(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::RaftLogRequest, sink: ::grpcio::UnarySink<super::debugpb::RaftLogResponse>); fn region_info(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::RegionInfoRequest, sink: ::grpcio::UnarySink<super::debugpb::RegionInfoResponse>); fn region_size(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::RegionSizeRequest, sink: ::grpcio::UnarySink<super::debugpb::RegionSizeResponse>); fn scan_mvcc(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::ScanMvccRequest, sink: ::grpcio::ServerStreamingSink<super::debugpb::ScanMvccResponse>); fn compact(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::CompactRequest, sink: ::grpcio::UnarySink<super::debugpb::CompactResponse>); fn inject_fail_point(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::InjectFailPointRequest, sink: ::grpcio::UnarySink<super::debugpb::InjectFailPointResponse>); fn recover_fail_point(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::RecoverFailPointRequest, sink: ::grpcio::UnarySink<super::debugpb::RecoverFailPointResponse>); fn list_fail_points(&self, ctx: ::grpcio::RpcContext, req: super::debugpb::ListFailPointsRequest, sink: ::grpcio::UnarySink<super::debugpb::ListFailPointsResponse>); } pub fn create_debug<S: Debug + Send + Clone + 'static>(s: S) -> ::grpcio::Service { let mut builder = ::grpcio::ServiceBuilder::new(); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_GET, move |ctx, req, resp| { instance.get(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_RAFT_LOG, move |ctx, req, resp| { instance.raft_log(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_REGION_INFO, move |ctx, req, resp| { instance.region_info(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_REGION_SIZE, move |ctx, req, resp| { instance.region_size(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_server_streaming_handler(&METHOD_DEBUG_SCAN_MVCC, move |ctx, req, resp| { instance.scan_mvcc(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_COMPACT, move |ctx, req, resp| { instance.compact(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_INJECT_FAIL_POINT, move |ctx, req, resp| { instance.inject_fail_point(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_RECOVER_FAIL_POINT, move |ctx, req, resp| { instance.recover_fail_point(ctx, req, resp) }); let instance = s.clone(); builder = builder.add_unary_handler(&METHOD_DEBUG_LIST_FAIL_POINTS, move |ctx, req, resp| { instance.list_fail_points(ctx, req, resp) }); builder.build() }
54.752613
215
0.700904
ef808b64863096782ab5075a43401390124856c8
2,468
use super::Loc; use ir::{BlockEnd, BlockId, Function, Instruction, Reg}; use std::collections::{HashMap, HashSet}; struct Volatility<'a> { function: &'a Function, reg: Reg, volatile_locations: HashSet<Loc>, checked_blocks: HashSet<(BlockId, bool)>, } impl<'a> Volatility<'a> { fn new(function: &'a Function, reg: Reg) -> Self { Volatility { function, reg, volatile_locations: HashSet::new(), checked_blocks: HashSet::new(), } } fn walk_block(&mut self, id: BlockId, volatile_start: bool) { if self.checked_blocks.contains(&(id, volatile_start)) { return; } self.checked_blocks.insert((id, volatile_start)); let block = &self.function.blocks[&id]; let mut is_volatile = volatile_start; for (pos, instr) in block.ops.iter().enumerate() { if is_volatile { self.volatile_locations.insert(Loc { block: id, pos }); } if referenced_register(instr) == Some(self.reg) { is_volatile = true; } if let Instruction::Drop(reg) = *instr { if reg == self.reg { is_volatile = false; } } } if is_volatile { self.volatile_locations.insert(Loc { block: id, pos: block.ops.len(), }); } match block.end { BlockEnd::Branch(_, a, b) => { self.walk_block(a, is_volatile); self.walk_block(b, is_volatile); } BlockEnd::Jump(a) => { self.walk_block(a, is_volatile); } BlockEnd::Return(_) | BlockEnd::ReturnProc | BlockEnd::Unreachable => {} } } } fn referenced_register(instr: &Instruction) -> Option<Reg> { match *instr { Instruction::TakeAddress(_, reg, _) => Some(reg), _ => None, } } pub fn register_volatile_locations(f: &Function, reg: Reg) -> HashSet<Loc> { let mut ctx = Volatility::new(f, reg); for &id in f.blocks.keys() { ctx.walk_block(id, false); } ctx.volatile_locations } pub fn volatile_locations(f: &Function) -> HashMap<Reg, HashSet<Loc>> { let mut locations = HashMap::new(); for &reg in f.registers.keys() { locations.insert(reg, register_volatile_locations(f, reg)); } locations }
29.73494
84
0.538088
62b72dfc949ebdce3a526d74c6be92eb20253e68
11,654
use alloc::vec::Vec; use core::result::Result; use ckb_std::{ ckb_constants::Source, debug, error::SysError, high_level::{load_cell_data, load_cell_lock_hash, load_cell_type_hash, load_script_hash}, }; use asvc_rollup::block::{Block, CellUpks}; use ckb_zkp::curve::bn_256::Bn_256; use crate::error::Error; // use simple UDT length const UDT_LEN: usize = 16; // u128 const BLOCK_CELL: usize = 0; const UPK_CELL: usize = 1; pub fn main() -> Result<(), Error> { // load now commit let now_commit = match load_cell_data(BLOCK_CELL, Source::Output) { Ok(data) => data, Err(err) => return Err(err.into()), }; let now_com_lock = load_cell_lock_hash(BLOCK_CELL, Source::Output)?; if now_commit.len() == 0 { return Err(Error::LengthNotEnough); } let now_upk = match load_cell_data(UPK_CELL, Source::Output) { Ok(data) => data, Err(err) => return Err(err.into()), }; let now_upk_lock = load_cell_lock_hash(UPK_CELL, Source::Output)?; let pre_commit = match load_cell_data(BLOCK_CELL, Source::Input) { Ok(data) => data, Err(err) => return Err(err.into()), }; let pre_com_lock = load_cell_lock_hash(BLOCK_CELL, Source::Input)?; let pre_upk = match load_cell_data(UPK_CELL, Source::Input) { Ok(data) => data, Err(err) => return Err(err.into()), }; let pre_upk_lock = load_cell_lock_hash(UPK_CELL, Source::Input)?; if now_upk != pre_upk { return Err(Error::Upk); } let self_script_hash = load_script_hash().unwrap(); if self_script_hash != now_com_lock { return Err(Error::Verify); } if (now_com_lock != now_upk_lock) || (now_com_lock != pre_com_lock) || (now_com_lock != pre_upk_lock) { return Err(Error::Verify); } let op = now_commit[0]; match op { 1u8 => { // DEPOSIT // // input0 => pre_commit // input1 => upk // input2 => pre_udt_pool // input3..n-1 => udt_unspend // output0 => now_commit // output1 => upk // output2 => now_udt_pool // output3..n-1 => udt_change // 2. pre udt amount in pool. debug!("DEPOSIT"); let pre_amount = match load_cell_data(2, Source::Input) { Ok(data) => { let mut buf = [0u8; UDT_LEN]; if data.len() != UDT_LEN { return Err(Error::Encoding); } buf.copy_from_slice(&data); u128::from_le_bytes(buf) } Err(err) => return Err(err.into()), }; let pre_amount_lock = load_cell_lock_hash(2, Source::Input)?; let pre_amount_type = load_cell_type_hash(2, Source::Input)?; // 3. inputs udt deposit. let mut deposit_amount: u128 = 0; let mut deposit_buf = [0u8; UDT_LEN]; for i in 3.. { let data = match load_cell_data(i, Source::Input) { Ok(data) => data, Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err.into()), }; let udt_type = load_cell_type_hash(i, Source::Input)?; if udt_type != pre_amount_type { continue; } if data.len() != UDT_LEN { return Err(Error::Encoding); } deposit_buf.copy_from_slice(&data); deposit_amount += u128::from_le_bytes(deposit_buf); } // 4. output udt amount. let now_amount = match load_cell_data(2, Source::Output) { Ok(data) => { let mut buf = [0u8; UDT_LEN]; if data.len() != UDT_LEN { return Err(Error::Encoding); } buf.copy_from_slice(&data); u128::from_le_bytes(buf) } Err(err) => return Err(err.into()), }; let now_amount_lock = load_cell_lock_hash(2, Source::Output)?; let now_amount_type = load_cell_type_hash(2, Source::Input)?; if (pre_amount_lock != now_amount_lock) || (pre_amount_type != now_amount_type) { return Err(Error::Amount); } if now_com_lock != pre_amount_lock { return Err(Error::Verify); } // 5. change outputs udt. let mut change_amount: u128 = 0; let mut change_buf = [0u8; UDT_LEN]; for i in 3.. { let data = match load_cell_data(i, Source::Output) { Ok(data) => data, Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err.into()), }; let udt_type = load_cell_type_hash(i, Source::Output)?; if udt_type != now_amount_type { continue; } if data.len() != UDT_LEN { return Err(Error::Encoding); } change_buf.copy_from_slice(&data); change_amount += u128::from_le_bytes(change_buf); } if now_amount < pre_amount { return Err(Error::Amount); } // 6. why not check UDT name is equal, because UDT's type will check it. if now_amount + change_amount != pre_amount + deposit_amount { return Err(Error::Amount); } // 7. verify commit info. verify( pre_commit, now_commit, now_upk, deposit_amount - change_amount, true, ) } 2u8 => { // WITHDRAW // // input0 => pre_commit // input1 => upk // input2 => pre_udt_pool // output0 => now_commit // output1 => upk // output2 => now_udt_pool // output3..n-1 => udt_unspend // 2. pre udt amount in pool. debug!("WITHDRAW"); let pre_amount = match load_cell_data(2, Source::Input) { Ok(data) => { let mut buf = [0u8; UDT_LEN]; if data.len() != UDT_LEN { return Err(Error::Encoding); } buf.copy_from_slice(&data); u128::from_le_bytes(buf) } Err(err) => return Err(err.into()), }; let pre_amount_lock = load_cell_lock_hash(2, Source::Input)?; let pre_amount_type = load_cell_type_hash(2, Source::Input)?; // 3. now udt pool amount. let now_amount = match load_cell_data(2, Source::Output) { Ok(data) => { let mut buf = [0u8; UDT_LEN]; if data.len() != UDT_LEN { return Err(Error::Encoding); } buf.copy_from_slice(&data); u128::from_le_bytes(buf) } Err(err) => return Err(err.into()), }; let now_amount_lock = load_cell_lock_hash(2, Source::Output)?; let now_amount_type = load_cell_type_hash(2, Source::Input)?; if (pre_amount_lock != now_amount_lock) || (pre_amount_type != now_amount_type) { return Err(Error::Amount); } if now_com_lock != pre_amount_lock { return Err(Error::Verify); } // 4. outputs udt. let mut withdraw_amount: u128 = 0; let mut withdraw_buf = [0u8; UDT_LEN]; for i in 3.. { let data = match load_cell_data(i, Source::Output) { Ok(data) => data, Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err.into()), }; let udt_type = load_cell_type_hash(i, Source::Output)?; if udt_type != now_amount_type { continue; } if data.len() != UDT_LEN { return Err(Error::Encoding); } withdraw_buf.copy_from_slice(&data); withdraw_amount += u128::from_le_bytes(withdraw_buf); } // 5. check amount. if now_amount + withdraw_amount != pre_amount { return Err(Error::Amount); } // 6. verify commit. verify(pre_commit, now_commit, now_upk, withdraw_amount, false) } 3u8 => { // POST BLOCK // // input0 => pre_commit // input1 => upk // output0 => now_commit // output1 => upk debug!("POST BLOCK"); // presence of any other cells with the same lock script // (to be precise, udt pool cells) is illegal. for i in 2.. { match load_cell_lock_hash(i, Source::Input) { Ok(lock) => { if lock == self_script_hash { return Err(Error::Amount); } } Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err.into()), } match load_cell_lock_hash(i, Source::Output) { Ok(lock) => { if lock == self_script_hash { return Err(Error::Amount); } } Err(SysError::IndexOutOfBound) => break, Err(err) => return Err(err.into()), } } // post block proof verify(pre_commit, now_commit, now_upk, 0, false) } _ => Err(Error::Encoding), } } fn verify( mut pre: Vec<u8>, mut now: Vec<u8>, upk: Vec<u8>, change: u128, is_add: bool, ) -> Result<(), Error> { debug!( "on-chain udt pool change: {}{}", if is_add { "+" } else { "-" }, change ); pre.remove(0); now.remove(0); let pre_block = Block::<Bn_256>::from_bytes(&pre[..]).unwrap(); let now_block = Block::<Bn_256>::from_bytes(&now[..]).unwrap(); debug!("pre & now block deserialization ok"); if pre_block.new_commit != now_block.commit { return Err(Error::Verify); } debug!("pre & now block is eq!"); let cell_upks = CellUpks::<Bn_256>::from_bytes(&upk[..]).unwrap(); match now_block.verify(&cell_upks) { Ok((income, outcome)) => { debug!( "on-chain udt pool change: {}{}, block income: {}, outcome: {}", if is_add { "+" } else { "-" }, change, income, outcome ); if (is_add && income >= outcome && income - outcome == change) || ((!is_add) && outcome >= income && outcome - income == change) { return Ok(()); } return Err(Error::Amount); } _ => { debug!("block.verify failure"); return Err(Error::Verify); } }; }
32.104683
93
0.470825
edb571e1cb13d90a3918ce9d1535582f438e12c5
3,298
#[derive(Default, Debug)] pub struct GeneralPurposeRegisters { //Special Purpose program_counter: u64, hi_lo: u64, llb: u64, //Misc. assembler_temporary: u64, return_address: u64, //Subroutine return value value0: u64, value1: u64, //Arguments argument0: u64, argument1: u64, argument2: u64, argument3: u64, //Temporary Registers temporary0: u64, temporary1: u64, temporary2: u64, temporary3: u64, temporary4: u64, temporary5: u64, temporary6: u64, temporary7: u64, temporary8: u64, temporary9: u64, //Saved Registers saved0: u64, saved1: u64, saved2: u64, saved3: u64, saved4: u64, saved5: u64, saved6: u64, saved7: u64, //Kernel Registers kernel0: u64, kernel1: u64, //Pointers global_pointer: u64, stack_pointer: u64, frame_pointer: u64, } impl GeneralPurposeRegisters { pub fn simulate_boot(&mut self) { self.temporary3 = 0xFFFF_FFFF_A400_0040; self.saved4 = 0x0000_0000_0000_0001; self.saved6 = 0x0000_0000_0000_003F; self.stack_pointer = 0xFFFF_FFFF_A400_1FF0; self.program_counter = 0x0000_0000_A400_0040; } pub fn get(&self, index: u8) -> u64 { match index { 0 => 0, 1 => self.assembler_temporary, 2 => self.value0, 3 => self.value1, 4 => self.argument0, 5 => self.argument1, 6 => self.argument2, 7 => self.argument3, 8 => self.temporary0, 9 => self.temporary1, 10 => self.temporary2, 11 => self.temporary3, 12 => self.temporary4, 13 => self.temporary5, 14 => self.temporary6, 15 => self.temporary7, 16 => self.saved0, 17 => self.saved1, 18 => self.saved2, 19 => self.saved3, 20 => self.saved4, 21 => self.saved5, 22 => self.saved6, 23 => self.saved7, 24 => self.temporary8, 25 => self.temporary9, 26 => self.kernel0, 27 => self.kernel1, 28 => self.global_pointer, 29 => self.stack_pointer, 30 => self.frame_pointer, 31 => self.return_address, _ => 0, } } pub fn set(&mut self, index: u8, value: u64) -> () { match index { 1 => self.assembler_temporary = value, 2 => self.value0 = value, 3 => self.value1 = value, 4 => self.argument0 = value, 5 => self.argument1 = value, 6 => self.argument2 = value, 7 => self.argument3 = value, 8 => self.temporary0 = value, 9 => self.temporary1 = value, 10 => self.temporary2 = value, 11 => self.temporary3 = value, 12 => self.temporary4 = value, 13 => self.temporary5 = value, 14 => self.temporary6 = value, 15 => self.temporary7 = value, 16 => self.saved0 = value, 17 => self.saved1 = value, 18 => self.saved2 = value, 19 => self.saved3 = value, 20 => self.saved4 = value, 21 => self.saved5 = value, 22 => self.saved6 = value, 23 => self.saved7 = value, 24 => self.temporary8 = value, 25 => self.temporary9 = value, 26 => self.kernel0 = value, 27 => self.kernel1 = value, 28 => self.global_pointer = value, 29 => self.stack_pointer = value, 30 => self.frame_pointer = value, 31 => self.return_address = value, _ => (), }; } }
24.984848
54
0.588235
9b8201fcdd875407ebaeedbe8c41e43daeb63455
4,151
use std::{collections::BTreeMap, convert::TryFrom, string::String}; use glob::Pattern; use miette::{IntoDiagnostic, Report, Result}; use crate::{ external::Vcs, mit::{Author, Authors}, }; pub struct InMemory<'a> { store: &'a mut BTreeMap<String, String>, } impl InMemory<'_> { #[must_use] pub fn new(store: &mut BTreeMap<String, String>) -> InMemory { InMemory { store } } } impl Vcs for InMemory<'_> { fn entries(&self, glob: Option<&str>) -> Result<Vec<String>> { let mut keys: Vec<String> = self.store.keys().map(String::from).collect(); if let Some(pattern) = glob { let compiled_glob = glob::Pattern::new(pattern).into_diagnostic()?; keys = keys .into_iter() .filter(|value| Pattern::matches(&compiled_glob, value)) .collect(); } Ok(keys) } fn get_bool(&self, name: &str) -> Result<Option<bool>> { match self.store.get(name) { None => Ok(None), Some(raw_value) => Ok(Some(raw_value.parse().into_diagnostic()?)), } } fn get_str(&self, name: &str) -> Result<Option<&str>> { Ok(self.store.get(name).map(String::as_str)) } fn get_i64(&self, name: &str) -> Result<Option<i64>> { match self.store.get(name) { None => Ok(None), Some(raw_value) => Ok(Some(raw_value.parse().into_diagnostic()?)), } } fn set_str(&mut self, name: &str, value: &str) -> Result<()> { self.store.insert(name.into(), value.into()); Ok(()) } fn set_i64(&mut self, name: &str, value: i64) -> Result<()> { self.store.insert(name.into(), format!("{}", value)); Ok(()) } fn remove(&mut self, name: &str) -> Result<()> { self.store.remove(name); Ok(()) } } impl TryFrom<&'_ InMemory<'_>> for Authors { type Error = Report; fn try_from(vcs: &'_ InMemory) -> Result<Self, Self::Error> { let raw_entries: BTreeMap<String, BTreeMap<String, String>> = vcs .entries(Some("mit.author.config.*"))? .iter() .map(|key| (key, key.trim_start_matches("mit.author.config."))) .map(|(key, parts)| (key, parts.split_terminator('.').collect::<Vec<_>>())) .try_fold::<_, _, Result<_, Self::Error>>( BTreeMap::new(), |mut acc, (key, fragments)| { let mut fragment_iterator = fragments.iter(); let initial = String::from(*fragment_iterator.next().unwrap()); let part = String::from(*fragment_iterator.next().unwrap()); let mut existing: BTreeMap<String, String> = acc.get(&initial).map(BTreeMap::clone).unwrap_or_default(); existing.insert(part, String::from(vcs.get_str(key)?.unwrap())); acc.insert(initial, existing); Ok(acc) }, )?; Ok(Authors::new( raw_entries .iter() .filter_map(|(key, cfg)| { let name = cfg.get("name").map(String::clone); let email = cfg.get("email").map(String::clone); let signingkey: Option<String> = cfg.get("signingkey").map(String::clone); match (name, email, signingkey) { (Some(name), Some(email), None) => { Some((key, Author::new(&name, &email, None))) } (Some(name), Some(email), Some(signingkey)) => { Some((key, Author::new(&name, &email, Some(&signingkey)))) } _ => None, } }) .fold( BTreeMap::new(), |mut acc: BTreeMap<String, Author>, (key, value): (&String, Author)| { acc.insert(key.clone(), value); acc }, ), )) } }
33.208
94
0.482293
0e8b5b9c75243bb0647d0f3df31967c2b1dedd3f
8,482
use std::sync; use std::sync::mpsc; use std::thread; type Data = Box<Vec<u8>>; /// `Event` is an enum that offers various type of events that will be /// handled by an mp2c carousel. #[derive(Debug, Clone)] enum Event { Message(Data), Terminate, } /// `Consumer` enables to implement handling logic for a vector of bytes. /// /// Each consumer which would like to receive a message should implement /// this trait. pub trait Consumer { fn consume(&mut self, data: Vec<u8>); } /// `Poller` is a simple struct that encapsulates a polling thread that calls /// the encapsulating `Consumer` for each `Event`. struct Poller { thread: Option<thread::JoinHandle<()>>, } impl Poller { fn new<T: ?Sized>(consumer: Box<T>, rx: sync::Arc<sync::Mutex<mpsc::Receiver<Event>>>) -> Poller where T: Consumer + Send + 'static, { let mut consumer = consumer; let thread = thread::spawn(move || loop { match rx.lock().unwrap().recv() { Ok(event) => match event { Event::Message(data) => { let data = data.clone(); consumer.consume(*data); } Event::Terminate => { break; } }, Err(e) => println!("Poller error receiving an event: {}", e), } }); Poller { thread: Some(thread), } } } struct Multipier { pollers: Vec<Poller>, thread: Option<thread::JoinHandle<()>>, } impl Multipier { fn new<T: ?Sized>( consumers: Vec<Box<T>>, rx: sync::Arc<sync::Mutex<mpsc::Receiver<Event>>>, ) -> Multipier where T: Consumer + Send + 'static, { let mut multiplier_txs: Vec<mpsc::Sender<Event>> = Vec::with_capacity(consumers.len()); let pollers: Vec<Poller> = consumers .into_iter() .map(|c| { let (ctx, crx) = mpsc::channel::<Event>(); let crx = sync::Arc::new(sync::Mutex::new(crx)); multiplier_txs.push(ctx); Poller::new(c, sync::Arc::clone(&crx)) }) .collect(); let thread = thread::spawn(move || loop { let cloned = multiplier_txs.clone(); match rx.lock().unwrap().recv() { Ok(event) => { cloned.into_iter().for_each(|tx| { tx.send(event.clone()).unwrap(); }); if let Event::Terminate = event { break; } } Err(e) => println!("Multiplier error receiving an event: {}", e), } }); Multipier { pollers, thread: Some(thread), } } } /// `Carousel` represents a multi producer multi polling consumer data carousel. It enables /// message passing from multiple producers to multiple consumers asynchronously. /// /// It accepts a vector of bytes as a message/ event. /// /// A mp2c `Carousel` can be created for a list of consumers. However, each consumer /// is expected to implement the `Consumer` trait. /// /// A multiplier thread is started which receives one end of an async channel. /// Each message `put` on the `Carousel` is sent to this multiplier thread. The job /// of the `Multiplier` is to clone each incoming event/ message and send it to each /// polling consumer. /// /// For each consumer, a poller thread is started which receives one end of an async /// channel. The transmitting end of the channel is with the `Multiplier` thread. The /// poller calls `Consumer::consume` on it's registered consumer. /// /// An `Carousel` can be cloned and the clone creates a clone of the `Sender` from which it is /// cloned. When `Carousel::put` is called to send a message, it'll be sent to the pollers in /// the originating `Carousel`. /// /// # Example /// ``` /// use mp2c::asynch::{Carousel, Consumer}; /// /// struct TestConsumer1; /// /// impl Consumer for TestConsumer1 { /// fn consume(&mut self, data: Vec<u8>) { /// let msg = String::from_utf8(data).unwrap(); /// // do something with msg /// } /// } /// /// struct TestConsumer2; /// /// impl Consumer for TestConsumer2 { /// fn consume(&mut self, data: Vec<u8>) { /// let msg = String::from_utf8(data).unwrap(); /// // do something with msg /// } /// } /// /// let mut v: Vec<Box<dyn Consumer + Send + 'static>> = Vec::new(); /// v.push(Box::new(TestConsumer1)); /// v.push(Box::new(TestConsumer2)); /// /// let c = Carousel::new(v); /// /// for _ in 1..10 { /// let cloned_c = c.clone(); /// let t = std::thread::spawn(move || { /// cloned_c.put(String::from("test").into_bytes()); /// }); /// t.join().unwrap(); /// } /// /// ``` pub struct Carousel { tx: mpsc::Sender<Event>, multiplier: Option<Multipier>, } impl Carousel { /// Creates a new `Carousel` for a vector of consumers. pub fn new<T: ?Sized>(consumers: Vec<Box<T>>) -> Carousel where T: Consumer + Send + 'static, { assert!(consumers.len() > 0); let (tx, rx) = mpsc::channel::<Event>(); let rx = sync::Arc::new(sync::Mutex::new(rx)); let multiplier = Multipier::new(consumers, rx); Carousel { tx, multiplier: Some(multiplier), } } /// Puts a message on the `Carousel` which will be asynchronously /// sent to all it's consumers. pub fn put(&self, data: Vec<u8>) { let data = Box::new(data); let event = Event::Message(data); self.tx.send(event).unwrap(); } } impl Clone for Carousel { fn clone(&self) -> Self { Carousel { tx: self.tx.clone(), multiplier: Option::None, } } } impl Drop for Carousel { fn drop(&mut self) { if let Some(multiplier) = &mut self.multiplier { println!("Sending terminate message to all pollers."); self.tx.send(Event::Terminate).unwrap(); if let Some(multiplier_thread) = multiplier.thread.take() { multiplier_thread.join().unwrap(); } println!("Shutting down all pollers."); for poller in &mut multiplier.pollers { if let Some(thread) = poller.thread.take() { thread.join().unwrap(); } } } } } #[cfg(test)] mod tests { use crate::asynch::{Carousel, Consumer}; #[test] fn basic() { struct TestConsumer1; impl Consumer for TestConsumer1 { fn consume(&mut self, data: Vec<u8>) { assert_eq!(String::from_utf8(data).unwrap(), String::from("test")); } } struct TestConsumer2; impl Consumer for TestConsumer2 { fn consume(&mut self, data: Vec<u8>) { assert_eq!(String::from_utf8(data).unwrap(), String::from("test")); } } let mut v: Vec<Box<dyn Consumer + Send + 'static>> = Vec::new(); v.push(Box::new(TestConsumer1)); v.push(Box::new(TestConsumer2)); let c = Carousel::new(v); c.put(String::from("test").into_bytes()); c.put(String::from("test").into_bytes()); c.put(String::from("test").into_bytes()); c.put(String::from("test").into_bytes()); std::thread::sleep(std::time::Duration::from_secs(2)); } #[test] fn multi_producer() { struct TestConsumer1; impl Consumer for TestConsumer1 { fn consume(&mut self, data: Vec<u8>) { assert_eq!(String::from_utf8(data).unwrap(), String::from("test")); } } struct TestConsumer2; impl Consumer for TestConsumer2 { fn consume(&mut self, data: Vec<u8>) { assert_eq!(String::from_utf8(data).unwrap(), String::from("test")); } } let mut v: Vec<Box<dyn Consumer + Send + 'static>> = Vec::new(); v.push(Box::new(TestConsumer1)); v.push(Box::new(TestConsumer2)); let c = Carousel::new(v); for _ in 1..10 { let cloned_c = c.clone(); let t = std::thread::spawn(move || { cloned_c.put(String::from("test").into_bytes()); }); t.join().unwrap(); } } }
28.463087
100
0.539024
8f3097ad4233eb6796c072c28d6fbfbc2b24671c
61,096
//! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131) //! //! Rust targets a wide variety of usecases, and in the interest of flexibility, //! allows new target triples to be defined in configuration files. Most users //! will not need to care about these, but this is invaluable when porting Rust //! to a new platform, and allows for an unprecedented level of control over how //! the compiler works. //! //! # Using custom targets //! //! A target triple, as passed via `rustc --target=TRIPLE`, will first be //! compared against the list of built-in targets. This is to ease distributing //! rustc (no need for configuration files) and also to hold these built-in //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it //! will be loaded as the target configuration. If the file does not exist, //! rustc will search each directory in the environment variable //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will //! be loaded. If no file is found in any of those directories, a fatal error //! will be given. //! //! Projects defining their own targets should use //! `--target=path/to/my-awesome-platform.json` instead of adding to //! `RUST_TARGET_PATH`. //! //! # Defining a new target //! //! Targets are defined using [JSON](http://json.org/). The `Target` struct in //! this module defines the format the JSON file should take, though each //! underscore in the field names should be replaced with a hyphen (`-`) in the //! JSON file. Some fields are required in every target specification, such as //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`, //! `arch`, and `os`. In general, options passed to rustc with `-C` override //! the target's settings, though `target-feature` and `link-args` will *add* //! to the list specified by the target, rather than replace. use crate::spec::abi::{lookup as lookup_abi, Abi}; use rustc_serialize::json::{Json, ToJson}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fmt, io}; use rustc_macros::HashStable_Generic; pub mod abi; mod android_base; mod apple_base; mod apple_sdk_base; mod arm_base; mod cloudabi_base; mod dragonfly_base; mod freebsd_base; mod fuchsia_base; mod haiku_base; mod hermit_base; mod hermit_kernel_base; mod illumos_base; mod l4re_base; mod linux_base; mod linux_kernel_base; mod linux_musl_base; mod msvc_base; mod netbsd_base; mod openbsd_base; mod redox_base; mod riscv_base; mod solaris_base; mod thumb_base; mod uefi_msvc_base; mod vxworks_base; mod wasm32_base; mod windows_gnu_base; mod windows_msvc_base; mod windows_uwp_gnu_base; mod windows_uwp_msvc_base; #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum LinkerFlavor { Em, Gcc, Ld, Msvc, Lld(LldFlavor), PtxLinker, } #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum LldFlavor { Wasm, Ld64, Ld, Link, } impl LldFlavor { fn from_str(s: &str) -> Option<Self> { Some(match s { "darwin" => LldFlavor::Ld64, "gnu" => LldFlavor::Ld, "link" => LldFlavor::Link, "wasm" => LldFlavor::Wasm, _ => return None, }) } } impl ToJson for LldFlavor { fn to_json(&self) -> Json { match *self { LldFlavor::Ld64 => "darwin", LldFlavor::Ld => "gnu", LldFlavor::Link => "link", LldFlavor::Wasm => "wasm", } .to_json() } } impl ToJson for LinkerFlavor { fn to_json(&self) -> Json { self.desc().to_json() } } macro_rules! flavor_mappings { ($((($($flavor:tt)*), $string:expr),)*) => ( impl LinkerFlavor { pub const fn one_of() -> &'static str { concat!("one of: ", $($string, " ",)*) } pub fn from_str(s: &str) -> Option<Self> { Some(match s { $($string => $($flavor)*,)* _ => return None, }) } pub fn desc(&self) -> &str { match *self { $($($flavor)* => $string,)* } } } ) } flavor_mappings! { ((LinkerFlavor::Em), "em"), ((LinkerFlavor::Gcc), "gcc"), ((LinkerFlavor::Ld), "ld"), ((LinkerFlavor::Msvc), "msvc"), ((LinkerFlavor::PtxLinker), "ptx-linker"), ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"), ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"), ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"), ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"), } #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable, HashStable_Generic)] pub enum PanicStrategy { Unwind, Abort, } impl PanicStrategy { pub fn desc(&self) -> &str { match *self { PanicStrategy::Unwind => "unwind", PanicStrategy::Abort => "abort", } } } impl ToJson for PanicStrategy { fn to_json(&self) -> Json { match *self { PanicStrategy::Abort => "abort".to_json(), PanicStrategy::Unwind => "unwind".to_json(), } } } #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] pub enum RelroLevel { Full, Partial, Off, None, } impl RelroLevel { pub fn desc(&self) -> &str { match *self { RelroLevel::Full => "full", RelroLevel::Partial => "partial", RelroLevel::Off => "off", RelroLevel::None => "none", } } } impl FromStr for RelroLevel { type Err = (); fn from_str(s: &str) -> Result<RelroLevel, ()> { match s { "full" => Ok(RelroLevel::Full), "partial" => Ok(RelroLevel::Partial), "off" => Ok(RelroLevel::Off), "none" => Ok(RelroLevel::None), _ => Err(()), } } } impl ToJson for RelroLevel { fn to_json(&self) -> Json { match *self { RelroLevel::Full => "full".to_json(), RelroLevel::Partial => "partial".to_json(), RelroLevel::Off => "off".to_json(), RelroLevel::None => "None".to_json(), } } } #[derive(Clone, Copy, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)] pub enum MergeFunctions { Disabled, Trampolines, Aliases, } impl MergeFunctions { pub fn desc(&self) -> &str { match *self { MergeFunctions::Disabled => "disabled", MergeFunctions::Trampolines => "trampolines", MergeFunctions::Aliases => "aliases", } } } impl FromStr for MergeFunctions { type Err = (); fn from_str(s: &str) -> Result<MergeFunctions, ()> { match s { "disabled" => Ok(MergeFunctions::Disabled), "trampolines" => Ok(MergeFunctions::Trampolines), "aliases" => Ok(MergeFunctions::Aliases), _ => Err(()), } } } impl ToJson for MergeFunctions { fn to_json(&self) -> Json { match *self { MergeFunctions::Disabled => "disabled".to_json(), MergeFunctions::Trampolines => "trampolines".to_json(), MergeFunctions::Aliases => "aliases".to_json(), } } } pub enum LoadTargetError { BuiltinTargetNotFound(String), Other(String), } pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>; pub type TargetResult = Result<Target, String>; macro_rules! supported_targets { ( $(($( $triple:literal, )+ $module:ident ),)+ ) => { $(mod $module;)+ /// List of supported targets const TARGETS: &[&str] = &[$($($triple),+),+]; fn load_specific(target: &str) -> Result<Target, LoadTargetError> { match target { $( $($triple)|+ => { let mut t = $module::target() .map_err(LoadTargetError::Other)?; t.options.is_builtin = true; // round-trip through the JSON parser to ensure at // run-time that the parser works correctly t = Target::from_json(t.to_json()) .map_err(LoadTargetError::Other)?; debug!("got builtin target: {:?}", t); Ok(t) }, )+ _ => Err(LoadTargetError::BuiltinTargetNotFound( format!("Unable to find target: {}", target))) } } pub fn get_targets() -> impl Iterator<Item = String> { TARGETS.iter().filter_map(|t| -> Option<String> { load_specific(t) .and(Ok(t.to_string())) .ok() }) } #[cfg(test)] mod tests { mod tests_impl; // Cannot put this into a separate file without duplication, make an exception. $( #[test] // `#[test]` fn $module() { tests_impl::test_target(super::$module::target()); } )+ } }; } supported_targets! { ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu), ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32), ("i686-unknown-linux-gnu", i686_unknown_linux_gnu), ("i586-unknown-linux-gnu", i586_unknown_linux_gnu), ("mips-unknown-linux-gnu", mips_unknown_linux_gnu), ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64), ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64), ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu), ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu), ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64), ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64), ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu), ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu), ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe), ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl), ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu), ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl), ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu), ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl), ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu), ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu), ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu), ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi), ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf), ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi), ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf), ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi), ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi), ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi), ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi), ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf), ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf), ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf), ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi), ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf), ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu), ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl), ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl), ("i686-unknown-linux-musl", i686_unknown_linux_musl), ("i586-unknown-linux-musl", i586_unknown_linux_musl), ("mips-unknown-linux-musl", mips_unknown_linux_musl), ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl), ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64), ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64), ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl), ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc), ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc), ("i686-linux-android", i686_linux_android), ("x86_64-linux-android", x86_64_linux_android), ("arm-linux-androideabi", arm_linux_androideabi), ("armv7-linux-androideabi", armv7_linux_androideabi), ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi), ("aarch64-linux-android", aarch64_linux_android), ("x86_64-linux-kernel", x86_64_linux_kernel), ("aarch64-unknown-freebsd", aarch64_unknown_freebsd), ("armv6-unknown-freebsd", armv6_unknown_freebsd), ("armv7-unknown-freebsd", armv7_unknown_freebsd), ("i686-unknown-freebsd", i686_unknown_freebsd), ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd), ("x86_64-unknown-freebsd", x86_64_unknown_freebsd), ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly), ("aarch64-unknown-openbsd", aarch64_unknown_openbsd), ("i686-unknown-openbsd", i686_unknown_openbsd), ("sparc64-unknown-openbsd", sparc64_unknown_openbsd), ("x86_64-unknown-openbsd", x86_64_unknown_openbsd), ("aarch64-unknown-netbsd", aarch64_unknown_netbsd), ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf), ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf), ("i686-unknown-netbsd", i686_unknown_netbsd), ("powerpc-unknown-netbsd", powerpc_unknown_netbsd), ("sparc64-unknown-netbsd", sparc64_unknown_netbsd), ("x86_64-unknown-netbsd", x86_64_unknown_netbsd), ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd), ("i686-unknown-haiku", i686_unknown_haiku), ("x86_64-unknown-haiku", x86_64_unknown_haiku), ("x86_64-apple-darwin", x86_64_apple_darwin), ("i686-apple-darwin", i686_apple_darwin), ("aarch64-fuchsia", aarch64_fuchsia), ("x86_64-fuchsia", x86_64_fuchsia), ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc), ("aarch64-unknown-redox", aarch64_unknown_redox), ("x86_64-unknown-redox", x86_64_unknown_redox), ("i386-apple-ios", i386_apple_ios), ("x86_64-apple-ios", x86_64_apple_ios), ("aarch64-apple-ios", aarch64_apple_ios), ("armv7-apple-ios", armv7_apple_ios), ("armv7s-apple-ios", armv7s_apple_ios), ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi), ("aarch64-apple-tvos", aarch64_apple_tvos), ("x86_64-apple-tvos", x86_64_apple_tvos), ("armebv7r-none-eabi", armebv7r_none_eabi), ("armebv7r-none-eabihf", armebv7r_none_eabihf), ("armv7r-none-eabi", armv7r_none_eabi), ("armv7r-none-eabihf", armv7r_none_eabihf), // `x86_64-pc-solaris` is an alias for `x86_64_sun_solaris` for backwards compatibility reasons. // (See <https://github.com/rust-lang/rust/issues/40531>.) ("x86_64-sun-solaris", "x86_64-pc-solaris", x86_64_sun_solaris), ("sparcv9-sun-solaris", sparcv9_sun_solaris), ("x86_64-unknown-illumos", x86_64_unknown_illumos), ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu), ("i686-pc-windows-gnu", i686_pc_windows_gnu), ("i686-uwp-windows-gnu", i686_uwp_windows_gnu), ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu), ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc), ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc), ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc), ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc), ("i686-pc-windows-msvc", i686_pc_windows_msvc), ("i686-uwp-windows-msvc", i686_uwp_windows_msvc), ("i586-pc-windows-msvc", i586_pc_windows_msvc), ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc), ("asmjs-unknown-emscripten", asmjs_unknown_emscripten), ("wasm32-unknown-emscripten", wasm32_unknown_emscripten), ("wasm32-unknown-unknown", wasm32_unknown_unknown), ("wasm32-wasi", wasm32_wasi), ("thumbv6m-none-eabi", thumbv6m_none_eabi), ("thumbv7m-none-eabi", thumbv7m_none_eabi), ("thumbv7em-none-eabi", thumbv7em_none_eabi), ("thumbv7em-none-eabihf", thumbv7em_none_eabihf), ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi), ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi), ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf), ("armv7a-none-eabi", armv7a_none_eabi), ("armv7a-none-eabihf", armv7a_none_eabihf), ("msp430-none-elf", msp430_none_elf), ("aarch64-unknown-cloudabi", aarch64_unknown_cloudabi), ("armv7-unknown-cloudabi-eabihf", armv7_unknown_cloudabi_eabihf), ("i686-unknown-cloudabi", i686_unknown_cloudabi), ("x86_64-unknown-cloudabi", x86_64_unknown_cloudabi), ("aarch64-unknown-hermit", aarch64_unknown_hermit), ("x86_64-unknown-hermit", x86_64_unknown_hermit), ("x86_64-unknown-hermit-kernel", x86_64_unknown_hermit_kernel), ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf), ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf), ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf), ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf), ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf), ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu), ("aarch64-unknown-none", aarch64_unknown_none), ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat), ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx), ("x86_64-unknown-uefi", x86_64_unknown_uefi), ("i686-unknown-uefi", i686_unknown_uefi), ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda), ("i686-wrs-vxworks", i686_wrs_vxworks), ("x86_64-wrs-vxworks", x86_64_wrs_vxworks), ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf), ("aarch64-wrs-vxworks", aarch64_wrs_vxworks), ("powerpc-wrs-vxworks", powerpc_wrs_vxworks), ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe), ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks), } /// Everything `rustc` knows about how to compile for a specific target. /// /// Every field here must be specified, and has no default value. #[derive(PartialEq, Clone, Debug)] pub struct Target { /// Target triple to pass to LLVM. pub llvm_target: String, /// String to use as the `target_endian` `cfg` variable. pub target_endian: String, /// String to use as the `target_pointer_width` `cfg` variable. pub target_pointer_width: String, /// Width of c_int type pub target_c_int_width: String, /// OS name to use for conditional compilation. pub target_os: String, /// Environment name to use for conditional compilation. pub target_env: String, /// Vendor name to use for conditional compilation. pub target_vendor: String, /// Architecture to use for ABI considerations. Valid options include: "x86", /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others. pub arch: String, /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM. pub data_layout: String, /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed /// on the command line. pub linker_flavor: LinkerFlavor, /// Optional settings with defaults. pub options: TargetOptions, } pub trait HasTargetSpec { fn target_spec(&self) -> &Target; } impl HasTargetSpec for Target { fn target_spec(&self) -> &Target { self } } /// Optional aspects of a target specification. /// /// This has an implementation of `Default`, see each field for what the default is. In general, /// these try to take "minimal defaults" that don't assume anything about the runtime they run in. #[derive(PartialEq, Clone, Debug)] pub struct TargetOptions { /// Whether the target is built-in or loaded from a custom target specification. pub is_builtin: bool, /// Linker to invoke pub linker: Option<String>, /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker /// without clarifying its flavor in any way. pub lld_flavor: LldFlavor, /// Linker arguments that are passed *before* any user-defined libraries. pub pre_link_args: LinkArgs, // ... unconditionally pub pre_link_args_crt: LinkArgs, // ... when linking with a bundled crt /// Objects to link before all others, always found within the /// sysroot folder. pub pre_link_objects_exe: Vec<String>, // ... when linking an executable, unconditionally pub pre_link_objects_exe_crt: Vec<String>, // ... when linking an executable with a bundled crt pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib /// Linker arguments that are unconditionally passed after any /// user-defined but before post_link_objects. Standard platform /// libraries that should be always be linked to, usually go here. pub late_link_args: LinkArgs, /// Linker arguments used in addition to `late_link_args` if at least one /// Rust dependency is dynamically linked. pub late_link_args_dynamic: LinkArgs, /// Linker arguments used in addition to `late_link_args` if aall Rust /// dependencies are statically linked. pub late_link_args_static: LinkArgs, /// Objects to link after all others, always found within the /// sysroot folder. pub post_link_objects: Vec<String>, // ... unconditionally pub post_link_objects_crt: Vec<String>, // ... when linking with a bundled crt /// Linker arguments that are unconditionally passed *after* any /// user-defined libraries. pub post_link_args: LinkArgs, /// Environment variables to be set for the linker invocation. pub link_env: Vec<(String, String)>, /// Environment variables to be removed for the linker invocation. pub link_env_remove: Vec<String>, /// Extra arguments to pass to the external assembler (when used) pub asm_args: Vec<String>, /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults /// to "generic". pub cpu: String, /// Default target features to pass to LLVM. These features will *always* be /// passed, and cannot be disabled even via `-C`. Corresponds to `llc /// -mattr=$features`. pub features: String, /// Whether dynamic linking is available on this target. Defaults to false. pub dynamic_linking: bool, /// If dynamic linking is available, whether only cdylibs are supported. pub only_cdylib: bool, /// Whether executables are available on this target. iOS, for example, only allows static /// libraries. Defaults to false. pub executables: bool, /// Relocation model to use in object file. Corresponds to `llc /// -relocation-model=$relocation_model`. Defaults to "pic". pub relocation_model: String, /// Code model to use. Corresponds to `llc -code-model=$code_model`. pub code_model: Option<String>, /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec" /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang. pub tls_model: String, /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false. pub disable_redzone: bool, /// Eliminate frame pointers from stack frames if possible. Defaults to true. pub eliminate_frame_pointer: bool, /// Emit each function in its own section. Defaults to true. pub function_sections: bool, /// String to prepend to the name of every dynamic library. Defaults to "lib". pub dll_prefix: String, /// String to append to the name of every dynamic library. Defaults to ".so". pub dll_suffix: String, /// String to append to the name of every executable. pub exe_suffix: String, /// String to prepend to the name of every static library. Defaults to "lib". pub staticlib_prefix: String, /// String to append to the name of every static library. Defaults to ".a". pub staticlib_suffix: String, /// OS family to use for conditional compilation. Valid options: "unix", "windows". pub target_family: Option<String>, /// Whether the target toolchain's ABI supports returning small structs as an integer. pub abi_return_struct_as_int: bool, /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS, /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false. pub is_like_osx: bool, /// Whether the target toolchain is like Solaris's. /// Only useful for compiling against Illumos/Solaris, /// as they have a different set of linker flags. Defaults to false. pub is_like_solaris: bool, /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows, /// only really used for figuring out how to find libraries, since Windows uses its own /// library naming convention. Defaults to false. pub is_like_windows: bool, pub is_like_msvc: bool, /// Whether the target toolchain is like Android's. Only useful for compiling against Android. /// Defaults to false. pub is_like_android: bool, /// Whether the target toolchain is like Emscripten's. Only useful for compiling with /// Emscripten toolchain. /// Defaults to false. pub is_like_emscripten: bool, /// Whether the target toolchain is like Fuchsia's. pub is_like_fuchsia: bool, /// Whether the linker support GNU-like arguments such as -O. Defaults to false. pub linker_is_gnu: bool, /// The MinGW toolchain has a known issue that prevents it from correctly /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak /// symbol needs its own COMDAT section, weak linkage implies a large /// number sections that easily exceeds the given limit for larger /// codebases. Consequently we want a way to disallow weak linkage on some /// platforms. pub allows_weak_linkage: bool, /// Whether the linker support rpaths or not. Defaults to false. pub has_rpath: bool, /// Whether to disable linking to the default libraries, typically corresponds /// to `-nodefaultlibs`. Defaults to true. pub no_default_libraries: bool, /// Dynamically linked executables can be compiled as position independent /// if the default relocation model of position independent code is not /// changed. This is a requirement to take advantage of ASLR, as otherwise /// the functions in the executable are not randomized and can be used /// during an exploit of a vulnerability in any code. pub position_independent_executables: bool, /// Determines if the target always requires using the PLT for indirect /// library calls or not. This controls the default value of the `-Z plt` flag. pub needs_plt: bool, /// Either partial, full, or off. Full RELRO makes the dynamic linker /// resolve all symbols at startup and marks the GOT read-only before /// starting the program, preventing overwriting the GOT. pub relro_level: RelroLevel, /// Format that archives should be emitted in. This affects whether we use /// LLVM to assemble an archive or fall back to the system linker, and /// currently only "gnu" is used to fall into LLVM. Unknown strings cause /// the system linker to be used. pub archive_format: String, /// Is asm!() allowed? Defaults to true. pub allow_asm: bool, /// Whether the runtime startup code requires the `main` function be passed /// `argc` and `argv` values. pub main_needs_argc_argv: bool, /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for /// this target. pub has_elf_tls: bool, // This is mainly for easy compatibility with emscripten. // If we give emcc .o files that are actually .bc files it // will 'just work'. pub obj_is_bitcode: bool, /// Don't use this field; instead use the `.min_atomic_width()` method. pub min_atomic_width: Option<u64>, /// Don't use this field; instead use the `.max_atomic_width()` method. pub max_atomic_width: Option<u64>, /// Whether the target supports atomic CAS operations natively pub atomic_cas: bool, /// Panic strategy: "unwind" or "abort" pub panic_strategy: PanicStrategy, /// A blacklist of ABIs unsupported by the current target. Note that generic /// ABIs are considered to be supported on all platforms and cannot be blacklisted. pub abi_blacklist: Vec<Abi>, /// Whether or not linking dylibs to a static CRT is allowed. pub crt_static_allows_dylibs: bool, /// Whether or not the CRT is statically linked by default. pub crt_static_default: bool, /// Whether or not crt-static is respected by the compiler (or is a no-op). pub crt_static_respected: bool, /// Whether or not stack probes (__rust_probestack) are enabled pub stack_probes: bool, /// The minimum alignment for global symbols. pub min_global_align: Option<u64>, /// Default number of codegen units to use in debug mode pub default_codegen_units: Option<u64>, /// Whether to generate trap instructions in places where optimization would /// otherwise produce control flow that falls through into unrelated memory. pub trap_unreachable: bool, /// This target requires everything to be compiled with LTO to emit a final /// executable, aka there is no native linker for this target. pub requires_lto: bool, /// This target has no support for threads. pub singlethread: bool, /// Whether library functions call lowering/optimization is disabled in LLVM /// for this target unconditionally. pub no_builtins: bool, /// The codegen backend to use for this target, typically "llvm" pub codegen_backend: String, /// The default visibility for symbols in this target should be "hidden" /// rather than "default" pub default_hidden_visibility: bool, /// Whether a .debug_gdb_scripts section will be added to the output object file pub emit_debug_gdb_scripts: bool, /// Whether or not to unconditionally `uwtable` attributes on functions, /// typically because the platform needs to unwind for things like stack /// unwinders. pub requires_uwtable: bool, /// Whether or not SIMD types are passed by reference in the Rust ABI, /// typically required if a target can be compiled with a mixed set of /// target features. This is `true` by default, and `false` for targets like /// wasm32 where the whole program either has simd or not. pub simd_types_indirect: bool, /// Pass a list of symbol which should be exported in the dylib to the linker. pub limit_rdylib_exports: bool, /// If set, have the linker export exactly these symbols, instead of using /// the usual logic to figure this out from the crate itself. pub override_export_symbols: Option<Vec<String>>, /// Determines how or whether the MergeFunctions LLVM pass should run for /// this target. Either "disabled", "trampolines", or "aliases". /// The MergeFunctions pass is generally useful, but some targets may need /// to opt out. The default is "aliases". /// /// Workaround for: https://github.com/rust-lang/rust/issues/57356 pub merge_functions: MergeFunctions, /// Use platform dependent mcount function pub target_mcount: String, /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers pub llvm_abiname: String, /// Whether or not RelaxElfRelocation flag will be passed to the linker pub relax_elf_relocations: bool, /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option. pub llvm_args: Vec<String>, } impl Default for TargetOptions { /// Creates a set of "sane defaults" for any target. This is still /// incomplete, and if used for compilation, will certainly not work. fn default() -> TargetOptions { TargetOptions { is_builtin: false, linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()), lld_flavor: LldFlavor::Ld, pre_link_args: LinkArgs::new(), pre_link_args_crt: LinkArgs::new(), post_link_args: LinkArgs::new(), asm_args: Vec::new(), cpu: "generic".to_string(), features: String::new(), dynamic_linking: false, only_cdylib: false, executables: false, relocation_model: "pic".to_string(), code_model: None, tls_model: "global-dynamic".to_string(), disable_redzone: false, eliminate_frame_pointer: true, function_sections: true, dll_prefix: "lib".to_string(), dll_suffix: ".so".to_string(), exe_suffix: String::new(), staticlib_prefix: "lib".to_string(), staticlib_suffix: ".a".to_string(), target_family: None, abi_return_struct_as_int: false, is_like_osx: false, is_like_solaris: false, is_like_windows: false, is_like_android: false, is_like_emscripten: false, is_like_msvc: false, is_like_fuchsia: false, linker_is_gnu: false, allows_weak_linkage: true, has_rpath: false, no_default_libraries: true, position_independent_executables: false, needs_plt: false, relro_level: RelroLevel::None, pre_link_objects_exe: Vec::new(), pre_link_objects_exe_crt: Vec::new(), pre_link_objects_dll: Vec::new(), post_link_objects: Vec::new(), post_link_objects_crt: Vec::new(), late_link_args: LinkArgs::new(), late_link_args_dynamic: LinkArgs::new(), late_link_args_static: LinkArgs::new(), link_env: Vec::new(), link_env_remove: Vec::new(), archive_format: "gnu".to_string(), main_needs_argc_argv: true, allow_asm: true, has_elf_tls: false, obj_is_bitcode: false, min_atomic_width: None, max_atomic_width: None, atomic_cas: true, panic_strategy: PanicStrategy::Unwind, abi_blacklist: vec![], crt_static_allows_dylibs: false, crt_static_default: false, crt_static_respected: false, stack_probes: false, min_global_align: None, default_codegen_units: None, trap_unreachable: true, requires_lto: false, singlethread: false, no_builtins: false, codegen_backend: "llvm".to_string(), default_hidden_visibility: false, emit_debug_gdb_scripts: true, requires_uwtable: false, simd_types_indirect: true, limit_rdylib_exports: true, override_export_symbols: None, merge_functions: MergeFunctions::Aliases, target_mcount: "mcount".to_string(), llvm_abiname: "".to_string(), relax_elf_relocations: false, llvm_args: vec![], } } } impl Target { /// Given a function ABI, turn it into the correct ABI for this target. pub fn adjust_abi(&self, abi: Abi) -> Abi { match abi { Abi::System => { if self.options.is_like_windows && self.arch == "x86" { Abi::Stdcall } else { Abi::C } } // These ABI kinds are ignored on non-x86 Windows targets. // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions // and the individual pages for __stdcall et al. Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => { if self.options.is_like_windows && self.arch != "x86" { Abi::C } else { abi } } Abi::EfiApi => { if self.arch == "x86_64" { Abi::Win64 } else { Abi::C } } abi => abi, } } /// Minimum integer size in bits that this target can perform atomic /// operations on. pub fn min_atomic_width(&self) -> u64 { self.options.min_atomic_width.unwrap_or(8) } /// Maximum integer size in bits that this target can perform atomic /// operations on. pub fn max_atomic_width(&self) -> u64 { self.options.max_atomic_width.unwrap_or_else(|| self.target_pointer_width.parse().unwrap()) } pub fn is_abi_supported(&self, abi: Abi) -> bool { abi.generic() || !self.options.abi_blacklist.contains(&abi) } /// Loads a target descriptor from a JSON object. pub fn from_json(obj: Json) -> TargetResult { // While ugly, this code must remain this way to retain // compatibility with existing JSON fields and the internal // expected naming of the Target and TargetOptions structs. // To ensure compatibility is retained, the built-in targets // are round-tripped through this code to catch cases where // the JSON parser is not updated to match the structs. let get_req_field = |name: &str| { obj.find(name) .map(|s| s.as_string()) .and_then(|os| os.map(|s| s.to_string())) .ok_or_else(|| format!("Field {} in target specification is required", name)) }; let get_opt_field = |name: &str, default: &str| { obj.find(name) .and_then(|s| s.as_string()) .map(|s| s.to_string()) .unwrap_or_else(|| default.to_string()) }; let mut base = Target { llvm_target: get_req_field("llvm-target")?, target_endian: get_req_field("target-endian")?, target_pointer_width: get_req_field("target-pointer-width")?, target_c_int_width: get_req_field("target-c-int-width")?, data_layout: get_req_field("data-layout")?, arch: get_req_field("arch")?, target_os: get_req_field("os")?, target_env: get_opt_field("env", ""), target_vendor: get_opt_field("vendor", "unknown"), linker_flavor: LinkerFlavor::from_str(&*get_req_field("linker-flavor")?) .ok_or_else(|| format!("linker flavor must be {}", LinkerFlavor::one_of()))?, options: Default::default(), }; macro_rules! key { ($key_name:ident) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).map(|o| o.as_string() .map(|s| base.options.$key_name = s.to_string())); } ); ($key_name:ident, bool) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]) .map(|o| o.as_boolean() .map(|s| base.options.$key_name = s)); } ); ($key_name:ident, Option<u64>) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]) .map(|o| o.as_u64() .map(|s| base.options.$key_name = Some(s))); } ); ($key_name:ident, MergeFunctions) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { match s.parse::<MergeFunctions>() { Ok(mergefunc) => base.options.$key_name = mergefunc, _ => return Some(Err(format!("'{}' is not a valid value for \ merge-functions. Use 'disabled', \ 'trampolines', or 'aliases'.", s))), } Some(Ok(())) })).unwrap_or(Ok(())) } ); ($key_name:ident, PanicStrategy) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { match s { "unwind" => base.options.$key_name = PanicStrategy::Unwind, "abort" => base.options.$key_name = PanicStrategy::Abort, _ => return Some(Err(format!("'{}' is not a valid value for \ panic-strategy. Use 'unwind' or 'abort'.", s))), } Some(Ok(())) })).unwrap_or(Ok(())) } ); ($key_name:ident, RelroLevel) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { match s.parse::<RelroLevel>() { Ok(level) => base.options.$key_name = level, _ => return Some(Err(format!("'{}' is not a valid value for \ relro-level. Use 'full', 'partial, or 'off'.", s))), } Some(Ok(())) })).unwrap_or(Ok(())) } ); ($key_name:ident, list) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).map(|o| o.as_array() .map(|v| base.options.$key_name = v.iter() .map(|a| a.as_string().unwrap().to_string()).collect() ) ); } ); ($key_name:ident, opt_list) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).map(|o| o.as_array() .map(|v| base.options.$key_name = Some(v.iter() .map(|a| a.as_string().unwrap().to_string()).collect()) ) ); } ); ($key_name:ident, optional) => ( { let name = (stringify!($key_name)).replace("_", "-"); if let Some(o) = obj.find(&name[..]) { base.options.$key_name = o .as_string() .map(|s| s.to_string() ); } } ); ($key_name:ident, LldFlavor) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { if let Some(flavor) = LldFlavor::from_str(&s) { base.options.$key_name = flavor; } else { return Some(Err(format!( "'{}' is not a valid value for lld-flavor. \ Use 'darwin', 'gnu', 'link' or 'wasm.", s))) } Some(Ok(())) })).unwrap_or(Ok(())) } ); ($key_name:ident, LinkerFlavor) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.find(&name[..]).and_then(|o| o.as_string().map(|s| { LinkerFlavor::from_str(&s).ok_or_else(|| { Err(format!("'{}' is not a valid value for linker-flavor. \ Use 'em', 'gcc', 'ld' or 'msvc.", s)) }) })).unwrap_or(Ok(())) } ); ($key_name:ident, link_args) => ( { let name = (stringify!($key_name)).replace("_", "-"); if let Some(val) = obj.find(&name[..]) { let obj = val.as_object().ok_or_else(|| format!("{}: expected a \ JSON object with fields per linker-flavor.", name))?; let mut args = LinkArgs::new(); for (k, v) in obj { let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| { format!("{}: '{}' is not a valid value for linker-flavor. \ Use 'em', 'gcc', 'ld' or 'msvc'", name, k) })?; let v = v.as_array().ok_or_else(|| format!("{}.{}: expected a JSON array", name, k) )?.iter().enumerate() .map(|(i,s)| { let s = s.as_string().ok_or_else(|| format!("{}.{}[{}]: expected a JSON string", name, k, i))?; Ok(s.to_owned()) }) .collect::<Result<Vec<_>, String>>()?; args.insert(flavor, v); } base.options.$key_name = args; } } ); ($key_name:ident, env) => ( { let name = (stringify!($key_name)).replace("_", "-"); if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) { for o in a { if let Some(s) = o.as_string() { let p = s.split('=').collect::<Vec<_>>(); if p.len() == 2 { let k = p[0].to_string(); let v = p[1].to_string(); base.options.$key_name.push((k, v)); } } } } } ); } key!(is_builtin, bool); key!(linker, optional); key!(lld_flavor, LldFlavor)?; key!(pre_link_args, link_args); key!(pre_link_args_crt, link_args); key!(pre_link_objects_exe, list); key!(pre_link_objects_exe_crt, list); key!(pre_link_objects_dll, list); key!(late_link_args, link_args); key!(late_link_args_dynamic, link_args); key!(late_link_args_static, link_args); key!(post_link_objects, list); key!(post_link_objects_crt, list); key!(post_link_args, link_args); key!(link_env, env); key!(link_env_remove, list); key!(asm_args, list); key!(cpu); key!(features); key!(dynamic_linking, bool); key!(only_cdylib, bool); key!(executables, bool); key!(relocation_model); key!(code_model, optional); key!(tls_model); key!(disable_redzone, bool); key!(eliminate_frame_pointer, bool); key!(function_sections, bool); key!(dll_prefix); key!(dll_suffix); key!(exe_suffix); key!(staticlib_prefix); key!(staticlib_suffix); key!(target_family, optional); key!(abi_return_struct_as_int, bool); key!(is_like_osx, bool); key!(is_like_solaris, bool); key!(is_like_windows, bool); key!(is_like_msvc, bool); key!(is_like_emscripten, bool); key!(is_like_android, bool); key!(is_like_fuchsia, bool); key!(linker_is_gnu, bool); key!(allows_weak_linkage, bool); key!(has_rpath, bool); key!(no_default_libraries, bool); key!(position_independent_executables, bool); key!(needs_plt, bool); key!(relro_level, RelroLevel)?; key!(archive_format); key!(allow_asm, bool); key!(main_needs_argc_argv, bool); key!(has_elf_tls, bool); key!(obj_is_bitcode, bool); key!(max_atomic_width, Option<u64>); key!(min_atomic_width, Option<u64>); key!(atomic_cas, bool); key!(panic_strategy, PanicStrategy)?; key!(crt_static_allows_dylibs, bool); key!(crt_static_default, bool); key!(crt_static_respected, bool); key!(stack_probes, bool); key!(min_global_align, Option<u64>); key!(default_codegen_units, Option<u64>); key!(trap_unreachable, bool); key!(requires_lto, bool); key!(singlethread, bool); key!(no_builtins, bool); key!(codegen_backend); key!(default_hidden_visibility, bool); key!(emit_debug_gdb_scripts, bool); key!(requires_uwtable, bool); key!(simd_types_indirect, bool); key!(limit_rdylib_exports, bool); key!(override_export_symbols, opt_list); key!(merge_functions, MergeFunctions)?; key!(target_mcount); key!(llvm_abiname); key!(relax_elf_relocations, bool); key!(llvm_args, list); if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) { for name in array.iter().filter_map(|abi| abi.as_string()) { match lookup_abi(name) { Some(abi) => { if abi.generic() { return Err(format!( "The ABI \"{}\" is considered to be supported on \ all targets and cannot be blacklisted", abi )); } base.options.abi_blacklist.push(abi) } None => { return Err(format!("Unknown ABI \"{}\" in target specification", name)); } } } } Ok(base) } /// Search RUST_TARGET_PATH for a JSON file specifying the given target /// triple. Note that it could also just be a bare filename already, so also /// check for that. If one of the hardcoded targets we know about, just /// return it directly. /// /// The error string could come from any of the APIs called, including /// filesystem access and JSON decoding. pub fn search(target_triple: &TargetTriple) -> Result<Target, String> { use rustc_serialize::json; use std::env; use std::fs; fn load_file(path: &Path) -> Result<Target, String> { let contents = fs::read(path).map_err(|e| e.to_string())?; let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?; Target::from_json(obj) } match *target_triple { TargetTriple::TargetTriple(ref target_triple) => { // check if triple is in list of supported targets match load_specific(target_triple) { Ok(t) => return Ok(t), Err(LoadTargetError::BuiltinTargetNotFound(_)) => (), Err(LoadTargetError::Other(e)) => return Err(e), } // search for a file named `target_triple`.json in RUST_TARGET_PATH let path = { let mut target = target_triple.to_string(); target.push_str(".json"); PathBuf::from(target) }; let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default(); // FIXME 16351: add a sane default search path? for dir in env::split_paths(&target_path) { let p = dir.join(&path); if p.is_file() { return load_file(&p); } } Err(format!("Could not find specification for target {:?}", target_triple)) } TargetTriple::TargetPath(ref target_path) => { if target_path.is_file() { return load_file(&target_path); } Err(format!("Target path {:?} is not a valid file", target_path)) } } } } impl ToJson for Target { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); let default: TargetOptions = Default::default(); macro_rules! target_val { ($attr:ident) => {{ let name = (stringify!($attr)).replace("_", "-"); d.insert(name, self.$attr.to_json()); }}; ($attr:ident, $key_name:expr) => {{ let name = $key_name; d.insert(name.to_string(), self.$attr.to_json()); }}; } macro_rules! target_option_val { ($attr:ident) => {{ let name = (stringify!($attr)).replace("_", "-"); if default.$attr != self.options.$attr { d.insert(name, self.options.$attr.to_json()); } }}; ($attr:ident, $key_name:expr) => {{ let name = $key_name; if default.$attr != self.options.$attr { d.insert(name.to_string(), self.options.$attr.to_json()); } }}; (link_args - $attr:ident) => {{ let name = (stringify!($attr)).replace("_", "-"); if default.$attr != self.options.$attr { let obj = self .options .$attr .iter() .map(|(k, v)| (k.desc().to_owned(), v.clone())) .collect::<BTreeMap<_, _>>(); d.insert(name, obj.to_json()); } }}; (env - $attr:ident) => {{ let name = (stringify!($attr)).replace("_", "-"); if default.$attr != self.options.$attr { let obj = self .options .$attr .iter() .map(|&(ref k, ref v)| k.clone() + "=" + &v) .collect::<Vec<_>>(); d.insert(name, obj.to_json()); } }}; } target_val!(llvm_target); target_val!(target_endian); target_val!(target_pointer_width); target_val!(target_c_int_width); target_val!(arch); target_val!(target_os, "os"); target_val!(target_env, "env"); target_val!(target_vendor, "vendor"); target_val!(data_layout); target_val!(linker_flavor); target_option_val!(is_builtin); target_option_val!(linker); target_option_val!(lld_flavor); target_option_val!(link_args - pre_link_args); target_option_val!(link_args - pre_link_args_crt); target_option_val!(pre_link_objects_exe); target_option_val!(pre_link_objects_exe_crt); target_option_val!(pre_link_objects_dll); target_option_val!(link_args - late_link_args); target_option_val!(link_args - late_link_args_dynamic); target_option_val!(link_args - late_link_args_static); target_option_val!(post_link_objects); target_option_val!(post_link_objects_crt); target_option_val!(link_args - post_link_args); target_option_val!(env - link_env); target_option_val!(link_env_remove); target_option_val!(asm_args); target_option_val!(cpu); target_option_val!(features); target_option_val!(dynamic_linking); target_option_val!(only_cdylib); target_option_val!(executables); target_option_val!(relocation_model); target_option_val!(code_model); target_option_val!(tls_model); target_option_val!(disable_redzone); target_option_val!(eliminate_frame_pointer); target_option_val!(function_sections); target_option_val!(dll_prefix); target_option_val!(dll_suffix); target_option_val!(exe_suffix); target_option_val!(staticlib_prefix); target_option_val!(staticlib_suffix); target_option_val!(target_family); target_option_val!(abi_return_struct_as_int); target_option_val!(is_like_osx); target_option_val!(is_like_solaris); target_option_val!(is_like_windows); target_option_val!(is_like_msvc); target_option_val!(is_like_emscripten); target_option_val!(is_like_android); target_option_val!(is_like_fuchsia); target_option_val!(linker_is_gnu); target_option_val!(allows_weak_linkage); target_option_val!(has_rpath); target_option_val!(no_default_libraries); target_option_val!(position_independent_executables); target_option_val!(needs_plt); target_option_val!(relro_level); target_option_val!(archive_format); target_option_val!(allow_asm); target_option_val!(main_needs_argc_argv); target_option_val!(has_elf_tls); target_option_val!(obj_is_bitcode); target_option_val!(min_atomic_width); target_option_val!(max_atomic_width); target_option_val!(atomic_cas); target_option_val!(panic_strategy); target_option_val!(crt_static_allows_dylibs); target_option_val!(crt_static_default); target_option_val!(crt_static_respected); target_option_val!(stack_probes); target_option_val!(min_global_align); target_option_val!(default_codegen_units); target_option_val!(trap_unreachable); target_option_val!(requires_lto); target_option_val!(singlethread); target_option_val!(no_builtins); target_option_val!(codegen_backend); target_option_val!(default_hidden_visibility); target_option_val!(emit_debug_gdb_scripts); target_option_val!(requires_uwtable); target_option_val!(simd_types_indirect); target_option_val!(limit_rdylib_exports); target_option_val!(override_export_symbols); target_option_val!(merge_functions); target_option_val!(target_mcount); target_option_val!(llvm_abiname); target_option_val!(relax_elf_relocations); target_option_val!(llvm_args); if default.abi_blacklist != self.options.abi_blacklist { d.insert( "abi-blacklist".to_string(), self.options .abi_blacklist .iter() .map(|&name| Abi::name(name).to_json()) .collect::<Vec<_>>() .to_json(), ); } Json::Object(d) } } /// Either a target triple string or a path to a JSON file. #[derive(PartialEq, Clone, Debug, Hash, RustcEncodable, RustcDecodable)] pub enum TargetTriple { TargetTriple(String), TargetPath(PathBuf), } impl TargetTriple { /// Creates a target triple from the passed target triple string. pub fn from_triple(triple: &str) -> Self { TargetTriple::TargetTriple(triple.to_string()) } /// Creates a target triple from the passed target path. pub fn from_path(path: &Path) -> Result<Self, io::Error> { let canonicalized_path = path.canonicalize()?; Ok(TargetTriple::TargetPath(canonicalized_path)) } /// Returns a string triple for this target. /// /// If this target is a path, the file name (without extension) is returned. pub fn triple(&self) -> &str { match *self { TargetTriple::TargetTriple(ref triple) => triple, TargetTriple::TargetPath(ref path) => path .file_stem() .expect("target path must not be empty") .to_str() .expect("target path must be valid unicode"), } } /// Returns an extended string triple for this target. /// /// If this target is a path, a hash of the path is appended to the triple returned /// by `triple()`. pub fn debug_triple(&self) -> String { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let triple = self.triple(); if let TargetTriple::TargetPath(ref path) = *self { let mut hasher = DefaultHasher::new(); path.hash(&mut hasher); let hash = hasher.finish(); format!("{}-{}", triple, hash) } else { triple.to_owned() } } } impl fmt::Display for TargetTriple { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.debug_triple()) } }
40.514589
100
0.595571
03ee2d74e8a4fce208d559442c5be92753482d6b
2,460
use std::os::raw::c_char; use libloading::{Library, Symbol}; use super::{State, Function}; lazy_static::lazy_static! { pub static ref INSTANCE: Functions = { Functions::new() }; } type Int = std::os::raw::c_int; type Size = usize; pub struct Functions { pub lua_settop: Symbol<'static, unsafe extern "C" fn(state: State, count: Int)>, pub lua_pushvalue: Symbol<'static, unsafe extern "C" fn(state: State, index: Int)>, pub lua_replace: Symbol<'static, unsafe extern "C" fn(state: State, index: Int)>, pub lua_pushlstring: Symbol<'static, unsafe extern "C" fn(state: State, data: *const c_char, length: Size)>, pub lua_pushcclosure: Symbol<'static, unsafe extern "C" fn(state: State, func: Function, upvalues: Int)>, pub lua_settable: Symbol<'static, unsafe extern "C" fn(state: State, index: Int)>, pub lua_tolstring: Symbol<'static, unsafe extern "C" fn(state: State, index: Int, out_size: *mut Size) -> *const c_char>, pub lual_loadbuffer: Symbol<'static, unsafe extern "C" fn(state: State, code: *const c_char, length: Size, name: *const c_char) -> i32>, } impl Functions { fn new() -> Self { unsafe { let library = Box::new(Self::find_library()); let library = Box::leak(library); // Keep this library referenced forever Functions { lua_settop: Self::find_symbol(library, b"lua_settop"), lua_pushvalue: Self::find_symbol(library, b"lua_pushvalue"), lua_replace: Self::find_symbol(library, b"lua_replace"), lua_pushlstring: Self::find_symbol(library, b"lua_pushlstring"), lua_pushcclosure: Self::find_symbol(library, b"lua_pushcclosure"), lua_settable: Self::find_symbol(library, b"lua_settable"), lua_tolstring: Self::find_symbol(library, b"lua_tolstring"), lual_loadbuffer: Self::find_symbol(library, b"luaL_loadbuffer"), } } } unsafe fn find_symbol<T>(library: &'static Library, symbol: &[u8]) -> Symbol<'static, T> { library.get(symbol).unwrap() } #[cfg(target_os = "windows")] unsafe fn find_library() -> Library { Library::new("lua_shared.dll").unwrap() } #[cfg(target_os = "linux")] unsafe fn find_library() -> Library { Library::new("lua_shared_srv.so") .or_else(|_| Library::new("lua_shared.so")) .unwrap() } }
40.327869
140
0.627236
0e1239bb923f9b3ded8856ffd77280e8e0800f8a
4,204
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved. // Use of this source is governed by Apache-2.0 License that can be found // in the LICENSE file. use super::hugetlb_encode::*; use super::ipc::*; use super::types::*; /// SHMMNI, SHMMAX and SHMALL are default upper limits which can be /// modified by sysctl. The SHMMAX and SHMALL values have been chosen to /// be as large possible without facilitating scenarios where userspace /// causes overflows when adjusting the limits via operations of the form /// "retrieve current limit; add X; update limit". It is therefore not /// advised to make SHMMAX and SHMALL any larger. These limits are /// suitable for both 32 and 64-bit systems. /// min shared seg size (bytes) pub const SHMMIN: i32 = 1; /// max num of segs system wide pub const SHMMNI: i32 = 4096; /// max shared seg size (bytes) pub const SHMMAX: usize = core::usize::MAX - (1_usize << 24); /// max shm system wide (pages) pub const SHMALL: usize = core::usize::MAX - (1_usize << 24); /// max shared segs per process pub const SHMSEG: i32 = SHMMNI; /// Obsolete, used only for backwards compatibility and libc5 compiles #[repr(C)] #[derive(Debug, Default, Clone, Copy)] pub struct shmid_ds_t { /// operation perms pub shm_perm: ipc_perm_t, /// size of segment (bytes) pub shm_segsz: i32, /// last attach time pub shm_atime: time_t, /// last detach time pub shm_dtime: time_t, ///* last change time pub shm_ctime: time_t, /// pid of creator pub shm_cpid: ipc_pid_t, /// pid of last operator pub shm_lpid: ipc_pid_t, /// no. of current attaches pub shm_nattch: u16, /// compatibility shm_unused: u16, /// ditto - used by DIPC shm_unused2: usize, shm_unused3: usize, } /// shmget() shmflg values. /// The bottom nine bits are the same as open(2) mode flags /// or S_IRUGO from <linux/stat.h> pub const SHM_R: i32 = 0o400; /// or S_IWUGO from <linux/stat.h> pub const SHM_W: i32 = 0o200; /// Bits 9 & 10 are IPC_CREAT and IPC_EXCL /// segment will use huge TLB pages pub const SHM_HUGETLB: i32 = 0o4000; /// don't check for reservations pub const SHM_NORESERVE: i32 = 0o10_000; /// Huge page size encoding when SHM_HUGETLB is specified, and a huge page /// size other than the default is desired. See hugetlb_encode.h pub const SHM_HUGE_SHIFT: i32 = HUGETLB_FLAG_ENCODE_SHIFT; pub const SHM_HUGE_MASK: i32 = HUGETLB_FLAG_ENCODE_MASK; pub const SHM_HUGE_64KB: usize = HUGETLB_FLAG_ENCODE_64KB; pub const SHM_HUGE_512KB: usize = HUGETLB_FLAG_ENCODE_512KB; pub const SHM_HUGE_1MB: usize = HUGETLB_FLAG_ENCODE_1MB; pub const SHM_HUGE_2MB: usize = HUGETLB_FLAG_ENCODE_2MB; pub const SHM_HUGE_8MB: usize = HUGETLB_FLAG_ENCODE_8MB; pub const SHM_HUGE_16MB: usize = HUGETLB_FLAG_ENCODE_16MB; pub const SHM_HUGE_32MB: usize = HUGETLB_FLAG_ENCODE_32MB; pub const SHM_HUGE_256MB: usize = HUGETLB_FLAG_ENCODE_256MB; pub const SHM_HUGE_512MB: usize = HUGETLB_FLAG_ENCODE_512MB; pub const SHM_HUGE_1GB: usize = HUGETLB_FLAG_ENCODE_1GB; pub const SHM_HUGE_2GB: usize = HUGETLB_FLAG_ENCODE_2GB; pub const SHM_HUGE_16GB: usize = HUGETLB_FLAG_ENCODE_16GB; /// shmat() shmflg values /// read-only access pub const SHM_RDONLY: i32 = 0o10_000; /// round attach address to SHMLBA boundary pub const SHM_RND: i32 = 0o20_000; /// take-over region on attach pub const SHM_REMAP: i32 = 0o40_000; /// execution access pub const SHM_EXEC: i32 = 0o100_000; /// super user shmctl commands pub const SHM_LOCK: i32 = 11; pub const SHM_UNLOCK: i32 = 12; /// ipcs ctl commands pub const SHM_STAT: i32 = 13; pub const SHM_INFO: i32 = 14; pub const SHM_STAT_ANY: i32 = 15; /// Obsolete, used only for backwards compatibility #[repr(C)] #[derive(Debug, Default, Clone, Copy)] pub struct shminfo_t { pub shmmax: i32, pub shmmin: i32, pub shmmni: i32, pub shmseg: i32, pub shmall: i32, } #[repr(C)] #[derive(Debug, Default, Clone, Copy)] pub struct shm_info_t { pub used_ids: i32, /// total allocated shm pub shm_tot: usize, /// total resident shm pub shm_rss: usize, /// total swapped shm pub shm_swp: usize, swap_attempts: usize, swap_successes: usize, }
33.102362
75
0.721218
e8d07b39fe89afe05dc80a0c410599fb0d6528c2
632,900
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[derive(Clone)] pub struct Client { endpoint: String, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, pipeline: azure_core::Pipeline, } #[derive(Clone)] pub struct ClientBuilder { credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, endpoint: Option<String>, scopes: Option<Vec<String>>, } pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD; impl ClientBuilder { pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self { Self { credential, endpoint: None, scopes: None, } } pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self { self.endpoint = Some(endpoint.into()); self } pub fn scopes(mut self, scopes: &[&str]) -> Self { self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect()); self } pub fn build(self) -> Client { let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()); let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]); Client::new(endpoint, self.credential, scopes) } } impl Client { pub(crate) fn endpoint(&self) -> &str { self.endpoint.as_str() } pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential { self.credential.as_ref() } pub(crate) fn scopes(&self) -> Vec<&str> { self.scopes.iter().map(String::as_str).collect() } pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> Result<azure_core::Response, azure_core::Error> { let mut context = azure_core::Context::default(); let mut request = request.into(); self.pipeline.send(&mut context, &mut request).await } pub fn new( endpoint: impl Into<String>, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, ) -> Self { let endpoint = endpoint.into(); let pipeline = azure_core::Pipeline::new( option_env!("CARGO_PKG_NAME"), option_env!("CARGO_PKG_VERSION"), azure_core::ClientOptions::default(), Vec::new(), Vec::new(), ); Self { endpoint, credential, scopes, pipeline, } } pub fn activity(&self) -> activity::Client { activity::Client(self.clone()) } pub fn agent_registration_information(&self) -> agent_registration_information::Client { agent_registration_information::Client(self.clone()) } pub fn automation_account(&self) -> automation_account::Client { automation_account::Client(self.clone()) } pub fn certificate(&self) -> certificate::Client { certificate::Client(self.clone()) } pub fn connection(&self) -> connection::Client { connection::Client(self.clone()) } pub fn connection_type(&self) -> connection_type::Client { connection_type::Client(self.clone()) } pub fn credential(&self) -> credential::Client { credential::Client(self.clone()) } pub fn dsc_compilation_job(&self) -> dsc_compilation_job::Client { dsc_compilation_job::Client(self.clone()) } pub fn dsc_compilation_job_stream(&self) -> dsc_compilation_job_stream::Client { dsc_compilation_job_stream::Client(self.clone()) } pub fn dsc_configuration(&self) -> dsc_configuration::Client { dsc_configuration::Client(self.clone()) } pub fn dsc_node(&self) -> dsc_node::Client { dsc_node::Client(self.clone()) } pub fn dsc_node_configuration(&self) -> dsc_node_configuration::Client { dsc_node_configuration::Client(self.clone()) } pub fn fields(&self) -> fields::Client { fields::Client(self.clone()) } pub fn hybrid_runbook_worker_group(&self) -> hybrid_runbook_worker_group::Client { hybrid_runbook_worker_group::Client(self.clone()) } pub fn job(&self) -> job::Client { job::Client(self.clone()) } pub fn job_schedule(&self) -> job_schedule::Client { job_schedule::Client(self.clone()) } pub fn job_stream(&self) -> job_stream::Client { job_stream::Client(self.clone()) } pub fn keys(&self) -> keys::Client { keys::Client(self.clone()) } pub fn linked_workspace(&self) -> linked_workspace::Client { linked_workspace::Client(self.clone()) } pub fn module(&self) -> module::Client { module::Client(self.clone()) } pub fn node_reports(&self) -> node_reports::Client { node_reports::Client(self.clone()) } pub fn object_data_types(&self) -> object_data_types::Client { object_data_types::Client(self.clone()) } pub fn operations(&self) -> operations::Client { operations::Client(self.clone()) } pub fn runbook(&self) -> runbook::Client { runbook::Client(self.clone()) } pub fn runbook_draft(&self) -> runbook_draft::Client { runbook_draft::Client(self.clone()) } pub fn schedule(&self) -> schedule::Client { schedule::Client(self.clone()) } pub fn statistics(&self) -> statistics::Client { statistics::Client(self.clone()) } pub fn test_job(&self) -> test_job::Client { test_job::Client(self.clone()) } pub fn test_job_streams(&self) -> test_job_streams::Client { test_job_streams::Client(self.clone()) } pub fn usages(&self) -> usages::Client { usages::Client(self.clone()) } pub fn variable(&self) -> variable::Client { variable::Client(self.clone()) } pub fn watcher(&self) -> watcher::Client { watcher::Client(self.clone()) } pub fn webhook(&self) -> webhook::Client { webhook::Client(self.clone()) } } #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] AutomationAccount_Get(#[from] automation_account::get::Error), #[error(transparent)] AutomationAccount_CreateOrUpdate(#[from] automation_account::create_or_update::Error), #[error(transparent)] AutomationAccount_Update(#[from] automation_account::update::Error), #[error(transparent)] AutomationAccount_Delete(#[from] automation_account::delete::Error), #[error(transparent)] AutomationAccount_ListByResourceGroup(#[from] automation_account::list_by_resource_group::Error), #[error(transparent)] Operations_List(#[from] operations::list::Error), #[error(transparent)] AutomationAccount_List(#[from] automation_account::list::Error), #[error(transparent)] Statistics_ListByAutomationAccount(#[from] statistics::list_by_automation_account::Error), #[error(transparent)] Usages_ListByAutomationAccount(#[from] usages::list_by_automation_account::Error), #[error(transparent)] Keys_ListByAutomationAccount(#[from] keys::list_by_automation_account::Error), #[error(transparent)] Certificate_Get(#[from] certificate::get::Error), #[error(transparent)] Certificate_CreateOrUpdate(#[from] certificate::create_or_update::Error), #[error(transparent)] Certificate_Update(#[from] certificate::update::Error), #[error(transparent)] Certificate_Delete(#[from] certificate::delete::Error), #[error(transparent)] Certificate_ListByAutomationAccount(#[from] certificate::list_by_automation_account::Error), #[error(transparent)] Connection_Get(#[from] connection::get::Error), #[error(transparent)] Connection_CreateOrUpdate(#[from] connection::create_or_update::Error), #[error(transparent)] Connection_Update(#[from] connection::update::Error), #[error(transparent)] Connection_Delete(#[from] connection::delete::Error), #[error(transparent)] Connection_ListByAutomationAccount(#[from] connection::list_by_automation_account::Error), #[error(transparent)] ConnectionType_Get(#[from] connection_type::get::Error), #[error(transparent)] ConnectionType_CreateOrUpdate(#[from] connection_type::create_or_update::Error), #[error(transparent)] ConnectionType_Delete(#[from] connection_type::delete::Error), #[error(transparent)] ConnectionType_ListByAutomationAccount(#[from] connection_type::list_by_automation_account::Error), #[error(transparent)] Credential_Get(#[from] credential::get::Error), #[error(transparent)] Credential_CreateOrUpdate(#[from] credential::create_or_update::Error), #[error(transparent)] Credential_Update(#[from] credential::update::Error), #[error(transparent)] Credential_Delete(#[from] credential::delete::Error), #[error(transparent)] Credential_ListByAutomationAccount(#[from] credential::list_by_automation_account::Error), #[error(transparent)] DscCompilationJob_Get(#[from] dsc_compilation_job::get::Error), #[error(transparent)] DscCompilationJob_Create(#[from] dsc_compilation_job::create::Error), #[error(transparent)] DscCompilationJob_ListByAutomationAccount(#[from] dsc_compilation_job::list_by_automation_account::Error), #[error(transparent)] DscCompilationJobStream_ListByJob(#[from] dsc_compilation_job_stream::list_by_job::Error), #[error(transparent)] DscCompilationJob_GetStream(#[from] dsc_compilation_job::get_stream::Error), #[error(transparent)] Job_GetOutput(#[from] job::get_output::Error), #[error(transparent)] Job_GetRunbookContent(#[from] job::get_runbook_content::Error), #[error(transparent)] Job_Suspend(#[from] job::suspend::Error), #[error(transparent)] Job_Stop(#[from] job::stop::Error), #[error(transparent)] Job_Get(#[from] job::get::Error), #[error(transparent)] Job_Create(#[from] job::create::Error), #[error(transparent)] Job_ListByAutomationAccount(#[from] job::list_by_automation_account::Error), #[error(transparent)] Job_Resume(#[from] job::resume::Error), #[error(transparent)] JobStream_Get(#[from] job_stream::get::Error), #[error(transparent)] JobStream_ListByJob(#[from] job_stream::list_by_job::Error), #[error(transparent)] DscConfiguration_Get(#[from] dsc_configuration::get::Error), #[error(transparent)] DscConfiguration_CreateOrUpdate(#[from] dsc_configuration::create_or_update::Error), #[error(transparent)] DscConfiguration_Update(#[from] dsc_configuration::update::Error), #[error(transparent)] DscConfiguration_Delete(#[from] dsc_configuration::delete::Error), #[error(transparent)] DscConfiguration_GetContent(#[from] dsc_configuration::get_content::Error), #[error(transparent)] DscConfiguration_ListByAutomationAccount(#[from] dsc_configuration::list_by_automation_account::Error), #[error(transparent)] AgentRegistrationInformation_Get(#[from] agent_registration_information::get::Error), #[error(transparent)] AgentRegistrationInformation_RegenerateKey(#[from] agent_registration_information::regenerate_key::Error), #[error(transparent)] DscNode_Get(#[from] dsc_node::get::Error), #[error(transparent)] DscNode_Update(#[from] dsc_node::update::Error), #[error(transparent)] DscNode_Delete(#[from] dsc_node::delete::Error), #[error(transparent)] DscNode_ListByAutomationAccount(#[from] dsc_node::list_by_automation_account::Error), #[error(transparent)] NodeReports_ListByNode(#[from] node_reports::list_by_node::Error), #[error(transparent)] NodeReports_Get(#[from] node_reports::get::Error), #[error(transparent)] NodeReports_GetContent(#[from] node_reports::get_content::Error), #[error(transparent)] DscNodeConfiguration_Get(#[from] dsc_node_configuration::get::Error), #[error(transparent)] DscNodeConfiguration_CreateOrUpdate(#[from] dsc_node_configuration::create_or_update::Error), #[error(transparent)] DscNodeConfiguration_Delete(#[from] dsc_node_configuration::delete::Error), #[error(transparent)] DscNodeConfiguration_ListByAutomationAccount(#[from] dsc_node_configuration::list_by_automation_account::Error), #[error(transparent)] HybridRunbookWorkerGroup_Get(#[from] hybrid_runbook_worker_group::get::Error), #[error(transparent)] HybridRunbookWorkerGroup_Update(#[from] hybrid_runbook_worker_group::update::Error), #[error(transparent)] HybridRunbookWorkerGroup_Delete(#[from] hybrid_runbook_worker_group::delete::Error), #[error(transparent)] HybridRunbookWorkerGroup_ListByAutomationAccount(#[from] hybrid_runbook_worker_group::list_by_automation_account::Error), #[error(transparent)] JobSchedule_Get(#[from] job_schedule::get::Error), #[error(transparent)] JobSchedule_Create(#[from] job_schedule::create::Error), #[error(transparent)] JobSchedule_Delete(#[from] job_schedule::delete::Error), #[error(transparent)] JobSchedule_ListByAutomationAccount(#[from] job_schedule::list_by_automation_account::Error), #[error(transparent)] LinkedWorkspace_Get(#[from] linked_workspace::get::Error), #[error(transparent)] Activity_Get(#[from] activity::get::Error), #[error(transparent)] Activity_ListByModule(#[from] activity::list_by_module::Error), #[error(transparent)] Module_Get(#[from] module::get::Error), #[error(transparent)] Module_CreateOrUpdate(#[from] module::create_or_update::Error), #[error(transparent)] Module_Update(#[from] module::update::Error), #[error(transparent)] Module_Delete(#[from] module::delete::Error), #[error(transparent)] Module_ListByAutomationAccount(#[from] module::list_by_automation_account::Error), #[error(transparent)] ObjectDataTypes_ListFieldsByModuleAndType(#[from] object_data_types::list_fields_by_module_and_type::Error), #[error(transparent)] ObjectDataTypes_ListFieldsByType(#[from] object_data_types::list_fields_by_type::Error), #[error(transparent)] Fields_ListByType(#[from] fields::list_by_type::Error), #[error(transparent)] RunbookDraft_GetContent(#[from] runbook_draft::get_content::Error), #[error(transparent)] RunbookDraft_ReplaceContent(#[from] runbook_draft::replace_content::Error), #[error(transparent)] RunbookDraft_Get(#[from] runbook_draft::get::Error), #[error(transparent)] RunbookDraft_Publish(#[from] runbook_draft::publish::Error), #[error(transparent)] RunbookDraft_UndoEdit(#[from] runbook_draft::undo_edit::Error), #[error(transparent)] Runbook_GetContent(#[from] runbook::get_content::Error), #[error(transparent)] Runbook_Get(#[from] runbook::get::Error), #[error(transparent)] Runbook_CreateOrUpdate(#[from] runbook::create_or_update::Error), #[error(transparent)] Runbook_Update(#[from] runbook::update::Error), #[error(transparent)] Runbook_Delete(#[from] runbook::delete::Error), #[error(transparent)] Runbook_ListByAutomationAccount(#[from] runbook::list_by_automation_account::Error), #[error(transparent)] TestJobStreams_Get(#[from] test_job_streams::get::Error), #[error(transparent)] TestJobStreams_ListByTestJob(#[from] test_job_streams::list_by_test_job::Error), #[error(transparent)] TestJob_Get(#[from] test_job::get::Error), #[error(transparent)] TestJob_Create(#[from] test_job::create::Error), #[error(transparent)] TestJob_Resume(#[from] test_job::resume::Error), #[error(transparent)] TestJob_Stop(#[from] test_job::stop::Error), #[error(transparent)] TestJob_Suspend(#[from] test_job::suspend::Error), #[error(transparent)] Schedule_Get(#[from] schedule::get::Error), #[error(transparent)] Schedule_CreateOrUpdate(#[from] schedule::create_or_update::Error), #[error(transparent)] Schedule_Update(#[from] schedule::update::Error), #[error(transparent)] Schedule_Delete(#[from] schedule::delete::Error), #[error(transparent)] Schedule_ListByAutomationAccount(#[from] schedule::list_by_automation_account::Error), #[error(transparent)] Variable_Get(#[from] variable::get::Error), #[error(transparent)] Variable_CreateOrUpdate(#[from] variable::create_or_update::Error), #[error(transparent)] Variable_Update(#[from] variable::update::Error), #[error(transparent)] Variable_Delete(#[from] variable::delete::Error), #[error(transparent)] Variable_ListByAutomationAccount(#[from] variable::list_by_automation_account::Error), #[error(transparent)] Watcher_Get(#[from] watcher::get::Error), #[error(transparent)] Watcher_CreateOrUpdate(#[from] watcher::create_or_update::Error), #[error(transparent)] Watcher_Update(#[from] watcher::update::Error), #[error(transparent)] Watcher_Delete(#[from] watcher::delete::Error), #[error(transparent)] Watcher_Start(#[from] watcher::start::Error), #[error(transparent)] Watcher_Stop(#[from] watcher::stop::Error), #[error(transparent)] Watcher_ListByAutomationAccount(#[from] watcher::list_by_automation_account::Error), #[error(transparent)] Webhook_GenerateUri(#[from] webhook::generate_uri::Error), #[error(transparent)] Webhook_Get(#[from] webhook::get::Error), #[error(transparent)] Webhook_CreateOrUpdate(#[from] webhook::create_or_update::Error), #[error(transparent)] Webhook_Update(#[from] webhook::update::Error), #[error(transparent)] Webhook_Delete(#[from] webhook::delete::Error), #[error(transparent)] Webhook_ListByAutomationAccount(#[from] webhook::list_by_automation_account::Error), } pub mod automation_account { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, parameters: impl Into<models::AutomationAccountCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, parameters: impl Into<models::AutomationAccountUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_resource_group( &self, resource_group_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_resource_group::Builder { list_by_resource_group::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), subscription_id: subscription_id.into(), } } #[doc = "Lists the Automation Accounts within an Azure subscription."] pub fn list(&self, subscription_id: impl Into<String>) -> list::Builder { list::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AutomationAccount, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccount = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::AutomationAccount), Ok200(models::AutomationAccount), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) parameters: models::AutomationAccountCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccount = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccount = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) parameters: models::AutomationAccountUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AutomationAccount, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccount = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_resource_group { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::AutomationAccountListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts", self.client.endpoint(), &self.subscription_id, &self.resource_group_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccountListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::AutomationAccountListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Automation/automationAccounts", self.client.endpoint(), &self.subscription_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AutomationAccountListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod operations { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list(&self) -> list::Builder { list::Builder { client: self.0.clone() } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::OperationListResult, Error>> { Box::pin(async move { let url_str = &format!("{}/providers/Microsoft.Automation/operations", self.client.endpoint(),); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::OperationListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod statistics { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::StatisticsListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/statistics", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::StatisticsListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod usages { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::UsageListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/usages", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::UsageListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod keys { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::KeyListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/listKeys", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::KeyListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod certificate { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, certificate_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), certificate_name: certificate_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, certificate_name: impl Into<String>, parameters: impl Into<models::CertificateCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), certificate_name: certificate_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, certificate_name: impl Into<String>, parameters: impl Into<models::CertificateUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), certificate_name: certificate_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, certificate_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), certificate_name: certificate_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) certificate_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Certificate, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/certificates/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.certificate_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Certificate = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::Certificate), Ok200(models::Certificate), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) certificate_name: String, pub(crate) parameters: models::CertificateCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/certificates/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.certificate_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Certificate = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Certificate = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) certificate_name: String, pub(crate) parameters: models::CertificateUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Certificate, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/certificates/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.certificate_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Certificate = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) certificate_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/certificates/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.certificate_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CertificateListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/certificates", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::CertificateListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod connection { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_name: connection_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_name: impl Into<String>, parameters: impl Into<models::ConnectionCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_name: connection_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_name: impl Into<String>, parameters: impl Into<models::ConnectionUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_name: connection_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_name: connection_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Connection, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connections/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Connection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::Connection), Ok200(models::Connection), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_name: String, pub(crate) parameters: models::ConnectionCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connections/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Connection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Connection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_name: String, pub(crate) parameters: models::ConnectionUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Connection, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connections/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Connection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Connection), NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connections/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Connection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ConnectionListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connections", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ConnectionListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod connection_type { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_type_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_type_name: connection_type_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_type_name: impl Into<String>, parameters: impl Into<models::ConnectionTypeCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_type_name: connection_type_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, connection_type_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), connection_type_name: connection_type_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_type_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ConnectionType, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connectionTypes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_type_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ConnectionType = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Error response #response_type")] Conflict409 { value: models::ConnectionType }, #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_type_name: String, pub(crate) parameters: models::ConnectionTypeCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ConnectionType, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connectionTypes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_type_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ConnectionType = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } http::StatusCode::CONFLICT => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ConnectionType = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::Conflict409 { value: rsp_value }) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) connection_type_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connectionTypes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.connection_type_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ConnectionTypeListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/connectionTypes", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ConnectionTypeListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod credential { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, credential_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), credential_name: credential_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, credential_name: impl Into<String>, parameters: impl Into<models::CredentialCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), credential_name: credential_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, credential_name: impl Into<String>, parameters: impl Into<models::CredentialUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), credential_name: credential_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, credential_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), credential_name: credential_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) credential_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Credential, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/credentials/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.credential_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Credential = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::Credential), Ok200(models::Credential), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) credential_name: String, pub(crate) parameters: models::CredentialCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/credentials/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.credential_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Credential = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Credential = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) credential_name: String, pub(crate) parameters: models::CredentialUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Credential, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/credentials/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.credential_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Credential = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) credential_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/credentials/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.credential_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Unexpected HTTP status code {}", status_code)] UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CredentialListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/credentials", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::CredentialListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; Err(Error::UnexpectedResponse { status_code, body: rsp_body, }) } } }) } } } } pub mod dsc_compilation_job { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, compilation_job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), compilation_job_id: compilation_job_id.into(), subscription_id: subscription_id.into(), } } pub fn create( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, compilation_job_id: impl Into<String>, parameters: impl Into<models::DscCompilationJobCreateParameters>, subscription_id: impl Into<String>, ) -> create::Builder { create::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), compilation_job_id: compilation_job_id.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } pub fn get_stream( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, job_stream_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get_stream::Builder { get_stream::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), job_stream_id: job_stream_id.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) compilation_job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscCompilationJob, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/compilationjobs/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.compilation_job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscCompilationJob = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) compilation_job_id: String, pub(crate) parameters: models::DscCompilationJobCreateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscCompilationJob, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/compilationjobs/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.compilation_job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscCompilationJob = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::DscCompilationJobListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/compilationjobs", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscCompilationJobListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_stream { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) job_stream_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStream, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/compilationjobs/{}/streams/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . job_id , & self . job_stream_id) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStream = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod dsc_compilation_job_stream { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_job( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_job::Builder { list_by_job::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } } pub mod list_by_job { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStreamListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/compilationjobs/{}/streams/" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . job_id) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStreamListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod job { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get_output( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get_output::Builder { get_output::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } pub fn get_runbook_content( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get_runbook_content::Builder { get_runbook_content::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } pub fn suspend( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> suspend::Builder { suspend::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } pub fn stop( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> stop::Builder { stop::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } pub fn create( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, parameters: impl Into<models::JobCreateParameters>, subscription_id: impl Into<String>, ) -> create::Builder { create::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } pub fn resume( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> resume::Builder { resume::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), } } } pub mod get_output { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<bytes::Bytes, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/output", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_runbook_content { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<bytes::Bytes, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/runbookContent", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod suspend { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/suspend", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod stop { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/stop", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Job, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Job = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) parameters: models::JobCreateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Job, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Job = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod resume { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/resume", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod job_stream { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, job_stream_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), job_stream_id: job_stream_id.into(), subscription_id: subscription_id.into(), } } pub fn list_by_job( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_id: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_job::Builder { list_by_job::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_id: job_id.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) job_stream_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStream, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/streams/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id, &self.job_stream_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStream = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_job { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_id: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStreamListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobs/{}/streams", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStreamListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod dsc_configuration { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), configuration_name: configuration_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, configuration_name: impl Into<String>, parameters: impl Into<models::DscConfigurationCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), configuration_name: configuration_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), configuration_name: configuration_name.into(), subscription_id: subscription_id.into(), parameters: None, } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), configuration_name: configuration_name.into(), subscription_id: subscription_id.into(), } } pub fn get_content( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get_content::Builder { get_content::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), configuration_name: configuration_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, skip: None, top: None, inlinecount: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) configuration_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscConfiguration, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::DscConfiguration), Created201(models::DscConfiguration), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) configuration_name: String, pub(crate) parameters: models::DscConfigurationCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) configuration_name: String, pub(crate) subscription_id: String, pub(crate) parameters: Option<models::DscConfigurationUpdateParameters>, } impl Builder { pub fn parameters(mut self, parameters: impl Into<models::DscConfigurationUpdateParameters>) -> Self { self.parameters = Some(parameters.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscConfiguration, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = if let Some(parameters) = &self.parameters { req_builder = req_builder.header("content-type", "application/json"); azure_core::to_json(parameters).map_err(Error::Serialize)? } else { azure_core::EMPTY_BODY }; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) configuration_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_content { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) configuration_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<bytes::Bytes, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations/{}/content" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . configuration_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, pub(crate) skip: Option<i64>, pub(crate) top: Option<i64>, pub(crate) inlinecount: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn skip(mut self, skip: i64) -> Self { self.skip = Some(skip); self } pub fn top(mut self, top: i64) -> Self { self.top = Some(top); self } pub fn inlinecount(mut self, inlinecount: impl Into<String>) -> Self { self.inlinecount = Some(inlinecount.into()); self } pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::DscConfigurationListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/configurations", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skip) = &self.skip { url.query_pairs_mut().append_pair("$skip", &skip.to_string()); } if let Some(top) = &self.top { url.query_pairs_mut().append_pair("$top", &top.to_string()); } if let Some(inlinecount) = &self.inlinecount { url.query_pairs_mut().append_pair("$inlinecount", inlinecount); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscConfigurationListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod agent_registration_information { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } pub fn regenerate_key( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, parameters: impl Into<models::AgentRegistrationRegenerateKeyParameter>, subscription_id: impl Into<String>, ) -> regenerate_key::Builder { regenerate_key::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AgentRegistration, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/agentRegistrationInformation" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AgentRegistration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod regenerate_key { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) parameters: models::AgentRegistrationRegenerateKeyParameter, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AgentRegistration, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/agentRegistrationInformation/regenerateKey" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::AgentRegistration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod dsc_node { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, parameters: impl Into<models::DscNodeUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNode, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNode = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) parameters: models::DscNodeUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNode, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNode = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNode, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNode = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod node_reports { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_node( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_node::Builder { list_by_node::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), subscription_id: subscription_id.into(), filter: None, } } pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, report_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), report_id: report_id.into(), subscription_id: subscription_id.into(), } } pub fn get_content( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_id: impl Into<String>, report_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get_content::Builder { get_content::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_id: node_id.into(), report_id: report_id.into(), subscription_id: subscription_id.into(), } } } pub mod list_by_node { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeReportListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}/reports", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeReportListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) report_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeReport, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}/reports/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_id, &self.report_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeReport = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_content { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_id: String, pub(crate) report_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<serde_json::Value, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodes/{}/reports/{}/content" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . node_id , & self . report_id) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: serde_json::Value = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod dsc_node_configuration { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_configuration_name: node_configuration_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_configuration_name: impl Into<String>, parameters: impl Into<models::DscNodeConfigurationCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_configuration_name: node_configuration_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, node_configuration_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), node_configuration_name: node_configuration_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_configuration_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeConfiguration, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodeConfigurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_configuration_name: String, pub(crate) parameters: models::DscNodeConfigurationCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeConfiguration, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodeConfigurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeConfiguration = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) node_configuration_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodeConfigurations/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.node_configuration_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::DscNodeConfigurationListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/nodeConfigurations", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::DscNodeConfigurationListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod hybrid_runbook_worker_group { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, hybrid_runbook_worker_group_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), hybrid_runbook_worker_group_name: hybrid_runbook_worker_group_name.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, hybrid_runbook_worker_group_name: impl Into<String>, parameters: impl Into<models::HybridRunbookWorkerGroupUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), hybrid_runbook_worker_group_name: hybrid_runbook_worker_group_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, hybrid_runbook_worker_group_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), hybrid_runbook_worker_group_name: hybrid_runbook_worker_group_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) hybrid_runbook_worker_group_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::HybridRunbookWorkerGroup, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/hybridRunbookWorkerGroups/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . hybrid_runbook_worker_group_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::HybridRunbookWorkerGroup = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) hybrid_runbook_worker_group_name: String, pub(crate) parameters: models::HybridRunbookWorkerGroupUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::HybridRunbookWorkerGroup, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/hybridRunbookWorkerGroups/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . hybrid_runbook_worker_group_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::HybridRunbookWorkerGroup = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) hybrid_runbook_worker_group_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/hybridRunbookWorkerGroups/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . hybrid_runbook_worker_group_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::HybridRunbookWorkerGroupsListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/hybridRunbookWorkerGroups" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::HybridRunbookWorkerGroupsListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod job_schedule { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_schedule_id: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_schedule_id: job_schedule_id.into(), subscription_id: subscription_id.into(), } } pub fn create( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_schedule_id: impl Into<String>, parameters: impl Into<models::JobScheduleCreateParameters>, subscription_id: impl Into<String>, ) -> create::Builder { create::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_schedule_id: job_schedule_id.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, job_schedule_id: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), job_schedule_id: job_schedule_id.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_schedule_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobSchedule, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobSchedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_schedule_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobSchedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_schedule_id: String, pub(crate) parameters: models::JobScheduleCreateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobSchedule, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobSchedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_schedule_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobSchedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) job_schedule_id: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobSchedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.job_schedule_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobScheduleListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/jobSchedules", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobScheduleListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod linked_workspace { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::LinkedWorkspace, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/linkedWorkspace", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::LinkedWorkspace = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod activity { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, activity_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), activity_name: activity_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_module( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_module::Builder { list_by_module::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) activity_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Activity, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}/activities/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . module_name , & self . activity_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Activity = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_module { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ActivityListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}/activities", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.module_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ActivityListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod module { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, parameters: impl Into<models::ModuleCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, parameters: impl Into<models::ModuleUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Module, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.module_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Module = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::Module), Ok200(models::Module), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) parameters: models::ModuleCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.module_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Module = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Module = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) parameters: models::ModuleUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Module, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.module_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Module = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.module_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ModuleListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ModuleListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod object_data_types { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_fields_by_module_and_type( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, type_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_fields_by_module_and_type::Builder { list_fields_by_module_and_type::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), type_name: type_name.into(), subscription_id: subscription_id.into(), } } pub fn list_fields_by_type( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, type_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_fields_by_type::Builder { list_fields_by_type::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), type_name: type_name.into(), subscription_id: subscription_id.into(), } } } pub mod list_fields_by_module_and_type { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) type_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TypeFieldListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}/objectDataTypes/{}/fields" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . module_name , & self . type_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::TypeFieldListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_fields_by_type { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) type_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TypeFieldListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/objectDataTypes/{}/fields" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . type_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::TypeFieldListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod fields { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_type( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, module_name: impl Into<String>, type_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_type::Builder { list_by_type::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), module_name: module_name.into(), type_name: type_name.into(), subscription_id: subscription_id.into(), } } } pub mod list_by_type { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) module_name: String, pub(crate) type_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TypeFieldListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/modules/{}/types/{}/fields" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . module_name , & self . type_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::TypeFieldListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod runbook_draft { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get_content( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> get_content::Builder { get_content::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn replace_content( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, runbook_content: impl Into<serde_json::Value>, ) -> replace_content::Builder { replace_content::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), runbook_content: runbook_content.into(), } } pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn publish( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> publish::Builder { publish::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn undo_edit( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> undo_edit::Builder { undo_edit::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } } pub mod get_content { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<bytes::Bytes, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/content" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod replace_content { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(bytes::Bytes), Accepted202, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) runbook_content: serde_json::Value, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/content" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.runbook_content).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(Response::Ok200(rsp_value)) } http::StatusCode::ACCEPTED => Ok(Response::Accepted202), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::RunbookDraft, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::RunbookDraft = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod publish { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/publish" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::ACCEPTED => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod undo_edit { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::RunbookDraftUndoEditResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/undoEdit" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::RunbookDraftUndoEditResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod runbook { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get_content( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> get_content::Builder { get_content::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn create_or_update( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, parameters: impl Into<models::RunbookCreateOrUpdateParameters>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), parameters: parameters.into(), } } pub fn update( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, parameters: impl Into<models::RunbookUpdateParameters>, ) -> update::Builder { update::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), parameters: parameters.into(), } } pub fn delete( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn list_by_automation_account( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), } } } pub mod get_content { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<bytes::Bytes, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/content", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value = rsp_body; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Runbook, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Runbook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Runbook), Created201(models::Runbook), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Error response #response_type")] BadRequest400 {}, #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) parameters: models::RunbookCreateOrUpdateParameters, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Runbook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Runbook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::BAD_REQUEST => Err(Error::BadRequest400 {}), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) parameters: models::RunbookUpdateParameters, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Runbook, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Runbook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.runbook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::RunbookListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::RunbookListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod test_job_streams { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, job_stream_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), job_stream_id: job_stream_id.into(), } } pub fn list_by_test_job( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> list_by_test_job::Builder { list_by_test_job::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) job_stream_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStream, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob/streams/{}" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name , & self . job_stream_id) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStream = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_test_job { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobStreamListResult, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob/streams" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::JobStreamListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod test_job { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn create( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, parameters: impl Into<models::TestJobCreateParameters>, ) -> create::Builder { create::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), parameters: parameters.into(), } } pub fn resume( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> resume::Builder { resume::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn stop( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> stop::Builder { stop::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } pub fn suspend( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, runbook_name: impl Into<String>, ) -> suspend::Builder { suspend::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), runbook_name: runbook_name.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TestJob, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::TestJob = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, pub(crate) parameters: models::TestJobCreateParameters, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TestJob, Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::TestJob = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod resume { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob/resume" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod stop { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob/stop" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod suspend { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) runbook_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/runbooks/{}/draft/testJob/suspend" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . automation_account_name , & self . runbook_name) ; let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod schedule { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, schedule_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), schedule_name: schedule_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, schedule_name: impl Into<String>, parameters: impl Into<models::ScheduleCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), schedule_name: schedule_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, schedule_name: impl Into<String>, parameters: impl Into<models::ScheduleUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), schedule_name: schedule_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, schedule_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), schedule_name: schedule_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) schedule_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Schedule, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/schedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.schedule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Schedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Created201(models::Schedule), Ok200(models::Schedule), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Error response #response_type")] Conflict409 {}, #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) schedule_name: String, pub(crate) parameters: models::ScheduleCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/schedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.schedule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Schedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Schedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CONFLICT => Err(Error::Conflict409 {}), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) schedule_name: String, pub(crate) parameters: models::ScheduleUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Schedule, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/schedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.schedule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Schedule = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) schedule_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/schedules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.schedule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ScheduleListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/schedules", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduleListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod variable { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, variable_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), variable_name: variable_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, variable_name: impl Into<String>, parameters: impl Into<models::VariableCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), variable_name: variable_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, variable_name: impl Into<String>, parameters: impl Into<models::VariableUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), variable_name: variable_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, variable_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), variable_name: variable_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) variable_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Variable, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/variables/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.variable_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Variable = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Variable), Created201(models::Variable), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) variable_name: String, pub(crate) parameters: models::VariableCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/variables/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.variable_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Variable = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Variable = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) variable_name: String, pub(crate) parameters: models::VariableUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Variable, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/variables/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.variable_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Variable = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) variable_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/variables/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.variable_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::VariableListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/variables", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::VariableListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod watcher { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, parameters: impl Into<models::Watcher>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, parameters: impl Into<models::WatcherUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), subscription_id: subscription_id.into(), } } pub fn start( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, subscription_id: impl Into<String>, ) -> start::Builder { start::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), subscription_id: subscription_id.into(), } } pub fn stop( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, watcher_name: impl Into<String>, subscription_id: impl Into<String>, ) -> stop::Builder { stop::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), watcher_name: watcher_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Watcher, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Watcher = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Watcher), Created201(models::Watcher), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) parameters: models::Watcher, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Watcher = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Watcher = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) parameters: models::WatcherUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Watcher, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Watcher = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod start { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}/start", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod stop { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) watcher_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers/{}/stop", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.watcher_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::WatcherListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/watchers", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::WatcherListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod webhook { use super::{models, API_VERSION}; pub struct Client(pub(crate) super::Client); impl Client { pub fn generate_uri( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> generate_uri::Builder { generate_uri::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), } } pub fn get( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, webhook_name: impl Into<String>, subscription_id: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), webhook_name: webhook_name.into(), subscription_id: subscription_id.into(), } } pub fn create_or_update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, webhook_name: impl Into<String>, parameters: impl Into<models::WebhookCreateOrUpdateParameters>, subscription_id: impl Into<String>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), webhook_name: webhook_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn update( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, webhook_name: impl Into<String>, parameters: impl Into<models::WebhookUpdateParameters>, subscription_id: impl Into<String>, ) -> update::Builder { update::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), webhook_name: webhook_name.into(), parameters: parameters.into(), subscription_id: subscription_id.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, webhook_name: impl Into<String>, subscription_id: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), webhook_name: webhook_name.into(), subscription_id: subscription_id.into(), } } pub fn list_by_automation_account( &self, resource_group_name: impl Into<String>, automation_account_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_automation_account::Builder { list_by_automation_account::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), automation_account_name: automation_account_name.into(), subscription_id: subscription_id.into(), filter: None, } } } pub mod generate_uri { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<String, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks/generateUri", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: String = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) webhook_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Webhook, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.webhook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Webhook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Webhook), Created201(models::Webhook), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) webhook_name: String, pub(crate) parameters: models::WebhookCreateOrUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.webhook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Webhook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Webhook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) webhook_name: String, pub(crate) parameters: models::WebhookUpdateParameters, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Webhook, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.webhook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::Webhook = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) webhook_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name, &self.webhook_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_automation_account { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL: {0}")] ParseUrl(url::ParseError), #[error("Failed to build request: {0}")] BuildRequest(http::Error), #[error("Failed to serialize request body: {0}")] Serialize(serde_json::Error), #[error("Failed to get access token: {0}")] GetToken(azure_core::Error), #[error("Failed to execute request: {0}")] SendRequest(azure_core::Error), #[error("Failed to get response bytes: {0}")] ResponseBytes(azure_core::StreamError), #[error("Failed to deserialize response: {0}, body: {1:?}")] Deserialize(serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) automation_account_name: String, pub(crate) subscription_id: String, pub(crate) filter: Option<String>, } impl Builder { pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::WebhookListResult, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Automation/automationAccounts/{}/webhooks", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.automation_account_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::WebhookListResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } }
51.728647
350
0.52247
331ddc06652dab58ab7320344a0d131f58ea591f
806
/* * File: update_flag.rs * Project: src * Created Date: 26/11/2021 * Author: Shun Suzuki * ----- * Last Modified: 26/11/2021 * Modified By: Shun Suzuki ([email protected]) * ----- * Copyright (c) 2021 Hapis Lab. All rights reserved. * */ bitflags! { pub struct UpdateFlag: u32 { const UPDATE_SOURCE_DRIVE = 1 << 1; const UPDATE_COLOR_MAP = 1 << 2; const UPDATE_WAVENUM = 1 << 3; const UPDATE_CAMERA_POS = 1 << 4; const UPDATE_SLICE_POS = 1 << 5; const UPDATE_SLICE_SIZE = 1 << 6; const UPDATE_SOURCE_ALPHA = 1 << 7; const UPDATE_SOURCE_FLAG = 1 << 8; const INIT_SOURCE = 1 << 9; const INIT_AXIS = 1 << 10; const UPDATE_AXIS_SIZE = 1 << 11; const UPDATE_AXIS_FLAG = 1 << 12; } }
26.866667
58
0.580645
eb71bd33791235b091a6c23948575d38e377ebf8
19,097
use crate::traits::{BitTest, ExactRoots, PrimalityUtils}; use either::Either; use num_integer::{Integer, Roots}; use num_modular::{ModularCoreOps, ModularRefOps, ModularUnaryOps}; use num_traits::{FromPrimitive, NumRef, RefNum, ToPrimitive}; /// Utilities for the Lucas pseudoprime test pub trait LucasUtils { /// Find Lucas sequence to n with modulo m, i.e. $U_{n+1}(P,Q)$ mod m and $V_{n+1}(P,Q)$ fn lucasm(p: usize, q: isize, m: Self, n: Self) -> (Self, Self) where Self: Sized; /// Find proper parameters P and Q of Lucas pseudoprime test for n, such that Jacobi(D|n) is -1, /// using Selfridge's method (referred as method A by Baillie). fn pq_selfridge(n: &Self) -> (usize, isize); /// Find proper parameters P of extra strong Lucas pseudoprime test for n, such that Jacobi(D|n) is -1, /// using brute-force searching (referred as method C by Baillie) fn p_bruteforce(n: &Self) -> usize; } impl<T> LucasUtils for T where T: Integer + FromPrimitive + ToPrimitive + NumRef + BitTest + ExactRoots + Clone + ModularRefOps, for<'r> &'r T: RefNum<T> + ModularUnaryOps<&'r T, Output = T> + ModularCoreOps<&'r T, &'r T, Output = T>, { fn lucasm(p: usize, q: isize, m: Self, n: Self) -> (Self, Self) { // Reference: <https://en.wikipedia.org/wiki/Lucas_sequence> // and Peter Hackman, "Elementary Number Theory", section "L.XVII Scalar" <http://hackmat.se/kurser/TATM54/booktot.pdf> let p = T::from_usize(p).unwrap() % &m; let q = if q >= 0 { T::from_isize(q).unwrap() % &m } else { T::from_isize(-q).unwrap().negm(&m) }; let mut uk = T::zero() % &m; // U(k), mod m for montgomery form let mut uk1 = T::one() % &m; // U(k+1) for i in (0..n.bits()).rev() { if n.bit(i) { // k' = 2k+1 // U(k'+1) = U(2k+2) = PU(k+1)² - 2*QU(k+1)U(k) let uk1sq = (&uk1).sqm(&m); let t1 = (&p).mulm(&uk1sq, &m); let t2 = (&q).mulm(&uk1, &m).mulm(&uk, &m).dblm(&m); let new_uk1 = t1.subm(&t2, &m); // U(k') = U(2k+1) = U(k+1)² - QU(k)² let t1 = uk1sq; let t2 = (&q).mulm(&uk.sqm(&m), &m); let new_uk = t1.subm(&t2, &m); uk1 = new_uk1; uk = new_uk; } else { // k' = 2k // U(k'+1) = U(2k+1) = U(k+1)² - QU(k)² let uksq = (&uk).sqm(&m); let t1 = (&uk1).sqm(&m); let t2 = (&uksq).mulm(&q, &m); let new_uk1 = t1.subm(&t2, &m); // U(k') = U(2k) = 2U(k+1)U(k) - PU(k)² let t1 = uk1.mulm(&uk, &m).dblm(&m); let t2 = uksq.mulm(&p, &m); let new_uk = t1.subm(&t2, &m); uk1 = new_uk1; uk = new_uk; } } // V(k) = 2U(k+1) - PU(k) let vk = (&uk1).dblm(&m).subm(&p.mulm(&uk, &m), &m); (uk, vk) } fn pq_selfridge(n: &Self) -> (usize, isize) { let mut d = T::from_u8(5).unwrap(); let mut neg = false; loop { // check if n is a square number after several trials if &d == &T::from_u8(13).unwrap() && (*n).is_square() { break (0, 0); } let sd = if neg { (&d).negm(n) } else { d.clone() }; let j = sd.jacobi(n); if j == 0 && &d != n { break (0, 0); } // modification from Baillie, see https://oeis.org/A217120/a217120_1.txt if j == -1 { let d = if neg { -d.to_isize().unwrap() } else { d.to_isize().unwrap() }; break (1, (1 - d) / 4); } d = d + T::from_u8(2).unwrap(); neg = !neg; } } fn p_bruteforce(n: &Self) -> usize { let mut p: usize = 3; loop { // check if n is a square number after several trials if p == 10 && (*n).is_square() { break 0; } let d = T::from_usize(p * p - 4).unwrap(); let j = d.jacobi(n); if j == 0 && &d != n { break 0; } if j == -1 { break p; } p += 1; } } } impl<T: Integer + NumRef + Clone + FromPrimitive + LucasUtils + BitTest + ModularRefOps> PrimalityUtils for T where for<'r> &'r T: RefNum<T> + std::ops::Shr<usize, Output = T> + ModularUnaryOps<&'r T, Output = T>, { #[inline] fn is_prp(&self, base: Self) -> bool { if self < &Self::one() { return false; } let tm1 = self - Self::one(); base.powm(&tm1, self).is_one() } #[inline] fn is_sprp(&self, base: Self) -> bool { self.test_sprp(base).either(|v| v, |_| false) } fn test_sprp(&self, base: T) -> Either<bool, T> { if self < &Self::one() { return Either::Left(false); } // find 2^shift*u + 1 = n let tm1 = self - T::one(); let shift = tm1.trailing_zeros(); let u = &tm1 >> shift; // prevent reduction if the input is in montgomery form let m1 = T::one() % self; let mm1 = (&m1).negm(self); let mut x = base.powm(&u, self); if x == m1 || x == mm1 { return Either::Left(true); } for _ in 0..shift { let y = (&x).sqm(self); if y == m1 { return Either::Right(self.gcd(&(x - T::one()))); } if y == mm1 { return Either::Left(true); } x = y; } Either::Left(x == m1) } fn is_lprp(&self, p: Option<usize>, q: Option<isize>) -> bool { if self < &Self::one() { return false; } if self.is_even() { return false; } let (p, q) = match (p, q) { (Some(sp), Some(sq)) => (sp, sq), (_, _) => { let (sp, sq) = LucasUtils::pq_selfridge(self); if sp == 0 { return false; }; // is a perfect power (sp, sq) } }; let d = (p * p) as isize - 4 * q; let d = if d > 0 { Self::from_isize(d).unwrap() } else { Self::from_isize(-d).unwrap().negm(self) }; let delta = match d.jacobi(self) { 0 => self.clone(), -1 => self + Self::one(), 1 => self - Self::one(), _ => unreachable!(), }; let (u, _) = LucasUtils::lucasm(p, q, self.clone(), delta); u.is_zero() } fn is_slprp(&self, p: Option<usize>, q: Option<isize>) -> bool { if self < &Self::one() { return false; } if self.is_even() { return false; } let (p, q) = match (p, q) { (Some(sp), Some(sq)) => (sp, sq), (_, _) => { let (sp, sq) = LucasUtils::pq_selfridge(self); if sp == 0 { return false; }; // is a perfect power (sp, sq) } }; let d = (p * p) as isize - 4 * q; let d = if d > 0 { Self::from_isize(d).unwrap() } else { Self::from_isize(-d).unwrap().negm(self) }; let delta = match d.jacobi(self) { 0 => self.clone(), -1 => self + Self::one(), 1 => self - Self::one(), _ => unreachable!(), }; let shift = delta.trailing_zeros(); let base = &delta >> shift; let (ud, vd) = LucasUtils::lucasm(p, q, self.clone(), base.clone()); if ud.is_zero() || vd.is_zero() { return true; } // do first iteration to remove the sign on Q if shift == 0 { return false; } let mut qk = Self::from_isize(q.abs()).unwrap().powm(&base, self); // V(2k) = V(k)² - 2Q^k let mut vd = if q >= 0 { vd.sqm(self).subm(&(&qk).dblm(self), self) } else { vd.sqm(self).addm(&(&qk).dblm(self), self) }; if vd.is_zero() { return true; } for _ in 1..shift { // V(2k) = V(k)² - 2Q^k qk = qk.sqm(self); vd = vd.sqm(self).subm(&(&qk).dblm(self), self); if vd.is_zero() { return true; } } false } fn is_eslprp(&self, p: Option<usize>) -> bool { if self < &Self::one() { return false; } if self.is_even() { return false; } let p = match p { Some(sp) => sp, None => { let sp = LucasUtils::p_bruteforce(self); if sp == 0 { return false; }; // is a perfect power sp } }; let d = (p * p) as isize - 4; let d = if d > 0 { Self::from_isize(d).unwrap() } else { Self::from_isize(-d).unwrap().negm(self) }; let delta = match d.jacobi(self) { 0 => self.clone(), -1 => self + Self::one(), 1 => self - Self::one(), _ => unreachable!(), }; let shift = delta.trailing_zeros(); let base = &delta >> shift; let (ud, mut vd) = LucasUtils::lucasm(p, 1, self.clone(), base.clone()); let two = Self::from_u8(2).unwrap(); // U(d) = 0 or V(d) = ±2 if ud.is_zero() && (vd == two || vd == self - &two) { return true; } if vd.is_zero() { return true; } for _ in 1..(shift - 1) { // V(2k) = V(k)² - 2 vd = vd.sqm(self).subm(&two, self); if vd.is_zero() { return true; } } false } } /// A dummy trait for integer type. All types that implements this and [PrimalityRefBase] /// will be supported by most functions in `num-primes` pub trait PrimalityBase: Integer + Roots + NumRef + Clone + FromPrimitive + ToPrimitive + ExactRoots + BitTest + ModularRefOps { } impl< T: Integer + Roots + NumRef + Clone + FromPrimitive + ToPrimitive + ExactRoots + BitTest + ModularRefOps, > PrimalityBase for T { } /// A dummy trait for integer reference type. All types that implements this and [PrimalityBase] /// will be supported by most functions in `num-primes` pub trait PrimalityRefBase<Base>: RefNum<Base> + std::ops::Shr<usize, Output = Base> + for<'r> ModularUnaryOps<&'r Base, Output = Base> + for<'r> ModularCoreOps<&'r Base, &'r Base, Output = Base> { } impl<T, Base> PrimalityRefBase<Base> for T where T: RefNum<Base> + std::ops::Shr<usize, Output = Base> + for<'r> ModularUnaryOps<&'r Base, Output = Base> + for<'r> ModularCoreOps<&'r Base, &'r Base, Output = Base> { } #[cfg(test)] mod tests { use super::*; use crate::mint::SmallMint; use num_modular::{ModularAbs, ModularSymbols}; use rand::random; #[cfg(feature = "num-bigint")] use num_bigint::BigUint; #[test] fn fermat_prp_test() { // 341 is the smallest pseudoprime for base 2 assert!(341u16.is_prp(2)); assert!(!340u16.is_prp(2)); assert!(!105u16.is_prp(2)); // Carmichael number 561 = 3*11*17 is fermat pseudoprime for any base coprime to 561 for p in [2, 5, 7, 13, 19] { assert!(561u32.is_prp(p)); } } #[test] fn sprp_test() { // strong pseudoprimes of base 2 (OEIS:A001262) under 10000 let spsp: [u16; 5] = [2047, 3277, 4033, 4681, 8321]; for psp in spsp { assert!(psp.is_sprp(2)); assert!(SmallMint::from(psp).is_sprp(2.into())); // test Mint execution } // test cofactor return assert_eq!(341u16.test_sprp(2), Either::Right(31)); assert_eq!( SmallMint::from(341u16).test_sprp(2.into()), Either::Right(31.into()) ); } #[test] fn lucas_mod_test() { // OEIS:A006190 let p3qm1: [u64; 26] = [ 0, 1, 3, 10, 33, 109, 360, 1189, 3927, 12970, 42837, 141481, 467280, 1543321, 5097243, 16835050, 55602393, 183642229, 606529080, 2003229469, 6616217487, 21851881930, 72171863277, 238367471761, 787274278560, 2600190307441, ]; let m = random::<u16>(); for n in 2..p3qm1.len() { let (uk, _) = LucasUtils::lucasm(3, -1, m as u64, n as u64); assert_eq!(uk, p3qm1[n] % (m as u64)); #[cfg(feature = "num-bigint")] { let (uk, _) = LucasUtils::lucasm(3, -1, BigUint::from(m), BigUint::from(n)); assert_eq!(uk, BigUint::from(p3qm1[n] % (m as u64))); } } fn lucasm_naive(p: usize, q: isize, m: u16, n: u16) -> (u16, u16) { if n == 0 { return (0, 2); } let m = m as usize; let q = q.absm(&m); let (mut um1, mut u) = (0, 1); // U_{n-1}, U_{n} let (mut vm1, mut v) = (2, p % m); // V_{n-1}, V_{n} for _ in 1..n { let new_u = p.mulm(u, &m).subm(q.mulm(um1, &m), &m); um1 = u; u = new_u; let new_v = p.mulm(v, &m).subm(q.mulm(vm1, &m), &m); vm1 = v; v = new_v; } (u as u16, v as u16) } for _ in 0..10 { let n = random::<u8>() as u16; let m = random::<u16>(); let p = random::<u16>() as usize; let q = random::<i16>() as isize; assert_eq!( LucasUtils::lucasm(p, q, m, n), lucasm_naive(p, q, m, n), "failed with Lucas settings: p={}, q={}, m={}, n={}", p, q, m, n ); } } #[test] fn lucas_prp_test() { // Some known cases assert!(19u8.is_lprp(Some(3), Some(-1))); assert!(5u8.is_lprp(None, None)); assert!(7u8.is_lprp(None, None)); assert!(!9u8.is_lprp(None, None)); assert!(!5719u16.is_lprp(None, None)); assert!(!1239u16.is_eslprp(None)); // least lucas pseudo primes for Q=-1 and Jacobi(D/n) = -1 (from Wikipedia) let plimit: [u16; 5] = [323, 35, 119, 9, 9]; for (i, l) in plimit.iter().cloned().enumerate() { let p = i + 1; assert!(l.is_lprp(Some(p), Some(-1))); // test four random numbers under limit for _ in 0..10 { let n = random::<u16>() % l; if n <= 3 || n.is_sprp(2) { continue; } // skip real primes let d = (p * p + 4) as u16; if n.is_odd() && d.jacobi(&n) != -1 { continue; } assert!( !n.is_lprp(Some(p), Some(-1)), "lucas prp test on {} with p = {}", n, p ); } } // least strong lucas pseudoprimes for Q=-1 and Jacobi(D/n) = -1 (from Wikipedia) let plimit: [u16; 3] = [4181, 169, 119]; for (i, l) in plimit.iter().cloned().enumerate() { let p = i + 1; assert!(l.is_slprp(Some(p), Some(-1))); // test random numbers under limit for _ in 0..10 { let n = random::<u16>() % l; if n <= 3 || (n.is_sprp(2) && n.is_sprp(3)) { continue; } // skip real primes let d = (p * p + 4) as u16; if n.is_odd() && d.jacobi(&n) != -1 { continue; } assert!( !n.is_slprp(Some(p), Some(-1)), "strong lucas prp test on {} with p = {}", n, p ); } } // lucas pseudoprimes (OEIS:A217120) under 10000 let lpsp: [u16; 9] = [323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179]; for psp in lpsp { assert!( psp.is_lprp(None, None), "lucas prp test on pseudoprime {}", psp ); } for _ in 0..50 { let n = random::<u16>() % 10000; if n <= 3 || (n.is_sprp(2) && n.is_sprp(3)) { continue; } // skip real primes if lpsp.iter().find(|&x| x == &n).is_some() { continue; } // skip pseudoprimes assert!(!n.is_lprp(None, None), "lucas prp test on {}", n); } // strong lucas pseudoprimes (OEIS:A217255) under 10000 let slpsp: [u16; 2] = [5459, 5777]; for psp in slpsp { assert!( psp.is_slprp(None, None), "strong lucas prp test on pseudoprime {}", psp ); } for _ in 0..50 { let n = random::<u16>() % 10000; if n <= 3 || (n.is_sprp(2) && n.is_sprp(3)) { continue; } // skip real primes if slpsp.iter().find(|&x| x == &n).is_some() { continue; } // skip pseudoprimes assert!(!n.is_slprp(None, None), "strong lucas prp test on {}", n); } // extra strong lucas pseudoprimes (OEIS:A217719) under 10000 let eslpsp: [u16; 3] = [989, 3239, 5777]; for psp in eslpsp { assert!( psp.is_eslprp(None), "extra strong lucas prp test on pseudoprime {}", psp ); } for _ in 0..50 { let n = random::<u16>() % 10000; if n <= 3 || (n.is_sprp(2) && n.is_sprp(3)) { continue; } // skip real primes if eslpsp.iter().find(|&x| x == &n).is_some() { continue; } // skip pseudoprimes assert!(!n.is_eslprp(None), "extra strong lucas prp test on {}", n); } } }
30.264659
127
0.428549
3ac8549a59c5057bff052f96cca1983fd8ad363a
973
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::AccountAddress; use anyhow::Result; use move_core_types::move_resource::MoveResource; use serde::{Deserialize, Serialize}; /// Struct that represents a NewBlockEvent. #[derive(Debug, Serialize, Deserialize)] pub struct NewBlockEvent { round: u64, proposer: AccountAddress, previous_block_votes: Vec<AccountAddress>, time_micro_seconds: u64, } impl NewBlockEvent { pub fn round(&self) -> u64 { self.round } pub fn proposer(&self) -> AccountAddress { self.proposer } pub fn proposed_time(&self) -> u64 { self.time_micro_seconds } pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> { bcs::from_bytes(bytes).map_err(Into::into) } } impl MoveResource for NewBlockEvent { const MODULE_NAME: &'static str = "DiemBlock"; const STRUCT_NAME: &'static str = "NewBlockEvent"; }
24.325
57
0.684481
62b8a2159f1653ff78c8ac04d99890ac4055fe84
1,502
#![feature(once_cell)] use std::time::Duration; use tokio::time::sleep; use context::TestContext; use leaderchip_etcd::lease; mod context; #[tokio::test] async fn should_keep_alive_leases() { let mut ctx = TestContext::new().await; // when a lease is acquired let lease = lease::acquire_lease(&ctx.etcd, 1).await.unwrap(); sleep(Duration::from_secs(3)).await; // then the lease is kept alive let leases = ctx.etcd.leases().await.unwrap(); assert_eq!(1, leases.leases().len()); assert_eq!(lease.id, leases.leases().get(0).unwrap().id()); } #[tokio::test] async fn dropped_lease_is_not_kept_alive() { let mut ctx = TestContext::new().await; // given a lease let lease = lease::acquire_lease(&ctx.etcd, 1).await.unwrap(); sleep(Duration::from_secs(2)).await; // when the lease is dropped drop(lease); // then the lease is not alive anymore sleep(Duration::from_secs(1)).await; let leases = ctx.etcd.leases().await.unwrap(); assert_eq!(0, leases.leases().len()); } #[tokio::test] async fn can_listen_lease_expiration() { let mut ctx = TestContext::new().await; // given a lease let lease = lease::acquire_lease(&ctx.etcd, 1).await.unwrap(); sleep(Duration::from_secs(1)).await; // when the lease expires ctx.etcd.lease_revoke(lease.id).await.unwrap(); sleep(Duration::from_secs(1)).await; // the channel is notified let result = lease.cancel.await; assert_eq!(Ok(()), result); }
25.457627
66
0.660453
5da28be8435d2a7e0bb53901d0b63c78db1a534f
809,622
/* automatically generated by rust-bindgen */ pub type czmq_destructor = unsafe extern "C" fn(item: *mut *mut ::std::os::raw::c_void); pub type czmq_duplicator = unsafe extern "C" fn(item: *const ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub type czmq_comparator = unsafe extern "C" fn(item1: *const ::std::os::raw::c_void, item2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type errno_t = ::std::os::raw::c_int; pub type __int8_t = ::std::os::raw::c_char; pub type __uint8_t = ::std::os::raw::c_uchar; pub type __int16_t = ::std::os::raw::c_short; pub type __uint16_t = ::std::os::raw::c_ushort; pub type __int32_t = ::std::os::raw::c_int; pub type __uint32_t = ::std::os::raw::c_uint; pub type __int64_t = ::std::os::raw::c_longlong; pub type __uint64_t = ::std::os::raw::c_ulonglong; pub type __darwin_intptr_t = ::std::os::raw::c_long; pub type __darwin_natural_t = ::std::os::raw::c_uint; pub type __darwin_ct_rune_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed1 { pub _bindgen_data_: [u64; 16usize], } impl Union_Unnamed1 { pub unsafe fn __mbstate8(&mut self) -> *mut [::std::os::raw::c_char; 128usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn _mbstateL(&mut self) -> *mut ::std::os::raw::c_longlong { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed1 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __mbstate_t = Union_Unnamed1; pub type __darwin_mbstate_t = __mbstate_t; pub type __darwin_ptrdiff_t = ::std::os::raw::c_long; pub type __darwin_size_t = ::std::os::raw::c_ulong; pub type __darwin_va_list = __builtin_va_list; pub type __darwin_wchar_t = ::std::os::raw::c_int; pub type __darwin_rune_t = __darwin_wchar_t; pub type __darwin_wint_t = ::std::os::raw::c_int; pub type __darwin_clock_t = ::std::os::raw::c_ulong; pub type __darwin_socklen_t = __uint32_t; pub type __darwin_ssize_t = ::std::os::raw::c_long; pub type __darwin_time_t = ::std::os::raw::c_long; pub type __darwin_blkcnt_t = __int64_t; pub type __darwin_blksize_t = __int32_t; pub type __darwin_dev_t = __int32_t; pub type __darwin_fsblkcnt_t = ::std::os::raw::c_uint; pub type __darwin_fsfilcnt_t = ::std::os::raw::c_uint; pub type __darwin_gid_t = __uint32_t; pub type __darwin_id_t = __uint32_t; pub type __darwin_ino64_t = __uint64_t; pub type __darwin_ino_t = __darwin_ino64_t; pub type __darwin_mach_port_name_t = __darwin_natural_t; pub type __darwin_mach_port_t = __darwin_mach_port_name_t; pub type __darwin_mode_t = __uint16_t; pub type __darwin_off_t = __int64_t; pub type __darwin_pid_t = __int32_t; pub type __darwin_sigset_t = __uint32_t; pub type __darwin_suseconds_t = __int32_t; pub type __darwin_uid_t = __uint32_t; pub type __darwin_useconds_t = __uint32_t; pub type __darwin_uuid_t = [::std::os::raw::c_uchar; 16usize]; pub type __darwin_uuid_string_t = [::std::os::raw::c_char; 37usize]; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_pthread_handler_rec { pub __routine: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void)>, pub __arg: *mut ::std::os::raw::c_void, pub __next: *mut Struct___darwin_pthread_handler_rec, } impl ::std::clone::Clone for Struct___darwin_pthread_handler_rec { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_pthread_handler_rec { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_attr_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 56usize], } impl ::std::clone::Clone for Struct__opaque_pthread_attr_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_attr_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_cond_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 40usize], } impl ::std::clone::Clone for Struct__opaque_pthread_cond_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_cond_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_condattr_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 8usize], } impl ::std::clone::Clone for Struct__opaque_pthread_condattr_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_condattr_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_mutex_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 56usize], } impl ::std::clone::Clone for Struct__opaque_pthread_mutex_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_mutex_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_mutexattr_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 8usize], } impl ::std::clone::Clone for Struct__opaque_pthread_mutexattr_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_mutexattr_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_once_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 8usize], } impl ::std::clone::Clone for Struct__opaque_pthread_once_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_once_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_rwlock_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 192usize], } impl ::std::clone::Clone for Struct__opaque_pthread_rwlock_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_rwlock_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_rwlockattr_t { pub __sig: ::std::os::raw::c_long, pub __opaque: [::std::os::raw::c_char; 16usize], } impl ::std::clone::Clone for Struct__opaque_pthread_rwlockattr_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_rwlockattr_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__opaque_pthread_t { pub __sig: ::std::os::raw::c_long, pub __cleanup_stack: *mut Struct___darwin_pthread_handler_rec, pub __opaque: [::std::os::raw::c_char; 8176usize], } impl ::std::clone::Clone for Struct__opaque_pthread_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__opaque_pthread_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __darwin_pthread_attr_t = Struct__opaque_pthread_attr_t; pub type __darwin_pthread_cond_t = Struct__opaque_pthread_cond_t; pub type __darwin_pthread_condattr_t = Struct__opaque_pthread_condattr_t; pub type __darwin_pthread_key_t = ::std::os::raw::c_ulong; pub type __darwin_pthread_mutex_t = Struct__opaque_pthread_mutex_t; pub type __darwin_pthread_mutexattr_t = Struct__opaque_pthread_mutexattr_t; pub type __darwin_pthread_once_t = Struct__opaque_pthread_once_t; pub type __darwin_pthread_rwlock_t = Struct__opaque_pthread_rwlock_t; pub type __darwin_pthread_rwlockattr_t = Struct__opaque_pthread_rwlockattr_t; pub type __darwin_pthread_t = *mut Struct__opaque_pthread_t; pub type __darwin_nl_item = ::std::os::raw::c_int; pub type __darwin_wctrans_t = ::std::os::raw::c_int; pub type __darwin_wctype_t = __uint32_t; pub type ptrdiff_t = __darwin_ptrdiff_t; pub type rsize_t = __darwin_size_t; pub type size_t = __darwin_size_t; pub type wchar_t = __darwin_wchar_t; pub type wint_t = __darwin_wint_t; pub type max_align_t = ::std::os::raw::c_double; pub type va_list = __builtin_va_list; pub type fpos_t = __darwin_off_t; #[repr(C)] #[derive(Copy)] pub struct Struct___sbuf { pub _base: *mut ::std::os::raw::c_uchar, pub _size: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct___sbuf { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___sbuf { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub enum Struct___sFILEX { } #[repr(C)] #[derive(Copy)] pub struct Struct___sFILE { pub _p: *mut ::std::os::raw::c_uchar, pub _r: ::std::os::raw::c_int, pub _w: ::std::os::raw::c_int, pub _flags: ::std::os::raw::c_short, pub _file: ::std::os::raw::c_short, pub _bf: Struct___sbuf, pub _lbfsize: ::std::os::raw::c_int, pub _cookie: *mut ::std::os::raw::c_void, pub _close: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int>, pub _read: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub _seek: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: fpos_t, arg3: ::std::os::raw::c_int) -> fpos_t>, pub _write: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub _ub: Struct___sbuf, pub _extra: *mut Struct___sFILEX, pub _ur: ::std::os::raw::c_int, pub _ubuf: [::std::os::raw::c_uchar; 3usize], pub _nbuf: [::std::os::raw::c_uchar; 1usize], pub _lb: Struct___sbuf, pub _blksize: ::std::os::raw::c_int, pub _offset: fpos_t, } impl ::std::clone::Clone for Struct___sFILE { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___sFILE { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type FILE = Struct___sFILE; pub type off_t = __darwin_off_t; pub type ssize_t = __darwin_ssize_t; pub type int8_t = ::std::os::raw::c_char; pub type int16_t = ::std::os::raw::c_short; pub type int32_t = ::std::os::raw::c_int; pub type int64_t = ::std::os::raw::c_longlong; pub type uint8_t = ::std::os::raw::c_uchar; pub type uint16_t = ::std::os::raw::c_ushort; pub type uint32_t = ::std::os::raw::c_uint; pub type uint64_t = ::std::os::raw::c_ulonglong; pub type int_least8_t = int8_t; pub type int_least16_t = int16_t; pub type int_least32_t = int32_t; pub type int_least64_t = int64_t; pub type uint_least8_t = uint8_t; pub type uint_least16_t = uint16_t; pub type uint_least32_t = uint32_t; pub type uint_least64_t = uint64_t; pub type int_fast8_t = int8_t; pub type int_fast16_t = int16_t; pub type int_fast32_t = int32_t; pub type int_fast64_t = int64_t; pub type uint_fast8_t = uint8_t; pub type uint_fast16_t = uint16_t; pub type uint_fast32_t = uint32_t; pub type uint_fast64_t = uint64_t; pub type intptr_t = __darwin_intptr_t; pub type uintptr_t = ::std::os::raw::c_ulong; pub type intmax_t = ::std::os::raw::c_long; pub type uintmax_t = ::std::os::raw::c_ulong; #[repr(C)] #[derive(Copy)] pub struct Struct_zmq_msg_t { pub unnamed_field1: [::std::os::raw::c_uchar; 64usize], } impl ::std::clone::Clone for Struct_zmq_msg_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_zmq_msg_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type zmq_msg_t = Struct_zmq_msg_t; pub type zmq_free_fn = unsafe extern "C" fn(data: *mut ::std::os::raw::c_void, hint: *mut ::std::os::raw::c_void); #[repr(C)] #[derive(Copy)] pub struct Struct_zmq_pollitem_t { pub socket: *mut ::std::os::raw::c_void, pub fd: ::std::os::raw::c_int, pub events: ::std::os::raw::c_short, pub revents: ::std::os::raw::c_short, } impl ::std::clone::Clone for Struct_zmq_pollitem_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_zmq_pollitem_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type zmq_pollitem_t = Struct_zmq_pollitem_t; pub type zmq_thread_fn = unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void); pub type ct_rune_t = __darwin_ct_rune_t; pub type rune_t = __darwin_rune_t; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed2 { pub __min: __darwin_rune_t, pub __max: __darwin_rune_t, pub __map: __darwin_rune_t, pub __types: *mut __uint32_t, } impl ::std::clone::Clone for Struct_Unnamed2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type _RuneEntry = Struct_Unnamed2; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed3 { pub __nranges: ::std::os::raw::c_int, pub __ranges: *mut _RuneEntry, } impl ::std::clone::Clone for Struct_Unnamed3 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed3 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type _RuneRange = Struct_Unnamed3; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed4 { pub __name: [::std::os::raw::c_char; 14usize], pub __mask: __uint32_t, } impl ::std::clone::Clone for Struct_Unnamed4 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed4 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type _RuneCharClass = Struct_Unnamed4; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed5 { pub __magic: [::std::os::raw::c_char; 8usize], pub __encoding: [::std::os::raw::c_char; 32usize], pub __sgetrune: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_char, arg2: __darwin_size_t, arg3: *mut *const ::std::os::raw::c_char) -> __darwin_rune_t>, pub __sputrune: ::std::option::Option<unsafe extern "C" fn(arg1: __darwin_rune_t, arg2: *mut ::std::os::raw::c_char, arg3: __darwin_size_t, arg4: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int>, pub __invalid_rune: __darwin_rune_t, pub __runetype: [__uint32_t; 256usize], pub __maplower: [__darwin_rune_t; 256usize], pub __mapupper: [__darwin_rune_t; 256usize], pub __runetype_ext: _RuneRange, pub __maplower_ext: _RuneRange, pub __mapupper_ext: _RuneRange, pub __variable: *mut ::std::os::raw::c_void, pub __variable_len: ::std::os::raw::c_int, pub __ncharclasses: ::std::os::raw::c_int, pub __charclasses: *mut _RuneCharClass, } impl ::std::clone::Clone for Struct_Unnamed5 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed5 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type _RuneLocale = Struct_Unnamed5; pub type __gnuc_va_list = __builtin_va_list; #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_Unnamed6 { P_ALL = 0, P_PID = 1, P_PGID = 2, } pub type idtype_t = Enum_Unnamed6; pub type pid_t = __darwin_pid_t; pub type id_t = __darwin_id_t; pub type sig_atomic_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_i386_thread_state { pub __eax: ::std::os::raw::c_uint, pub __ebx: ::std::os::raw::c_uint, pub __ecx: ::std::os::raw::c_uint, pub __edx: ::std::os::raw::c_uint, pub __edi: ::std::os::raw::c_uint, pub __esi: ::std::os::raw::c_uint, pub __ebp: ::std::os::raw::c_uint, pub __esp: ::std::os::raw::c_uint, pub __ss: ::std::os::raw::c_uint, pub __eflags: ::std::os::raw::c_uint, pub __eip: ::std::os::raw::c_uint, pub __cs: ::std::os::raw::c_uint, pub __ds: ::std::os::raw::c_uint, pub __es: ::std::os::raw::c_uint, pub __fs: ::std::os::raw::c_uint, pub __gs: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct___darwin_i386_thread_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_i386_thread_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_fp_control { pub _bindgen_bitfield_1_: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct___darwin_fp_control { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_fp_control { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __darwin_fp_control_t = Struct___darwin_fp_control; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_fp_status { pub _bindgen_bitfield_1_: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct___darwin_fp_status { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_fp_status { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __darwin_fp_status_t = Struct___darwin_fp_status; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_mmst_reg { pub __mmst_reg: [::std::os::raw::c_char; 10usize], pub __mmst_rsrv: [::std::os::raw::c_char; 6usize], } impl ::std::clone::Clone for Struct___darwin_mmst_reg { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_mmst_reg { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_xmm_reg { pub __xmm_reg: [::std::os::raw::c_char; 16usize], } impl ::std::clone::Clone for Struct___darwin_xmm_reg { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_xmm_reg { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_i386_float_state { pub __fpu_reserved: [::std::os::raw::c_int; 2usize], pub __fpu_fcw: Struct___darwin_fp_control, pub __fpu_fsw: Struct___darwin_fp_status, pub __fpu_ftw: __uint8_t, pub __fpu_rsrv1: __uint8_t, pub __fpu_fop: __uint16_t, pub __fpu_ip: __uint32_t, pub __fpu_cs: __uint16_t, pub __fpu_rsrv2: __uint16_t, pub __fpu_dp: __uint32_t, pub __fpu_ds: __uint16_t, pub __fpu_rsrv3: __uint16_t, pub __fpu_mxcsr: __uint32_t, pub __fpu_mxcsrmask: __uint32_t, pub __fpu_stmm0: Struct___darwin_mmst_reg, pub __fpu_stmm1: Struct___darwin_mmst_reg, pub __fpu_stmm2: Struct___darwin_mmst_reg, pub __fpu_stmm3: Struct___darwin_mmst_reg, pub __fpu_stmm4: Struct___darwin_mmst_reg, pub __fpu_stmm5: Struct___darwin_mmst_reg, pub __fpu_stmm6: Struct___darwin_mmst_reg, pub __fpu_stmm7: Struct___darwin_mmst_reg, pub __fpu_xmm0: Struct___darwin_xmm_reg, pub __fpu_xmm1: Struct___darwin_xmm_reg, pub __fpu_xmm2: Struct___darwin_xmm_reg, pub __fpu_xmm3: Struct___darwin_xmm_reg, pub __fpu_xmm4: Struct___darwin_xmm_reg, pub __fpu_xmm5: Struct___darwin_xmm_reg, pub __fpu_xmm6: Struct___darwin_xmm_reg, pub __fpu_xmm7: Struct___darwin_xmm_reg, pub __fpu_rsrv4: [::std::os::raw::c_char; 224usize], pub __fpu_reserved1: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct___darwin_i386_float_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_i386_float_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_i386_avx_state { pub __fpu_reserved: [::std::os::raw::c_int; 2usize], pub __fpu_fcw: Struct___darwin_fp_control, pub __fpu_fsw: Struct___darwin_fp_status, pub __fpu_ftw: __uint8_t, pub __fpu_rsrv1: __uint8_t, pub __fpu_fop: __uint16_t, pub __fpu_ip: __uint32_t, pub __fpu_cs: __uint16_t, pub __fpu_rsrv2: __uint16_t, pub __fpu_dp: __uint32_t, pub __fpu_ds: __uint16_t, pub __fpu_rsrv3: __uint16_t, pub __fpu_mxcsr: __uint32_t, pub __fpu_mxcsrmask: __uint32_t, pub __fpu_stmm0: Struct___darwin_mmst_reg, pub __fpu_stmm1: Struct___darwin_mmst_reg, pub __fpu_stmm2: Struct___darwin_mmst_reg, pub __fpu_stmm3: Struct___darwin_mmst_reg, pub __fpu_stmm4: Struct___darwin_mmst_reg, pub __fpu_stmm5: Struct___darwin_mmst_reg, pub __fpu_stmm6: Struct___darwin_mmst_reg, pub __fpu_stmm7: Struct___darwin_mmst_reg, pub __fpu_xmm0: Struct___darwin_xmm_reg, pub __fpu_xmm1: Struct___darwin_xmm_reg, pub __fpu_xmm2: Struct___darwin_xmm_reg, pub __fpu_xmm3: Struct___darwin_xmm_reg, pub __fpu_xmm4: Struct___darwin_xmm_reg, pub __fpu_xmm5: Struct___darwin_xmm_reg, pub __fpu_xmm6: Struct___darwin_xmm_reg, pub __fpu_xmm7: Struct___darwin_xmm_reg, pub __fpu_rsrv4: [::std::os::raw::c_char; 224usize], pub __fpu_reserved1: ::std::os::raw::c_int, pub __avx_reserved1: [::std::os::raw::c_char; 64usize], pub __fpu_ymmh0: Struct___darwin_xmm_reg, pub __fpu_ymmh1: Struct___darwin_xmm_reg, pub __fpu_ymmh2: Struct___darwin_xmm_reg, pub __fpu_ymmh3: Struct___darwin_xmm_reg, pub __fpu_ymmh4: Struct___darwin_xmm_reg, pub __fpu_ymmh5: Struct___darwin_xmm_reg, pub __fpu_ymmh6: Struct___darwin_xmm_reg, pub __fpu_ymmh7: Struct___darwin_xmm_reg, } impl ::std::clone::Clone for Struct___darwin_i386_avx_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_i386_avx_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_i386_exception_state { pub __trapno: __uint16_t, pub __cpu: __uint16_t, pub __err: __uint32_t, pub __faultvaddr: __uint32_t, } impl ::std::clone::Clone for Struct___darwin_i386_exception_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_i386_exception_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_debug_state32 { pub __dr0: ::std::os::raw::c_uint, pub __dr1: ::std::os::raw::c_uint, pub __dr2: ::std::os::raw::c_uint, pub __dr3: ::std::os::raw::c_uint, pub __dr4: ::std::os::raw::c_uint, pub __dr5: ::std::os::raw::c_uint, pub __dr6: ::std::os::raw::c_uint, pub __dr7: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct___darwin_x86_debug_state32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_debug_state32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_thread_state64 { pub __rax: __uint64_t, pub __rbx: __uint64_t, pub __rcx: __uint64_t, pub __rdx: __uint64_t, pub __rdi: __uint64_t, pub __rsi: __uint64_t, pub __rbp: __uint64_t, pub __rsp: __uint64_t, pub __r8: __uint64_t, pub __r9: __uint64_t, pub __r10: __uint64_t, pub __r11: __uint64_t, pub __r12: __uint64_t, pub __r13: __uint64_t, pub __r14: __uint64_t, pub __r15: __uint64_t, pub __rip: __uint64_t, pub __rflags: __uint64_t, pub __cs: __uint64_t, pub __fs: __uint64_t, pub __gs: __uint64_t, } impl ::std::clone::Clone for Struct___darwin_x86_thread_state64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_thread_state64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_float_state64 { pub __fpu_reserved: [::std::os::raw::c_int; 2usize], pub __fpu_fcw: Struct___darwin_fp_control, pub __fpu_fsw: Struct___darwin_fp_status, pub __fpu_ftw: __uint8_t, pub __fpu_rsrv1: __uint8_t, pub __fpu_fop: __uint16_t, pub __fpu_ip: __uint32_t, pub __fpu_cs: __uint16_t, pub __fpu_rsrv2: __uint16_t, pub __fpu_dp: __uint32_t, pub __fpu_ds: __uint16_t, pub __fpu_rsrv3: __uint16_t, pub __fpu_mxcsr: __uint32_t, pub __fpu_mxcsrmask: __uint32_t, pub __fpu_stmm0: Struct___darwin_mmst_reg, pub __fpu_stmm1: Struct___darwin_mmst_reg, pub __fpu_stmm2: Struct___darwin_mmst_reg, pub __fpu_stmm3: Struct___darwin_mmst_reg, pub __fpu_stmm4: Struct___darwin_mmst_reg, pub __fpu_stmm5: Struct___darwin_mmst_reg, pub __fpu_stmm6: Struct___darwin_mmst_reg, pub __fpu_stmm7: Struct___darwin_mmst_reg, pub __fpu_xmm0: Struct___darwin_xmm_reg, pub __fpu_xmm1: Struct___darwin_xmm_reg, pub __fpu_xmm2: Struct___darwin_xmm_reg, pub __fpu_xmm3: Struct___darwin_xmm_reg, pub __fpu_xmm4: Struct___darwin_xmm_reg, pub __fpu_xmm5: Struct___darwin_xmm_reg, pub __fpu_xmm6: Struct___darwin_xmm_reg, pub __fpu_xmm7: Struct___darwin_xmm_reg, pub __fpu_xmm8: Struct___darwin_xmm_reg, pub __fpu_xmm9: Struct___darwin_xmm_reg, pub __fpu_xmm10: Struct___darwin_xmm_reg, pub __fpu_xmm11: Struct___darwin_xmm_reg, pub __fpu_xmm12: Struct___darwin_xmm_reg, pub __fpu_xmm13: Struct___darwin_xmm_reg, pub __fpu_xmm14: Struct___darwin_xmm_reg, pub __fpu_xmm15: Struct___darwin_xmm_reg, pub __fpu_rsrv4: [::std::os::raw::c_char; 96usize], pub __fpu_reserved1: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct___darwin_x86_float_state64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_float_state64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_avx_state64 { pub __fpu_reserved: [::std::os::raw::c_int; 2usize], pub __fpu_fcw: Struct___darwin_fp_control, pub __fpu_fsw: Struct___darwin_fp_status, pub __fpu_ftw: __uint8_t, pub __fpu_rsrv1: __uint8_t, pub __fpu_fop: __uint16_t, pub __fpu_ip: __uint32_t, pub __fpu_cs: __uint16_t, pub __fpu_rsrv2: __uint16_t, pub __fpu_dp: __uint32_t, pub __fpu_ds: __uint16_t, pub __fpu_rsrv3: __uint16_t, pub __fpu_mxcsr: __uint32_t, pub __fpu_mxcsrmask: __uint32_t, pub __fpu_stmm0: Struct___darwin_mmst_reg, pub __fpu_stmm1: Struct___darwin_mmst_reg, pub __fpu_stmm2: Struct___darwin_mmst_reg, pub __fpu_stmm3: Struct___darwin_mmst_reg, pub __fpu_stmm4: Struct___darwin_mmst_reg, pub __fpu_stmm5: Struct___darwin_mmst_reg, pub __fpu_stmm6: Struct___darwin_mmst_reg, pub __fpu_stmm7: Struct___darwin_mmst_reg, pub __fpu_xmm0: Struct___darwin_xmm_reg, pub __fpu_xmm1: Struct___darwin_xmm_reg, pub __fpu_xmm2: Struct___darwin_xmm_reg, pub __fpu_xmm3: Struct___darwin_xmm_reg, pub __fpu_xmm4: Struct___darwin_xmm_reg, pub __fpu_xmm5: Struct___darwin_xmm_reg, pub __fpu_xmm6: Struct___darwin_xmm_reg, pub __fpu_xmm7: Struct___darwin_xmm_reg, pub __fpu_xmm8: Struct___darwin_xmm_reg, pub __fpu_xmm9: Struct___darwin_xmm_reg, pub __fpu_xmm10: Struct___darwin_xmm_reg, pub __fpu_xmm11: Struct___darwin_xmm_reg, pub __fpu_xmm12: Struct___darwin_xmm_reg, pub __fpu_xmm13: Struct___darwin_xmm_reg, pub __fpu_xmm14: Struct___darwin_xmm_reg, pub __fpu_xmm15: Struct___darwin_xmm_reg, pub __fpu_rsrv4: [::std::os::raw::c_char; 96usize], pub __fpu_reserved1: ::std::os::raw::c_int, pub __avx_reserved1: [::std::os::raw::c_char; 64usize], pub __fpu_ymmh0: Struct___darwin_xmm_reg, pub __fpu_ymmh1: Struct___darwin_xmm_reg, pub __fpu_ymmh2: Struct___darwin_xmm_reg, pub __fpu_ymmh3: Struct___darwin_xmm_reg, pub __fpu_ymmh4: Struct___darwin_xmm_reg, pub __fpu_ymmh5: Struct___darwin_xmm_reg, pub __fpu_ymmh6: Struct___darwin_xmm_reg, pub __fpu_ymmh7: Struct___darwin_xmm_reg, pub __fpu_ymmh8: Struct___darwin_xmm_reg, pub __fpu_ymmh9: Struct___darwin_xmm_reg, pub __fpu_ymmh10: Struct___darwin_xmm_reg, pub __fpu_ymmh11: Struct___darwin_xmm_reg, pub __fpu_ymmh12: Struct___darwin_xmm_reg, pub __fpu_ymmh13: Struct___darwin_xmm_reg, pub __fpu_ymmh14: Struct___darwin_xmm_reg, pub __fpu_ymmh15: Struct___darwin_xmm_reg, } impl ::std::clone::Clone for Struct___darwin_x86_avx_state64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_avx_state64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_exception_state64 { pub __trapno: __uint16_t, pub __cpu: __uint16_t, pub __err: __uint32_t, pub __faultvaddr: __uint64_t, } impl ::std::clone::Clone for Struct___darwin_x86_exception_state64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_exception_state64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_x86_debug_state64 { pub __dr0: __uint64_t, pub __dr1: __uint64_t, pub __dr2: __uint64_t, pub __dr3: __uint64_t, pub __dr4: __uint64_t, pub __dr5: __uint64_t, pub __dr6: __uint64_t, pub __dr7: __uint64_t, } impl ::std::clone::Clone for Struct___darwin_x86_debug_state64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_x86_debug_state64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_mcontext32 { pub __es: Struct___darwin_i386_exception_state, pub __ss: Struct___darwin_i386_thread_state, pub __fs: Struct___darwin_i386_float_state, } impl ::std::clone::Clone for Struct___darwin_mcontext32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_mcontext32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_mcontext_avx32 { pub __es: Struct___darwin_i386_exception_state, pub __ss: Struct___darwin_i386_thread_state, pub __fs: Struct___darwin_i386_avx_state, } impl ::std::clone::Clone for Struct___darwin_mcontext_avx32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_mcontext_avx32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_mcontext64 { pub __es: Struct___darwin_x86_exception_state64, pub __ss: Struct___darwin_x86_thread_state64, pub __fs: Struct___darwin_x86_float_state64, } impl ::std::clone::Clone for Struct___darwin_mcontext64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_mcontext64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_mcontext_avx64 { pub __es: Struct___darwin_x86_exception_state64, pub __ss: Struct___darwin_x86_thread_state64, pub __fs: Struct___darwin_x86_avx_state64, } impl ::std::clone::Clone for Struct___darwin_mcontext_avx64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_mcontext_avx64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mcontext_t = *mut Struct___darwin_mcontext64; pub type pthread_attr_t = __darwin_pthread_attr_t; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_sigaltstack { pub ss_sp: *mut ::std::os::raw::c_void, pub ss_size: __darwin_size_t, pub ss_flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct___darwin_sigaltstack { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_sigaltstack { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type stack_t = Struct___darwin_sigaltstack; #[repr(C)] #[derive(Copy)] pub struct Struct___darwin_ucontext { pub uc_onstack: ::std::os::raw::c_int, pub uc_sigmask: __darwin_sigset_t, pub uc_stack: Struct___darwin_sigaltstack, pub uc_link: *mut Struct___darwin_ucontext, pub uc_mcsize: __darwin_size_t, pub uc_mcontext: *mut Struct___darwin_mcontext64, } impl ::std::clone::Clone for Struct___darwin_ucontext { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___darwin_ucontext { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ucontext_t = Struct___darwin_ucontext; pub type sigset_t = __darwin_sigset_t; pub type uid_t = __darwin_uid_t; #[repr(C)] #[derive(Copy)] pub struct Union_sigval { pub _bindgen_data_: [u64; 1usize], } impl Union_sigval { pub unsafe fn sival_int(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn sival_ptr(&mut self) -> *mut *mut ::std::os::raw::c_void { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_sigval { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_sigval { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sigevent { pub sigev_notify: ::std::os::raw::c_int, pub sigev_signo: ::std::os::raw::c_int, pub sigev_value: Union_sigval, pub sigev_notify_function: ::std::option::Option<extern "C" fn(arg1: Union_sigval)>, pub sigev_notify_attributes: *mut pthread_attr_t, } impl ::std::clone::Clone for Struct_sigevent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sigevent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___siginfo { pub si_signo: ::std::os::raw::c_int, pub si_errno: ::std::os::raw::c_int, pub si_code: ::std::os::raw::c_int, pub si_pid: pid_t, pub si_uid: uid_t, pub si_status: ::std::os::raw::c_int, pub si_addr: *mut ::std::os::raw::c_void, pub si_value: Union_sigval, pub si_band: ::std::os::raw::c_long, pub __pad: [::std::os::raw::c_ulong; 7usize], } impl ::std::clone::Clone for Struct___siginfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___siginfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type siginfo_t = Struct___siginfo; #[repr(C)] #[derive(Copy)] pub struct Union___sigaction_u { pub _bindgen_data_: [u64; 1usize], } impl Union___sigaction_u { pub unsafe fn __sa_handler(&mut self) -> *mut ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)> { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn __sa_sigaction(&mut self) -> *mut ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int, arg2: *mut Struct___siginfo, arg3: *mut ::std::os::raw::c_void)> { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___sigaction_u { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___sigaction_u { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___sigaction { pub __sigaction_u: Union___sigaction_u, pub sa_tramp: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *mut siginfo_t, arg5: *mut ::std::os::raw::c_void)>, pub sa_mask: sigset_t, pub sa_flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct___sigaction { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___sigaction { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sigaction { pub __sigaction_u: Union___sigaction_u, pub sa_mask: sigset_t, pub sa_flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_sigaction { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sigaction { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type sig_t = ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>; #[repr(C)] #[derive(Copy)] pub struct Struct_sigvec { pub sv_handler: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>, pub sv_mask: ::std::os::raw::c_int, pub sv_flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_sigvec { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sigvec { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sigstack { pub ss_sp: *mut ::std::os::raw::c_char, pub ss_onstack: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_sigstack { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sigstack { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_timeval { pub tv_sec: __darwin_time_t, pub tv_usec: __darwin_suseconds_t, } impl ::std::clone::Clone for Struct_timeval { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_timeval { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rlim_t = __uint64_t; #[repr(C)] #[derive(Copy)] pub struct Struct_rusage { pub ru_utime: Struct_timeval, pub ru_stime: Struct_timeval, pub ru_maxrss: ::std::os::raw::c_long, pub ru_ixrss: ::std::os::raw::c_long, pub ru_idrss: ::std::os::raw::c_long, pub ru_isrss: ::std::os::raw::c_long, pub ru_minflt: ::std::os::raw::c_long, pub ru_majflt: ::std::os::raw::c_long, pub ru_nswap: ::std::os::raw::c_long, pub ru_inblock: ::std::os::raw::c_long, pub ru_oublock: ::std::os::raw::c_long, pub ru_msgsnd: ::std::os::raw::c_long, pub ru_msgrcv: ::std::os::raw::c_long, pub ru_nsignals: ::std::os::raw::c_long, pub ru_nvcsw: ::std::os::raw::c_long, pub ru_nivcsw: ::std::os::raw::c_long, } impl ::std::clone::Clone for Struct_rusage { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rusage { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rusage_info_t = *mut ::std::os::raw::c_void; #[repr(C)] #[derive(Copy)] pub struct Struct_rusage_info_v0 { pub ri_uuid: [uint8_t; 16usize], pub ri_user_time: uint64_t, pub ri_system_time: uint64_t, pub ri_pkg_idle_wkups: uint64_t, pub ri_interrupt_wkups: uint64_t, pub ri_pageins: uint64_t, pub ri_wired_size: uint64_t, pub ri_resident_size: uint64_t, pub ri_phys_footprint: uint64_t, pub ri_proc_start_abstime: uint64_t, pub ri_proc_exit_abstime: uint64_t, } impl ::std::clone::Clone for Struct_rusage_info_v0 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rusage_info_v0 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rusage_info_v1 { pub ri_uuid: [uint8_t; 16usize], pub ri_user_time: uint64_t, pub ri_system_time: uint64_t, pub ri_pkg_idle_wkups: uint64_t, pub ri_interrupt_wkups: uint64_t, pub ri_pageins: uint64_t, pub ri_wired_size: uint64_t, pub ri_resident_size: uint64_t, pub ri_phys_footprint: uint64_t, pub ri_proc_start_abstime: uint64_t, pub ri_proc_exit_abstime: uint64_t, pub ri_child_user_time: uint64_t, pub ri_child_system_time: uint64_t, pub ri_child_pkg_idle_wkups: uint64_t, pub ri_child_interrupt_wkups: uint64_t, pub ri_child_pageins: uint64_t, pub ri_child_elapsed_abstime: uint64_t, } impl ::std::clone::Clone for Struct_rusage_info_v1 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rusage_info_v1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rusage_info_v2 { pub ri_uuid: [uint8_t; 16usize], pub ri_user_time: uint64_t, pub ri_system_time: uint64_t, pub ri_pkg_idle_wkups: uint64_t, pub ri_interrupt_wkups: uint64_t, pub ri_pageins: uint64_t, pub ri_wired_size: uint64_t, pub ri_resident_size: uint64_t, pub ri_phys_footprint: uint64_t, pub ri_proc_start_abstime: uint64_t, pub ri_proc_exit_abstime: uint64_t, pub ri_child_user_time: uint64_t, pub ri_child_system_time: uint64_t, pub ri_child_pkg_idle_wkups: uint64_t, pub ri_child_interrupt_wkups: uint64_t, pub ri_child_pageins: uint64_t, pub ri_child_elapsed_abstime: uint64_t, pub ri_diskio_bytesread: uint64_t, pub ri_diskio_byteswritten: uint64_t, } impl ::std::clone::Clone for Struct_rusage_info_v2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rusage_info_v2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rusage_info_v3 { pub ri_uuid: [uint8_t; 16usize], pub ri_user_time: uint64_t, pub ri_system_time: uint64_t, pub ri_pkg_idle_wkups: uint64_t, pub ri_interrupt_wkups: uint64_t, pub ri_pageins: uint64_t, pub ri_wired_size: uint64_t, pub ri_resident_size: uint64_t, pub ri_phys_footprint: uint64_t, pub ri_proc_start_abstime: uint64_t, pub ri_proc_exit_abstime: uint64_t, pub ri_child_user_time: uint64_t, pub ri_child_system_time: uint64_t, pub ri_child_pkg_idle_wkups: uint64_t, pub ri_child_interrupt_wkups: uint64_t, pub ri_child_pageins: uint64_t, pub ri_child_elapsed_abstime: uint64_t, pub ri_diskio_bytesread: uint64_t, pub ri_diskio_byteswritten: uint64_t, pub ri_cpu_time_qos_default: uint64_t, pub ri_cpu_time_qos_maintenance: uint64_t, pub ri_cpu_time_qos_background: uint64_t, pub ri_cpu_time_qos_utility: uint64_t, pub ri_cpu_time_qos_legacy: uint64_t, pub ri_cpu_time_qos_user_initiated: uint64_t, pub ri_cpu_time_qos_user_interactive: uint64_t, pub ri_billed_system_time: uint64_t, pub ri_serviced_system_time: uint64_t, } impl ::std::clone::Clone for Struct_rusage_info_v3 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rusage_info_v3 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rusage_info_current = Struct_rusage_info_v3; #[repr(C)] #[derive(Copy)] pub struct Struct_rlimit { pub rlim_cur: rlim_t, pub rlim_max: rlim_t, } impl ::std::clone::Clone for Struct_rlimit { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rlimit { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_proc_rlimit_control_wakeupmon { pub wm_flags: uint32_t, pub wm_rate: int32_t, } impl ::std::clone::Clone for Struct_proc_rlimit_control_wakeupmon { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_proc_rlimit_control_wakeupmon { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_wait { pub _bindgen_data_: [u32; 1usize], } impl Union_wait { pub unsafe fn w_status(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn w_T(&mut self) -> *mut Struct_Unnamed7 { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn w_S(&mut self) -> *mut Struct_Unnamed8 { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_wait { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_wait { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed7 { pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_Unnamed7 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed7 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed8 { pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_Unnamed8 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed8 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed9 { pub quot: ::std::os::raw::c_int, pub rem: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed9 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed9 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type div_t = Struct_Unnamed9; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed10 { pub quot: ::std::os::raw::c_long, pub rem: ::std::os::raw::c_long, } impl ::std::clone::Clone for Struct_Unnamed10 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed10 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ldiv_t = Struct_Unnamed10; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed11 { pub quot: ::std::os::raw::c_longlong, pub rem: ::std::os::raw::c_longlong, } impl ::std::clone::Clone for Struct_Unnamed11 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed11 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type lldiv_t = Struct_Unnamed11; pub type u_int8_t = ::std::os::raw::c_uchar; pub type u_int16_t = ::std::os::raw::c_ushort; pub type u_int32_t = ::std::os::raw::c_uint; pub type u_int64_t = ::std::os::raw::c_ulonglong; pub type register_t = int64_t; pub type user_addr_t = u_int64_t; pub type user_size_t = u_int64_t; pub type user_ssize_t = int64_t; pub type user_long_t = int64_t; pub type user_ulong_t = u_int64_t; pub type user_time_t = int64_t; pub type user_off_t = int64_t; pub type syscall_arg_t = u_int64_t; pub type dev_t = __darwin_dev_t; pub type mode_t = __darwin_mode_t; pub type clock_t = __darwin_clock_t; pub type time_t = __darwin_time_t; #[repr(C)] #[derive(Copy)] pub struct Struct_timespec { pub tv_sec: __darwin_time_t, pub tv_nsec: ::std::os::raw::c_long, } impl ::std::clone::Clone for Struct_timespec { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_timespec { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_tm { pub tm_sec: ::std::os::raw::c_int, pub tm_min: ::std::os::raw::c_int, pub tm_hour: ::std::os::raw::c_int, pub tm_mday: ::std::os::raw::c_int, pub tm_mon: ::std::os::raw::c_int, pub tm_year: ::std::os::raw::c_int, pub tm_wday: ::std::os::raw::c_int, pub tm_yday: ::std::os::raw::c_int, pub tm_isdst: ::std::os::raw::c_int, pub tm_gmtoff: ::std::os::raw::c_long, pub tm_zone: *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_tm { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_tm { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type float_t = ::std::os::raw::c_float; pub type double_t = ::std::os::raw::c_double; #[repr(C)] #[derive(Copy)] pub struct Struct___float2 { pub __sinval: ::std::os::raw::c_float, pub __cosval: ::std::os::raw::c_float, } impl ::std::clone::Clone for Struct___float2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___float2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___double2 { pub __sinval: ::std::os::raw::c_double, pub __cosval: ::std::os::raw::c_double, } impl ::std::clone::Clone for Struct___double2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___double2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_exception { pub _type: ::std::os::raw::c_int, pub name: *mut ::std::os::raw::c_char, pub arg1: ::std::os::raw::c_double, pub arg2: ::std::os::raw::c_double, pub retval: ::std::os::raw::c_double, } impl ::std::clone::Clone for Struct_exception { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_exception { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type pthread_t = __darwin_pthread_t; pub type jmp_buf = [::std::os::raw::c_int; 37usize]; pub type sigjmp_buf = [::std::os::raw::c_int; 38usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_flock { pub l_start: off_t, pub l_len: off_t, pub l_pid: pid_t, pub l_type: ::std::os::raw::c_short, pub l_whence: ::std::os::raw::c_short, } impl ::std::clone::Clone for Struct_flock { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_flock { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_flocktimeout { pub fl: Struct_flock, pub timeout: Struct_timespec, } impl ::std::clone::Clone for Struct_flocktimeout { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_flocktimeout { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_radvisory { pub ra_offset: off_t, pub ra_count: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_radvisory { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_radvisory { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_fcodeblobs { pub f_cd_hash: *mut ::std::os::raw::c_void, pub f_hash_size: size_t, pub f_cd_buffer: *mut ::std::os::raw::c_void, pub f_cd_size: size_t, pub f_out_size: *mut ::std::os::raw::c_uint, pub f_arch: ::std::os::raw::c_int, pub __padding: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_fcodeblobs { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_fcodeblobs { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type fcodeblobs_t = Struct_fcodeblobs; #[repr(C)] #[derive(Copy)] pub struct Struct_fsignatures { pub fs_file_start: off_t, pub fs_blob_start: *mut ::std::os::raw::c_void, pub fs_blob_size: size_t, } impl ::std::clone::Clone for Struct_fsignatures { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_fsignatures { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type fsignatures_t = Struct_fsignatures; #[repr(C)] #[derive(Copy)] pub struct Struct_fstore { pub fst_flags: ::std::os::raw::c_uint, pub fst_posmode: ::std::os::raw::c_int, pub fst_offset: off_t, pub fst_length: off_t, pub fst_bytesalloc: off_t, } impl ::std::clone::Clone for Struct_fstore { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_fstore { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type fstore_t = Struct_fstore; #[repr(C)] #[derive(Copy)] pub struct Struct_fbootstraptransfer { pub fbt_offset: off_t, pub fbt_length: size_t, pub fbt_buffer: *mut ::std::os::raw::c_void, } impl ::std::clone::Clone for Struct_fbootstraptransfer { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_fbootstraptransfer { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type fbootstraptransfer_t = Struct_fbootstraptransfer; #[repr(C)] #[derive(Copy)] pub struct Struct_log2phys { pub l2p_flags: ::std::os::raw::c_uint, pub l2p_contigbytes: off_t, pub l2p_devoffset: off_t, } impl ::std::clone::Clone for Struct_log2phys { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_log2phys { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub enum Struct__filesec { } pub type filesec_t = *mut Struct__filesec; #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_Unnamed12 { FILESEC_OWNER = 1, FILESEC_GROUP = 2, FILESEC_UUID = 3, FILESEC_MODE = 4, FILESEC_ACL = 5, FILESEC_GRPUUID = 6, FILESEC_ACL_RAW = 100, FILESEC_ACL_ALLOCSIZE = 101, } pub type filesec_property_t = Enum_Unnamed12; pub type socklen_t = __darwin_socklen_t; pub type in_addr_t = __uint32_t; pub type in_port_t = __uint16_t; pub type u_char = ::std::os::raw::c_uchar; pub type u_short = ::std::os::raw::c_ushort; pub type u_int = ::std::os::raw::c_uint; pub type u_long = ::std::os::raw::c_ulong; pub type ushort = ::std::os::raw::c_ushort; pub type _uint = ::std::os::raw::c_uint; pub type u_quad_t = u_int64_t; pub type quad_t = int64_t; pub type qaddr_t = *mut quad_t; pub type caddr_t = *mut ::std::os::raw::c_char; pub type daddr_t = int32_t; pub type fixpt_t = u_int32_t; pub type blkcnt_t = __darwin_blkcnt_t; pub type blksize_t = __darwin_blksize_t; pub type gid_t = __darwin_gid_t; pub type ino_t = __darwin_ino_t; pub type ino64_t = __darwin_ino64_t; pub type key_t = __int32_t; pub type nlink_t = __uint16_t; pub type segsz_t = int32_t; pub type swblk_t = int32_t; pub type useconds_t = __darwin_useconds_t; pub type suseconds_t = __darwin_suseconds_t; #[repr(C)] #[derive(Copy)] pub struct Struct_fd_set { pub fds_bits: [__int32_t; 32usize], } impl ::std::clone::Clone for Struct_fd_set { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_fd_set { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type fd_set = Struct_fd_set; pub type fd_mask = __int32_t; pub type pthread_cond_t = __darwin_pthread_cond_t; pub type pthread_condattr_t = __darwin_pthread_condattr_t; pub type pthread_mutex_t = __darwin_pthread_mutex_t; pub type pthread_mutexattr_t = __darwin_pthread_mutexattr_t; pub type pthread_once_t = __darwin_pthread_once_t; pub type pthread_rwlock_t = __darwin_pthread_rwlock_t; pub type pthread_rwlockattr_t = __darwin_pthread_rwlockattr_t; pub type pthread_key_t = __darwin_pthread_key_t; pub type fsblkcnt_t = __darwin_fsblkcnt_t; pub type fsfilcnt_t = __darwin_fsfilcnt_t; pub type sa_family_t = __uint8_t; #[repr(C)] #[derive(Copy)] pub struct Struct_iovec { pub iov_base: *mut ::std::os::raw::c_void, pub iov_len: size_t, } impl ::std::clone::Clone for Struct_iovec { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_iovec { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type sae_associd_t = __uint32_t; pub type sae_connid_t = __uint32_t; #[repr(C)] #[derive(Copy)] pub struct Struct_sa_endpoints { pub sae_srcif: ::std::os::raw::c_uint, pub sae_srcaddr: *mut Struct_sockaddr, pub sae_srcaddrlen: socklen_t, pub sae_dstaddr: *mut Struct_sockaddr, pub sae_dstaddrlen: socklen_t, } impl ::std::clone::Clone for Struct_sa_endpoints { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sa_endpoints { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type sa_endpoints_t = Struct_sa_endpoints; #[repr(C)] #[derive(Copy)] pub struct Struct_linger { pub l_onoff: ::std::os::raw::c_int, pub l_linger: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_linger { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_linger { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_so_np_extensions { pub npx_flags: u_int32_t, pub npx_mask: u_int32_t, } impl ::std::clone::Clone for Struct_so_np_extensions { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_so_np_extensions { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sockaddr { pub sa_len: __uint8_t, pub sa_family: sa_family_t, pub sa_data: [::std::os::raw::c_char; 14usize], } impl ::std::clone::Clone for Struct_sockaddr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockaddr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sockproto { pub sp_family: __uint16_t, pub sp_protocol: __uint16_t, } impl ::std::clone::Clone for Struct_sockproto { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockproto { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sockaddr_storage { pub ss_len: __uint8_t, pub ss_family: sa_family_t, pub __ss_pad1: [::std::os::raw::c_char; 6usize], pub __ss_align: __int64_t, pub __ss_pad2: [::std::os::raw::c_char; 112usize], } impl ::std::clone::Clone for Struct_sockaddr_storage { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockaddr_storage { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_msghdr { pub msg_name: *mut ::std::os::raw::c_void, pub msg_namelen: socklen_t, pub msg_iov: *mut Struct_iovec, pub msg_iovlen: ::std::os::raw::c_int, pub msg_control: *mut ::std::os::raw::c_void, pub msg_controllen: socklen_t, pub msg_flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_msghdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_msghdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_cmsghdr { pub cmsg_len: socklen_t, pub cmsg_level: ::std::os::raw::c_int, pub cmsg_type: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_cmsghdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_cmsghdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sf_hdtr { pub headers: *mut Struct_iovec, pub hdr_cnt: ::std::os::raw::c_int, pub trailers: *mut Struct_iovec, pub trl_cnt: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_sf_hdtr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sf_hdtr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_in_addr { pub s_addr: in_addr_t, } impl ::std::clone::Clone for Struct_in_addr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_in_addr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sockaddr_in { pub sin_len: __uint8_t, pub sin_family: sa_family_t, pub sin_port: in_port_t, pub sin_addr: Struct_in_addr, pub sin_zero: [::std::os::raw::c_char; 8usize], } impl ::std::clone::Clone for Struct_sockaddr_in { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockaddr_in { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ip_opts { pub ip_dst: Struct_in_addr, pub ip_opts: [::std::os::raw::c_char; 40usize], } impl ::std::clone::Clone for Struct_ip_opts { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ip_opts { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ip_mreq { pub imr_multiaddr: Struct_in_addr, pub imr_interface: Struct_in_addr, } impl ::std::clone::Clone for Struct_ip_mreq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ip_mreq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ip_mreqn { pub imr_multiaddr: Struct_in_addr, pub imr_address: Struct_in_addr, pub imr_ifindex: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_ip_mreqn { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ip_mreqn { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ip_mreq_source { pub imr_multiaddr: Struct_in_addr, pub imr_sourceaddr: Struct_in_addr, pub imr_interface: Struct_in_addr, } impl ::std::clone::Clone for Struct_ip_mreq_source { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ip_mreq_source { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_group_req { pub gr_interface: uint32_t, pub gr_group: Struct_sockaddr_storage, } impl ::std::clone::Clone for Struct_group_req { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_group_req { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_group_source_req { pub gsr_interface: uint32_t, pub gsr_group: Struct_sockaddr_storage, pub gsr_source: Struct_sockaddr_storage, } impl ::std::clone::Clone for Struct_group_source_req { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_group_source_req { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct___msfilterreq { pub msfr_ifindex: uint32_t, pub msfr_fmode: uint32_t, pub msfr_nsrcs: uint32_t, pub __msfr_align: uint32_t, pub msfr_group: Struct_sockaddr_storage, pub msfr_srcs: *mut Struct_sockaddr_storage, } impl ::std::clone::Clone for Struct___msfilterreq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___msfilterreq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_in_pktinfo { pub ipi_ifindex: ::std::os::raw::c_uint, pub ipi_spec_dst: Struct_in_addr, pub ipi_addr: Struct_in_addr, } impl ::std::clone::Clone for Struct_in_pktinfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_in_pktinfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_in6_addr { pub __u6_addr: Union_Unnamed13, } impl ::std::clone::Clone for Struct_in6_addr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_in6_addr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed13 { pub _bindgen_data_: [u32; 4usize], } impl Union_Unnamed13 { pub unsafe fn __u6_addr8(&mut self) -> *mut [__uint8_t; 16usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn __u6_addr16(&mut self) -> *mut [__uint16_t; 8usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn __u6_addr32(&mut self) -> *mut [__uint32_t; 4usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed13 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed13 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_sockaddr_in6 { pub sin6_len: __uint8_t, pub sin6_family: sa_family_t, pub sin6_port: in_port_t, pub sin6_flowinfo: __uint32_t, pub sin6_addr: Struct_in6_addr, pub sin6_scope_id: __uint32_t, } impl ::std::clone::Clone for Struct_sockaddr_in6 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockaddr_in6 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ipv6_mreq { pub ipv6mr_multiaddr: Struct_in6_addr, pub ipv6mr_interface: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_ipv6_mreq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ipv6_mreq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_in6_pktinfo { pub ipi6_addr: Struct_in6_addr, pub ipi6_ifindex: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_in6_pktinfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_in6_pktinfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ip6_mtuinfo { pub ip6m_addr: Struct_sockaddr_in6, pub ip6m_mtu: uint32_t, } impl ::std::clone::Clone for Struct_ip6_mtuinfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ip6_mtuinfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_hostent { pub h_name: *mut ::std::os::raw::c_char, pub h_aliases: *mut *mut ::std::os::raw::c_char, pub h_addrtype: ::std::os::raw::c_int, pub h_length: ::std::os::raw::c_int, pub h_addr_list: *mut *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_hostent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_hostent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_netent { pub n_name: *mut ::std::os::raw::c_char, pub n_aliases: *mut *mut ::std::os::raw::c_char, pub n_addrtype: ::std::os::raw::c_int, pub n_net: uint32_t, } impl ::std::clone::Clone for Struct_netent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_netent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_servent { pub s_name: *mut ::std::os::raw::c_char, pub s_aliases: *mut *mut ::std::os::raw::c_char, pub s_port: ::std::os::raw::c_int, pub s_proto: *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_servent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_servent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_protoent { pub p_name: *mut ::std::os::raw::c_char, pub p_aliases: *mut *mut ::std::os::raw::c_char, pub p_proto: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_protoent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_protoent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_addrinfo { pub ai_flags: ::std::os::raw::c_int, pub ai_family: ::std::os::raw::c_int, pub ai_socktype: ::std::os::raw::c_int, pub ai_protocol: ::std::os::raw::c_int, pub ai_addrlen: socklen_t, pub ai_canonname: *mut ::std::os::raw::c_char, pub ai_addr: *mut Struct_sockaddr, pub ai_next: *mut Struct_addrinfo, } impl ::std::clone::Clone for Struct_addrinfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_addrinfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rpcent { pub r_name: *mut ::std::os::raw::c_char, pub r_aliases: *mut *mut ::std::os::raw::c_char, pub r_number: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_rpcent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rpcent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_accessx_descriptor { pub ad_name_offset: ::std::os::raw::c_uint, pub ad_flags: ::std::os::raw::c_int, pub ad_pad: [::std::os::raw::c_int; 2usize], } impl ::std::clone::Clone for Struct_accessx_descriptor { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_accessx_descriptor { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type uuid_t = __darwin_uuid_t; pub enum Struct_fssearchblock { } pub enum Struct_searchstate { } #[repr(C)] #[derive(Copy)] pub struct Struct_sched_param { pub sched_priority: ::std::os::raw::c_int, pub __opaque: [::std::os::raw::c_char; 4usize], } impl ::std::clone::Clone for Struct_sched_param { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sched_param { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_Unnamed14 { QOS_CLASS_USER_INTERACTIVE = 33, QOS_CLASS_USER_INITIATED = 25, QOS_CLASS_DEFAULT = 21, QOS_CLASS_UTILITY = 17, QOS_CLASS_BACKGROUND = 9, QOS_CLASS_UNSPECIFIED = 0, } pub type qos_class_t = ::std::os::raw::c_uint; pub enum Struct_pthread_override_s { } pub type pthread_override_t = *mut Struct_pthread_override_s; pub type mach_port_t = __darwin_mach_port_t; #[repr(C)] #[derive(Copy)] pub struct Struct_dirent { pub d_ino: __uint64_t, pub d_seekoff: __uint64_t, pub d_reclen: __uint16_t, pub d_namlen: __uint16_t, pub d_type: __uint8_t, pub d_name: [::std::os::raw::c_char; 1024usize], } impl ::std::clone::Clone for Struct_dirent { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_dirent { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub enum Struct__telldir { } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed15 { pub __dd_fd: ::std::os::raw::c_int, pub __dd_loc: ::std::os::raw::c_long, pub __dd_size: ::std::os::raw::c_long, pub __dd_buf: *mut ::std::os::raw::c_char, pub __dd_len: ::std::os::raw::c_int, pub __dd_seek: ::std::os::raw::c_long, pub __dd_rewind: ::std::os::raw::c_long, pub __dd_flags: ::std::os::raw::c_int, pub __dd_lock: __darwin_pthread_mutex_t, pub __dd_td: *mut Struct__telldir, } impl ::std::clone::Clone for Struct_Unnamed15 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed15 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type DIR = Struct_Unnamed15; #[repr(C)] #[derive(Copy)] pub struct Struct_passwd { pub pw_name: *mut ::std::os::raw::c_char, pub pw_passwd: *mut ::std::os::raw::c_char, pub pw_uid: uid_t, pub pw_gid: gid_t, pub pw_change: __darwin_time_t, pub pw_class: *mut ::std::os::raw::c_char, pub pw_gecos: *mut ::std::os::raw::c_char, pub pw_dir: *mut ::std::os::raw::c_char, pub pw_shell: *mut ::std::os::raw::c_char, pub pw_expire: __darwin_time_t, } impl ::std::clone::Clone for Struct_passwd { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_passwd { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type uuid_string_t = __darwin_uuid_string_t; #[repr(C)] #[derive(Copy)] pub struct Struct_group { pub gr_name: *mut ::std::os::raw::c_char, pub gr_passwd: *mut ::std::os::raw::c_char, pub gr_gid: gid_t, pub gr_mem: *mut *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_group { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_group { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_utimbuf { pub actime: time_t, pub modtime: time_t, } impl ::std::clone::Clone for Struct_utimbuf { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_utimbuf { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed16 { pub quot: intmax_t, pub rem: intmax_t, } impl ::std::clone::Clone for Struct_Unnamed16 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed16 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type imaxdiv_t = Struct_Unnamed16; #[repr(C)] #[derive(Copy)] pub struct Struct_timeval64 { pub tv_sec: __int64_t, pub tv_usec: __int64_t, } impl ::std::clone::Clone for Struct_timeval64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_timeval64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_itimerval { pub it_interval: Struct_timeval, pub it_value: Struct_timeval, } impl ::std::clone::Clone for Struct_itimerval { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_itimerval { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_timezone { pub tz_minuteswest: ::std::os::raw::c_int, pub tz_dsttime: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_timezone { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_timezone { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_clockinfo { pub hz: ::std::os::raw::c_int, pub tick: ::std::os::raw::c_int, pub tickadj: ::std::os::raw::c_int, pub stathz: ::std::os::raw::c_int, pub profhz: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_clockinfo { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_clockinfo { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ostat { pub st_dev: __uint16_t, pub st_ino: ino_t, pub st_mode: mode_t, pub st_nlink: nlink_t, pub st_uid: __uint16_t, pub st_gid: __uint16_t, pub st_rdev: __uint16_t, pub st_size: __int32_t, pub st_atimespec: Struct_timespec, pub st_mtimespec: Struct_timespec, pub st_ctimespec: Struct_timespec, pub st_blksize: __int32_t, pub st_blocks: __int32_t, pub st_flags: __uint32_t, pub st_gen: __uint32_t, } impl ::std::clone::Clone for Struct_ostat { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ostat { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_stat { pub st_dev: dev_t, pub st_mode: mode_t, pub st_nlink: nlink_t, pub st_ino: __darwin_ino64_t, pub st_uid: uid_t, pub st_gid: gid_t, pub st_rdev: dev_t, pub st_atimespec: Struct_timespec, pub st_mtimespec: Struct_timespec, pub st_ctimespec: Struct_timespec, pub st_birthtimespec: Struct_timespec, pub st_size: off_t, pub st_blocks: blkcnt_t, pub st_blksize: blksize_t, pub st_flags: __uint32_t, pub st_gen: __uint32_t, pub st_lspare: __int32_t, pub st_qspare: [__int64_t; 2usize], } impl ::std::clone::Clone for Struct_stat { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_stat { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_stat64 { pub st_dev: dev_t, pub st_mode: mode_t, pub st_nlink: nlink_t, pub st_ino: __darwin_ino64_t, pub st_uid: uid_t, pub st_gid: gid_t, pub st_rdev: dev_t, pub st_atimespec: Struct_timespec, pub st_mtimespec: Struct_timespec, pub st_ctimespec: Struct_timespec, pub st_birthtimespec: Struct_timespec, pub st_size: off_t, pub st_blocks: blkcnt_t, pub st_blksize: blksize_t, pub st_flags: __uint32_t, pub st_gen: __uint32_t, pub st_lspare: __int32_t, pub st_qspare: [__int64_t; 2usize], } impl ::std::clone::Clone for Struct_stat64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_stat64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_winsize { pub ws_row: ::std::os::raw::c_ushort, pub ws_col: ::std::os::raw::c_ushort, pub ws_xpixel: ::std::os::raw::c_ushort, pub ws_ypixel: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_winsize { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_winsize { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ttysize { pub ts_lines: ::std::os::raw::c_ushort, pub ts_cols: ::std::os::raw::c_ushort, pub ts_xxx: ::std::os::raw::c_ushort, pub ts_yyy: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_ttysize { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ttysize { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub enum Struct_ucred { } pub type kauth_cred_t = *mut Struct_ucred; pub enum Struct_posix_cred { } pub type posix_cred_t = *mut Struct_posix_cred; #[repr(C)] #[derive(Copy)] pub struct Struct_sockaddr_un { pub sun_len: ::std::os::raw::c_uchar, pub sun_family: sa_family_t, pub sun_path: [::std::os::raw::c_char; 104usize], } impl ::std::clone::Clone for Struct_sockaddr_un { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_sockaddr_un { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_uio_rw { UIO_READ = 0, UIO_WRITE = 1, } #[repr(C)] #[derive(Copy)] pub struct Struct_ifaddrs { pub ifa_next: *mut Struct_ifaddrs, pub ifa_name: *mut ::std::os::raw::c_char, pub ifa_flags: ::std::os::raw::c_uint, pub ifa_addr: *mut Struct_sockaddr, pub ifa_netmask: *mut Struct_sockaddr, pub ifa_dstaddr: *mut Struct_sockaddr, pub ifa_data: *mut ::std::os::raw::c_void, } impl ::std::clone::Clone for Struct_ifaddrs { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifaddrs { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifmaddrs { pub ifma_next: *mut Struct_ifmaddrs, pub ifma_name: *mut Struct_sockaddr, pub ifma_addr: *mut Struct_sockaddr, pub ifma_lladdr: *mut Struct_sockaddr, } impl ::std::clone::Clone for Struct_ifmaddrs { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifmaddrs { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type tcp_seq = __uint32_t; pub type tcp_cc = __uint32_t; #[repr(C)] #[derive(Copy)] pub struct Struct_tcphdr { pub th_sport: ::std::os::raw::c_ushort, pub th_dport: ::std::os::raw::c_ushort, pub th_seq: tcp_seq, pub th_ack: tcp_seq, pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, pub th_flags: ::std::os::raw::c_uchar, pub th_win: ::std::os::raw::c_ushort, pub th_sum: ::std::os::raw::c_ushort, pub th_urp: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_tcphdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_tcphdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_tcp_connection_info { pub tcpi_state: u_int8_t, pub tcpi_snd_wscale: u_int8_t, pub tcpi_rcv_wscale: u_int8_t, pub __pad1: u_int8_t, pub tcpi_options: u_int32_t, pub tcpi_flags: u_int32_t, pub tcpi_rto: u_int32_t, pub tcpi_maxseg: u_int32_t, pub tcpi_snd_ssthresh: u_int32_t, pub tcpi_snd_cwnd: u_int32_t, pub tcpi_snd_wnd: u_int32_t, pub tcpi_snd_sbbytes: u_int32_t, pub tcpi_rcv_wnd: u_int32_t, pub tcpi_rttcur: u_int32_t, pub tcpi_srtt: u_int32_t, pub tcpi_rttvar: u_int32_t, pub _bindgen_bitfield_1_: u_int32_t, pub _bindgen_bitfield_2_: u_int32_t, pub _bindgen_bitfield_3_: u_int32_t, pub _bindgen_bitfield_4_: u_int32_t, pub _bindgen_bitfield_5_: u_int32_t, pub _bindgen_bitfield_6_: u_int32_t, pub _bindgen_bitfield_7_: u_int32_t, pub _bindgen_bitfield_8_: u_int32_t, pub _bindgen_bitfield_9_: u_int32_t, pub _bindgen_bitfield_10_: u_int32_t, pub tcpi_txpackets: u_int64_t, pub tcpi_txbytes: u_int64_t, pub tcpi_txretransmitbytes: u_int64_t, pub tcpi_rxpackets: u_int64_t, pub tcpi_rxbytes: u_int64_t, pub tcpi_rxoutoforderbytes: u_int64_t, } impl ::std::clone::Clone for Struct_tcp_connection_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_tcp_connection_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_Unnamed17 { OSUnknownByteOrder = 0, OSLittleEndian = 1, OSBigEndian = 2, } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed18 { pub mig_vers: ::std::os::raw::c_uchar, pub if_vers: ::std::os::raw::c_uchar, pub reserved1: ::std::os::raw::c_uchar, pub mig_encoding: ::std::os::raw::c_uchar, pub int_rep: ::std::os::raw::c_uchar, pub char_rep: ::std::os::raw::c_uchar, pub float_rep: ::std::os::raw::c_uchar, pub reserved2: ::std::os::raw::c_uchar, } impl ::std::clone::Clone for Struct_Unnamed18 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed18 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type NDR_record_t = Struct_Unnamed18; pub type boolean_t = ::std::os::raw::c_uint; pub type kern_return_t = ::std::os::raw::c_int; pub type natural_t = __darwin_natural_t; pub type integer_t = ::std::os::raw::c_int; pub type vm_offset_t = uintptr_t; pub type vm_size_t = uintptr_t; pub type mach_vm_address_t = uint64_t; pub type mach_vm_offset_t = uint64_t; pub type mach_vm_size_t = uint64_t; pub type vm_map_offset_t = uint64_t; pub type vm_map_address_t = uint64_t; pub type vm_map_size_t = uint64_t; pub type mach_port_context_t = mach_vm_address_t; pub type mach_port_name_t = natural_t; pub type mach_port_name_array_t = *mut mach_port_name_t; pub type mach_port_array_t = *mut mach_port_t; pub type mach_port_right_t = natural_t; pub type mach_port_type_t = natural_t; pub type mach_port_type_array_t = *mut mach_port_type_t; pub type mach_port_urefs_t = natural_t; pub type mach_port_delta_t = integer_t; pub type mach_port_seqno_t = natural_t; pub type mach_port_mscount_t = natural_t; pub type mach_port_msgcount_t = natural_t; pub type mach_port_rights_t = natural_t; pub type mach_port_srights_t = ::std::os::raw::c_uint; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_port_status { pub mps_pset: mach_port_rights_t, pub mps_seqno: mach_port_seqno_t, pub mps_mscount: mach_port_mscount_t, pub mps_qlimit: mach_port_msgcount_t, pub mps_msgcount: mach_port_msgcount_t, pub mps_sorights: mach_port_rights_t, pub mps_srights: boolean_t, pub mps_pdrequest: boolean_t, pub mps_nsrequest: boolean_t, pub mps_flags: natural_t, } impl ::std::clone::Clone for Struct_mach_port_status { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_port_status { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_status_t = Struct_mach_port_status; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_port_limits { pub mpl_qlimit: mach_port_msgcount_t, } impl ::std::clone::Clone for Struct_mach_port_limits { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_port_limits { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_limits_t = Struct_mach_port_limits; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_port_info_ext { pub mpie_status: mach_port_status_t, pub mpie_boost_cnt: mach_port_msgcount_t, pub reserved: [uint32_t; 6usize], } impl ::std::clone::Clone for Struct_mach_port_info_ext { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_port_info_ext { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_info_ext_t = Struct_mach_port_info_ext; pub type mach_port_info_t = *mut integer_t; pub type mach_port_flavor_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_port_qos { pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, pub _bindgen_bitfield_2_: boolean_t, pub len: natural_t, } impl ::std::clone::Clone for Struct_mach_port_qos { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_port_qos { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_qos_t = Struct_mach_port_qos; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_port_options { pub flags: uint32_t, pub mpl: mach_port_limits_t, pub reserved: [uint64_t; 2usize], } impl ::std::clone::Clone for Struct_mach_port_options { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_port_options { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_options_t = Struct_mach_port_options; pub type mach_port_options_ptr_t = *mut mach_port_options_t; #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_mach_port_guard_exception_codes { kGUARD_EXC_DESTROY = 1, kGUARD_EXC_MOD_REFS = 2, kGUARD_EXC_SET_CONTEXT = 4, kGUARD_EXC_UNGUARDED = 8, kGUARD_EXC_INCORRECT_GUARD = 16, } pub type mach_msg_timeout_t = natural_t; pub type mach_msg_bits_t = ::std::os::raw::c_uint; pub type mach_msg_size_t = natural_t; pub type mach_msg_id_t = integer_t; pub type mach_msg_type_name_t = ::std::os::raw::c_uint; pub type mach_msg_copy_options_t = ::std::os::raw::c_uint; pub type mach_msg_descriptor_type_t = ::std::os::raw::c_uint; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed19 { pub pad1: natural_t, pub pad2: mach_msg_size_t, pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, pub _bindgen_bitfield_2_: mach_msg_descriptor_type_t, } impl ::std::clone::Clone for Struct_Unnamed19 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed19 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_type_descriptor_t = Struct_Unnamed19; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed20 { pub name: mach_port_t, pub pad1: mach_msg_size_t, pub _bindgen_bitfield_1_: ::std::os::raw::c_uint, pub _bindgen_bitfield_2_: mach_msg_type_name_t, pub _bindgen_bitfield_3_: mach_msg_descriptor_type_t, } impl ::std::clone::Clone for Struct_Unnamed20 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed20 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_port_descriptor_t = Struct_Unnamed20; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed21 { pub address: uint32_t, pub size: mach_msg_size_t, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: ::std::os::raw::c_uint, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, } impl ::std::clone::Clone for Struct_Unnamed21 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed21 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_descriptor32_t = Struct_Unnamed21; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed22 { pub address: uint64_t, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: ::std::os::raw::c_uint, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, pub size: mach_msg_size_t, } impl ::std::clone::Clone for Struct_Unnamed22 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed22 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_descriptor64_t = Struct_Unnamed22; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed23 { pub address: *mut ::std::os::raw::c_void, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: ::std::os::raw::c_uint, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, pub size: mach_msg_size_t, } impl ::std::clone::Clone for Struct_Unnamed23 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed23 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_descriptor_t = Struct_Unnamed23; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed24 { pub address: uint32_t, pub count: mach_msg_size_t, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: mach_msg_type_name_t, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, } impl ::std::clone::Clone for Struct_Unnamed24 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed24 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_ports_descriptor32_t = Struct_Unnamed24; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed25 { pub address: uint64_t, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: mach_msg_type_name_t, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, pub count: mach_msg_size_t, } impl ::std::clone::Clone for Struct_Unnamed25 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed25 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_ports_descriptor64_t = Struct_Unnamed25; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed26 { pub address: *mut ::std::os::raw::c_void, pub _bindgen_bitfield_1_: boolean_t, pub _bindgen_bitfield_2_: mach_msg_copy_options_t, pub _bindgen_bitfield_3_: mach_msg_type_name_t, pub _bindgen_bitfield_4_: mach_msg_descriptor_type_t, pub count: mach_msg_size_t, } impl ::std::clone::Clone for Struct_Unnamed26 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed26 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_ool_ports_descriptor_t = Struct_Unnamed26; #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed27 { pub _bindgen_data_: [u32; 4usize], } impl Union_Unnamed27 { pub unsafe fn port(&mut self) -> *mut mach_msg_port_descriptor_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn out_of_line(&mut self) -> *mut mach_msg_ool_descriptor_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ool_ports(&mut self) -> *mut mach_msg_ool_ports_descriptor_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn _type(&mut self) -> *mut mach_msg_type_descriptor_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed27 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed27 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_descriptor_t = Union_Unnamed27; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed28 { pub msgh_descriptor_count: mach_msg_size_t, } impl ::std::clone::Clone for Struct_Unnamed28 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed28 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_body_t = Struct_Unnamed28; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed29 { pub msgh_bits: mach_msg_bits_t, pub msgh_size: mach_msg_size_t, pub msgh_remote_port: mach_port_t, pub msgh_local_port: mach_port_t, pub msgh_voucher_port: mach_port_name_t, pub msgh_id: mach_msg_id_t, } impl ::std::clone::Clone for Struct_Unnamed29 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed29 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_header_t = Struct_Unnamed29; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed30 { pub header: mach_msg_header_t, pub body: mach_msg_body_t, } impl ::std::clone::Clone for Struct_Unnamed30 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed30 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_base_t = Struct_Unnamed30; pub type mach_msg_trailer_type_t = ::std::os::raw::c_uint; pub type mach_msg_trailer_size_t = ::std::os::raw::c_uint; pub type mach_msg_trailer_info_t = *mut ::std::os::raw::c_char; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed31 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, } impl ::std::clone::Clone for Struct_Unnamed31 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed31 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_trailer_t = Struct_Unnamed31; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed32 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, pub msgh_seqno: mach_port_seqno_t, } impl ::std::clone::Clone for Struct_Unnamed32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_seqno_trailer_t = Struct_Unnamed32; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed33 { pub val: [::std::os::raw::c_uint; 2usize], } impl ::std::clone::Clone for Struct_Unnamed33 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed33 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type security_token_t = Struct_Unnamed33; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed34 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, pub msgh_seqno: mach_port_seqno_t, pub msgh_sender: security_token_t, } impl ::std::clone::Clone for Struct_Unnamed34 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed34 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_security_trailer_t = Struct_Unnamed34; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed35 { pub val: [::std::os::raw::c_uint; 8usize], } impl ::std::clone::Clone for Struct_Unnamed35 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed35 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type audit_token_t = Struct_Unnamed35; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed36 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, pub msgh_seqno: mach_port_seqno_t, pub msgh_sender: security_token_t, pub msgh_audit: audit_token_t, } impl ::std::clone::Clone for Struct_Unnamed36 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed36 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_audit_trailer_t = Struct_Unnamed36; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed37 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, pub msgh_seqno: mach_port_seqno_t, pub msgh_sender: security_token_t, pub msgh_audit: audit_token_t, pub msgh_context: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed37 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed37 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_context_trailer_t = Struct_Unnamed37; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed38 { pub sender: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed38 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed38 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type msg_labels_t = Struct_Unnamed38; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed39 { pub msgh_trailer_type: mach_msg_trailer_type_t, pub msgh_trailer_size: mach_msg_trailer_size_t, pub msgh_seqno: mach_port_seqno_t, pub msgh_sender: security_token_t, pub msgh_audit: audit_token_t, pub msgh_context: mach_port_context_t, pub msgh_ad: ::std::os::raw::c_int, pub msgh_labels: msg_labels_t, } impl ::std::clone::Clone for Struct_Unnamed39 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed39 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_mac_trailer_t = Struct_Unnamed39; pub type mach_msg_max_trailer_t = mach_msg_mac_trailer_t; pub type mach_msg_format_0_trailer_t = mach_msg_security_trailer_t; pub type mach_msg_options_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed40 { pub header: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed40 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed40 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_empty_send_t = Struct_Unnamed40; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed41 { pub header: mach_msg_header_t, pub trailer: mach_msg_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed41 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed41 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_empty_rcv_t = Struct_Unnamed41; #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed42 { pub _bindgen_data_: [u32; 8usize], } impl Union_Unnamed42 { pub unsafe fn send(&mut self) -> *mut mach_msg_empty_send_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn rcv(&mut self) -> *mut mach_msg_empty_rcv_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed42 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed42 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_msg_empty_t = Union_Unnamed42; pub type mach_msg_type_size_t = natural_t; pub type mach_msg_type_number_t = natural_t; pub type mach_msg_option_t = integer_t; pub type mach_msg_return_t = kern_return_t; pub type notify_port_t = mach_port_t; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed43 { pub not_header: mach_msg_header_t, pub NDR: NDR_record_t, pub not_port: mach_port_name_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed43 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed43 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_deleted_notification_t = Struct_Unnamed43; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed44 { pub not_header: mach_msg_header_t, pub NDR: NDR_record_t, pub not_port: mach_port_name_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed44 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed44 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_send_possible_notification_t = Struct_Unnamed44; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed45 { pub not_header: mach_msg_header_t, pub not_body: mach_msg_body_t, pub not_port: mach_msg_port_descriptor_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed45 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed45 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_port_destroyed_notification_t = Struct_Unnamed45; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed46 { pub not_header: mach_msg_header_t, pub NDR: NDR_record_t, pub not_count: mach_msg_type_number_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed46 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed46 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_no_senders_notification_t = Struct_Unnamed46; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed47 { pub not_header: mach_msg_header_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed47 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed47 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_send_once_notification_t = Struct_Unnamed47; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed48 { pub not_header: mach_msg_header_t, pub NDR: NDR_record_t, pub not_port: mach_port_name_t, pub trailer: mach_msg_format_0_trailer_t, } impl ::std::clone::Clone for Struct_Unnamed48 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed48 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_dead_name_notification_t = Struct_Unnamed48; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_statistics { pub free_count: natural_t, pub active_count: natural_t, pub inactive_count: natural_t, pub wire_count: natural_t, pub zero_fill_count: natural_t, pub reactivations: natural_t, pub pageins: natural_t, pub pageouts: natural_t, pub faults: natural_t, pub cow_faults: natural_t, pub lookups: natural_t, pub hits: natural_t, pub purgeable_count: natural_t, pub purges: natural_t, pub speculative_count: natural_t, } impl ::std::clone::Clone for Struct_vm_statistics { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_statistics { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_statistics_t = *mut Struct_vm_statistics; pub type vm_statistics_data_t = Struct_vm_statistics; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_statistics64 { pub free_count: natural_t, pub active_count: natural_t, pub inactive_count: natural_t, pub wire_count: natural_t, pub zero_fill_count: uint64_t, pub reactivations: uint64_t, pub pageins: uint64_t, pub pageouts: uint64_t, pub faults: uint64_t, pub cow_faults: uint64_t, pub lookups: uint64_t, pub hits: uint64_t, pub purges: uint64_t, pub purgeable_count: natural_t, pub speculative_count: natural_t, pub decompressions: uint64_t, pub compressions: uint64_t, pub swapins: uint64_t, pub swapouts: uint64_t, pub compressor_page_count: natural_t, pub throttled_count: natural_t, pub external_page_count: natural_t, pub internal_page_count: natural_t, pub total_uncompressed_pages_in_compressor: uint64_t, } impl ::std::clone::Clone for Struct_vm_statistics64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_statistics64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_statistics64_t = *mut Struct_vm_statistics64; pub type vm_statistics64_data_t = Struct_vm_statistics64; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_extmod_statistics { pub task_for_pid_count: int64_t, pub task_for_pid_caller_count: int64_t, pub thread_creation_count: int64_t, pub thread_creation_caller_count: int64_t, pub thread_set_state_count: int64_t, pub thread_set_state_caller_count: int64_t, } impl ::std::clone::Clone for Struct_vm_extmod_statistics { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_extmod_statistics { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_extmod_statistics_t = *mut Struct_vm_extmod_statistics; pub type vm_extmod_statistics_data_t = Struct_vm_extmod_statistics; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_purgeable_stat { pub count: uint64_t, pub size: uint64_t, } impl ::std::clone::Clone for Struct_vm_purgeable_stat { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_purgeable_stat { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_purgeable_stat_t = Struct_vm_purgeable_stat; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_purgeable_info { pub fifo_data: [vm_purgeable_stat_t; 8usize], pub obsolete_data: vm_purgeable_stat_t, pub lifo_data: [vm_purgeable_stat_t; 8usize], } impl ::std::clone::Clone for Struct_vm_purgeable_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_purgeable_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_purgeable_info_t = *mut Struct_vm_purgeable_info; pub type cpu_type_t = integer_t; pub type cpu_subtype_t = integer_t; pub type cpu_threadtype_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_time_value { pub seconds: integer_t, pub microseconds: integer_t, } impl ::std::clone::Clone for Struct_time_value { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_time_value { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type time_value_t = Struct_time_value; pub type host_info_t = *mut integer_t; pub type host_info64_t = *mut integer_t; pub type host_info_data_t = [integer_t; 1024usize]; pub type kernel_version_t = [::std::os::raw::c_char; 512usize]; pub type kernel_boot_info_t = [::std::os::raw::c_char; 4096usize]; pub type host_flavor_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_host_basic_info { pub max_cpus: integer_t, pub avail_cpus: integer_t, pub memory_size: natural_t, pub cpu_type: cpu_type_t, pub cpu_subtype: cpu_subtype_t, pub cpu_threadtype: cpu_threadtype_t, pub physical_cpu: integer_t, pub physical_cpu_max: integer_t, pub logical_cpu: integer_t, pub logical_cpu_max: integer_t, pub max_mem: uint64_t, } impl ::std::clone::Clone for Struct_host_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_host_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type host_basic_info_data_t = Struct_host_basic_info; pub type host_basic_info_t = *mut Struct_host_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_host_sched_info { pub min_timeout: integer_t, pub min_quantum: integer_t, } impl ::std::clone::Clone for Struct_host_sched_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_host_sched_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type host_sched_info_data_t = Struct_host_sched_info; pub type host_sched_info_t = *mut Struct_host_sched_info; #[repr(C)] #[derive(Copy)] pub struct Struct_kernel_resource_sizes { pub task: natural_t, pub thread: natural_t, pub port: natural_t, pub memory_region: natural_t, pub memory_object: natural_t, } impl ::std::clone::Clone for Struct_kernel_resource_sizes { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kernel_resource_sizes { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type kernel_resource_sizes_data_t = Struct_kernel_resource_sizes; pub type kernel_resource_sizes_t = *mut Struct_kernel_resource_sizes; #[repr(C)] #[derive(Copy)] pub struct Struct_host_priority_info { pub kernel_priority: integer_t, pub system_priority: integer_t, pub server_priority: integer_t, pub user_priority: integer_t, pub depress_priority: integer_t, pub idle_priority: integer_t, pub minimum_priority: integer_t, pub maximum_priority: integer_t, } impl ::std::clone::Clone for Struct_host_priority_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_host_priority_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type host_priority_info_data_t = Struct_host_priority_info; pub type host_priority_info_t = *mut Struct_host_priority_info; #[repr(C)] #[derive(Copy)] pub struct Struct_host_load_info { pub avenrun: [integer_t; 3usize], pub mach_factor: [integer_t; 3usize], } impl ::std::clone::Clone for Struct_host_load_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_host_load_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type host_load_info_data_t = Struct_host_load_info; pub type host_load_info_t = *mut Struct_host_load_info; pub type host_purgable_info_data_t = Struct_vm_purgeable_info; pub type host_purgable_info_t = *mut Struct_vm_purgeable_info; #[repr(C)] #[derive(Copy)] pub struct Struct_host_cpu_load_info { pub cpu_ticks: [natural_t; 4usize], } impl ::std::clone::Clone for Struct_host_cpu_load_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_host_cpu_load_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type host_cpu_load_info_data_t = Struct_host_cpu_load_info; pub type host_cpu_load_info_t = *mut Struct_host_cpu_load_info; pub type vm_prot_t = ::std::os::raw::c_int; pub type vm_sync_t = ::std::os::raw::c_uint; pub type pointer_t = vm_offset_t; pub type vm_address_t = vm_offset_t; pub type addr64_t = uint64_t; pub type reg64_t = uint32_t; pub type ppnum_t = uint32_t; pub type vm_map_t = mach_port_t; pub type vm_object_offset_t = uint64_t; pub type vm_object_size_t = uint64_t; pub type upl_t = mach_port_t; pub type vm_named_entry_t = mach_port_t; pub type memory_object_offset_t = ::std::os::raw::c_ulonglong; pub type memory_object_size_t = ::std::os::raw::c_ulonglong; pub type memory_object_cluster_size_t = natural_t; pub type memory_object_fault_info_t = *mut natural_t; pub type vm_object_id_t = ::std::os::raw::c_ulonglong; pub type memory_object_t = mach_port_t; pub type memory_object_control_t = mach_port_t; pub type memory_object_array_t = *mut memory_object_t; pub type memory_object_name_t = mach_port_t; pub type memory_object_default_t = mach_port_t; pub type memory_object_copy_strategy_t = ::std::os::raw::c_int; pub type memory_object_return_t = ::std::os::raw::c_int; pub type memory_object_info_t = *mut ::std::os::raw::c_int; pub type memory_object_flavor_t = ::std::os::raw::c_int; pub type memory_object_info_data_t = [::std::os::raw::c_int; 1024usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_memory_object_perf_info { pub cluster_size: memory_object_cluster_size_t, pub may_cache: boolean_t, } impl ::std::clone::Clone for Struct_memory_object_perf_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_memory_object_perf_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_memory_object_attr_info { pub copy_strategy: memory_object_copy_strategy_t, pub cluster_size: memory_object_cluster_size_t, pub may_cache_object: boolean_t, pub temporary: boolean_t, } impl ::std::clone::Clone for Struct_memory_object_attr_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_memory_object_attr_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_memory_object_behave_info { pub copy_strategy: memory_object_copy_strategy_t, pub temporary: boolean_t, pub invalidate: boolean_t, pub silent_overwrite: boolean_t, pub advisory_pageout: boolean_t, } impl ::std::clone::Clone for Struct_memory_object_behave_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_memory_object_behave_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type memory_object_behave_info_t = *mut Struct_memory_object_behave_info; pub type memory_object_behave_info_data_t = Struct_memory_object_behave_info; pub type memory_object_perf_info_t = *mut Struct_memory_object_perf_info; pub type memory_object_perf_info_data_t = Struct_memory_object_perf_info; pub type memory_object_attr_info_t = *mut Struct_memory_object_attr_info; pub type memory_object_attr_info_data_t = Struct_memory_object_attr_info; #[repr(C)] #[derive(Copy)] pub struct Struct_x86_state_hdr { pub flavor: ::std::os::raw::c_int, pub count: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_x86_state_hdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_state_hdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type x86_state_hdr_t = Struct_x86_state_hdr; pub type i386_thread_state_t = Struct___darwin_i386_thread_state; pub type x86_thread_state32_t = Struct___darwin_i386_thread_state; pub type i386_float_state_t = Struct___darwin_i386_float_state; pub type x86_float_state32_t = Struct___darwin_i386_float_state; pub type x86_avx_state32_t = Struct___darwin_i386_avx_state; pub type i386_exception_state_t = Struct___darwin_i386_exception_state; pub type x86_exception_state32_t = Struct___darwin_i386_exception_state; pub type x86_debug_state32_t = Struct___darwin_x86_debug_state32; pub type x86_thread_state64_t = Struct___darwin_x86_thread_state64; pub type x86_float_state64_t = Struct___darwin_x86_float_state64; pub type x86_avx_state64_t = Struct___darwin_x86_avx_state64; pub type x86_exception_state64_t = Struct___darwin_x86_exception_state64; pub type x86_debug_state64_t = Struct___darwin_x86_debug_state64; #[repr(C)] #[derive(Copy)] pub struct Struct_x86_thread_state { pub tsh: x86_state_hdr_t, pub uts: Union_Unnamed49, } impl ::std::clone::Clone for Struct_x86_thread_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_thread_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed49 { pub _bindgen_data_: [u64; 21usize], } impl Union_Unnamed49 { pub unsafe fn ts32(&mut self) -> *mut x86_thread_state32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ts64(&mut self) -> *mut x86_thread_state64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed49 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed49 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_x86_float_state { pub fsh: x86_state_hdr_t, pub ufs: Union_Unnamed50, } impl ::std::clone::Clone for Struct_x86_float_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_float_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed50 { pub _bindgen_data_: [u32; 131usize], } impl Union_Unnamed50 { pub unsafe fn fs32(&mut self) -> *mut x86_float_state32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn fs64(&mut self) -> *mut x86_float_state64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed50 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed50 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_x86_exception_state { pub esh: x86_state_hdr_t, pub ues: Union_Unnamed51, } impl ::std::clone::Clone for Struct_x86_exception_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_exception_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed51 { pub _bindgen_data_: [u64; 2usize], } impl Union_Unnamed51 { pub unsafe fn es32(&mut self) -> *mut x86_exception_state32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn es64(&mut self) -> *mut x86_exception_state64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed51 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed51 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_x86_debug_state { pub dsh: x86_state_hdr_t, pub uds: Union_Unnamed52, } impl ::std::clone::Clone for Struct_x86_debug_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_debug_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed52 { pub _bindgen_data_: [u64; 8usize], } impl Union_Unnamed52 { pub unsafe fn ds32(&mut self) -> *mut x86_debug_state32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ds64(&mut self) -> *mut x86_debug_state64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed52 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed52 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_x86_avx_state { pub ash: x86_state_hdr_t, pub ufs: Union_Unnamed53, } impl ::std::clone::Clone for Struct_x86_avx_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_x86_avx_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed53 { pub _bindgen_data_: [u32; 211usize], } impl Union_Unnamed53 { pub unsafe fn as32(&mut self) -> *mut x86_avx_state32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn as64(&mut self) -> *mut x86_avx_state64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed53 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed53 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type x86_thread_state_t = Struct_x86_thread_state; pub type x86_float_state_t = Struct_x86_float_state; pub type x86_exception_state_t = Struct_x86_exception_state; pub type x86_debug_state_t = Struct_x86_debug_state; pub type x86_avx_state_t = Struct_x86_avx_state; pub type thread_state_t = *mut natural_t; pub type thread_state_data_t = [natural_t; 224usize]; pub type thread_state_flavor_t = ::std::os::raw::c_int; pub type thread_state_flavor_array_t = *mut thread_state_flavor_t; pub type exception_type_t = ::std::os::raw::c_int; pub type exception_data_type_t = integer_t; pub type mach_exception_data_type_t = int64_t; pub type exception_behavior_t = ::std::os::raw::c_int; pub type exception_data_t = *mut exception_data_type_t; pub type mach_exception_data_t = *mut mach_exception_data_type_t; pub type exception_mask_t = ::std::os::raw::c_uint; pub type exception_mask_array_t = *mut exception_mask_t; pub type exception_behavior_array_t = *mut exception_behavior_t; pub type exception_flavor_array_t = *mut thread_state_flavor_t; pub type exception_port_array_t = *mut mach_port_t; pub type mach_exception_code_t = mach_exception_data_type_t; pub type mach_exception_subcode_t = mach_exception_data_type_t; pub type mach_voucher_t = mach_port_t; pub type mach_voucher_name_t = mach_port_name_t; pub type mach_voucher_name_array_t = *mut mach_voucher_name_t; pub type ipc_voucher_t = mach_voucher_t; pub type mach_voucher_selector_t = uint32_t; pub type mach_voucher_attr_key_t = uint32_t; pub type mach_voucher_attr_key_array_t = *mut mach_voucher_attr_key_t; pub type mach_voucher_attr_content_t = *mut uint8_t; pub type mach_voucher_attr_content_size_t = uint32_t; pub type mach_voucher_attr_command_t = uint32_t; pub type mach_voucher_attr_recipe_command_t = uint32_t; pub type mach_voucher_attr_recipe_command_array_t = *mut mach_voucher_attr_recipe_command_t; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_voucher_attr_recipe_data { pub key: mach_voucher_attr_key_t, pub command: mach_voucher_attr_recipe_command_t, pub previous_voucher: mach_voucher_name_t, pub content_size: mach_voucher_attr_content_size_t, pub content: *mut uint8_t, } impl ::std::clone::Clone for Struct_mach_voucher_attr_recipe_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_voucher_attr_recipe_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_voucher_attr_recipe_data_t = Struct_mach_voucher_attr_recipe_data; pub type mach_voucher_attr_recipe_t = *mut mach_voucher_attr_recipe_data_t; pub type mach_voucher_attr_recipe_size_t = mach_msg_type_number_t; pub type mach_voucher_attr_raw_recipe_t = *mut uint8_t; pub type mach_voucher_attr_raw_recipe_array_t = mach_voucher_attr_raw_recipe_t; pub type mach_voucher_attr_raw_recipe_size_t = mach_msg_type_number_t; pub type mach_voucher_attr_raw_recipe_array_size_t = mach_msg_type_number_t; pub type mach_voucher_attr_manager_t = mach_port_t; pub type mach_voucher_attr_control_t = mach_port_t; pub type ipc_voucher_attr_manager_t = mach_port_t; pub type ipc_voucher_attr_control_t = mach_port_t; pub type mach_voucher_attr_value_handle_t = uint64_t; pub type mach_voucher_attr_value_handle_array_t = *mut mach_voucher_attr_value_handle_t; pub type mach_voucher_attr_value_handle_array_size_t = mach_msg_type_number_t; pub type mach_voucher_attr_value_reference_t = uint32_t; pub type mach_voucher_attr_value_flags_t = uint32_t; pub type mach_voucher_attr_control_flags_t = uint32_t; pub type mach_voucher_attr_importance_refs = uint32_t; pub type processor_info_t = *mut integer_t; pub type processor_info_array_t = *mut integer_t; pub type processor_info_data_t = [integer_t; 1024usize]; pub type processor_set_info_t = *mut integer_t; pub type processor_set_info_data_t = [integer_t; 1024usize]; pub type processor_flavor_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_processor_basic_info { pub cpu_type: cpu_type_t, pub cpu_subtype: cpu_subtype_t, pub running: boolean_t, pub slot_num: ::std::os::raw::c_int, pub is_master: boolean_t, } impl ::std::clone::Clone for Struct_processor_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_processor_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type processor_basic_info_data_t = Struct_processor_basic_info; pub type processor_basic_info_t = *mut Struct_processor_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_processor_cpu_load_info { pub cpu_ticks: [::std::os::raw::c_uint; 4usize], } impl ::std::clone::Clone for Struct_processor_cpu_load_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_processor_cpu_load_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type processor_cpu_load_info_data_t = Struct_processor_cpu_load_info; pub type processor_cpu_load_info_t = *mut Struct_processor_cpu_load_info; pub type processor_set_flavor_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_processor_set_basic_info { pub processor_count: ::std::os::raw::c_int, pub default_policy: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_processor_set_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_processor_set_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type processor_set_basic_info_data_t = Struct_processor_set_basic_info; pub type processor_set_basic_info_t = *mut Struct_processor_set_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_processor_set_load_info { pub task_count: ::std::os::raw::c_int, pub thread_count: ::std::os::raw::c_int, pub load_average: integer_t, pub mach_factor: integer_t, } impl ::std::clone::Clone for Struct_processor_set_load_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_processor_set_load_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type processor_set_load_info_data_t = Struct_processor_set_load_info; pub type processor_set_load_info_t = *mut Struct_processor_set_load_info; pub type policy_t = ::std::os::raw::c_int; pub type policy_info_t = *mut integer_t; pub type policy_base_t = *mut integer_t; pub type policy_limit_t = *mut integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_policy_timeshare_base { pub base_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_timeshare_base { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_timeshare_base { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_timeshare_limit { pub max_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_timeshare_limit { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_timeshare_limit { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_timeshare_info { pub max_priority: integer_t, pub base_priority: integer_t, pub cur_priority: integer_t, pub depressed: boolean_t, pub depress_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_timeshare_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_timeshare_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type policy_timeshare_base_t = *mut Struct_policy_timeshare_base; pub type policy_timeshare_limit_t = *mut Struct_policy_timeshare_limit; pub type policy_timeshare_info_t = *mut Struct_policy_timeshare_info; pub type policy_timeshare_base_data_t = Struct_policy_timeshare_base; pub type policy_timeshare_limit_data_t = Struct_policy_timeshare_limit; pub type policy_timeshare_info_data_t = Struct_policy_timeshare_info; #[repr(C)] #[derive(Copy)] pub struct Struct_policy_rr_base { pub base_priority: integer_t, pub quantum: integer_t, } impl ::std::clone::Clone for Struct_policy_rr_base { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_rr_base { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_rr_limit { pub max_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_rr_limit { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_rr_limit { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_rr_info { pub max_priority: integer_t, pub base_priority: integer_t, pub quantum: integer_t, pub depressed: boolean_t, pub depress_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_rr_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_rr_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type policy_rr_base_t = *mut Struct_policy_rr_base; pub type policy_rr_limit_t = *mut Struct_policy_rr_limit; pub type policy_rr_info_t = *mut Struct_policy_rr_info; pub type policy_rr_base_data_t = Struct_policy_rr_base; pub type policy_rr_limit_data_t = Struct_policy_rr_limit; pub type policy_rr_info_data_t = Struct_policy_rr_info; #[repr(C)] #[derive(Copy)] pub struct Struct_policy_fifo_base { pub base_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_fifo_base { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_fifo_base { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_fifo_limit { pub max_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_fifo_limit { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_fifo_limit { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_fifo_info { pub max_priority: integer_t, pub base_priority: integer_t, pub depressed: boolean_t, pub depress_priority: integer_t, } impl ::std::clone::Clone for Struct_policy_fifo_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_fifo_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type policy_fifo_base_t = *mut Struct_policy_fifo_base; pub type policy_fifo_limit_t = *mut Struct_policy_fifo_limit; pub type policy_fifo_info_t = *mut Struct_policy_fifo_info; pub type policy_fifo_base_data_t = Struct_policy_fifo_base; pub type policy_fifo_limit_data_t = Struct_policy_fifo_limit; pub type policy_fifo_info_data_t = Struct_policy_fifo_info; #[repr(C)] #[derive(Copy)] pub struct Struct_policy_bases { pub ts: policy_timeshare_base_data_t, pub rr: policy_rr_base_data_t, pub fifo: policy_fifo_base_data_t, } impl ::std::clone::Clone for Struct_policy_bases { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_bases { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_limits { pub ts: policy_timeshare_limit_data_t, pub rr: policy_rr_limit_data_t, pub fifo: policy_fifo_limit_data_t, } impl ::std::clone::Clone for Struct_policy_limits { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_limits { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_policy_infos { pub ts: policy_timeshare_info_data_t, pub rr: policy_rr_info_data_t, pub fifo: policy_fifo_info_data_t, } impl ::std::clone::Clone for Struct_policy_infos { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_policy_infos { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type policy_base_data_t = Struct_policy_bases; pub type policy_limit_data_t = Struct_policy_limits; pub type policy_info_data_t = Struct_policy_infos; pub type task_flavor_t = natural_t; pub type task_info_t = *mut integer_t; pub type task_info_data_t = [integer_t; 1024usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_task_basic_info_32 { pub suspend_count: integer_t, pub virtual_size: natural_t, pub resident_size: natural_t, pub user_time: time_value_t, pub system_time: time_value_t, pub policy: policy_t, } impl ::std::clone::Clone for Struct_task_basic_info_32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_basic_info_32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_basic_info_32_data_t = Struct_task_basic_info_32; pub type task_basic_info_32_t = *mut Struct_task_basic_info_32; #[repr(C)] #[derive(Copy)] pub struct Struct_task_basic_info_64 { pub suspend_count: integer_t, pub virtual_size: mach_vm_size_t, pub resident_size: mach_vm_size_t, pub user_time: time_value_t, pub system_time: time_value_t, pub policy: policy_t, } impl ::std::clone::Clone for Struct_task_basic_info_64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_basic_info_64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_basic_info_64_data_t = Struct_task_basic_info_64; pub type task_basic_info_64_t = *mut Struct_task_basic_info_64; #[repr(C)] #[derive(Copy)] pub struct Struct_task_basic_info { pub suspend_count: integer_t, pub virtual_size: vm_size_t, pub resident_size: vm_size_t, pub user_time: time_value_t, pub system_time: time_value_t, pub policy: policy_t, } impl ::std::clone::Clone for Struct_task_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_basic_info_data_t = Struct_task_basic_info; pub type task_basic_info_t = *mut Struct_task_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_events_info { pub faults: integer_t, pub pageins: integer_t, pub cow_faults: integer_t, pub messages_sent: integer_t, pub messages_received: integer_t, pub syscalls_mach: integer_t, pub syscalls_unix: integer_t, pub csw: integer_t, } impl ::std::clone::Clone for Struct_task_events_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_events_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_events_info_data_t = Struct_task_events_info; pub type task_events_info_t = *mut Struct_task_events_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_thread_times_info { pub user_time: time_value_t, pub system_time: time_value_t, } impl ::std::clone::Clone for Struct_task_thread_times_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_thread_times_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_thread_times_info_data_t = Struct_task_thread_times_info; pub type task_thread_times_info_t = *mut Struct_task_thread_times_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_absolutetime_info { pub total_user: uint64_t, pub total_system: uint64_t, pub threads_user: uint64_t, pub threads_system: uint64_t, } impl ::std::clone::Clone for Struct_task_absolutetime_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_absolutetime_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_absolutetime_info_data_t = Struct_task_absolutetime_info; pub type task_absolutetime_info_t = *mut Struct_task_absolutetime_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_kernelmemory_info { pub total_palloc: uint64_t, pub total_pfree: uint64_t, pub total_salloc: uint64_t, pub total_sfree: uint64_t, } impl ::std::clone::Clone for Struct_task_kernelmemory_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_kernelmemory_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_kernelmemory_info_data_t = Struct_task_kernelmemory_info; pub type task_kernelmemory_info_t = *mut Struct_task_kernelmemory_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_affinity_tag_info { pub set_count: integer_t, pub min: integer_t, pub max: integer_t, pub task_count: integer_t, } impl ::std::clone::Clone for Struct_task_affinity_tag_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_affinity_tag_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_affinity_tag_info_data_t = Struct_task_affinity_tag_info; pub type task_affinity_tag_info_t = *mut Struct_task_affinity_tag_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_dyld_info { pub all_image_info_addr: mach_vm_address_t, pub all_image_info_size: mach_vm_size_t, pub all_image_info_format: integer_t, } impl ::std::clone::Clone for Struct_task_dyld_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_dyld_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_dyld_info_data_t = Struct_task_dyld_info; pub type task_dyld_info_t = *mut Struct_task_dyld_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_extmod_info { pub task_uuid: [::std::os::raw::c_uchar; 16usize], pub extmod_statistics: vm_extmod_statistics_data_t, } impl ::std::clone::Clone for Struct_task_extmod_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_extmod_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_extmod_info_data_t = Struct_task_extmod_info; pub type task_extmod_info_t = *mut Struct_task_extmod_info; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_task_basic_info { pub virtual_size: mach_vm_size_t, pub resident_size: mach_vm_size_t, pub resident_size_max: mach_vm_size_t, pub user_time: time_value_t, pub system_time: time_value_t, pub policy: policy_t, pub suspend_count: integer_t, } impl ::std::clone::Clone for Struct_mach_task_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_task_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_task_basic_info_data_t = Struct_mach_task_basic_info; pub type mach_task_basic_info_t = *mut Struct_mach_task_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_power_info { pub total_user: uint64_t, pub total_system: uint64_t, pub task_interrupt_wakeups: uint64_t, pub task_platform_idle_wakeups: uint64_t, pub task_timer_wakeups_bin_1: uint64_t, pub task_timer_wakeups_bin_2: uint64_t, } impl ::std::clone::Clone for Struct_task_power_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_power_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_power_info_data_t = Struct_task_power_info; pub type task_power_info_t = *mut Struct_task_power_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_vm_info { pub virtual_size: mach_vm_size_t, pub region_count: integer_t, pub page_size: integer_t, pub resident_size: mach_vm_size_t, pub resident_size_peak: mach_vm_size_t, pub device: mach_vm_size_t, pub device_peak: mach_vm_size_t, pub internal: mach_vm_size_t, pub internal_peak: mach_vm_size_t, pub external: mach_vm_size_t, pub external_peak: mach_vm_size_t, pub reusable: mach_vm_size_t, pub reusable_peak: mach_vm_size_t, pub purgeable_volatile_pmap: mach_vm_size_t, pub purgeable_volatile_resident: mach_vm_size_t, pub purgeable_volatile_virtual: mach_vm_size_t, pub compressed: mach_vm_size_t, pub compressed_peak: mach_vm_size_t, pub compressed_lifetime: mach_vm_size_t, pub phys_footprint: mach_vm_size_t, } impl ::std::clone::Clone for Struct_task_vm_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_vm_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_vm_info_data_t = Struct_task_vm_info; pub type task_vm_info_t = *mut Struct_task_vm_info; pub type task_purgable_info_t = Struct_vm_purgeable_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_trace_memory_info { pub user_memory_address: uint64_t, pub buffer_size: uint64_t, pub mailbox_array_size: uint64_t, } impl ::std::clone::Clone for Struct_task_trace_memory_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_trace_memory_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_trace_memory_info_data_t = Struct_task_trace_memory_info; pub type task_trace_memory_info_t = *mut Struct_task_trace_memory_info; #[repr(C)] #[derive(Copy)] pub struct Struct_task_wait_state_info { pub total_wait_state_time: uint64_t, pub total_wait_sfi_state_time: uint64_t, pub _reserved: [uint32_t; 4usize], } impl ::std::clone::Clone for Struct_task_wait_state_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_wait_state_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_wait_state_info_data_t = Struct_task_wait_state_info; pub type task_wait_state_info_t = *mut Struct_task_wait_state_info; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed54 { pub task_gpu_utilisation: uint64_t, pub task_gpu_stat_reserved0: uint64_t, pub task_gpu_stat_reserved1: uint64_t, pub task_gpu_stat_reserved2: uint64_t, } impl ::std::clone::Clone for Struct_Unnamed54 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed54 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type gpu_energy_data = Struct_Unnamed54; pub type gpu_energy_data_t = *mut gpu_energy_data; #[repr(C)] #[derive(Copy)] pub struct Struct_task_power_info_v2 { pub cpu_energy: task_power_info_data_t, pub gpu_energy: gpu_energy_data, } impl ::std::clone::Clone for Struct_task_power_info_v2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_power_info_v2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_power_info_v2_data_t = Struct_task_power_info_v2; pub type task_power_info_v2_t = *mut Struct_task_power_info_v2; #[repr(C)] #[derive(Copy)] pub struct Struct_task_flags_info { pub flags: uint32_t, } impl ::std::clone::Clone for Struct_task_flags_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_flags_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_flags_info_data_t = Struct_task_flags_info; pub type task_flags_info_t = *mut Struct_task_flags_info; pub type task_policy_flavor_t = natural_t; pub type task_policy_t = *mut integer_t; #[derive(Clone, Copy)] #[repr(i32)] pub enum Enum_task_role { TASK_RENICED = -1, TASK_UNSPECIFIED = 0, TASK_FOREGROUND_APPLICATION = 1, TASK_BACKGROUND_APPLICATION = 2, TASK_CONTROL_APPLICATION = 3, TASK_GRAPHICS_SERVER = 4, TASK_THROTTLE_APPLICATION = 5, TASK_NONUI_APPLICATION = 6, TASK_DEFAULT_APPLICATION = 7, } pub type task_role_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_task_category_policy { pub role: task_role_t, } impl ::std::clone::Clone for Struct_task_category_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_category_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_category_policy_data_t = Struct_task_category_policy; pub type task_category_policy_t = *mut Struct_task_category_policy; #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_task_latency_qos { LATENCY_QOS_TIER_UNSPECIFIED = 0, LATENCY_QOS_TIER_0 = 16711681, LATENCY_QOS_TIER_1 = 16711682, LATENCY_QOS_TIER_2 = 16711683, LATENCY_QOS_TIER_3 = 16711684, LATENCY_QOS_TIER_4 = 16711685, LATENCY_QOS_TIER_5 = 16711686, } pub type task_latency_qos_t = integer_t; #[derive(Clone, Copy)] #[repr(u32)] pub enum Enum_task_throughput_qos { THROUGHPUT_QOS_TIER_UNSPECIFIED = 0, THROUGHPUT_QOS_TIER_0 = 16646145, THROUGHPUT_QOS_TIER_1 = 16646146, THROUGHPUT_QOS_TIER_2 = 16646147, THROUGHPUT_QOS_TIER_3 = 16646148, THROUGHPUT_QOS_TIER_4 = 16646149, THROUGHPUT_QOS_TIER_5 = 16646150, } pub type task_throughput_qos_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_task_qos_policy { pub task_latency_qos_tier: task_latency_qos_t, pub task_throughput_qos_tier: task_throughput_qos_t, } impl ::std::clone::Clone for Struct_task_qos_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_qos_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_qos_policy_t = *mut Struct_task_qos_policy; pub type task_special_port_t = ::std::os::raw::c_int; pub type thread_flavor_t = natural_t; pub type thread_info_t = *mut integer_t; pub type thread_info_data_t = [integer_t; 32usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_basic_info { pub user_time: time_value_t, pub system_time: time_value_t, pub cpu_usage: integer_t, pub policy: policy_t, pub run_state: integer_t, pub flags: integer_t, pub suspend_count: integer_t, pub sleep_time: integer_t, } impl ::std::clone::Clone for Struct_thread_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_basic_info_data_t = Struct_thread_basic_info; pub type thread_basic_info_t = *mut Struct_thread_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_identifier_info { pub thread_id: uint64_t, pub thread_handle: uint64_t, pub dispatch_qaddr: uint64_t, } impl ::std::clone::Clone for Struct_thread_identifier_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_identifier_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_identifier_info_data_t = Struct_thread_identifier_info; pub type thread_identifier_info_t = *mut Struct_thread_identifier_info; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_extended_info { pub pth_user_time: uint64_t, pub pth_system_time: uint64_t, pub pth_cpu_usage: int32_t, pub pth_policy: int32_t, pub pth_run_state: int32_t, pub pth_flags: int32_t, pub pth_sleep_time: int32_t, pub pth_curpri: int32_t, pub pth_priority: int32_t, pub pth_maxpriority: int32_t, pub pth_name: [::std::os::raw::c_char; 64usize], } impl ::std::clone::Clone for Struct_thread_extended_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_extended_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_extended_info_data_t = Struct_thread_extended_info; pub type thread_extended_info_t = *mut Struct_thread_extended_info; #[repr(C)] #[derive(Copy)] pub struct Struct_io_stat_entry { pub count: uint64_t, pub size: uint64_t, } impl ::std::clone::Clone for Struct_io_stat_entry { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_io_stat_entry { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_io_stat_info { pub disk_reads: Struct_io_stat_entry, pub io_priority: [Struct_io_stat_entry; 4usize], pub paging: Struct_io_stat_entry, pub metadata: Struct_io_stat_entry, pub total_io: Struct_io_stat_entry, } impl ::std::clone::Clone for Struct_io_stat_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_io_stat_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type io_stat_info_t = *mut Struct_io_stat_info; pub type thread_policy_flavor_t = natural_t; pub type thread_policy_t = *mut integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_standard_policy { pub no_data: natural_t, } impl ::std::clone::Clone for Struct_thread_standard_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_standard_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_standard_policy_data_t = Struct_thread_standard_policy; pub type thread_standard_policy_t = *mut Struct_thread_standard_policy; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_extended_policy { pub timeshare: boolean_t, } impl ::std::clone::Clone for Struct_thread_extended_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_extended_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_extended_policy_data_t = Struct_thread_extended_policy; pub type thread_extended_policy_t = *mut Struct_thread_extended_policy; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_time_constraint_policy { pub period: uint32_t, pub computation: uint32_t, pub constraint: uint32_t, pub preemptible: boolean_t, } impl ::std::clone::Clone for Struct_thread_time_constraint_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_time_constraint_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_time_constraint_policy_data_t = Struct_thread_time_constraint_policy; pub type thread_time_constraint_policy_t = *mut Struct_thread_time_constraint_policy; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_precedence_policy { pub importance: integer_t, } impl ::std::clone::Clone for Struct_thread_precedence_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_precedence_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_precedence_policy_data_t = Struct_thread_precedence_policy; pub type thread_precedence_policy_t = *mut Struct_thread_precedence_policy; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_affinity_policy { pub affinity_tag: integer_t, } impl ::std::clone::Clone for Struct_thread_affinity_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_affinity_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_affinity_policy_data_t = Struct_thread_affinity_policy; pub type thread_affinity_policy_t = *mut Struct_thread_affinity_policy; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_background_policy { pub priority: integer_t, } impl ::std::clone::Clone for Struct_thread_background_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_background_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_background_policy_data_t = Struct_thread_background_policy; pub type thread_background_policy_t = *mut Struct_thread_background_policy; pub type thread_latency_qos_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_latency_qos_policy { pub thread_latency_qos_tier: thread_latency_qos_t, } impl ::std::clone::Clone for Struct_thread_latency_qos_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_latency_qos_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_latency_qos_policy_data_t = Struct_thread_latency_qos_policy; pub type thread_latency_qos_policy_t = *mut Struct_thread_latency_qos_policy; pub type thread_throughput_qos_t = integer_t; #[repr(C)] #[derive(Copy)] pub struct Struct_thread_throughput_qos_policy { pub thread_throughput_qos_tier: thread_throughput_qos_t, } impl ::std::clone::Clone for Struct_thread_throughput_qos_policy { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_thread_throughput_qos_policy { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type thread_throughput_qos_policy_data_t = Struct_thread_throughput_qos_policy; pub type thread_throughput_qos_policy_t = *mut Struct_thread_throughput_qos_policy; pub type alarm_type_t = ::std::os::raw::c_int; pub type sleep_type_t = ::std::os::raw::c_int; pub type clock_id_t = ::std::os::raw::c_int; pub type clock_flavor_t = ::std::os::raw::c_int; pub type clock_attr_t = *mut ::std::os::raw::c_int; pub type clock_res_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_timespec { pub tv_sec: ::std::os::raw::c_uint, pub tv_nsec: clock_res_t, } impl ::std::clone::Clone for Struct_mach_timespec { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_timespec { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_timespec_t = Struct_mach_timespec; pub type vm_machine_attribute_t = ::std::os::raw::c_uint; pub type vm_machine_attribute_val_t = ::std::os::raw::c_int; pub type vm_inherit_t = ::std::os::raw::c_uint; pub type vm_purgable_t = ::std::os::raw::c_int; pub type vm_behavior_t = ::std::os::raw::c_int; pub type vm32_object_id_t = uint32_t; pub type vm_region_info_t = *mut ::std::os::raw::c_int; pub type vm_region_info_64_t = *mut ::std::os::raw::c_int; pub type vm_region_recurse_info_t = *mut ::std::os::raw::c_int; pub type vm_region_recurse_info_64_t = *mut ::std::os::raw::c_int; pub type vm_region_flavor_t = ::std::os::raw::c_int; pub type vm_region_info_data_t = [::std::os::raw::c_int; 1024usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_basic_info_64 { pub protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, pub shared: boolean_t, pub reserved: boolean_t, pub offset: memory_object_offset_t, pub behavior: vm_behavior_t, pub user_wired_count: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_vm_region_basic_info_64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_basic_info_64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_basic_info_64_t = *mut Struct_vm_region_basic_info_64; pub type vm_region_basic_info_data_64_t = Struct_vm_region_basic_info_64; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_basic_info { pub protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, pub shared: boolean_t, pub reserved: boolean_t, pub offset: uint32_t, pub behavior: vm_behavior_t, pub user_wired_count: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_vm_region_basic_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_basic_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_basic_info_t = *mut Struct_vm_region_basic_info; pub type vm_region_basic_info_data_t = Struct_vm_region_basic_info; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_extended_info { pub protection: vm_prot_t, pub user_tag: ::std::os::raw::c_uint, pub pages_resident: ::std::os::raw::c_uint, pub pages_shared_now_private: ::std::os::raw::c_uint, pub pages_swapped_out: ::std::os::raw::c_uint, pub pages_dirtied: ::std::os::raw::c_uint, pub ref_count: ::std::os::raw::c_uint, pub shadow_depth: ::std::os::raw::c_ushort, pub external_pager: ::std::os::raw::c_uchar, pub share_mode: ::std::os::raw::c_uchar, pub pages_reusable: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_vm_region_extended_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_extended_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_extended_info_t = *mut Struct_vm_region_extended_info; pub type vm_region_extended_info_data_t = Struct_vm_region_extended_info; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_top_info { pub obj_id: ::std::os::raw::c_uint, pub ref_count: ::std::os::raw::c_uint, pub private_pages_resident: ::std::os::raw::c_uint, pub shared_pages_resident: ::std::os::raw::c_uint, pub share_mode: ::std::os::raw::c_uchar, } impl ::std::clone::Clone for Struct_vm_region_top_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_top_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_top_info_t = *mut Struct_vm_region_top_info; pub type vm_region_top_info_data_t = Struct_vm_region_top_info; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_submap_info { pub protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, pub offset: uint32_t, pub user_tag: ::std::os::raw::c_uint, pub pages_resident: ::std::os::raw::c_uint, pub pages_shared_now_private: ::std::os::raw::c_uint, pub pages_swapped_out: ::std::os::raw::c_uint, pub pages_dirtied: ::std::os::raw::c_uint, pub ref_count: ::std::os::raw::c_uint, pub shadow_depth: ::std::os::raw::c_ushort, pub external_pager: ::std::os::raw::c_uchar, pub share_mode: ::std::os::raw::c_uchar, pub is_submap: boolean_t, pub behavior: vm_behavior_t, pub object_id: vm32_object_id_t, pub user_wired_count: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_vm_region_submap_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_submap_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_submap_info_t = *mut Struct_vm_region_submap_info; pub type vm_region_submap_info_data_t = Struct_vm_region_submap_info; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_submap_info_64 { pub protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, pub offset: memory_object_offset_t, pub user_tag: ::std::os::raw::c_uint, pub pages_resident: ::std::os::raw::c_uint, pub pages_shared_now_private: ::std::os::raw::c_uint, pub pages_swapped_out: ::std::os::raw::c_uint, pub pages_dirtied: ::std::os::raw::c_uint, pub ref_count: ::std::os::raw::c_uint, pub shadow_depth: ::std::os::raw::c_ushort, pub external_pager: ::std::os::raw::c_uchar, pub share_mode: ::std::os::raw::c_uchar, pub is_submap: boolean_t, pub behavior: vm_behavior_t, pub object_id: vm32_object_id_t, pub user_wired_count: ::std::os::raw::c_ushort, pub pages_reusable: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_vm_region_submap_info_64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_submap_info_64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_submap_info_64_t = *mut Struct_vm_region_submap_info_64; pub type vm_region_submap_info_data_64_t = Struct_vm_region_submap_info_64; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_region_submap_short_info_64 { pub protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, pub offset: memory_object_offset_t, pub user_tag: ::std::os::raw::c_uint, pub ref_count: ::std::os::raw::c_uint, pub shadow_depth: ::std::os::raw::c_ushort, pub external_pager: ::std::os::raw::c_uchar, pub share_mode: ::std::os::raw::c_uchar, pub is_submap: boolean_t, pub behavior: vm_behavior_t, pub object_id: vm32_object_id_t, pub user_wired_count: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_vm_region_submap_short_info_64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_region_submap_short_info_64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_region_submap_short_info_64_t = *mut Struct_vm_region_submap_short_info_64; pub type vm_region_submap_short_info_data_64_t = Struct_vm_region_submap_short_info_64; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_vm_read_entry { pub address: mach_vm_address_t, pub size: mach_vm_size_t, } impl ::std::clone::Clone for Struct_mach_vm_read_entry { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_vm_read_entry { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_vm_read_entry { pub address: vm_address_t, pub size: vm_size_t, } impl ::std::clone::Clone for Struct_vm_read_entry { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_read_entry { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_vm_read_entry_t = [Struct_mach_vm_read_entry; 256usize]; pub type vm_read_entry_t = [Struct_vm_read_entry; 256usize]; pub type vm_page_info_t = *mut ::std::os::raw::c_int; pub type vm_page_info_data_t = *mut ::std::os::raw::c_int; pub type vm_page_info_flavor_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_page_info_basic { pub disposition: ::std::os::raw::c_int, pub ref_count: ::std::os::raw::c_int, pub object_id: vm_object_id_t, pub offset: memory_object_offset_t, pub depth: ::std::os::raw::c_int, pub __pad: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_vm_page_info_basic { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_page_info_basic { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_page_info_basic_t = *mut Struct_vm_page_info_basic; pub type vm_page_info_basic_data_t = Struct_vm_page_info_basic; pub type kmod_t = ::std::os::raw::c_int; pub type kmod_start_func_t = unsafe extern "C" fn(ki: *mut Struct_kmod_info, data: *mut ::std::os::raw::c_void) -> kern_return_t; pub type kmod_stop_func_t = unsafe extern "C" fn(ki: *mut Struct_kmod_info, data: *mut ::std::os::raw::c_void) -> kern_return_t; #[repr(C)] #[derive(Copy)] pub struct Struct_kmod_reference { pub next: *mut Struct_kmod_reference, pub info: *mut Struct_kmod_info, } impl ::std::clone::Clone for Struct_kmod_reference { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kmod_reference { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type kmod_reference_t = Struct_kmod_reference; #[repr(C)] #[derive(Copy)] pub struct Struct_kmod_info { pub next: *mut Struct_kmod_info, pub info_version: int32_t, pub id: uint32_t, pub name: [::std::os::raw::c_char; 64usize], pub version: [::std::os::raw::c_char; 64usize], pub reference_count: int32_t, pub reference_list: *mut kmod_reference_t, pub address: vm_address_t, pub size: vm_size_t, pub hdr_size: vm_size_t, pub start: *mut ::std::option::Option<extern "C" fn() -> kern_return_t>, pub stop: *mut ::std::option::Option<extern "C" fn() -> kern_return_t>, } impl ::std::clone::Clone for Struct_kmod_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kmod_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type kmod_info_t = Struct_kmod_info; #[repr(C)] #[derive(Copy)] pub struct Struct_kmod_info_32_v1 { pub next_addr: uint32_t, pub info_version: int32_t, pub id: uint32_t, pub name: [uint8_t; 64usize], pub version: [uint8_t; 64usize], pub reference_count: int32_t, pub reference_list_addr: uint32_t, pub address: uint32_t, pub size: uint32_t, pub hdr_size: uint32_t, pub start_addr: uint32_t, pub stop_addr: uint32_t, } impl ::std::clone::Clone for Struct_kmod_info_32_v1 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kmod_info_32_v1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type kmod_info_32_v1_t = Struct_kmod_info_32_v1; #[repr(C)] #[derive(Copy)] pub struct Struct_kmod_info_64_v1 { pub next_addr: uint64_t, pub info_version: int32_t, pub id: uint32_t, pub name: [uint8_t; 64usize], pub version: [uint8_t; 64usize], pub reference_count: int32_t, pub reference_list_addr: uint64_t, pub address: uint64_t, pub size: uint64_t, pub hdr_size: uint64_t, pub start_addr: uint64_t, pub stop_addr: uint64_t, } impl ::std::clone::Clone for Struct_kmod_info_64_v1 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kmod_info_64_v1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type kmod_info_64_v1_t = Struct_kmod_info_64_v1; pub type kmod_args_t = *mut ::std::os::raw::c_void; pub type kmod_control_flavor_t = ::std::os::raw::c_int; pub type kmod_info_array_t = *mut kmod_info_t; pub type task_t = mach_port_t; pub type task_name_t = mach_port_t; pub type task_suspension_token_t = mach_port_t; pub type thread_t = mach_port_t; pub type thread_act_t = mach_port_t; pub type ipc_space_t = mach_port_t; pub type coalition_t = mach_port_t; pub type host_t = mach_port_t; pub type host_priv_t = mach_port_t; pub type host_security_t = mach_port_t; pub type processor_t = mach_port_t; pub type processor_set_t = mach_port_t; pub type processor_set_control_t = mach_port_t; pub type semaphore_t = mach_port_t; pub type lock_set_t = mach_port_t; pub type ledger_t = mach_port_t; pub type alarm_t = mach_port_t; pub type clock_serv_t = mach_port_t; pub type clock_ctrl_t = mach_port_t; pub type processor_set_name_t = processor_set_t; pub type clock_reply_t = mach_port_t; pub type bootstrap_t = mach_port_t; pub type mem_entry_name_port_t = mach_port_t; pub type exception_handler_t = mach_port_t; pub type exception_handler_array_t = *mut exception_handler_t; pub type vm_task_entry_t = mach_port_t; pub type io_master_t = mach_port_t; pub type UNDServerRef = mach_port_t; pub type task_array_t = *mut task_t; pub type thread_array_t = *mut thread_t; pub type processor_set_array_t = *mut processor_set_t; pub type processor_set_name_array_t = *mut processor_set_t; pub type processor_array_t = *mut processor_t; pub type thread_act_array_t = *mut thread_act_t; pub type ledger_array_t = *mut ledger_t; pub type task_port_t = task_t; pub type task_port_array_t = task_array_t; pub type thread_port_t = thread_t; pub type thread_port_array_t = thread_array_t; pub type ipc_space_port_t = ipc_space_t; pub type host_name_t = host_t; pub type host_name_port_t = host_t; pub type processor_set_port_t = processor_set_t; pub type processor_set_name_port_t = processor_set_t; pub type processor_set_name_port_array_t = processor_set_array_t; pub type processor_set_control_port_t = processor_set_t; pub type processor_port_t = processor_t; pub type processor_port_array_t = processor_array_t; pub type thread_act_port_t = thread_act_t; pub type thread_act_port_array_t = thread_act_array_t; pub type semaphore_port_t = semaphore_t; pub type lock_set_port_t = lock_set_t; pub type ledger_port_t = ledger_t; pub type ledger_port_array_t = ledger_array_t; pub type alarm_port_t = alarm_t; pub type clock_serv_port_t = clock_serv_t; pub type clock_ctrl_port_t = clock_ctrl_t; pub type exception_port_t = exception_handler_t; pub type exception_port_arrary_t = exception_handler_array_t; pub type ledger_item_t = natural_t; pub type ledger_amount_t = int64_t; pub type emulation_vector_t = *mut mach_vm_offset_t; pub type user_subsystem_t = *mut ::std::os::raw::c_char; pub type labelstr_t = *mut ::std::os::raw::c_char; pub type mig_stub_routine_t = ::std::option::Option<unsafe extern "C" fn(InHeadP: *mut mach_msg_header_t, OutHeadP: *mut mach_msg_header_t)>; pub type mig_routine_t = mig_stub_routine_t; pub type mig_server_routine_t = ::std::option::Option<unsafe extern "C" fn(InHeadP: *mut mach_msg_header_t) -> mig_routine_t>; pub type mig_impl_routine_t = ::std::option::Option<extern "C" fn() -> kern_return_t>; pub type routine_arg_descriptor = mach_msg_type_descriptor_t; pub type routine_arg_descriptor_t = *mut mach_msg_type_descriptor_t; pub type mig_routine_arg_descriptor_t = *mut mach_msg_type_descriptor_t; #[repr(C)] #[derive(Copy)] pub struct Struct_routine_descriptor { pub impl_routine: mig_impl_routine_t, pub stub_routine: mig_stub_routine_t, pub argc: ::std::os::raw::c_uint, pub descr_count: ::std::os::raw::c_uint, pub arg_descr: routine_arg_descriptor_t, pub max_reply_msg: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_routine_descriptor { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_routine_descriptor { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type routine_descriptor_t = *mut Struct_routine_descriptor; pub type mig_routine_descriptor = Struct_routine_descriptor; pub type mig_routine_descriptor_t = *mut mig_routine_descriptor; #[repr(C)] #[derive(Copy)] pub struct Struct_mig_subsystem { pub server: mig_server_routine_t, pub start: mach_msg_id_t, pub end: mach_msg_id_t, pub maxsize: mach_msg_size_t, pub reserved: vm_address_t, pub routine: [mig_routine_descriptor; 1usize], } impl ::std::clone::Clone for Struct_mig_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mig_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mig_subsystem_t = *mut Struct_mig_subsystem; #[repr(C)] #[derive(Copy)] pub struct Struct_mig_symtab { pub ms_routine_name: *mut ::std::os::raw::c_char, pub ms_routine_number: ::std::os::raw::c_int, pub ms_routine: ::std::option::Option<extern "C" fn()>, } impl ::std::clone::Clone for Struct_mig_symtab { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mig_symtab { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mig_symtab_t = Struct_mig_symtab; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed55 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed55 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed55 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mig_reply_error_t = Struct_Unnamed55; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed56 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed56 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed56 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__clock_get_time_t = Struct_Unnamed56; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed57 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: clock_flavor_t, pub clock_attrCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed57 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed57 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__clock_get_attributes_t = Struct_Unnamed57; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed58 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub alarm_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub alarm_type: alarm_type_t, pub alarm_time: mach_timespec_t, } impl ::std::clone::Clone for Struct_Unnamed58 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed58 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__clock_alarm_t = Struct_Unnamed58; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__clock_subsystem { pub _bindgen_data_: [u32; 15usize], } impl Union___RequestUnion__clock_subsystem { pub unsafe fn Request_clock_get_time(&mut self) -> *mut __Request__clock_get_time_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_clock_get_attributes(&mut self) -> *mut __Request__clock_get_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_clock_alarm(&mut self) -> *mut __Request__clock_alarm_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__clock_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__clock_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed59 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub cur_time: mach_timespec_t, } impl ::std::clone::Clone for Struct_Unnamed59 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed59 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__clock_get_time_t = Struct_Unnamed59; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed60 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub clock_attrCnt: mach_msg_type_number_t, pub clock_attr: [::std::os::raw::c_int; 1usize], } impl ::std::clone::Clone for Struct_Unnamed60 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed60 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__clock_get_attributes_t = Struct_Unnamed60; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed61 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed61 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed61 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__clock_alarm_t = Struct_Unnamed61; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__clock_subsystem { pub _bindgen_data_: [u32; 11usize], } impl Union___ReplyUnion__clock_subsystem { pub unsafe fn Reply_clock_get_time(&mut self) -> *mut __Reply__clock_get_time_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_clock_get_attributes(&mut self) -> *mut __Reply__clock_get_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_clock_alarm(&mut self) -> *mut __Reply__clock_alarm_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__clock_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__clock_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed62 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub new_time: mach_timespec_t, } impl ::std::clone::Clone for Struct_Unnamed62 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed62 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__clock_set_time_t = Struct_Unnamed62; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed63 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: clock_flavor_t, pub clock_attrCnt: mach_msg_type_number_t, pub clock_attr: [::std::os::raw::c_int; 1usize], } impl ::std::clone::Clone for Struct_Unnamed63 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed63 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__clock_set_attributes_t = Struct_Unnamed63; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__clock_priv_subsystem { pub _bindgen_data_: [u32; 11usize], } impl Union___RequestUnion__clock_priv_subsystem { pub unsafe fn Request_clock_set_time(&mut self) -> *mut __Request__clock_set_time_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_clock_set_attributes(&mut self) -> *mut __Request__clock_set_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__clock_priv_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__clock_priv_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed64 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__clock_set_time_t = Struct_Unnamed64; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed65 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed65 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed65 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__clock_set_attributes_t = Struct_Unnamed65; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__clock_priv_subsystem { pub _bindgen_data_: [u32; 9usize], } impl Union___ReplyUnion__clock_priv_subsystem { pub unsafe fn Reply_clock_set_time(&mut self) -> *mut __Reply__clock_set_time_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_clock_set_attributes(&mut self) -> *mut __Reply__clock_set_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__clock_priv_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__clock_priv_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ipc_info_space { pub iis_genno_mask: natural_t, pub iis_table_size: natural_t, pub iis_table_next: natural_t, pub iis_tree_size: natural_t, pub iis_tree_small: natural_t, pub iis_tree_hash: natural_t, } impl ::std::clone::Clone for Struct_ipc_info_space { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ipc_info_space { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ipc_info_space_t = Struct_ipc_info_space; #[repr(C)] #[derive(Copy)] pub struct Struct_ipc_info_space_basic { pub iisb_genno_mask: natural_t, pub iisb_table_size: natural_t, pub iisb_table_next: natural_t, pub iisb_table_inuse: natural_t, pub iisb_reserved: [natural_t; 2usize], } impl ::std::clone::Clone for Struct_ipc_info_space_basic { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ipc_info_space_basic { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ipc_info_space_basic_t = Struct_ipc_info_space_basic; #[repr(C)] #[derive(Copy)] pub struct Struct_ipc_info_name { pub iin_name: mach_port_name_t, pub iin_collision: integer_t, pub iin_type: mach_port_type_t, pub iin_urefs: mach_port_urefs_t, pub iin_object: natural_t, pub iin_next: natural_t, pub iin_hash: natural_t, } impl ::std::clone::Clone for Struct_ipc_info_name { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ipc_info_name { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ipc_info_name_t = Struct_ipc_info_name; pub type ipc_info_name_array_t = *mut ipc_info_name_t; #[repr(C)] #[derive(Copy)] pub struct Struct_ipc_info_tree_name { pub iitn_name: ipc_info_name_t, pub iitn_lchild: mach_port_name_t, pub iitn_rchild: mach_port_name_t, } impl ::std::clone::Clone for Struct_ipc_info_tree_name { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ipc_info_tree_name { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type ipc_info_tree_name_t = Struct_ipc_info_tree_name; pub type ipc_info_tree_name_array_t = *mut ipc_info_tree_name_t; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_vm_info_region { pub vir_start: mach_vm_offset_t, pub vir_end: mach_vm_offset_t, pub vir_object: mach_vm_offset_t, pub vir_offset: memory_object_offset_t, pub vir_needs_copy: boolean_t, pub vir_protection: vm_prot_t, pub vir_max_protection: vm_prot_t, pub vir_inheritance: vm_inherit_t, pub vir_wired_count: natural_t, pub vir_user_wired_count: natural_t, } impl ::std::clone::Clone for Struct_mach_vm_info_region { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_vm_info_region { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_vm_info_region_t = Struct_mach_vm_info_region; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_info_region_64 { pub vir_start: natural_t, pub vir_end: natural_t, pub vir_object: natural_t, pub vir_offset: memory_object_offset_t, pub vir_needs_copy: boolean_t, pub vir_protection: vm_prot_t, pub vir_max_protection: vm_prot_t, pub vir_inheritance: vm_inherit_t, pub vir_wired_count: natural_t, pub vir_user_wired_count: natural_t, } impl ::std::clone::Clone for Struct_vm_info_region_64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_info_region_64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_info_region_64_t = Struct_vm_info_region_64; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_info_region { pub vir_start: natural_t, pub vir_end: natural_t, pub vir_object: natural_t, pub vir_offset: natural_t, pub vir_needs_copy: boolean_t, pub vir_protection: vm_prot_t, pub vir_max_protection: vm_prot_t, pub vir_inheritance: vm_inherit_t, pub vir_wired_count: natural_t, pub vir_user_wired_count: natural_t, } impl ::std::clone::Clone for Struct_vm_info_region { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_info_region { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_info_region_t = Struct_vm_info_region; #[repr(C)] #[derive(Copy)] pub struct Struct_vm_info_object { pub vio_object: natural_t, pub vio_size: natural_t, pub vio_ref_count: ::std::os::raw::c_uint, pub vio_resident_page_count: ::std::os::raw::c_uint, pub vio_absent_count: ::std::os::raw::c_uint, pub vio_copy: natural_t, pub vio_shadow: natural_t, pub vio_shadow_offset: natural_t, pub vio_paging_offset: natural_t, pub vio_copy_strategy: memory_object_copy_strategy_t, pub vio_last_alloc: vm_offset_t, pub vio_paging_in_progress: ::std::os::raw::c_uint, pub vio_pager_created: boolean_t, pub vio_pager_initialized: boolean_t, pub vio_pager_ready: boolean_t, pub vio_can_persist: boolean_t, pub vio_internal: boolean_t, pub vio_temporary: boolean_t, pub vio_alive: boolean_t, pub vio_purgable: boolean_t, pub vio_purgable_volatile: boolean_t, } impl ::std::clone::Clone for Struct_vm_info_object { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_vm_info_object { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type vm_info_object_t = Struct_vm_info_object; pub type vm_info_object_array_t = *mut vm_info_object_t; #[repr(C)] #[derive(Copy)] pub struct Struct_zone_name { pub zn_name: [::std::os::raw::c_char; 80usize], } impl ::std::clone::Clone for Struct_zone_name { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_zone_name { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type zone_name_t = Struct_zone_name; pub type zone_name_array_t = *mut zone_name_t; #[repr(C)] #[derive(Copy)] pub struct Struct_zone_info { pub zi_count: integer_t, pub zi_cur_size: vm_size_t, pub zi_max_size: vm_size_t, pub zi_elem_size: vm_size_t, pub zi_alloc_size: vm_size_t, pub zi_pageable: integer_t, pub zi_sleepable: integer_t, pub zi_exhaustible: integer_t, pub zi_collectable: integer_t, } impl ::std::clone::Clone for Struct_zone_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_zone_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type zone_info_t = Struct_zone_info; pub type zone_info_array_t = *mut zone_info_t; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_zone_name { pub mzn_name: [::std::os::raw::c_char; 80usize], } impl ::std::clone::Clone for Struct_mach_zone_name { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_zone_name { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_zone_name_t = Struct_mach_zone_name; pub type mach_zone_name_array_t = *mut mach_zone_name_t; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_zone_info_data { pub mzi_count: uint64_t, pub mzi_cur_size: uint64_t, pub mzi_max_size: uint64_t, pub mzi_elem_size: uint64_t, pub mzi_alloc_size: uint64_t, pub mzi_sum_size: uint64_t, pub mzi_exhaustible: uint64_t, pub mzi_collectable: uint64_t, } impl ::std::clone::Clone for Struct_mach_zone_info_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_zone_info_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_zone_info_t = Struct_mach_zone_info_data; pub type mach_zone_info_array_t = *mut mach_zone_info_t; #[repr(C)] #[derive(Copy)] pub struct Struct_task_zone_info_data { pub tzi_count: uint64_t, pub tzi_cur_size: uint64_t, pub tzi_max_size: uint64_t, pub tzi_elem_size: uint64_t, pub tzi_alloc_size: uint64_t, pub tzi_sum_size: uint64_t, pub tzi_exhaustible: uint64_t, pub tzi_collectable: uint64_t, pub tzi_caller_acct: uint64_t, pub tzi_task_alloc: uint64_t, pub tzi_task_free: uint64_t, } impl ::std::clone::Clone for Struct_task_zone_info_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_task_zone_info_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type task_zone_info_t = Struct_task_zone_info_data; pub type task_zone_info_array_t = *mut task_zone_info_t; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_memory_info { pub flags: uint64_t, pub site: uint64_t, pub size: uint64_t, pub free: uint64_t, pub largest: uint64_t, pub _resv: [uint64_t; 3usize], } impl ::std::clone::Clone for Struct_mach_memory_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_memory_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type mach_memory_info_t = Struct_mach_memory_info; pub type mach_memory_info_array_t = *mut mach_memory_info_t; pub type page_address_array_t = *mut vm_offset_t; #[repr(C)] #[derive(Copy)] pub struct Struct_hash_info_bucket { pub hib_count: natural_t, } impl ::std::clone::Clone for Struct_hash_info_bucket { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_hash_info_bucket { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type hash_info_bucket_t = Struct_hash_info_bucket; pub type hash_info_bucket_array_t = *mut hash_info_bucket_t; #[repr(C)] #[derive(Copy)] pub struct Struct_lockgroup_info { pub lockgroup_name: [::std::os::raw::c_char; 64usize], pub lockgroup_attr: uint64_t, pub lock_spin_cnt: uint64_t, pub lock_spin_util_cnt: uint64_t, pub lock_spin_held_cnt: uint64_t, pub lock_spin_miss_cnt: uint64_t, pub lock_spin_held_max: uint64_t, pub lock_spin_held_cum: uint64_t, pub lock_mtx_cnt: uint64_t, pub lock_mtx_util_cnt: uint64_t, pub lock_mtx_held_cnt: uint64_t, pub lock_mtx_miss_cnt: uint64_t, pub lock_mtx_wait_cnt: uint64_t, pub lock_mtx_held_max: uint64_t, pub lock_mtx_held_cum: uint64_t, pub lock_mtx_wait_max: uint64_t, pub lock_mtx_wait_cum: uint64_t, pub lock_rw_cnt: uint64_t, pub lock_rw_util_cnt: uint64_t, pub lock_rw_held_cnt: uint64_t, pub lock_rw_miss_cnt: uint64_t, pub lock_rw_wait_cnt: uint64_t, pub lock_rw_held_max: uint64_t, pub lock_rw_held_cum: uint64_t, pub lock_rw_wait_max: uint64_t, pub lock_rw_wait_cum: uint64_t, } impl ::std::clone::Clone for Struct_lockgroup_info { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_lockgroup_info { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type lockgroup_info_t = Struct_lockgroup_info; pub type lockgroup_info_array_t = *mut lockgroup_info_t; pub type symtab_name_t = [::std::os::raw::c_char; 32usize]; #[repr(C)] #[derive(Copy)] pub struct Struct_mach_core_fileheader { pub signature: uint64_t, pub log_offset: uint64_t, pub log_length: uint64_t, pub gzip_offset: uint64_t, pub gzip_length: uint64_t, } impl ::std::clone::Clone for Struct_mach_core_fileheader { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_mach_core_fileheader { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed66 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed66 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed66 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_boot_info_t = Struct_Unnamed66; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed67 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub options: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed67 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed67 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_reboot_t = Struct_Unnamed67; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed68 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: host_flavor_t, pub host_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed68 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed68 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_priv_statistics_t = Struct_Unnamed68; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed69 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub default_manager: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub cluster_size: memory_object_cluster_size_t, } impl ::std::clone::Clone for Struct_Unnamed69 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed69 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_default_memory_manager_t = Struct_Unnamed69; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed70 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub task: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub desired_access: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed70 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed70 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_wire_t = Struct_Unnamed70; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed71 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub thread: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub wired: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed71 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed71 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_wire_t = Struct_Unnamed71; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed72 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub task: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed72 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed72 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_allocate_cpm_t = Struct_Unnamed72; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed73 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed73 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed73 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_processors_t = Struct_Unnamed73; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed74 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub clock_id: clock_id_t, } impl ::std::clone::Clone for Struct_Unnamed74 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed74 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_clock_control_t = Struct_Unnamed74; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed75 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub info: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed75 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed75 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__kmod_create_t = Struct_Unnamed75; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed76 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub module: kmod_t, } impl ::std::clone::Clone for Struct_Unnamed76 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed76 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__kmod_destroy_t = Struct_Unnamed76; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed77 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub module: kmod_t, pub flavor: kmod_control_flavor_t, pub dataCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed77 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed77 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__kmod_control_t = Struct_Unnamed77; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed78 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub node: ::std::os::raw::c_int, pub which: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed78 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed78 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_special_port_t = Struct_Unnamed78; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed79 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub which: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed79 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed79 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_set_special_port_t = Struct_Unnamed79; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed80 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed80 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed80 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_set_exception_ports_t = Struct_Unnamed80; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed81 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, } impl ::std::clone::Clone for Struct_Unnamed81 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed81 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_exception_ports_t = Struct_Unnamed81; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed82 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed82 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed82 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_swap_exception_ports_t = Struct_Unnamed82; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed83 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub task: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: mach_vm_address_t, pub size: mach_vm_size_t, pub desired_access: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed83 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed83 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_vm_wire_t = Struct_Unnamed83; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed84 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed84 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed84 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_processor_sets_t = Struct_Unnamed84; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed85 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub set_name: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed85 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed85 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_processor_set_priv_t = Struct_Unnamed85; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed86 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub control_port: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed86 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed86 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__set_dp_control_port_t = Struct_Unnamed86; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed87 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed87 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed87 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__get_dp_control_port_t = Struct_Unnamed87; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed88 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub server: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed88 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed88 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_set_UNDServer_t = Struct_Unnamed88; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed89 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed89 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed89 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_UNDServer_t = Struct_Unnamed89; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed90 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub request_data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub user_log_flags: uint32_t, pub request_dataCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed90 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed90 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__kext_request_t = Struct_Unnamed90; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__host_priv_subsystem { pub _bindgen_data_: [u32; 17usize], } impl Union___RequestUnion__host_priv_subsystem { pub unsafe fn Request_host_get_boot_info(&mut self) -> *mut __Request__host_get_boot_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_reboot(&mut self) -> *mut __Request__host_reboot_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_priv_statistics(&mut self) -> *mut __Request__host_priv_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_default_memory_manager(&mut self) -> *mut __Request__host_default_memory_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_wire(&mut self) -> *mut __Request__vm_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_wire(&mut self) -> *mut __Request__thread_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_allocate_cpm(&mut self) -> *mut __Request__vm_allocate_cpm_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_processors(&mut self) -> *mut __Request__host_processors_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_clock_control(&mut self) -> *mut __Request__host_get_clock_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_kmod_create(&mut self) -> *mut __Request__kmod_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_kmod_destroy(&mut self) -> *mut __Request__kmod_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_kmod_control(&mut self) -> *mut __Request__kmod_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_special_port(&mut self) -> *mut __Request__host_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_set_special_port(&mut self) -> *mut __Request__host_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_set_exception_ports(&mut self) -> *mut __Request__host_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_exception_ports(&mut self) -> *mut __Request__host_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_swap_exception_ports(&mut self) -> *mut __Request__host_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_vm_wire(&mut self) -> *mut __Request__mach_vm_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_processor_sets(&mut self) -> *mut __Request__host_processor_sets_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_processor_set_priv(&mut self) -> *mut __Request__host_processor_set_priv_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_set_dp_control_port(&mut self) -> *mut __Request__set_dp_control_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_get_dp_control_port(&mut self) -> *mut __Request__get_dp_control_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_set_UNDServer(&mut self) -> *mut __Request__host_set_UNDServer_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_UNDServer(&mut self) -> *mut __Request__host_get_UNDServer_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_kext_request(&mut self) -> *mut __Request__kext_request_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__host_priv_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__host_priv_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed91 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub boot_infoOffset: mach_msg_type_number_t, pub boot_infoCnt: mach_msg_type_number_t, pub boot_info: [::std::os::raw::c_char; 4096usize], } impl ::std::clone::Clone for Struct_Unnamed91 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed91 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_boot_info_t = Struct_Unnamed91; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed92 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed92 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed92 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_reboot_t = Struct_Unnamed92; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed93 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub host_info_outCnt: mach_msg_type_number_t, pub host_info_out: [integer_t; 68usize], } impl ::std::clone::Clone for Struct_Unnamed93 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed93 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_priv_statistics_t = Struct_Unnamed93; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed94 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub default_manager: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed94 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed94 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_default_memory_manager_t = Struct_Unnamed94; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed95 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed95 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed95 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_wire_t = Struct_Unnamed95; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed96 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed96 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed96 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_wire_t = Struct_Unnamed96; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed97 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed97 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed97 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_allocate_cpm_t = Struct_Unnamed97; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed98 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub out_processor_list: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub out_processor_listCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed98 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed98 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_processors_t = Struct_Unnamed98; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed99 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub clock_ctrl: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed99 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed99 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_clock_control_t = Struct_Unnamed99; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed100 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub module: kmod_t, } impl ::std::clone::Clone for Struct_Unnamed100 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed100 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__kmod_create_t = Struct_Unnamed100; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed101 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed101 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed101 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__kmod_destroy_t = Struct_Unnamed101; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed102 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub dataCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed102 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed102 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__kmod_control_t = Struct_Unnamed102; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed103 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub port: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed103 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed103 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_special_port_t = Struct_Unnamed103; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed104 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed104 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed104 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_set_special_port_t = Struct_Unnamed104; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed105 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed105 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed105 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_set_exception_ports_t = Struct_Unnamed105; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed106 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlers: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed106 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed106 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_exception_ports_t = Struct_Unnamed106; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed107 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlerss: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed107 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed107 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_swap_exception_ports_t = Struct_Unnamed107; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed108 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed108 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed108 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_vm_wire_t = Struct_Unnamed108; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed109 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub processor_sets: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub processor_setsCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed109 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed109 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_processor_sets_t = Struct_Unnamed109; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed110 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed110 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed110 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_processor_set_priv_t = Struct_Unnamed110; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed111 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed111 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed111 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__set_dp_control_port_t = Struct_Unnamed111; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed112 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub contorl_port: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed112 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed112 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__get_dp_control_port_t = Struct_Unnamed112; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed113 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed113 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed113 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_set_UNDServer_t = Struct_Unnamed113; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed114 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub server: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed114 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed114 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_UNDServer_t = Struct_Unnamed114; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed115 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub response_data: mach_msg_ool_descriptor_t, pub log_data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub response_dataCnt: mach_msg_type_number_t, pub log_dataCnt: mach_msg_type_number_t, pub op_result: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed115 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed115 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__kext_request_t = Struct_Unnamed115; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__host_priv_subsystem { pub _bindgen_data_: [u32; 1035usize], } impl Union___ReplyUnion__host_priv_subsystem { pub unsafe fn Reply_host_get_boot_info(&mut self) -> *mut __Reply__host_get_boot_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_reboot(&mut self) -> *mut __Reply__host_reboot_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_priv_statistics(&mut self) -> *mut __Reply__host_priv_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_default_memory_manager(&mut self) -> *mut __Reply__host_default_memory_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_wire(&mut self) -> *mut __Reply__vm_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_wire(&mut self) -> *mut __Reply__thread_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_allocate_cpm(&mut self) -> *mut __Reply__vm_allocate_cpm_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_processors(&mut self) -> *mut __Reply__host_processors_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_clock_control(&mut self) -> *mut __Reply__host_get_clock_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_kmod_create(&mut self) -> *mut __Reply__kmod_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_kmod_destroy(&mut self) -> *mut __Reply__kmod_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_kmod_control(&mut self) -> *mut __Reply__kmod_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_special_port(&mut self) -> *mut __Reply__host_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_set_special_port(&mut self) -> *mut __Reply__host_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_set_exception_ports(&mut self) -> *mut __Reply__host_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_exception_ports(&mut self) -> *mut __Reply__host_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_swap_exception_ports(&mut self) -> *mut __Reply__host_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_vm_wire(&mut self) -> *mut __Reply__mach_vm_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_processor_sets(&mut self) -> *mut __Reply__host_processor_sets_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_processor_set_priv(&mut self) -> *mut __Reply__host_processor_set_priv_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_set_dp_control_port(&mut self) -> *mut __Reply__set_dp_control_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_get_dp_control_port(&mut self) -> *mut __Reply__get_dp_control_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_set_UNDServer(&mut self) -> *mut __Reply__host_set_UNDServer_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_UNDServer(&mut self) -> *mut __Reply__host_get_UNDServer_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_kext_request(&mut self) -> *mut __Reply__kext_request_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__host_priv_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__host_priv_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed116 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub parent_task: mach_msg_port_descriptor_t, pub host: mach_msg_port_descriptor_t, pub ledgers: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub sec_token: security_token_t, pub audit_token: audit_token_t, pub ledgersCnt: mach_msg_type_number_t, pub inherit_memory: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed116 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed116 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_security_create_task_token_t = Struct_Unnamed116; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed117 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub target_task: mach_msg_port_descriptor_t, pub host: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub sec_token: security_token_t, pub audit_token: audit_token_t, } impl ::std::clone::Clone for Struct_Unnamed117 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed117 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_security_set_task_token_t = Struct_Unnamed117; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__host_security_subsystem { pub _bindgen_data_: [u32; 31usize], } impl Union___RequestUnion__host_security_subsystem { pub unsafe fn Request_host_security_create_task_token(&mut self) -> *mut __Request__host_security_create_task_token_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_security_set_task_token(&mut self) -> *mut __Request__host_security_set_task_token_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__host_security_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__host_security_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed118 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub child_task: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed118 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed118 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_security_create_task_token_t = Struct_Unnamed118; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed119 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed119 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed119 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_security_set_task_token_t = Struct_Unnamed119; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__host_security_subsystem { pub _bindgen_data_: [u32; 10usize], } impl Union___ReplyUnion__host_security_subsystem { pub unsafe fn Reply_host_security_create_task_token(&mut self) -> *mut __Reply__host_security_create_task_token_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_security_set_task_token(&mut self) -> *mut __Reply__host_security_set_task_token_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__host_security_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__host_security_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed120 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed120 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed120 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_acquire_t = Struct_Unnamed120; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed121 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed121 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed121 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_release_t = Struct_Unnamed121; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed122 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed122 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed122 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_try_t = Struct_Unnamed122; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed123 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed123 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed123 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_make_stable_t = Struct_Unnamed123; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed124 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed124 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed124 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_handoff_t = Struct_Unnamed124; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed125 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub lock_id: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed125 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed125 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_handoff_accept_t = Struct_Unnamed125; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__lock_set_subsystem { pub _bindgen_data_: [u32; 9usize], } impl Union___RequestUnion__lock_set_subsystem { pub unsafe fn Request_lock_acquire(&mut self) -> *mut __Request__lock_acquire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_release(&mut self) -> *mut __Request__lock_release_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_try(&mut self) -> *mut __Request__lock_try_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_make_stable(&mut self) -> *mut __Request__lock_make_stable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_handoff(&mut self) -> *mut __Request__lock_handoff_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_handoff_accept(&mut self) -> *mut __Request__lock_handoff_accept_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__lock_set_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__lock_set_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed126 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed126 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed126 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_acquire_t = Struct_Unnamed126; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed127 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed127 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed127 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_release_t = Struct_Unnamed127; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed128 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed128 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed128 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_try_t = Struct_Unnamed128; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed129 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed129 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed129 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_make_stable_t = Struct_Unnamed129; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed130 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed130 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed130 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_handoff_t = Struct_Unnamed130; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed131 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed131 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed131 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_handoff_accept_t = Struct_Unnamed131; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__lock_set_subsystem { pub _bindgen_data_: [u32; 9usize], } impl Union___ReplyUnion__lock_set_subsystem { pub unsafe fn Reply_lock_acquire(&mut self) -> *mut __Reply__lock_acquire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_release(&mut self) -> *mut __Reply__lock_release_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_try(&mut self) -> *mut __Reply__lock_try_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_make_stable(&mut self) -> *mut __Reply__lock_make_stable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_handoff(&mut self) -> *mut __Reply__lock_handoff_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_handoff_accept(&mut self) -> *mut __Reply__lock_handoff_accept_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__lock_set_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__lock_set_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed132 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed132 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed132 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_start_t = Struct_Unnamed132; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed133 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed133 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed133 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_exit_t = Struct_Unnamed133; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed134 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: processor_flavor_t, pub processor_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed134 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed134 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_info_t = Struct_Unnamed134; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed135 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub processor_cmdCnt: mach_msg_type_number_t, pub processor_cmd: [integer_t; 12usize], } impl ::std::clone::Clone for Struct_Unnamed135 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed135 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_control_t = Struct_Unnamed135; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed136 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_set: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub wait: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed136 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed136 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_assign_t = Struct_Unnamed136; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed137 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed137 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed137 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_get_assignment_t = Struct_Unnamed137; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__processor_subsystem { pub _bindgen_data_: [u32; 21usize], } impl Union___RequestUnion__processor_subsystem { pub unsafe fn Request_processor_start(&mut self) -> *mut __Request__processor_start_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_exit(&mut self) -> *mut __Request__processor_exit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_info(&mut self) -> *mut __Request__processor_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_control(&mut self) -> *mut __Request__processor_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_assign(&mut self) -> *mut __Request__processor_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_get_assignment(&mut self) -> *mut __Request__processor_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__processor_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__processor_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed138 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed138 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed138 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_start_t = Struct_Unnamed138; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed139 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed139 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed139 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_exit_t = Struct_Unnamed139; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed140 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub host: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub processor_info_outCnt: mach_msg_type_number_t, pub processor_info_out: [integer_t; 12usize], } impl ::std::clone::Clone for Struct_Unnamed140 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed140 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_info_t = Struct_Unnamed140; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed141 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed141 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed141 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_control_t = Struct_Unnamed141; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed142 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed142 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed142 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_assign_t = Struct_Unnamed142; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed143 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub assigned_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed143 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed143 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_get_assignment_t = Struct_Unnamed143; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__processor_subsystem { pub _bindgen_data_: [u32; 25usize], } impl Union___ReplyUnion__processor_subsystem { pub unsafe fn Reply_processor_start(&mut self) -> *mut __Reply__processor_start_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_exit(&mut self) -> *mut __Reply__processor_exit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_info(&mut self) -> *mut __Reply__processor_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_control(&mut self) -> *mut __Reply__processor_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_assign(&mut self) -> *mut __Reply__processor_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_get_assignment(&mut self) -> *mut __Reply__processor_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__processor_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__processor_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed144 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: processor_set_flavor_t, pub info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed144 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed144 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_statistics_t = Struct_Unnamed144; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed145 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed145 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed145 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_destroy_t = Struct_Unnamed145; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed146 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub max_priority: ::std::os::raw::c_int, pub change_threads: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed146 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed146 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_max_priority_t = Struct_Unnamed146; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed147 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub policy: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed147 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed147 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_policy_enable_t = Struct_Unnamed147; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed148 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub policy: ::std::os::raw::c_int, pub change_threads: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed148 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed148 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_policy_disable_t = Struct_Unnamed148; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed149 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed149 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed149 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_tasks_t = Struct_Unnamed149; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed150 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed150 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed150 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_threads_t = Struct_Unnamed150; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed151 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: processor_set_flavor_t, pub policy_infoCnt: mach_msg_type_number_t, pub policy_info: [integer_t; 5usize], pub change: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed151 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed151 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_policy_control_t = Struct_Unnamed151; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed152 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed152 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed152 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_stack_usage_t = Struct_Unnamed152; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed153 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: ::std::os::raw::c_int, pub info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed153 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed153 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_info_t = Struct_Unnamed153; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__processor_set_subsystem { pub _bindgen_data_: [u32; 16usize], } impl Union___RequestUnion__processor_set_subsystem { pub unsafe fn Request_processor_set_statistics(&mut self) -> *mut __Request__processor_set_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_destroy(&mut self) -> *mut __Request__processor_set_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_max_priority(&mut self) -> *mut __Request__processor_set_max_priority_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_policy_enable(&mut self) -> *mut __Request__processor_set_policy_enable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_policy_disable(&mut self) -> *mut __Request__processor_set_policy_disable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_tasks(&mut self) -> *mut __Request__processor_set_tasks_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_threads(&mut self) -> *mut __Request__processor_set_threads_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_policy_control(&mut self) -> *mut __Request__processor_set_policy_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_stack_usage(&mut self) -> *mut __Request__processor_set_stack_usage_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_info(&mut self) -> *mut __Request__processor_set_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__processor_set_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__processor_set_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed154 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub info_outCnt: mach_msg_type_number_t, pub info_out: [integer_t; 5usize], } impl ::std::clone::Clone for Struct_Unnamed154 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed154 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_statistics_t = Struct_Unnamed154; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed155 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed155 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed155 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_destroy_t = Struct_Unnamed155; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed156 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed156 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed156 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_max_priority_t = Struct_Unnamed156; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed157 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed157 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed157 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_policy_enable_t = Struct_Unnamed157; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed158 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed158 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed158 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_policy_disable_t = Struct_Unnamed158; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed159 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub task_list: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub task_listCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed159 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed159 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_tasks_t = Struct_Unnamed159; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed160 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub thread_list: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub thread_listCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed160 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed160 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_threads_t = Struct_Unnamed160; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed161 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed161 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed161 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_policy_control_t = Struct_Unnamed161; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed162 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub ltotal: ::std::os::raw::c_uint, pub space: vm_size_t, pub resident: vm_size_t, pub maxusage: vm_size_t, pub maxstack: vm_offset_t, } impl ::std::clone::Clone for Struct_Unnamed162 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed162 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_stack_usage_t = Struct_Unnamed162; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed163 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub host: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub info_outCnt: mach_msg_type_number_t, pub info_out: [integer_t; 5usize], } impl ::std::clone::Clone for Struct_Unnamed163 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed163 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_info_t = Struct_Unnamed163; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__processor_set_subsystem { pub _bindgen_data_: [u32; 18usize], } impl Union___ReplyUnion__processor_set_subsystem { pub unsafe fn Reply_processor_set_statistics(&mut self) -> *mut __Reply__processor_set_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_destroy(&mut self) -> *mut __Reply__processor_set_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_max_priority(&mut self) -> *mut __Reply__processor_set_max_priority_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_policy_enable(&mut self) -> *mut __Reply__processor_set_policy_enable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_policy_disable(&mut self) -> *mut __Reply__processor_set_policy_disable_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_tasks(&mut self) -> *mut __Reply__processor_set_tasks_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_threads(&mut self) -> *mut __Reply__processor_set_threads_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_policy_control(&mut self) -> *mut __Reply__processor_set_policy_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_stack_usage(&mut self) -> *mut __Reply__processor_set_stack_usage_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_info(&mut self) -> *mut __Reply__processor_set_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__processor_set_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__processor_set_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type sync_policy_t = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed164 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub ledgers: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub ledgersCnt: mach_msg_type_number_t, pub inherit_memory: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed164 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed164 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_create_t = Struct_Unnamed164; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed165 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed165 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed165 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_terminate_t = Struct_Unnamed165; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed166 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed166 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed166 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_threads_t = Struct_Unnamed166; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed167 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub init_port_set: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub init_port_setCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed167 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed167 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_ports_register_t = Struct_Unnamed167; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed168 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed168 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed168 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_ports_lookup_t = Struct_Unnamed168; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed169 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: task_flavor_t, pub task_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed169 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed169 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_info_t = Struct_Unnamed169; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed170 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: task_flavor_t, pub task_info_inCnt: mach_msg_type_number_t, pub task_info_in: [integer_t; 52usize], } impl ::std::clone::Clone for Struct_Unnamed170 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed170 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_info_t = Struct_Unnamed170; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed171 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed171 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed171 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_suspend_t = Struct_Unnamed171; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed172 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed172 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed172 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_resume_t = Struct_Unnamed172; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed173 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub which_port: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed173 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed173 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_special_port_t = Struct_Unnamed173; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed174 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub special_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub which_port: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed174 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed174 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_special_port_t = Struct_Unnamed174; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed175 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed175 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed175 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_create_t = Struct_Unnamed175; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed176 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_state_flavor_t, pub new_stateCnt: mach_msg_type_number_t, pub new_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed176 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed176 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_create_running_t = Struct_Unnamed176; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed177 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed177 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed177 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_exception_ports_t = Struct_Unnamed177; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed178 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, } impl ::std::clone::Clone for Struct_Unnamed178 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed178 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_exception_ports_t = Struct_Unnamed178; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed179 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed179 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed179 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_swap_exception_ports_t = Struct_Unnamed179; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed180 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub n_ulocks: ::std::os::raw::c_int, pub policy: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed180 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed180 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_set_create_t = Struct_Unnamed180; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed181 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub lock_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed181 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed181 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__lock_set_destroy_t = Struct_Unnamed181; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed182 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub policy: ::std::os::raw::c_int, pub value: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed182 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed182 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__semaphore_create_t = Struct_Unnamed182; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed183 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub semaphore: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed183 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed183 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__semaphore_destroy_t = Struct_Unnamed183; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed184 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: task_policy_flavor_t, pub policy_infoCnt: mach_msg_type_number_t, pub policy_info: [integer_t; 16usize], } impl ::std::clone::Clone for Struct_Unnamed184 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed184 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_policy_set_t = Struct_Unnamed184; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed185 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: task_policy_flavor_t, pub policy_infoCnt: mach_msg_type_number_t, pub get_default: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed185 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed185 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_policy_get_t = Struct_Unnamed185; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed186 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub reply: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed186 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed186 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_sample_t = Struct_Unnamed186; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed187 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub policy: policy_t, pub baseCnt: mach_msg_type_number_t, pub base: [integer_t; 5usize], pub set_limit: boolean_t, pub change: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed187 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed187 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_policy_t = Struct_Unnamed187; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed188 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub routine_entry_pt: vm_address_t, pub routine_number: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed188 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed188 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_emulation_t = Struct_Unnamed188; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed189 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed189 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed189 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_emulation_vector_t = Struct_Unnamed189; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed190 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub emulation_vector: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub vector_start: ::std::os::raw::c_int, pub emulation_vectorCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed190 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed190 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_emulation_vector_t = Struct_Unnamed190; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed191 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub basepc: vm_address_t, pub boundspc: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed191 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed191 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_ras_pc_t = Struct_Unnamed191; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed192 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed192 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed192 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_zone_info_t = Struct_Unnamed192; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed193 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_set: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub assign_threads: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed193 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed193 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_assign_t = Struct_Unnamed193; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed194 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub assign_threads: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed194 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed194 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_assign_default_t = Struct_Unnamed194; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed195 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed195 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed195 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_assignment_t = Struct_Unnamed195; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed196 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub pset: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub policy: policy_t, pub baseCnt: mach_msg_type_number_t, pub base: [integer_t; 5usize], pub limitCnt: mach_msg_type_number_t, pub limit: [integer_t; 1usize], pub change: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed196 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed196 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_policy_t = Struct_Unnamed196; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed197 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_state_flavor_t, pub old_stateCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed197 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed197 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_state_t = Struct_Unnamed197; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed198 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_state_flavor_t, pub new_stateCnt: mach_msg_type_number_t, pub new_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed198 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed198 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_state_t = Struct_Unnamed198; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed199 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub new_limit: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed199 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed199 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_phys_footprint_limit_t = Struct_Unnamed199; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed200 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed200 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed200 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_suspend2_t = Struct_Unnamed200; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed201 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed201 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed201 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_resume2_t = Struct_Unnamed201; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed202 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed202 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed202 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_purgable_info_t = Struct_Unnamed202; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed203 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub which: mach_voucher_selector_t, } impl ::std::clone::Clone for Struct_Unnamed203 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed203 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_get_mach_voucher_t = Struct_Unnamed203; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed204 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed204 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed204 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_mach_voucher_t = Struct_Unnamed204; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed205 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_voucher: mach_msg_port_descriptor_t, pub old_voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed205 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed205 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_swap_mach_voucher_t = Struct_Unnamed205; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__task_subsystem { pub _bindgen_data_: [u32; 234usize], } impl Union___RequestUnion__task_subsystem { pub unsafe fn Request_task_create(&mut self) -> *mut __Request__task_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_terminate(&mut self) -> *mut __Request__task_terminate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_threads(&mut self) -> *mut __Request__task_threads_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_ports_register(&mut self) -> *mut __Request__mach_ports_register_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_ports_lookup(&mut self) -> *mut __Request__mach_ports_lookup_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_info(&mut self) -> *mut __Request__task_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_info(&mut self) -> *mut __Request__task_set_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_suspend(&mut self) -> *mut __Request__task_suspend_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_resume(&mut self) -> *mut __Request__task_resume_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_special_port(&mut self) -> *mut __Request__task_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_special_port(&mut self) -> *mut __Request__task_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_create(&mut self) -> *mut __Request__thread_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_create_running(&mut self) -> *mut __Request__thread_create_running_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_exception_ports(&mut self) -> *mut __Request__task_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_exception_ports(&mut self) -> *mut __Request__task_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_swap_exception_ports(&mut self) -> *mut __Request__task_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_set_create(&mut self) -> *mut __Request__lock_set_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_lock_set_destroy(&mut self) -> *mut __Request__lock_set_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_semaphore_create(&mut self) -> *mut __Request__semaphore_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_semaphore_destroy(&mut self) -> *mut __Request__semaphore_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_policy_set(&mut self) -> *mut __Request__task_policy_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_policy_get(&mut self) -> *mut __Request__task_policy_get_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_sample(&mut self) -> *mut __Request__task_sample_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_policy(&mut self) -> *mut __Request__task_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_emulation(&mut self) -> *mut __Request__task_set_emulation_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_emulation_vector(&mut self) -> *mut __Request__task_get_emulation_vector_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_emulation_vector(&mut self) -> *mut __Request__task_set_emulation_vector_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_ras_pc(&mut self) -> *mut __Request__task_set_ras_pc_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_zone_info(&mut self) -> *mut __Request__task_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_assign(&mut self) -> *mut __Request__task_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_assign_default(&mut self) -> *mut __Request__task_assign_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_assignment(&mut self) -> *mut __Request__task_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_policy(&mut self) -> *mut __Request__task_set_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_state(&mut self) -> *mut __Request__task_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_state(&mut self) -> *mut __Request__task_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_phys_footprint_limit(&mut self) -> *mut __Request__task_set_phys_footprint_limit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_suspend2(&mut self) -> *mut __Request__task_suspend2_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_resume2(&mut self) -> *mut __Request__task_resume2_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_purgable_info(&mut self) -> *mut __Request__task_purgable_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_get_mach_voucher(&mut self) -> *mut __Request__task_get_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_mach_voucher(&mut self) -> *mut __Request__task_set_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_swap_mach_voucher(&mut self) -> *mut __Request__task_swap_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__task_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__task_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed206 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub child_task: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed206 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed206 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_create_t = Struct_Unnamed206; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed207 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed207 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed207 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_terminate_t = Struct_Unnamed207; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed208 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub act_list: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub act_listCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed208 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed208 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_threads_t = Struct_Unnamed208; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed209 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed209 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed209 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_ports_register_t = Struct_Unnamed209; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed210 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub init_port_set: mach_msg_ool_ports_descriptor_t, pub NDR: NDR_record_t, pub init_port_setCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed210 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed210 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_ports_lookup_t = Struct_Unnamed210; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed211 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub task_info_outCnt: mach_msg_type_number_t, pub task_info_out: [integer_t; 52usize], } impl ::std::clone::Clone for Struct_Unnamed211 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed211 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_info_t = Struct_Unnamed211; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed212 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed212 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed212 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_info_t = Struct_Unnamed212; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed213 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed213 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed213 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_suspend_t = Struct_Unnamed213; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed214 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed214 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed214 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_resume_t = Struct_Unnamed214; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed215 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub special_port: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed215 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed215 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_special_port_t = Struct_Unnamed215; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed216 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed216 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed216 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_special_port_t = Struct_Unnamed216; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed217 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub child_act: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed217 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed217 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_create_t = Struct_Unnamed217; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed218 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub child_act: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed218 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed218 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_create_running_t = Struct_Unnamed218; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed219 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed219 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed219 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_exception_ports_t = Struct_Unnamed219; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed220 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlers: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed220 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed220 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_exception_ports_t = Struct_Unnamed220; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed221 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlerss: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed221 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed221 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_swap_exception_ports_t = Struct_Unnamed221; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed222 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_lock_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed222 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed222 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_set_create_t = Struct_Unnamed222; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed223 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed223 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed223 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__lock_set_destroy_t = Struct_Unnamed223; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed224 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub semaphore: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed224 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed224 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__semaphore_create_t = Struct_Unnamed224; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed225 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed225 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed225 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__semaphore_destroy_t = Struct_Unnamed225; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed226 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed226 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed226 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_policy_set_t = Struct_Unnamed226; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed227 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub policy_infoCnt: mach_msg_type_number_t, pub policy_info: [integer_t; 16usize], pub get_default: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed227 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed227 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_policy_get_t = Struct_Unnamed227; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed228 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed228 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed228 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_sample_t = Struct_Unnamed228; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed229 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed229 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed229 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_policy_t = Struct_Unnamed229; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed230 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed230 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed230 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_emulation_t = Struct_Unnamed230; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed231 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub emulation_vector: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub vector_start: ::std::os::raw::c_int, pub emulation_vectorCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed231 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed231 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_emulation_vector_t = Struct_Unnamed231; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed232 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed232 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed232 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_emulation_vector_t = Struct_Unnamed232; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed233 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed233 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed233 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_ras_pc_t = Struct_Unnamed233; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed234 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub names: mach_msg_ool_descriptor_t, pub info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub namesCnt: mach_msg_type_number_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed234 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed234 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_zone_info_t = Struct_Unnamed234; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed235 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed235 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed235 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_assign_t = Struct_Unnamed235; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed236 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed236 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed236 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_assign_default_t = Struct_Unnamed236; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed237 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub assigned_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed237 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed237 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_assignment_t = Struct_Unnamed237; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed238 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed238 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed238 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_policy_t = Struct_Unnamed238; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed239 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub old_stateCnt: mach_msg_type_number_t, pub old_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed239 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed239 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_state_t = Struct_Unnamed239; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed240 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed240 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed240 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_state_t = Struct_Unnamed240; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed241 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub old_limit: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed241 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed241 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_phys_footprint_limit_t = Struct_Unnamed241; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed242 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub suspend_token: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed242 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed242 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_suspend2_t = Struct_Unnamed242; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed243 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed243 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed243 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_resume2_t = Struct_Unnamed243; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed244 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub stats: task_purgable_info_t, } impl ::std::clone::Clone for Struct_Unnamed244 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed244 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_purgable_info_t = Struct_Unnamed244; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed245 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed245 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed245 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_get_mach_voucher_t = Struct_Unnamed245; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed246 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed246 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed246 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_mach_voucher_t = Struct_Unnamed246; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed247 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed247 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed247 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_swap_mach_voucher_t = Struct_Unnamed247; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__task_subsystem { pub _bindgen_data_: [u32; 234usize], } impl Union___ReplyUnion__task_subsystem { pub unsafe fn Reply_task_create(&mut self) -> *mut __Reply__task_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_terminate(&mut self) -> *mut __Reply__task_terminate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_threads(&mut self) -> *mut __Reply__task_threads_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_ports_register(&mut self) -> *mut __Reply__mach_ports_register_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_ports_lookup(&mut self) -> *mut __Reply__mach_ports_lookup_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_info(&mut self) -> *mut __Reply__task_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_info(&mut self) -> *mut __Reply__task_set_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_suspend(&mut self) -> *mut __Reply__task_suspend_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_resume(&mut self) -> *mut __Reply__task_resume_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_special_port(&mut self) -> *mut __Reply__task_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_special_port(&mut self) -> *mut __Reply__task_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_create(&mut self) -> *mut __Reply__thread_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_create_running(&mut self) -> *mut __Reply__thread_create_running_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_exception_ports(&mut self) -> *mut __Reply__task_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_exception_ports(&mut self) -> *mut __Reply__task_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_swap_exception_ports(&mut self) -> *mut __Reply__task_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_set_create(&mut self) -> *mut __Reply__lock_set_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_lock_set_destroy(&mut self) -> *mut __Reply__lock_set_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_semaphore_create(&mut self) -> *mut __Reply__semaphore_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_semaphore_destroy(&mut self) -> *mut __Reply__semaphore_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_policy_set(&mut self) -> *mut __Reply__task_policy_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_policy_get(&mut self) -> *mut __Reply__task_policy_get_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_sample(&mut self) -> *mut __Reply__task_sample_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_policy(&mut self) -> *mut __Reply__task_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_emulation(&mut self) -> *mut __Reply__task_set_emulation_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_emulation_vector(&mut self) -> *mut __Reply__task_get_emulation_vector_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_emulation_vector(&mut self) -> *mut __Reply__task_set_emulation_vector_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_ras_pc(&mut self) -> *mut __Reply__task_set_ras_pc_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_zone_info(&mut self) -> *mut __Reply__task_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_assign(&mut self) -> *mut __Reply__task_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_assign_default(&mut self) -> *mut __Reply__task_assign_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_assignment(&mut self) -> *mut __Reply__task_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_policy(&mut self) -> *mut __Reply__task_set_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_state(&mut self) -> *mut __Reply__task_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_state(&mut self) -> *mut __Reply__task_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_phys_footprint_limit(&mut self) -> *mut __Reply__task_set_phys_footprint_limit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_suspend2(&mut self) -> *mut __Reply__task_suspend2_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_resume2(&mut self) -> *mut __Reply__task_resume2_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_purgable_info(&mut self) -> *mut __Reply__task_purgable_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_get_mach_voucher(&mut self) -> *mut __Reply__task_get_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_mach_voucher(&mut self) -> *mut __Reply__task_set_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_swap_mach_voucher(&mut self) -> *mut __Reply__task_swap_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__task_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__task_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed248 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed248 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed248 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_terminate_t = Struct_Unnamed248; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed249 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: ::std::os::raw::c_int, pub old_stateCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed249 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed249 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__act_get_state_t = Struct_Unnamed249; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed250 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: ::std::os::raw::c_int, pub new_stateCnt: mach_msg_type_number_t, pub new_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed250 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed250 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__act_set_state_t = Struct_Unnamed250; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed251 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_state_flavor_t, pub old_stateCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed251 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed251 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_get_state_t = Struct_Unnamed251; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed252 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_state_flavor_t, pub new_stateCnt: mach_msg_type_number_t, pub new_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed252 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed252 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_set_state_t = Struct_Unnamed252; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed253 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed253 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed253 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_suspend_t = Struct_Unnamed253; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed254 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed254 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed254 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_resume_t = Struct_Unnamed254; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed255 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed255 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed255 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_abort_t = Struct_Unnamed255; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed256 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed256 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed256 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_abort_safely_t = Struct_Unnamed256; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed257 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed257 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed257 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_depress_abort_t = Struct_Unnamed257; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed258 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub which_port: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed258 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed258 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_get_special_port_t = Struct_Unnamed258; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed259 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub special_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub which_port: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed259 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed259 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_set_special_port_t = Struct_Unnamed259; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed260 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_flavor_t, pub thread_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed260 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed260 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_info_t = Struct_Unnamed260; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed261 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed261 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed261 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_set_exception_ports_t = Struct_Unnamed261; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed262 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, } impl ::std::clone::Clone for Struct_Unnamed262 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed262 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_get_exception_ports_t = Struct_Unnamed262; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed263 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub exception_mask: exception_mask_t, pub behavior: exception_behavior_t, pub new_flavor: thread_state_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed263 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed263 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_swap_exception_ports_t = Struct_Unnamed263; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed264 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub policy: policy_t, pub baseCnt: mach_msg_type_number_t, pub base: [integer_t; 5usize], pub set_limit: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed264 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed264 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_policy_t = Struct_Unnamed264; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed265 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_policy_flavor_t, pub policy_infoCnt: mach_msg_type_number_t, pub policy_info: [integer_t; 16usize], } impl ::std::clone::Clone for Struct_Unnamed265 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed265 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_policy_set_t = Struct_Unnamed265; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed266 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: thread_policy_flavor_t, pub policy_infoCnt: mach_msg_type_number_t, pub get_default: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed266 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed266 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_policy_get_t = Struct_Unnamed266; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed267 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub reply: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed267 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed267 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_sample_t = Struct_Unnamed267; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed268 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub trace_status: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed268 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed268 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__etap_trace_thread_t = Struct_Unnamed268; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed269 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed269 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed269 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_assign_t = Struct_Unnamed269; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed270 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed270 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed270 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_assign_default_t = Struct_Unnamed270; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed271 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed271 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed271 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_get_assignment_t = Struct_Unnamed271; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed272 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub pset: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub policy: policy_t, pub baseCnt: mach_msg_type_number_t, pub base: [integer_t; 5usize], pub limitCnt: mach_msg_type_number_t, pub limit: [integer_t; 1usize], } impl ::std::clone::Clone for Struct_Unnamed272 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed272 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_set_policy_t = Struct_Unnamed272; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed273 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub which: mach_voucher_selector_t, } impl ::std::clone::Clone for Struct_Unnamed273 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed273 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_get_mach_voucher_t = Struct_Unnamed273; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed274 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed274 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed274 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_set_mach_voucher_t = Struct_Unnamed274; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed275 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_voucher: mach_msg_port_descriptor_t, pub old_voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed275 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed275 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__thread_swap_mach_voucher_t = Struct_Unnamed275; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__thread_act_subsystem { pub _bindgen_data_: [u32; 234usize], } impl Union___RequestUnion__thread_act_subsystem { pub unsafe fn Request_thread_terminate(&mut self) -> *mut __Request__thread_terminate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_act_get_state(&mut self) -> *mut __Request__act_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_act_set_state(&mut self) -> *mut __Request__act_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_get_state(&mut self) -> *mut __Request__thread_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_set_state(&mut self) -> *mut __Request__thread_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_suspend(&mut self) -> *mut __Request__thread_suspend_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_resume(&mut self) -> *mut __Request__thread_resume_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_abort(&mut self) -> *mut __Request__thread_abort_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_abort_safely(&mut self) -> *mut __Request__thread_abort_safely_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_depress_abort(&mut self) -> *mut __Request__thread_depress_abort_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_get_special_port(&mut self) -> *mut __Request__thread_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_set_special_port(&mut self) -> *mut __Request__thread_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_info(&mut self) -> *mut __Request__thread_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_set_exception_ports(&mut self) -> *mut __Request__thread_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_get_exception_ports(&mut self) -> *mut __Request__thread_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_swap_exception_ports(&mut self) -> *mut __Request__thread_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_policy(&mut self) -> *mut __Request__thread_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_policy_set(&mut self) -> *mut __Request__thread_policy_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_policy_get(&mut self) -> *mut __Request__thread_policy_get_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_sample(&mut self) -> *mut __Request__thread_sample_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_etap_trace_thread(&mut self) -> *mut __Request__etap_trace_thread_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_assign(&mut self) -> *mut __Request__thread_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_assign_default(&mut self) -> *mut __Request__thread_assign_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_get_assignment(&mut self) -> *mut __Request__thread_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_set_policy(&mut self) -> *mut __Request__thread_set_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_get_mach_voucher(&mut self) -> *mut __Request__thread_get_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_set_mach_voucher(&mut self) -> *mut __Request__thread_set_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_thread_swap_mach_voucher(&mut self) -> *mut __Request__thread_swap_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__thread_act_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__thread_act_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed276 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed276 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed276 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_terminate_t = Struct_Unnamed276; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed277 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub old_stateCnt: mach_msg_type_number_t, pub old_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed277 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed277 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__act_get_state_t = Struct_Unnamed277; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed278 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed278 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed278 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__act_set_state_t = Struct_Unnamed278; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed279 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub old_stateCnt: mach_msg_type_number_t, pub old_state: [natural_t; 224usize], } impl ::std::clone::Clone for Struct_Unnamed279 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed279 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_get_state_t = Struct_Unnamed279; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed280 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed280 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed280 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_set_state_t = Struct_Unnamed280; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed281 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed281 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed281 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_suspend_t = Struct_Unnamed281; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed282 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed282 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed282 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_resume_t = Struct_Unnamed282; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed283 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed283 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed283 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_abort_t = Struct_Unnamed283; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed284 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed284 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed284 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_abort_safely_t = Struct_Unnamed284; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed285 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed285 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed285 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_depress_abort_t = Struct_Unnamed285; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed286 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub special_port: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed286 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed286 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_get_special_port_t = Struct_Unnamed286; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed287 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed287 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed287 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_set_special_port_t = Struct_Unnamed287; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed288 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub thread_info_outCnt: mach_msg_type_number_t, pub thread_info_out: [integer_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed288 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed288 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_info_t = Struct_Unnamed288; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed289 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed289 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed289 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_set_exception_ports_t = Struct_Unnamed289; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed290 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlers: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed290 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed290 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_get_exception_ports_t = Struct_Unnamed290; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed291 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_handlers: [mach_msg_port_descriptor_t; 32usize], pub NDR: NDR_record_t, pub masksCnt: mach_msg_type_number_t, pub masks: [exception_mask_t; 32usize], pub old_behaviors: [exception_behavior_t; 32usize], pub old_flavors: [thread_state_flavor_t; 32usize], } impl ::std::clone::Clone for Struct_Unnamed291 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed291 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_swap_exception_ports_t = Struct_Unnamed291; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed292 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed292 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed292 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_policy_t = Struct_Unnamed292; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed293 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed293 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed293 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_policy_set_t = Struct_Unnamed293; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed294 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub policy_infoCnt: mach_msg_type_number_t, pub policy_info: [integer_t; 16usize], pub get_default: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed294 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed294 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_policy_get_t = Struct_Unnamed294; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed295 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed295 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed295 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_sample_t = Struct_Unnamed295; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed296 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed296 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed296 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__etap_trace_thread_t = Struct_Unnamed296; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed297 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed297 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed297 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_assign_t = Struct_Unnamed297; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed298 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed298 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed298 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_assign_default_t = Struct_Unnamed298; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed299 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub assigned_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed299 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed299 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_get_assignment_t = Struct_Unnamed299; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed300 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed300 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed300 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_set_policy_t = Struct_Unnamed300; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed301 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed301 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed301 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_get_mach_voucher_t = Struct_Unnamed301; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed302 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed302 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed302 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_set_mach_voucher_t = Struct_Unnamed302; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed303 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub old_voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed303 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed303 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__thread_swap_mach_voucher_t = Struct_Unnamed303; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__thread_act_subsystem { pub _bindgen_data_: [u32; 234usize], } impl Union___ReplyUnion__thread_act_subsystem { pub unsafe fn Reply_thread_terminate(&mut self) -> *mut __Reply__thread_terminate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_act_get_state(&mut self) -> *mut __Reply__act_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_act_set_state(&mut self) -> *mut __Reply__act_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_get_state(&mut self) -> *mut __Reply__thread_get_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_set_state(&mut self) -> *mut __Reply__thread_set_state_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_suspend(&mut self) -> *mut __Reply__thread_suspend_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_resume(&mut self) -> *mut __Reply__thread_resume_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_abort(&mut self) -> *mut __Reply__thread_abort_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_abort_safely(&mut self) -> *mut __Reply__thread_abort_safely_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_depress_abort(&mut self) -> *mut __Reply__thread_depress_abort_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_get_special_port(&mut self) -> *mut __Reply__thread_get_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_set_special_port(&mut self) -> *mut __Reply__thread_set_special_port_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_info(&mut self) -> *mut __Reply__thread_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_set_exception_ports(&mut self) -> *mut __Reply__thread_set_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_get_exception_ports(&mut self) -> *mut __Reply__thread_get_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_swap_exception_ports(&mut self) -> *mut __Reply__thread_swap_exception_ports_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_policy(&mut self) -> *mut __Reply__thread_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_policy_set(&mut self) -> *mut __Reply__thread_policy_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_policy_get(&mut self) -> *mut __Reply__thread_policy_get_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_sample(&mut self) -> *mut __Reply__thread_sample_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_etap_trace_thread(&mut self) -> *mut __Reply__etap_trace_thread_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_assign(&mut self) -> *mut __Reply__thread_assign_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_assign_default(&mut self) -> *mut __Reply__thread_assign_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_get_assignment(&mut self) -> *mut __Reply__thread_get_assignment_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_set_policy(&mut self) -> *mut __Reply__thread_set_policy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_get_mach_voucher(&mut self) -> *mut __Reply__thread_get_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_set_mach_voucher(&mut self) -> *mut __Reply__thread_set_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_thread_swap_mach_voucher(&mut self) -> *mut __Reply__thread_swap_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__thread_act_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__thread_act_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed304 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub flavor: vm_region_flavor_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed304 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed304 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_region_t = Struct_Unnamed304; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed305 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub flags: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed305 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed305 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_allocate_t = Struct_Unnamed305; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed306 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, } impl ::std::clone::Clone for Struct_Unnamed306 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed306 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_deallocate_t = Struct_Unnamed306; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed307 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub set_maximum: boolean_t, pub new_protection: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed307 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed307 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_protect_t = Struct_Unnamed307; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed308 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub new_inheritance: vm_inherit_t, } impl ::std::clone::Clone for Struct_Unnamed308 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed308 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_inherit_t = Struct_Unnamed308; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed309 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, } impl ::std::clone::Clone for Struct_Unnamed309 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed309 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_read_t = Struct_Unnamed309; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed310 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub data_list: vm_read_entry_t, pub count: natural_t, } impl ::std::clone::Clone for Struct_Unnamed310 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed310 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_read_list_t = Struct_Unnamed310; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed311 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub dataCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed311 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed311 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_write_t = Struct_Unnamed311; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed312 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub source_address: vm_address_t, pub size: vm_size_t, pub dest_address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed312 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed312 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_copy_t = Struct_Unnamed312; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed313 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub data: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed313 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed313 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_read_overwrite_t = Struct_Unnamed313; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed314 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub sync_flags: vm_sync_t, } impl ::std::clone::Clone for Struct_Unnamed314 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed314 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_msync_t = Struct_Unnamed314; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed315 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub new_behavior: vm_behavior_t, } impl ::std::clone::Clone for Struct_Unnamed315 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed315 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_behavior_set_t = Struct_Unnamed315; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed316 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub mask: vm_address_t, pub flags: ::std::os::raw::c_int, pub offset: vm_offset_t, pub copy: boolean_t, pub cur_protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, } impl ::std::clone::Clone for Struct_Unnamed316 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed316 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_map_t = Struct_Unnamed316; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed317 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub attribute: vm_machine_attribute_t, pub value: vm_machine_attribute_val_t, } impl ::std::clone::Clone for Struct_Unnamed317 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed317 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_machine_attribute_t = Struct_Unnamed317; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed318 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub src_task: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub target_address: vm_address_t, pub size: vm_size_t, pub mask: vm_address_t, pub flags: ::std::os::raw::c_int, pub src_address: vm_address_t, pub copy: boolean_t, pub inheritance: vm_inherit_t, } impl ::std::clone::Clone for Struct_Unnamed318 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed318 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_remap_t = Struct_Unnamed318; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed319 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub must_wire: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed319 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed319 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_wire_t = Struct_Unnamed319; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed320 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub parent_entry: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub size: vm_size_t, pub offset: vm_offset_t, pub permission: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed320 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed320 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_make_memory_entry_t = Struct_Unnamed320; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed321 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub offset: vm_offset_t, } impl ::std::clone::Clone for Struct_Unnamed321 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed321 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_map_page_query_t = Struct_Unnamed321; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed322 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed322 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed322 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_vm_region_info_t = Struct_Unnamed322; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed323 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed323 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed323 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_mapped_pages_info_t = Struct_Unnamed323; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed324 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub nesting_depth: natural_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed324 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed324 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_region_recurse_t = Struct_Unnamed324; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed325 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub nesting_depth: natural_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed325 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed325 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_region_recurse_64_t = Struct_Unnamed325; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed326 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed326 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed326 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_vm_region_info_64_t = Struct_Unnamed326; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed327 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub flavor: vm_region_flavor_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed327 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed327 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_region_64_t = Struct_Unnamed327; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed328 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub parent_entry: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub size: memory_object_size_t, pub offset: memory_object_offset_t, pub permission: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed328 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed328 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_make_memory_entry_64_t = Struct_Unnamed328; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed329 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub mask: vm_address_t, pub flags: ::std::os::raw::c_int, pub offset: memory_object_offset_t, pub copy: boolean_t, pub cur_protection: vm_prot_t, pub max_protection: vm_prot_t, pub inheritance: vm_inherit_t, } impl ::std::clone::Clone for Struct_Unnamed329 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed329 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_map_64_t = Struct_Unnamed329; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed330 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub control: vm_purgable_t, pub state: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed330 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed330 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__vm_purgable_control_t = Struct_Unnamed330; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__vm_map_subsystem { pub _bindgen_data_: [u32; 1033usize], } impl Union___RequestUnion__vm_map_subsystem { pub unsafe fn Request_vm_region(&mut self) -> *mut __Request__vm_region_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_allocate(&mut self) -> *mut __Request__vm_allocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_deallocate(&mut self) -> *mut __Request__vm_deallocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_protect(&mut self) -> *mut __Request__vm_protect_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_inherit(&mut self) -> *mut __Request__vm_inherit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_read(&mut self) -> *mut __Request__vm_read_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_read_list(&mut self) -> *mut __Request__vm_read_list_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_write(&mut self) -> *mut __Request__vm_write_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_copy(&mut self) -> *mut __Request__vm_copy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_read_overwrite(&mut self) -> *mut __Request__vm_read_overwrite_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_msync(&mut self) -> *mut __Request__vm_msync_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_behavior_set(&mut self) -> *mut __Request__vm_behavior_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_map(&mut self) -> *mut __Request__vm_map_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_machine_attribute(&mut self) -> *mut __Request__vm_machine_attribute_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_remap(&mut self) -> *mut __Request__vm_remap_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_wire(&mut self) -> *mut __Request__task_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_make_memory_entry(&mut self) -> *mut __Request__mach_make_memory_entry_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_map_page_query(&mut self) -> *mut __Request__vm_map_page_query_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_vm_region_info(&mut self) -> *mut __Request__mach_vm_region_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_mapped_pages_info(&mut self) -> *mut __Request__vm_mapped_pages_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_region_recurse(&mut self) -> *mut __Request__vm_region_recurse_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_region_recurse_64(&mut self) -> *mut __Request__vm_region_recurse_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_vm_region_info_64(&mut self) -> *mut __Request__mach_vm_region_info_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_region_64(&mut self) -> *mut __Request__vm_region_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_make_memory_entry_64(&mut self) -> *mut __Request__mach_make_memory_entry_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_map_64(&mut self) -> *mut __Request__vm_map_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_vm_purgable_control(&mut self) -> *mut __Request__vm_purgable_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__vm_map_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__vm_map_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed331 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object_name: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub infoCnt: mach_msg_type_number_t, pub info: [::std::os::raw::c_int; 10usize], } impl ::std::clone::Clone for Struct_Unnamed331 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed331 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_region_t = Struct_Unnamed331; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed332 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed332 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed332 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_allocate_t = Struct_Unnamed332; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed333 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed333 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed333 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_deallocate_t = Struct_Unnamed333; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed334 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed334 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed334 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_protect_t = Struct_Unnamed334; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed335 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed335 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed335 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_inherit_t = Struct_Unnamed335; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed336 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub data: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub dataCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed336 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed336 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_read_t = Struct_Unnamed336; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed337 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub data_list: vm_read_entry_t, } impl ::std::clone::Clone for Struct_Unnamed337 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed337 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_read_list_t = Struct_Unnamed337; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed338 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed338 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed338 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_write_t = Struct_Unnamed338; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed339 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed339 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed339 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_copy_t = Struct_Unnamed339; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed340 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub outsize: vm_size_t, } impl ::std::clone::Clone for Struct_Unnamed340 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed340 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_read_overwrite_t = Struct_Unnamed340; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed341 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed341 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed341 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_msync_t = Struct_Unnamed341; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed342 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed342 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed342 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_behavior_set_t = Struct_Unnamed342; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed343 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed343 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed343 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_map_t = Struct_Unnamed343; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed344 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub value: vm_machine_attribute_val_t, } impl ::std::clone::Clone for Struct_Unnamed344 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed344 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_machine_attribute_t = Struct_Unnamed344; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed345 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub target_address: vm_address_t, pub cur_protection: vm_prot_t, pub max_protection: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed345 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed345 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_remap_t = Struct_Unnamed345; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed346 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed346 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed346 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_wire_t = Struct_Unnamed346; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed347 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object_handle: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub size: vm_size_t, } impl ::std::clone::Clone for Struct_Unnamed347 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed347 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_make_memory_entry_t = Struct_Unnamed347; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed348 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub disposition: integer_t, pub ref_count: integer_t, } impl ::std::clone::Clone for Struct_Unnamed348 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed348 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_map_page_query_t = Struct_Unnamed348; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed349 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub objects: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub region: vm_info_region_t, pub objectsCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed349 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed349 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_vm_region_info_t = Struct_Unnamed349; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed350 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub pages: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub pagesCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed350 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed350 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_mapped_pages_info_t = Struct_Unnamed350; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed351 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, pub size: vm_size_t, pub nesting_depth: natural_t, pub infoCnt: mach_msg_type_number_t, pub info: [::std::os::raw::c_int; 19usize], } impl ::std::clone::Clone for Struct_Unnamed351 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed351 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_region_recurse_t = Struct_Unnamed351; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed352 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, pub size: vm_size_t, pub nesting_depth: natural_t, pub infoCnt: mach_msg_type_number_t, pub info: [::std::os::raw::c_int; 19usize], } impl ::std::clone::Clone for Struct_Unnamed352 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed352 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_region_recurse_64_t = Struct_Unnamed352; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed353 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub objects: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub region: vm_info_region_64_t, pub objectsCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed353 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed353 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_vm_region_info_64_t = Struct_Unnamed353; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed354 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object_name: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub address: vm_address_t, pub size: vm_size_t, pub infoCnt: mach_msg_type_number_t, pub info: [::std::os::raw::c_int; 10usize], } impl ::std::clone::Clone for Struct_Unnamed354 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed354 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_region_64_t = Struct_Unnamed354; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed355 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub object_handle: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub size: memory_object_size_t, } impl ::std::clone::Clone for Struct_Unnamed355 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed355 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_make_memory_entry_64_t = Struct_Unnamed355; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed356 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub address: vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed356 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed356 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_map_64_t = Struct_Unnamed356; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed357 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub state: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed357 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed357 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__vm_purgable_control_t = Struct_Unnamed357; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__vm_map_subsystem { pub _bindgen_data_: [u32; 1033usize], } impl Union___ReplyUnion__vm_map_subsystem { pub unsafe fn Reply_vm_region(&mut self) -> *mut __Reply__vm_region_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_allocate(&mut self) -> *mut __Reply__vm_allocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_deallocate(&mut self) -> *mut __Reply__vm_deallocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_protect(&mut self) -> *mut __Reply__vm_protect_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_inherit(&mut self) -> *mut __Reply__vm_inherit_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_read(&mut self) -> *mut __Reply__vm_read_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_read_list(&mut self) -> *mut __Reply__vm_read_list_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_write(&mut self) -> *mut __Reply__vm_write_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_copy(&mut self) -> *mut __Reply__vm_copy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_read_overwrite(&mut self) -> *mut __Reply__vm_read_overwrite_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_msync(&mut self) -> *mut __Reply__vm_msync_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_behavior_set(&mut self) -> *mut __Reply__vm_behavior_set_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_map(&mut self) -> *mut __Reply__vm_map_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_machine_attribute(&mut self) -> *mut __Reply__vm_machine_attribute_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_remap(&mut self) -> *mut __Reply__vm_remap_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_wire(&mut self) -> *mut __Reply__task_wire_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_make_memory_entry(&mut self) -> *mut __Reply__mach_make_memory_entry_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_map_page_query(&mut self) -> *mut __Reply__vm_map_page_query_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_vm_region_info(&mut self) -> *mut __Reply__mach_vm_region_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_mapped_pages_info(&mut self) -> *mut __Reply__vm_mapped_pages_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_region_recurse(&mut self) -> *mut __Reply__vm_region_recurse_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_region_recurse_64(&mut self) -> *mut __Reply__vm_region_recurse_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_vm_region_info_64(&mut self) -> *mut __Reply__mach_vm_region_info_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_region_64(&mut self) -> *mut __Reply__vm_region_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_make_memory_entry_64(&mut self) -> *mut __Reply__mach_make_memory_entry_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_map_64(&mut self) -> *mut __Reply__vm_map_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_vm_purgable_control(&mut self) -> *mut __Reply__vm_purgable_control_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__vm_map_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__vm_map_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed358 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed358 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed358 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_names_t = Struct_Unnamed358; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed359 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed359 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed359 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_type_t = Struct_Unnamed359; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed360 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub old_name: mach_port_name_t, pub new_name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed360 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed360 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_rename_t = Struct_Unnamed360; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed361 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub right: mach_port_right_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed361 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed361 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_allocate_name_t = Struct_Unnamed361; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed362 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub right: mach_port_right_t, } impl ::std::clone::Clone for Struct_Unnamed362 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed362 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_allocate_t = Struct_Unnamed362; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed363 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed363 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed363 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_destroy_t = Struct_Unnamed363; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed364 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed364 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed364 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_deallocate_t = Struct_Unnamed364; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed365 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub right: mach_port_right_t, } impl ::std::clone::Clone for Struct_Unnamed365 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed365 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_get_refs_t = Struct_Unnamed365; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed366 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub right: mach_port_right_t, pub delta: mach_port_delta_t, } impl ::std::clone::Clone for Struct_Unnamed366 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed366 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_mod_refs_t = Struct_Unnamed366; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed367 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub trailer_type: mach_msg_trailer_type_t, pub request_seqnop: mach_port_seqno_t, pub trailer_infopCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed367 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed367 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_peek_t = Struct_Unnamed367; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed368 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub mscount: mach_port_mscount_t, } impl ::std::clone::Clone for Struct_Unnamed368 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed368 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_set_mscount_t = Struct_Unnamed368; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed369 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed369 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed369 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_get_set_status_t = Struct_Unnamed369; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed370 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub member: mach_port_name_t, pub after: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed370 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed370 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_move_member_t = Struct_Unnamed370; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed371 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub notify: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub msgid: mach_msg_id_t, pub sync: mach_port_mscount_t, } impl ::std::clone::Clone for Struct_Unnamed371 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed371 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_request_notification_t = Struct_Unnamed371; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed372 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub poly: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed372 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed372 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_insert_right_t = Struct_Unnamed372; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed373 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub msgt_name: mach_msg_type_name_t, } impl ::std::clone::Clone for Struct_Unnamed373 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed373 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_extract_right_t = Struct_Unnamed373; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed374 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub seqno: mach_port_seqno_t, } impl ::std::clone::Clone for Struct_Unnamed374 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed374 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_set_seqno_t = Struct_Unnamed374; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed375 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub flavor: mach_port_flavor_t, pub port_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed375 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed375 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_get_attributes_t = Struct_Unnamed375; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed376 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub flavor: mach_port_flavor_t, pub port_infoCnt: mach_msg_type_number_t, pub port_info: [integer_t; 17usize], } impl ::std::clone::Clone for Struct_Unnamed376 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed376 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_set_attributes_t = Struct_Unnamed376; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed377 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub right: mach_port_right_t, pub qos: mach_port_qos_t, } impl ::std::clone::Clone for Struct_Unnamed377 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed377 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_allocate_qos_t = Struct_Unnamed377; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed378 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub proto: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub right: mach_port_right_t, pub qos: mach_port_qos_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed378 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed378 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_allocate_full_t = Struct_Unnamed378; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed379 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub table_entries: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed379 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed379 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__task_set_port_space_t = Struct_Unnamed379; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed380 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed380 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed380 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_get_srights_t = Struct_Unnamed380; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed381 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed381 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed381 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_space_info_t = Struct_Unnamed381; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed382 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed382 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed382 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_dnrequest_info_t = Struct_Unnamed382; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed383 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed383 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed383 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_kernel_object_t = Struct_Unnamed383; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed384 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub pset: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed384 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed384 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_insert_member_t = Struct_Unnamed384; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed385 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub pset: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed385 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed385 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_extract_member_t = Struct_Unnamed385; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed386 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed386 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed386 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_get_context_t = Struct_Unnamed386; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed387 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub context: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed387 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed387 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_set_context_t = Struct_Unnamed387; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed388 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed388 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed388 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_kobject_t = Struct_Unnamed388; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed389 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub options: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub context: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed389 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed389 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_construct_t = Struct_Unnamed389; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed390 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub srdelta: mach_port_delta_t, pub guard: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed390 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed390 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_destruct_t = Struct_Unnamed390; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed391 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub guard: mach_port_context_t, pub strict: boolean_t, } impl ::std::clone::Clone for Struct_Unnamed391 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed391 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_guard_t = Struct_Unnamed391; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed392 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub name: mach_port_name_t, pub guard: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed392 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed392 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_unguard_t = Struct_Unnamed392; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed393 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed393 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed393 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_port_space_basic_info_t = Struct_Unnamed393; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__mach_port_subsystem { pub _bindgen_data_: [u32; 28usize], } impl Union___RequestUnion__mach_port_subsystem { pub unsafe fn Request_mach_port_names(&mut self) -> *mut __Request__mach_port_names_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_type(&mut self) -> *mut __Request__mach_port_type_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_rename(&mut self) -> *mut __Request__mach_port_rename_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_allocate_name(&mut self) -> *mut __Request__mach_port_allocate_name_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_allocate(&mut self) -> *mut __Request__mach_port_allocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_destroy(&mut self) -> *mut __Request__mach_port_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_deallocate(&mut self) -> *mut __Request__mach_port_deallocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_get_refs(&mut self) -> *mut __Request__mach_port_get_refs_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_mod_refs(&mut self) -> *mut __Request__mach_port_mod_refs_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_peek(&mut self) -> *mut __Request__mach_port_peek_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_set_mscount(&mut self) -> *mut __Request__mach_port_set_mscount_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_get_set_status(&mut self) -> *mut __Request__mach_port_get_set_status_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_move_member(&mut self) -> *mut __Request__mach_port_move_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_request_notification(&mut self) -> *mut __Request__mach_port_request_notification_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_insert_right(&mut self) -> *mut __Request__mach_port_insert_right_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_extract_right(&mut self) -> *mut __Request__mach_port_extract_right_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_set_seqno(&mut self) -> *mut __Request__mach_port_set_seqno_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_get_attributes(&mut self) -> *mut __Request__mach_port_get_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_set_attributes(&mut self) -> *mut __Request__mach_port_set_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_allocate_qos(&mut self) -> *mut __Request__mach_port_allocate_qos_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_allocate_full(&mut self) -> *mut __Request__mach_port_allocate_full_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_task_set_port_space(&mut self) -> *mut __Request__task_set_port_space_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_get_srights(&mut self) -> *mut __Request__mach_port_get_srights_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_space_info(&mut self) -> *mut __Request__mach_port_space_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_dnrequest_info(&mut self) -> *mut __Request__mach_port_dnrequest_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_kernel_object(&mut self) -> *mut __Request__mach_port_kernel_object_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_insert_member(&mut self) -> *mut __Request__mach_port_insert_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_extract_member(&mut self) -> *mut __Request__mach_port_extract_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_get_context(&mut self) -> *mut __Request__mach_port_get_context_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_set_context(&mut self) -> *mut __Request__mach_port_set_context_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_kobject(&mut self) -> *mut __Request__mach_port_kobject_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_construct(&mut self) -> *mut __Request__mach_port_construct_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_destruct(&mut self) -> *mut __Request__mach_port_destruct_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_guard(&mut self) -> *mut __Request__mach_port_guard_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_unguard(&mut self) -> *mut __Request__mach_port_unguard_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_port_space_basic_info(&mut self) -> *mut __Request__mach_port_space_basic_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__mach_port_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__mach_port_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed394 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub names: mach_msg_ool_descriptor_t, pub types: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub namesCnt: mach_msg_type_number_t, pub typesCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed394 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed394 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_names_t = Struct_Unnamed394; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed395 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub ptype: mach_port_type_t, } impl ::std::clone::Clone for Struct_Unnamed395 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed395 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_type_t = Struct_Unnamed395; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed396 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed396 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed396 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_rename_t = Struct_Unnamed396; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed397 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed397 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed397 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_allocate_name_t = Struct_Unnamed397; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed398 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed398 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed398 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_allocate_t = Struct_Unnamed398; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed399 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed399 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed399 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_destroy_t = Struct_Unnamed399; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed400 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed400 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed400 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_deallocate_t = Struct_Unnamed400; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed401 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub refs: mach_port_urefs_t, } impl ::std::clone::Clone for Struct_Unnamed401 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed401 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_get_refs_t = Struct_Unnamed401; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed402 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed402 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed402 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_mod_refs_t = Struct_Unnamed402; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed403 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub request_seqnop: mach_port_seqno_t, pub msg_sizep: mach_msg_size_t, pub msg_idp: mach_msg_id_t, pub trailer_infopCnt: mach_msg_type_number_t, pub trailer_infop: [::std::os::raw::c_char; 68usize], } impl ::std::clone::Clone for Struct_Unnamed403 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed403 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_peek_t = Struct_Unnamed403; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed404 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed404 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed404 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_set_mscount_t = Struct_Unnamed404; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed405 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub members: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub membersCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed405 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed405 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_get_set_status_t = Struct_Unnamed405; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed406 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed406 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed406 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_move_member_t = Struct_Unnamed406; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed407 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub previous: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed407 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed407 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_request_notification_t = Struct_Unnamed407; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed408 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed408 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed408 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_insert_right_t = Struct_Unnamed408; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed409 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub poly: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed409 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed409 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_extract_right_t = Struct_Unnamed409; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed410 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed410 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed410 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_set_seqno_t = Struct_Unnamed410; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed411 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub port_info_outCnt: mach_msg_type_number_t, pub port_info_out: [integer_t; 17usize], } impl ::std::clone::Clone for Struct_Unnamed411 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed411 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_get_attributes_t = Struct_Unnamed411; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed412 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed412 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed412 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_set_attributes_t = Struct_Unnamed412; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed413 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub qos: mach_port_qos_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed413 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed413 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_allocate_qos_t = Struct_Unnamed413; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed414 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub qos: mach_port_qos_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed414 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed414 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_allocate_full_t = Struct_Unnamed414; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed415 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed415 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed415 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__task_set_port_space_t = Struct_Unnamed415; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed416 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub srights: mach_port_rights_t, } impl ::std::clone::Clone for Struct_Unnamed416 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed416 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_get_srights_t = Struct_Unnamed416; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed417 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub table_info: mach_msg_ool_descriptor_t, pub tree_info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub space_info: ipc_info_space_t, pub table_infoCnt: mach_msg_type_number_t, pub tree_infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed417 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed417 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_space_info_t = Struct_Unnamed417; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed418 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub dnr_total: ::std::os::raw::c_uint, pub dnr_used: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_Unnamed418 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed418 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_dnrequest_info_t = Struct_Unnamed418; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed419 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub object_type: ::std::os::raw::c_uint, pub object_addr: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_Unnamed419 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed419 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_kernel_object_t = Struct_Unnamed419; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed420 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed420 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed420 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_insert_member_t = Struct_Unnamed420; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed421 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed421 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed421 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_extract_member_t = Struct_Unnamed421; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed422 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub context: mach_port_context_t, } impl ::std::clone::Clone for Struct_Unnamed422 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed422 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_get_context_t = Struct_Unnamed422; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed423 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed423 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed423 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_set_context_t = Struct_Unnamed423; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed424 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub object_type: natural_t, pub object_addr: mach_vm_address_t, } impl ::std::clone::Clone for Struct_Unnamed424 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed424 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_kobject_t = Struct_Unnamed424; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed425 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub name: mach_port_name_t, } impl ::std::clone::Clone for Struct_Unnamed425 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed425 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_construct_t = Struct_Unnamed425; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed426 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed426 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed426 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_destruct_t = Struct_Unnamed426; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed427 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed427 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed427 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_guard_t = Struct_Unnamed427; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed428 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed428 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed428 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_unguard_t = Struct_Unnamed428; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed429 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub basic_info: ipc_info_space_basic_t, } impl ::std::clone::Clone for Struct_Unnamed429 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed429 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_port_space_basic_info_t = Struct_Unnamed429; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__mach_port_subsystem { pub _bindgen_data_: [u32; 30usize], } impl Union___ReplyUnion__mach_port_subsystem { pub unsafe fn Reply_mach_port_names(&mut self) -> *mut __Reply__mach_port_names_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_type(&mut self) -> *mut __Reply__mach_port_type_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_rename(&mut self) -> *mut __Reply__mach_port_rename_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_allocate_name(&mut self) -> *mut __Reply__mach_port_allocate_name_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_allocate(&mut self) -> *mut __Reply__mach_port_allocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_destroy(&mut self) -> *mut __Reply__mach_port_destroy_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_deallocate(&mut self) -> *mut __Reply__mach_port_deallocate_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_get_refs(&mut self) -> *mut __Reply__mach_port_get_refs_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_mod_refs(&mut self) -> *mut __Reply__mach_port_mod_refs_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_peek(&mut self) -> *mut __Reply__mach_port_peek_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_set_mscount(&mut self) -> *mut __Reply__mach_port_set_mscount_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_get_set_status(&mut self) -> *mut __Reply__mach_port_get_set_status_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_move_member(&mut self) -> *mut __Reply__mach_port_move_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_request_notification(&mut self) -> *mut __Reply__mach_port_request_notification_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_insert_right(&mut self) -> *mut __Reply__mach_port_insert_right_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_extract_right(&mut self) -> *mut __Reply__mach_port_extract_right_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_set_seqno(&mut self) -> *mut __Reply__mach_port_set_seqno_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_get_attributes(&mut self) -> *mut __Reply__mach_port_get_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_set_attributes(&mut self) -> *mut __Reply__mach_port_set_attributes_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_allocate_qos(&mut self) -> *mut __Reply__mach_port_allocate_qos_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_allocate_full(&mut self) -> *mut __Reply__mach_port_allocate_full_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_task_set_port_space(&mut self) -> *mut __Reply__task_set_port_space_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_get_srights(&mut self) -> *mut __Reply__mach_port_get_srights_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_space_info(&mut self) -> *mut __Reply__mach_port_space_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_dnrequest_info(&mut self) -> *mut __Reply__mach_port_dnrequest_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_kernel_object(&mut self) -> *mut __Reply__mach_port_kernel_object_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_insert_member(&mut self) -> *mut __Reply__mach_port_insert_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_extract_member(&mut self) -> *mut __Reply__mach_port_extract_member_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_get_context(&mut self) -> *mut __Reply__mach_port_get_context_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_set_context(&mut self) -> *mut __Reply__mach_port_set_context_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_kobject(&mut self) -> *mut __Reply__mach_port_kobject_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_construct(&mut self) -> *mut __Reply__mach_port_construct_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_destruct(&mut self) -> *mut __Reply__mach_port_destruct_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_guard(&mut self) -> *mut __Reply__mach_port_guard_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_unguard(&mut self) -> *mut __Reply__mach_port_unguard_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_port_space_basic_info(&mut self) -> *mut __Reply__mach_port_space_basic_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__mach_port_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__mach_port_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed430 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: host_flavor_t, pub host_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed430 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed430 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_info_t = Struct_Unnamed430; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed431 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed431 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed431 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_kernel_version_t = Struct_Unnamed431; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed432 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed432 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed432 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request___host_page_size_t = Struct_Unnamed432; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed433 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub pager: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub internal: boolean_t, pub size: vm_size_t, pub permission: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed433 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed433 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_memory_object_memory_entry_t = Struct_Unnamed433; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed434 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: processor_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed434 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed434 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_processor_info_t = Struct_Unnamed434; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed435 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed435 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed435 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_io_master_t = Struct_Unnamed435; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed436 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub clock_id: clock_id_t, } impl ::std::clone::Clone for Struct_Unnamed436 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed436 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_clock_service_t = Struct_Unnamed436; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed437 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed437 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed437 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__kmod_get_info_t = Struct_Unnamed437; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed438 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed438 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed438 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_zone_info_t = Struct_Unnamed438; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed439 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed439 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed439 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_virtual_physical_table_info_t = Struct_Unnamed439; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed440 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed440 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed440 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_default_t = Struct_Unnamed440; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed441 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed441 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed441 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__processor_set_create_t = Struct_Unnamed441; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed442 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub pager: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub internal: boolean_t, pub size: memory_object_size_t, pub permission: vm_prot_t, } impl ::std::clone::Clone for Struct_Unnamed442 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed442 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_memory_object_memory_entry_64_t = Struct_Unnamed442; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed443 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: host_flavor_t, pub host_info_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed443 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed443 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_statistics_t = Struct_Unnamed443; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed444 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub notify_port: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub notify_type: host_flavor_t, } impl ::std::clone::Clone for Struct_Unnamed444 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed444 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_request_notification_t = Struct_Unnamed444; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed445 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed445 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed445 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_lockgroup_info_t = Struct_Unnamed445; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed446 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub flavor: host_flavor_t, pub host_info64_outCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed446 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed446 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_statistics64_t = Struct_Unnamed446; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed447 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed447 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed447 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_zone_info_t = Struct_Unnamed447; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed448 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub recipesCnt: mach_msg_type_number_t, pub recipes: [uint8_t; 5120usize], } impl ::std::clone::Clone for Struct_Unnamed448 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed448 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_create_mach_voucher_t = Struct_Unnamed448; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed449 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub attr_manager: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub default_value: mach_voucher_attr_value_handle_t, } impl ::std::clone::Clone for Struct_Unnamed449 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed449 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_register_mach_voucher_attr_manager_t = Struct_Unnamed449; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed450 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub attr_manager: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub default_value: mach_voucher_attr_value_handle_t, pub key: mach_voucher_attr_key_t, } impl ::std::clone::Clone for Struct_Unnamed450 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed450 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_register_well_known_mach_voucher_attr_manager_t = Struct_Unnamed450; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed451 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub diagnostic_flag: uint32_t, } impl ::std::clone::Clone for Struct_Unnamed451 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed451 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_set_atm_diagnostic_flag_t = Struct_Unnamed451; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed452 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed452 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed452 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_atm_diagnostic_flag_t = Struct_Unnamed452; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed453 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed453 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed453 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__mach_memory_info_t = Struct_Unnamed453; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed454 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub multiuser_flags: uint32_t, } impl ::std::clone::Clone for Struct_Unnamed454 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed454 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_set_multiuser_config_flags_t = Struct_Unnamed454; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed455 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed455 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed455 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_get_multiuser_config_flags_t = Struct_Unnamed455; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed456 { pub Head: mach_msg_header_t, } impl ::std::clone::Clone for Struct_Unnamed456 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed456 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Request__host_check_multiuser_mode_t = Struct_Unnamed456; #[repr(C)] #[derive(Copy)] pub struct Union___RequestUnion__mach_host_subsystem { pub _bindgen_data_: [u32; 1289usize], } impl Union___RequestUnion__mach_host_subsystem { pub unsafe fn Request_host_info(&mut self) -> *mut __Request__host_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_kernel_version(&mut self) -> *mut __Request__host_kernel_version_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request__host_page_size(&mut self) -> *mut __Request___host_page_size_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_memory_object_memory_entry(&mut self) -> *mut __Request__mach_memory_object_memory_entry_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_processor_info(&mut self) -> *mut __Request__host_processor_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_io_master(&mut self) -> *mut __Request__host_get_io_master_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_clock_service(&mut self) -> *mut __Request__host_get_clock_service_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_kmod_get_info(&mut self) -> *mut __Request__kmod_get_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_zone_info(&mut self) -> *mut __Request__host_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_virtual_physical_table_info(&mut self) -> *mut __Request__host_virtual_physical_table_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_default(&mut self) -> *mut __Request__processor_set_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_processor_set_create(&mut self) -> *mut __Request__processor_set_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_memory_object_memory_entry_64(&mut self) -> *mut __Request__mach_memory_object_memory_entry_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_statistics(&mut self) -> *mut __Request__host_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_request_notification(&mut self) -> *mut __Request__host_request_notification_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_lockgroup_info(&mut self) -> *mut __Request__host_lockgroup_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_statistics64(&mut self) -> *mut __Request__host_statistics64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_zone_info(&mut self) -> *mut __Request__mach_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_create_mach_voucher(&mut self) -> *mut __Request__host_create_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_register_mach_voucher_attr_manager(&mut self) -> *mut __Request__host_register_mach_voucher_attr_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_register_well_known_mach_voucher_attr_manager(&mut self) -> *mut __Request__host_register_well_known_mach_voucher_attr_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_set_atm_diagnostic_flag(&mut self) -> *mut __Request__host_set_atm_diagnostic_flag_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_atm_diagnostic_flag(&mut self) -> *mut __Request__host_get_atm_diagnostic_flag_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_mach_memory_info(&mut self) -> *mut __Request__mach_memory_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_set_multiuser_config_flags(&mut self) -> *mut __Request__host_set_multiuser_config_flags_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_get_multiuser_config_flags(&mut self) -> *mut __Request__host_get_multiuser_config_flags_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Request_host_check_multiuser_mode(&mut self) -> *mut __Request__host_check_multiuser_mode_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___RequestUnion__mach_host_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___RequestUnion__mach_host_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed457 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub host_info_outCnt: mach_msg_type_number_t, pub host_info_out: [integer_t; 68usize], } impl ::std::clone::Clone for Struct_Unnamed457 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed457 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_info_t = Struct_Unnamed457; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed458 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub kernel_versionOffset: mach_msg_type_number_t, pub kernel_versionCnt: mach_msg_type_number_t, pub kernel_version: [::std::os::raw::c_char; 512usize], } impl ::std::clone::Clone for Struct_Unnamed458 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed458 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_kernel_version_t = Struct_Unnamed458; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed459 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub out_page_size: vm_size_t, } impl ::std::clone::Clone for Struct_Unnamed459 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed459 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply___host_page_size_t = Struct_Unnamed459; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed460 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub entry_handle: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed460 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed460 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_memory_object_memory_entry_t = Struct_Unnamed460; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed461 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub out_processor_info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub out_processor_count: natural_t, pub out_processor_infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed461 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed461 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_processor_info_t = Struct_Unnamed461; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed462 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub io_master: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed462 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed462 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_io_master_t = Struct_Unnamed462; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed463 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub clock_serv: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed463 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed463 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_clock_service_t = Struct_Unnamed463; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed464 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub modules: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub modulesCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed464 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed464 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__kmod_get_info_t = Struct_Unnamed464; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed465 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub names: mach_msg_ool_descriptor_t, pub info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub namesCnt: mach_msg_type_number_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed465 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed465 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_zone_info_t = Struct_Unnamed465; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed466 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed466 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed466 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_virtual_physical_table_info_t = Struct_Unnamed466; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed467 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub default_set: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed467 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed467 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_default_t = Struct_Unnamed467; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed468 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_set: mach_msg_port_descriptor_t, pub new_name: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed468 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed468 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__processor_set_create_t = Struct_Unnamed468; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed469 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub entry_handle: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed469 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed469 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_memory_object_memory_entry_64_t = Struct_Unnamed469; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed470 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub host_info_outCnt: mach_msg_type_number_t, pub host_info_out: [integer_t; 68usize], } impl ::std::clone::Clone for Struct_Unnamed470 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed470 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_statistics_t = Struct_Unnamed470; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed471 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed471 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed471 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_request_notification_t = Struct_Unnamed471; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed472 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub lockgroup_info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub lockgroup_infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed472 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed472 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_lockgroup_info_t = Struct_Unnamed472; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed473 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub host_info64_outCnt: mach_msg_type_number_t, pub host_info64_out: [integer_t; 256usize], } impl ::std::clone::Clone for Struct_Unnamed473 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed473 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_statistics64_t = Struct_Unnamed473; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed474 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub names: mach_msg_ool_descriptor_t, pub info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub namesCnt: mach_msg_type_number_t, pub infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed474 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed474 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_zone_info_t = Struct_Unnamed474; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed475 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub voucher: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed475 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed475 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_create_mach_voucher_t = Struct_Unnamed475; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed476 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_attr_control: mach_msg_port_descriptor_t, pub NDR: NDR_record_t, pub new_key: mach_voucher_attr_key_t, } impl ::std::clone::Clone for Struct_Unnamed476 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed476 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_register_mach_voucher_attr_manager_t = Struct_Unnamed476; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed477 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub new_attr_control: mach_msg_port_descriptor_t, } impl ::std::clone::Clone for Struct_Unnamed477 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed477 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_register_well_known_mach_voucher_attr_manager_t = Struct_Unnamed477; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed478 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed478 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed478 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_set_atm_diagnostic_flag_t = Struct_Unnamed478; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed479 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub diagnostic_flag: uint32_t, } impl ::std::clone::Clone for Struct_Unnamed479 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed479 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_atm_diagnostic_flag_t = Struct_Unnamed479; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed480 { pub Head: mach_msg_header_t, pub msgh_body: mach_msg_body_t, pub names: mach_msg_ool_descriptor_t, pub info: mach_msg_ool_descriptor_t, pub memory_info: mach_msg_ool_descriptor_t, pub NDR: NDR_record_t, pub namesCnt: mach_msg_type_number_t, pub infoCnt: mach_msg_type_number_t, pub memory_infoCnt: mach_msg_type_number_t, } impl ::std::clone::Clone for Struct_Unnamed480 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed480 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__mach_memory_info_t = Struct_Unnamed480; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed481 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, } impl ::std::clone::Clone for Struct_Unnamed481 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed481 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_set_multiuser_config_flags_t = Struct_Unnamed481; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed482 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub multiuser_flags: uint32_t, } impl ::std::clone::Clone for Struct_Unnamed482 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed482 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_get_multiuser_config_flags_t = Struct_Unnamed482; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed483 { pub Head: mach_msg_header_t, pub NDR: NDR_record_t, pub RetCode: kern_return_t, pub multiuser_mode: uint32_t, } impl ::std::clone::Clone for Struct_Unnamed483 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed483 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type __Reply__host_check_multiuser_mode_t = Struct_Unnamed483; #[repr(C)] #[derive(Copy)] pub struct Union___ReplyUnion__mach_host_subsystem { pub _bindgen_data_: [u32; 266usize], } impl Union___ReplyUnion__mach_host_subsystem { pub unsafe fn Reply_host_info(&mut self) -> *mut __Reply__host_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_kernel_version(&mut self) -> *mut __Reply__host_kernel_version_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply__host_page_size(&mut self) -> *mut __Reply___host_page_size_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_memory_object_memory_entry(&mut self) -> *mut __Reply__mach_memory_object_memory_entry_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_processor_info(&mut self) -> *mut __Reply__host_processor_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_io_master(&mut self) -> *mut __Reply__host_get_io_master_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_clock_service(&mut self) -> *mut __Reply__host_get_clock_service_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_kmod_get_info(&mut self) -> *mut __Reply__kmod_get_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_zone_info(&mut self) -> *mut __Reply__host_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_virtual_physical_table_info(&mut self) -> *mut __Reply__host_virtual_physical_table_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_default(&mut self) -> *mut __Reply__processor_set_default_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_processor_set_create(&mut self) -> *mut __Reply__processor_set_create_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_memory_object_memory_entry_64(&mut self) -> *mut __Reply__mach_memory_object_memory_entry_64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_statistics(&mut self) -> *mut __Reply__host_statistics_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_request_notification(&mut self) -> *mut __Reply__host_request_notification_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_lockgroup_info(&mut self) -> *mut __Reply__host_lockgroup_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_statistics64(&mut self) -> *mut __Reply__host_statistics64_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_zone_info(&mut self) -> *mut __Reply__mach_zone_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_create_mach_voucher(&mut self) -> *mut __Reply__host_create_mach_voucher_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_register_mach_voucher_attr_manager(&mut self) -> *mut __Reply__host_register_mach_voucher_attr_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_register_well_known_mach_voucher_attr_manager(&mut self) -> *mut __Reply__host_register_well_known_mach_voucher_attr_manager_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_set_atm_diagnostic_flag(&mut self) -> *mut __Reply__host_set_atm_diagnostic_flag_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_atm_diagnostic_flag(&mut self) -> *mut __Reply__host_get_atm_diagnostic_flag_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_mach_memory_info(&mut self) -> *mut __Reply__mach_memory_info_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_set_multiuser_config_flags(&mut self) -> *mut __Reply__host_set_multiuser_config_flags_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_get_multiuser_config_flags(&mut self) -> *mut __Reply__host_get_multiuser_config_flags_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn Reply_host_check_multiuser_mode(&mut self) -> *mut __Reply__host_check_multiuser_mode_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union___ReplyUnion__mach_host_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union___ReplyUnion__mach_host_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type routine_arg_type = ::std::os::raw::c_uint; pub type routine_arg_offset = ::std::os::raw::c_uint; pub type routine_arg_size = ::std::os::raw::c_uint; #[repr(C)] #[derive(Copy)] pub struct Struct_rpc_routine_arg_descriptor { pub _type: routine_arg_type, pub size: routine_arg_size, pub count: routine_arg_size, pub offset: routine_arg_offset, } impl ::std::clone::Clone for Struct_rpc_routine_arg_descriptor { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rpc_routine_arg_descriptor { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rpc_routine_arg_descriptor_t = *mut Struct_rpc_routine_arg_descriptor; #[repr(C)] #[derive(Copy)] pub struct Struct_rpc_routine_descriptor { pub impl_routine: mig_impl_routine_t, pub stub_routine: mig_stub_routine_t, pub argc: ::std::os::raw::c_uint, pub descr_count: ::std::os::raw::c_uint, pub arg_descr: rpc_routine_arg_descriptor_t, pub max_reply_msg: ::std::os::raw::c_uint, } impl ::std::clone::Clone for Struct_rpc_routine_descriptor { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rpc_routine_descriptor { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rpc_routine_descriptor_t = *mut Struct_rpc_routine_descriptor; #[repr(C)] #[derive(Copy)] pub struct Struct_rpc_signature { pub rd: Struct_rpc_routine_descriptor, pub rad: [Struct_rpc_routine_arg_descriptor; 1usize], } impl ::std::clone::Clone for Struct_rpc_signature { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rpc_signature { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rpc_subsystem { pub reserved: *mut ::std::os::raw::c_void, pub start: mach_msg_id_t, pub end: mach_msg_id_t, pub maxsize: ::std::os::raw::c_uint, pub base_addr: vm_address_t, pub routine: [Struct_rpc_routine_descriptor; 1usize], pub arg_descriptor: [Struct_rpc_routine_arg_descriptor; 1usize], } impl ::std::clone::Clone for Struct_rpc_subsystem { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rpc_subsystem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type rpc_subsystem_t = *mut Struct_rpc_subsystem; pub type mach_error_t = kern_return_t; pub type mach_error_fn_t = ::std::option::Option<extern "C" fn() -> mach_error_t>; pub enum Struct_voucher_mach_msg_state_s { } pub type voucher_mach_msg_state_t = *mut Struct_voucher_mach_msg_state_s; pub enum Struct_mach_header_64 { } pub type byte = ::std::os::raw::c_uchar; pub type dbyte = ::std::os::raw::c_ushort; pub type qbyte = ::std::os::raw::c_uint; pub type inaddr_t = Struct_sockaddr_in; pub type in6addr_t = Struct_sockaddr_in6; #[repr(C)] #[derive(Copy)] pub struct Struct_Unnamed484 { pub __inaddr_u: Union_Unnamed485, pub inaddrlen: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_Unnamed484 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_Unnamed484 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed485 { pub _bindgen_data_: [u32; 7usize], } impl Union_Unnamed485 { pub unsafe fn __addr(&mut self) -> *mut inaddr_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn __addr6(&mut self) -> *mut in6addr_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed485 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed485 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type inaddr_storage_t = Struct_Unnamed484; pub type ulong = ::std::os::raw::c_ulong; pub type SOCKET = ::std::os::raw::c_int; #[repr(C)] #[derive(Copy)] pub struct Struct_net_event_data { pub if_family: u_int32_t, pub if_unit: u_int32_t, pub if_name: [::std::os::raw::c_char; 16usize], } impl ::std::clone::Clone for Struct_net_event_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_net_event_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_timeval32 { pub tv_sec: __int32_t, pub tv_usec: __int32_t, } impl ::std::clone::Clone for Struct_timeval32 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_timeval32 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_data { pub ifi_type: u_char, pub ifi_typelen: u_char, pub ifi_physical: u_char, pub ifi_addrlen: u_char, pub ifi_hdrlen: u_char, pub ifi_recvquota: u_char, pub ifi_xmitquota: u_char, pub ifi_unused1: u_char, pub ifi_mtu: u_int32_t, pub ifi_metric: u_int32_t, pub ifi_baudrate: u_int32_t, pub ifi_ipackets: u_int32_t, pub ifi_ierrors: u_int32_t, pub ifi_opackets: u_int32_t, pub ifi_oerrors: u_int32_t, pub ifi_collisions: u_int32_t, pub ifi_ibytes: u_int32_t, pub ifi_obytes: u_int32_t, pub ifi_imcasts: u_int32_t, pub ifi_omcasts: u_int32_t, pub ifi_iqdrops: u_int32_t, pub ifi_noproto: u_int32_t, pub ifi_recvtiming: u_int32_t, pub ifi_xmittiming: u_int32_t, pub ifi_lastchange: Struct_timeval32, pub ifi_unused2: u_int32_t, pub ifi_hwassist: u_int32_t, pub ifi_reserved1: u_int32_t, pub ifi_reserved2: u_int32_t, } impl ::std::clone::Clone for Struct_if_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_data64 { pub ifi_type: u_char, pub ifi_typelen: u_char, pub ifi_physical: u_char, pub ifi_addrlen: u_char, pub ifi_hdrlen: u_char, pub ifi_recvquota: u_char, pub ifi_xmitquota: u_char, pub ifi_unused1: u_char, pub ifi_mtu: u_int32_t, pub ifi_metric: u_int32_t, pub ifi_baudrate: u_int64_t, pub ifi_ipackets: u_int64_t, pub ifi_ierrors: u_int64_t, pub ifi_opackets: u_int64_t, pub ifi_oerrors: u_int64_t, pub ifi_collisions: u_int64_t, pub ifi_ibytes: u_int64_t, pub ifi_obytes: u_int64_t, pub ifi_imcasts: u_int64_t, pub ifi_omcasts: u_int64_t, pub ifi_iqdrops: u_int64_t, pub ifi_noproto: u_int64_t, pub ifi_recvtiming: u_int32_t, pub ifi_xmittiming: u_int32_t, pub ifi_lastchange: Struct_timeval32, } impl ::std::clone::Clone for Struct_if_data64 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_data64 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifqueue { pub ifq_head: *mut ::std::os::raw::c_void, pub ifq_tail: *mut ::std::os::raw::c_void, pub ifq_len: ::std::os::raw::c_int, pub ifq_maxlen: ::std::os::raw::c_int, pub ifq_drops: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_ifqueue { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifqueue { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_clonereq { pub ifcr_total: ::std::os::raw::c_int, pub ifcr_count: ::std::os::raw::c_int, pub ifcr_buffer: *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_if_clonereq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_clonereq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_msghdr { pub ifm_msglen: ::std::os::raw::c_ushort, pub ifm_version: ::std::os::raw::c_uchar, pub ifm_type: ::std::os::raw::c_uchar, pub ifm_addrs: ::std::os::raw::c_int, pub ifm_flags: ::std::os::raw::c_int, pub ifm_index: ::std::os::raw::c_ushort, pub ifm_data: Struct_if_data, } impl ::std::clone::Clone for Struct_if_msghdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_msghdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifa_msghdr { pub ifam_msglen: ::std::os::raw::c_ushort, pub ifam_version: ::std::os::raw::c_uchar, pub ifam_type: ::std::os::raw::c_uchar, pub ifam_addrs: ::std::os::raw::c_int, pub ifam_flags: ::std::os::raw::c_int, pub ifam_index: ::std::os::raw::c_ushort, pub ifam_metric: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_ifa_msghdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifa_msghdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifma_msghdr { pub ifmam_msglen: ::std::os::raw::c_ushort, pub ifmam_version: ::std::os::raw::c_uchar, pub ifmam_type: ::std::os::raw::c_uchar, pub ifmam_addrs: ::std::os::raw::c_int, pub ifmam_flags: ::std::os::raw::c_int, pub ifmam_index: ::std::os::raw::c_ushort, } impl ::std::clone::Clone for Struct_ifma_msghdr { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifma_msghdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_msghdr2 { pub ifm_msglen: u_short, pub ifm_version: u_char, pub ifm_type: u_char, pub ifm_addrs: ::std::os::raw::c_int, pub ifm_flags: ::std::os::raw::c_int, pub ifm_index: u_short, pub ifm_snd_len: ::std::os::raw::c_int, pub ifm_snd_maxlen: ::std::os::raw::c_int, pub ifm_snd_drops: ::std::os::raw::c_int, pub ifm_timer: ::std::os::raw::c_int, pub ifm_data: Struct_if_data64, } impl ::std::clone::Clone for Struct_if_msghdr2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_msghdr2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifma_msghdr2 { pub ifmam_msglen: u_short, pub ifmam_version: u_char, pub ifmam_type: u_char, pub ifmam_addrs: ::std::os::raw::c_int, pub ifmam_flags: ::std::os::raw::c_int, pub ifmam_index: u_short, pub ifmam_refcount: int32_t, } impl ::std::clone::Clone for Struct_ifma_msghdr2 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifma_msghdr2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifdevmtu { pub ifdm_current: ::std::os::raw::c_int, pub ifdm_min: ::std::os::raw::c_int, pub ifdm_max: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_ifdevmtu { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifdevmtu { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifkpi { pub ifk_module_id: ::std::os::raw::c_uint, pub ifk_type: ::std::os::raw::c_uint, pub ifk_data: Union_Unnamed486, } impl ::std::clone::Clone for Struct_ifkpi { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifkpi { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed486 { pub _bindgen_data_: [u32; 2usize], } impl Union_Unnamed486 { pub unsafe fn ifk_ptr(&mut self) -> *mut *mut ::std::os::raw::c_void { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifk_value(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed486 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed486 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifreq { pub ifr_name: [::std::os::raw::c_char; 16usize], pub ifr_ifru: Union_Unnamed487, } impl ::std::clone::Clone for Struct_ifreq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifreq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed487 { pub _bindgen_data_: [u64; 2usize], } impl Union_Unnamed487 { pub unsafe fn ifru_addr(&mut self) -> *mut Struct_sockaddr { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_dstaddr(&mut self) -> *mut Struct_sockaddr { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_broadaddr(&mut self) -> *mut Struct_sockaddr { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_flags(&mut self) -> *mut ::std::os::raw::c_short { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_metric(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_mtu(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_phys(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_media(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_intval(&mut self) -> *mut ::std::os::raw::c_int { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_data(&mut self) -> *mut caddr_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_devmtu(&mut self) -> *mut Struct_ifdevmtu { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_kpi(&mut self) -> *mut Struct_ifkpi { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_wake_flags(&mut self) -> *mut u_int32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_route_refcnt(&mut self) -> *mut u_int32_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifru_cap(&mut self) -> *mut [::std::os::raw::c_int; 2usize] { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed487 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed487 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifaliasreq { pub ifra_name: [::std::os::raw::c_char; 16usize], pub ifra_addr: Struct_sockaddr, pub ifra_broadaddr: Struct_sockaddr, pub ifra_mask: Struct_sockaddr, } impl ::std::clone::Clone for Struct_ifaliasreq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifaliasreq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_rslvmulti_req { pub sa: *mut Struct_sockaddr, pub llsa: *mut *mut Struct_sockaddr, } impl ::std::clone::Clone for Struct_rslvmulti_req { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_rslvmulti_req { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifmediareq { pub ifm_name: [::std::os::raw::c_char; 16usize], pub ifm_current: ::std::os::raw::c_int, pub ifm_mask: ::std::os::raw::c_int, pub ifm_status: ::std::os::raw::c_int, pub ifm_active: ::std::os::raw::c_int, pub ifm_count: ::std::os::raw::c_int, pub ifm_ulist: *mut ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct_ifmediareq { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifmediareq { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifdrv { pub ifd_name: [::std::os::raw::c_char; 16usize], pub ifd_cmd: ::std::os::raw::c_ulong, pub ifd_len: size_t, pub ifd_data: *mut ::std::os::raw::c_void, } impl ::std::clone::Clone for Struct_ifdrv { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifdrv { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifstat { pub ifs_name: [::std::os::raw::c_char; 16usize], pub ascii: [::std::os::raw::c_char; 801usize], } impl ::std::clone::Clone for Struct_ifstat { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifstat { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifconf { pub ifc_len: ::std::os::raw::c_int, pub ifc_ifcu: Union_Unnamed488, } impl ::std::clone::Clone for Struct_ifconf { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifconf { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Union_Unnamed488 { pub _bindgen_data_: [u32; 2usize], } impl Union_Unnamed488 { pub unsafe fn ifcu_buf(&mut self) -> *mut caddr_t { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn ifcu_req(&mut self) -> *mut *mut Struct_ifreq { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } } impl ::std::clone::Clone for Union_Unnamed488 { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Union_Unnamed488 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_kev_dl_proto_data { pub link_data: Struct_net_event_data, pub proto_family: u_int32_t, pub proto_remaining_count: u_int32_t, } impl ::std::clone::Clone for Struct_kev_dl_proto_data { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_kev_dl_proto_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_if_nameindex { pub if_index: ::std::os::raw::c_uint, pub if_name: *mut ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_if_nameindex { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_if_nameindex { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct_ifmedia_description { pub ifmt_word: ::std::os::raw::c_int, pub ifmt_string: *const ::std::os::raw::c_char, } impl ::std::clone::Clone for Struct_ifmedia_description { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct_ifmedia_description { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub enum Struct__zactor_t { } pub type zactor_t = Struct__zactor_t; pub enum Struct__zarmour_t { } pub type zarmour_t = Struct__zarmour_t; pub enum Struct__zcert_t { } pub type zcert_t = Struct__zcert_t; pub type zcertstore_t = Struct__zcertstore_t; pub enum Struct__zchunk_t { } pub type zchunk_t = Struct__zchunk_t; pub enum Struct__zclock_t { } pub type zclock_t = Struct__zclock_t; pub enum Struct__zconfig_t { } pub type zconfig_t = Struct__zconfig_t; pub enum Struct__zdigest_t { } pub type zdigest_t = Struct__zdigest_t; pub enum Struct__zdir_t { } pub type zdir_t = Struct__zdir_t; pub enum Struct__zdir_patch_t { } pub type zdir_patch_t = Struct__zdir_patch_t; pub enum Struct__zfile_t { } pub type zfile_t = Struct__zfile_t; pub enum Struct__zframe_t { } pub type zframe_t = Struct__zframe_t; pub enum Struct__zhash_t { } pub type zhash_t = Struct__zhash_t; pub enum Struct__zhashx_t { } pub type zhashx_t = Struct__zhashx_t; pub enum Struct__ziflist_t { } pub type ziflist_t = Struct__ziflist_t; pub enum Struct__zlist_t { } pub type zlist_t = Struct__zlist_t; pub enum Struct__zlistx_t { } pub type zlistx_t = Struct__zlistx_t; pub enum Struct__zloop_t { } pub type zloop_t = Struct__zloop_t; pub enum Struct__zmsg_t { } pub type zmsg_t = Struct__zmsg_t; pub enum Struct__zpoller_t { } pub type zpoller_t = Struct__zpoller_t; pub enum Struct__zsock_t { } pub type zsock_t = Struct__zsock_t; pub enum Struct__zstr_t { } pub type zstr_t = Struct__zstr_t; pub enum Struct__zuuid_t { } pub type zuuid_t = Struct__zuuid_t; pub enum Struct__zauth_t { } pub type zauth_t = Struct__zauth_t; pub enum Struct__zbeacon_t { } pub type zbeacon_t = Struct__zbeacon_t; pub enum Struct__zgossip_t { } pub type zgossip_t = Struct__zgossip_t; pub enum Struct__zmonitor_t { } pub type zmonitor_t = Struct__zmonitor_t; pub enum Struct__zproxy_t { } pub type zproxy_t = Struct__zproxy_t; pub enum Struct__zrex_t { } pub type zrex_t = Struct__zrex_t; pub enum Struct__zsys_t { } pub type zsys_t = Struct__zsys_t; pub enum Struct__zauth_v2_t { } pub type zauth_v2_t = Struct__zauth_v2_t; pub enum Struct__zbeacon_v2_t { } pub type zbeacon_v2_t = Struct__zbeacon_v2_t; pub enum Struct__zctx_t { } pub type zctx_t = Struct__zctx_t; pub enum Struct__zmonitor_v2_t { } pub type zmonitor_v2_t = Struct__zmonitor_v2_t; pub enum Struct__zmutex_t { } pub type zmutex_t = Struct__zmutex_t; pub enum Struct__zproxy_v2_t { } pub type zproxy_v2_t = Struct__zproxy_v2_t; pub enum Struct__zsocket_t { } pub type zsocket_t = Struct__zsocket_t; pub enum Struct__zsockopt_t { } pub type zsockopt_t = Struct__zsockopt_t; pub enum Struct__zthread_t { } pub type zthread_t = Struct__zthread_t; pub enum Struct__zproc_t { } pub type zproc_t = Struct__zproc_t; pub enum Struct__ztimerset_t { } pub type ztimerset_t = Struct__ztimerset_t; pub enum Struct__ztrie_t { } pub type ztrie_t = Struct__ztrie_t; pub type zactor_fn = unsafe extern "C" fn(pipe: *mut zsock_t, args: *mut ::std::os::raw::c_void); pub type zcertstore_loader = unsafe extern "C" fn(_self: *mut zcertstore_t); pub type zcertstore_destructor = unsafe extern "C" fn(self_p: *mut *mut ::std::os::raw::c_void); pub type zconfig_fct = unsafe extern "C" fn(_self: *mut zconfig_t, arg: *mut ::std::os::raw::c_void, level: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub type zhash_free_fn = unsafe extern "C" fn(data: *mut ::std::os::raw::c_void); pub type zhash_foreach_fn = unsafe extern "C" fn(key: *const ::std::os::raw::c_char, item: *mut ::std::os::raw::c_void, argument: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zhashx_destructor_fn = unsafe extern "C" fn(item: *mut *mut ::std::os::raw::c_void); pub type zhashx_duplicator_fn = unsafe extern "C" fn(item: *const ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub type zhashx_comparator_fn = unsafe extern "C" fn(item1: *const ::std::os::raw::c_void, item2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zhashx_free_fn = unsafe extern "C" fn(data: *mut ::std::os::raw::c_void); pub type zhashx_hash_fn = unsafe extern "C" fn(key: *const ::std::os::raw::c_void) -> ::std::os::raw::c_ulong; pub type zhashx_foreach_fn = unsafe extern "C" fn(key: *const ::std::os::raw::c_char, item: *mut ::std::os::raw::c_void, argument: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zlist_compare_fn = unsafe extern "C" fn(item1: *mut ::std::os::raw::c_void, item2: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zlist_free_fn = unsafe extern "C" fn(data: *mut ::std::os::raw::c_void); pub type zlistx_destructor_fn = unsafe extern "C" fn(item: *mut *mut ::std::os::raw::c_void); pub type zlistx_duplicator_fn = unsafe extern "C" fn(item: *const ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub type zlistx_comparator_fn = unsafe extern "C" fn(item1: *const ::std::os::raw::c_void, item2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zloop_reader_fn = unsafe extern "C" fn(_loop: *mut zloop_t, reader: *mut zsock_t, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zloop_fn = unsafe extern "C" fn(_loop: *mut zloop_t, item: *mut zmq_pollitem_t, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zloop_timer_fn = unsafe extern "C" fn(_loop: *mut zloop_t, timer_id: ::std::os::raw::c_int, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub type zsys_handler_fn = extern "C" fn(signal_value: ::std::os::raw::c_int); pub type zsocket_free_fn = unsafe extern "C" fn(data: *mut ::std::os::raw::c_void, arg: *mut ::std::os::raw::c_void); pub type zthread_detached_fn = unsafe extern "C" fn(args: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub type zthread_attached_fn = unsafe extern "C" fn(args: *mut ::std::os::raw::c_void, ctx: *mut zctx_t, pipe: *mut ::std::os::raw::c_void); pub type ztimerset_fn = unsafe extern "C" fn(timer_id: ::std::os::raw::c_int, arg: *mut ::std::os::raw::c_void); pub type ztrie_destroy_data_fn = unsafe extern "C" fn(data: *mut *mut ::std::os::raw::c_void); pub enum Struct__zgossip_msg_t { } pub type zgossip_msg_t = Struct__zgossip_msg_t; #[repr(C)] #[derive(Copy)] pub struct Struct__disk_loader_state { pub location: *mut ::std::os::raw::c_char, pub modified: time_t, pub count: size_t, pub cursize: size_t, } impl ::std::clone::Clone for Struct__disk_loader_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__disk_loader_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type disk_loader_state = Struct__disk_loader_state; #[repr(C)] #[derive(Copy)] pub struct Struct__zcertstore_t { pub loader: *mut zcertstore_loader, pub destructor: *mut zcertstore_destructor, pub state: *mut ::std::os::raw::c_void, pub certs: *mut zhashx_t, } impl ::std::clone::Clone for Struct__zcertstore_t { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__zcertstore_t { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct Struct__test_loader_state { pub index: ::std::os::raw::c_int, } impl ::std::clone::Clone for Struct__test_loader_state { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct__test_loader_state { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type test_loader_state = Struct__test_loader_state; pub type __builtin_va_list = [__va_list_tag; 1usize]; pub type __va_list_tag = Struct___va_list_tag; #[repr(C)] #[derive(Copy)] pub struct Struct___va_list_tag { pub gp_offset: ::std::os::raw::c_uint, pub fp_offset: ::std::os::raw::c_uint, pub overflow_arg_area: *mut ::std::os::raw::c_void, pub reg_save_area: *mut ::std::os::raw::c_void, } impl ::std::clone::Clone for Struct___va_list_tag { fn clone(&self) -> Self { *self } } impl ::std::default::Default for Struct___va_list_tag { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[link(name = "czmq")] extern "C" { pub static mut __stdinp: *mut FILE; pub static mut __stdoutp: *mut FILE; pub static mut __stderrp: *mut FILE; pub static sys_nerr: ::std::os::raw::c_int; pub static mut sys_errlist: *const *const ::std::os::raw::c_char; pub static mut _DefaultRuneLocale: _RuneLocale; pub static mut _CurrentRuneLocale: *mut _RuneLocale; pub static mut __mb_cur_max: ::std::os::raw::c_int; pub static mut suboptarg: *mut ::std::os::raw::c_char; pub static mut tzname: *mut *mut ::std::os::raw::c_char; pub static mut getdate_err: ::std::os::raw::c_int; pub static mut timezone: ::std::os::raw::c_long; pub static mut daylight: ::std::os::raw::c_int; pub static mut signgam: ::std::os::raw::c_int; pub static mut sys_signame: [*const ::std::os::raw::c_char; 32usize]; pub static mut sys_siglist: [*const ::std::os::raw::c_char; 32usize]; pub static in6addr_any: Struct_in6_addr; pub static in6addr_loopback: Struct_in6_addr; pub static in6addr_nodelocal_allnodes: Struct_in6_addr; pub static in6addr_linklocal_allnodes: Struct_in6_addr; pub static in6addr_linklocal_allrouters: Struct_in6_addr; pub static in6addr_linklocal_allv2routers: Struct_in6_addr; pub static mut h_errno: ::std::os::raw::c_int; pub static mut optarg: *mut ::std::os::raw::c_char; pub static mut optind: ::std::os::raw::c_int; pub static mut opterr: ::std::os::raw::c_int; pub static mut optopt: ::std::os::raw::c_int; pub static mut optreset: ::std::os::raw::c_int; pub static mut NDR_record: NDR_record_t; pub static mut KERNEL_SECURITY_TOKEN: security_token_t; pub static mut KERNEL_AUDIT_TOKEN: audit_token_t; pub static mut vm_page_size: vm_size_t; pub static mut vm_page_mask: vm_size_t; pub static mut vm_page_shift: ::std::os::raw::c_int; pub static mut vm_kernel_page_size: vm_size_t; pub static mut vm_kernel_page_mask: vm_size_t; pub static mut vm_kernel_page_shift: ::std::os::raw::c_int; pub static mut mach_task_self_: mach_port_t; pub static mut bootstrap_port: mach_port_t; pub static mut vprintf_stderr_func: ::std::option::Option<unsafe extern "C" fn(format: *const ::std::os::raw::c_char, ap: va_list) -> ::std::os::raw::c_int>; pub static mut zsys_interrupted: ::std::os::raw::c_int; pub static mut zctx_interrupted: ::std::os::raw::c_int; } #[link(name = "czmq")] extern "C" { pub fn __error() -> *mut ::std::os::raw::c_int; pub fn renameat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn clearerr(arg1: *mut FILE); pub fn fclose(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn feof(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn ferror(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn fflush(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn fgetc(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn fgetpos(arg1: *mut FILE, arg2: *mut fpos_t) -> ::std::os::raw::c_int; pub fn fgets(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *mut FILE) -> *mut ::std::os::raw::c_char; pub fn fopen(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut FILE; pub fn fprintf(arg1: *mut FILE, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn fputc(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn fputs(arg1: *const ::std::os::raw::c_char, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn fread(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: *mut FILE) -> size_t; pub fn freopen(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut FILE) -> *mut FILE; pub fn fscanf(arg1: *mut FILE, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn fseek(arg1: *mut FILE, arg2: ::std::os::raw::c_long, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn fsetpos(arg1: *mut FILE, arg2: *const fpos_t) -> ::std::os::raw::c_int; pub fn ftell(arg1: *mut FILE) -> ::std::os::raw::c_long; pub fn fwrite(arg1: *const ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: *mut FILE) -> size_t; pub fn getc(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn getchar() -> ::std::os::raw::c_int; pub fn gets(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn perror(arg1: *const ::std::os::raw::c_char); pub fn printf(arg1: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn putc(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn putchar(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn puts(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn remove(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn rename(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn rewind(arg1: *mut FILE); pub fn scanf(arg1: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn setbuf(arg1: *mut FILE, arg2: *mut ::std::os::raw::c_char); pub fn setvbuf(arg1: *mut FILE, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: size_t) -> ::std::os::raw::c_int; pub fn sprintf(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn sscanf(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn tmpfile() -> *mut FILE; pub fn tmpnam(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn ungetc(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn vfprintf(arg1: *mut FILE, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn vprintf(arg1: *const ::std::os::raw::c_char, arg2: va_list) -> ::std::os::raw::c_int; pub fn vsprintf(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn ctermid(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn fdopen(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char) -> *mut FILE; pub fn fileno(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn pclose(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn popen(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut FILE; pub fn __srget(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn __svfscanf(arg1: *mut FILE, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn __swbuf(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn __sputc(_c: ::std::os::raw::c_int, _p: *mut FILE) -> ::std::os::raw::c_int; pub fn flockfile(arg1: *mut FILE); pub fn ftrylockfile(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn funlockfile(arg1: *mut FILE); pub fn getc_unlocked(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn getchar_unlocked() -> ::std::os::raw::c_int; pub fn putc_unlocked(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn putchar_unlocked(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getw(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn putw(arg1: ::std::os::raw::c_int, arg2: *mut FILE) -> ::std::os::raw::c_int; pub fn tempnam(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn fseeko(arg1: *mut FILE, arg2: off_t, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ftello(arg1: *mut FILE) -> off_t; pub fn snprintf(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn vfscanf(arg1: *mut FILE, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn vscanf(arg1: *const ::std::os::raw::c_char, arg2: va_list) -> ::std::os::raw::c_int; pub fn vsnprintf(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: *const ::std::os::raw::c_char, arg4: va_list) -> ::std::os::raw::c_int; pub fn vsscanf(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn dprintf(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn vdprintf(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn getdelim(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut size_t, arg3: ::std::os::raw::c_int, arg4: *mut FILE) -> ssize_t; pub fn getline(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut size_t, arg3: *mut FILE) -> ssize_t; pub fn asprintf(arg1: *mut *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn ctermid_r(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn fgetln(arg1: *mut FILE, arg2: *mut size_t) -> *mut ::std::os::raw::c_char; pub fn fmtcheck(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *const ::std::os::raw::c_char; pub fn fpurge(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn setbuffer(arg1: *mut FILE, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int); pub fn setlinebuf(arg1: *mut FILE) -> ::std::os::raw::c_int; pub fn vasprintf(arg1: *mut *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: va_list) -> ::std::os::raw::c_int; pub fn zopen(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> *mut FILE; pub fn funopen(arg1: *const ::std::os::raw::c_void, arg2: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, arg3: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: fpos_t, arg3: ::std::os::raw::c_int) -> fpos_t>, arg5: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int>) -> *mut FILE; pub fn __sprintf_chk(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: size_t, arg4: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn __snprintf_chk(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: ::std::os::raw::c_int, arg4: size_t, arg5: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn __vsprintf_chk(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: size_t, arg4: *const ::std::os::raw::c_char, arg5: va_list) -> ::std::os::raw::c_int; pub fn __vsnprintf_chk(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: ::std::os::raw::c_int, arg4: size_t, arg5: *const ::std::os::raw::c_char, arg6: va_list) -> ::std::os::raw::c_int; pub fn zmq_errno() -> ::std::os::raw::c_int; pub fn zmq_strerror(errnum: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char; pub fn zmq_version(major: *mut ::std::os::raw::c_int, minor: *mut ::std::os::raw::c_int, patch: *mut ::std::os::raw::c_int); pub fn zmq_ctx_new() -> *mut ::std::os::raw::c_void; pub fn zmq_ctx_term(context: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_ctx_shutdown(ctx_: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_ctx_set(context: *mut ::std::os::raw::c_void, option: ::std::os::raw::c_int, optval: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_ctx_get(context: *mut ::std::os::raw::c_void, option: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_init(io_threads: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn zmq_term(context: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_ctx_destroy(context: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_msg_init(msg: *mut zmq_msg_t) -> ::std::os::raw::c_int; pub fn zmq_msg_init_size(msg: *mut zmq_msg_t, size: size_t) -> ::std::os::raw::c_int; pub fn zmq_msg_init_data(msg: *mut zmq_msg_t, data: *mut ::std::os::raw::c_void, size: size_t, ffn: *mut zmq_free_fn, hint: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_msg_send(msg: *mut zmq_msg_t, s: *mut ::std::os::raw::c_void, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_msg_recv(msg: *mut zmq_msg_t, s: *mut ::std::os::raw::c_void, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_msg_close(msg: *mut zmq_msg_t) -> ::std::os::raw::c_int; pub fn zmq_msg_move(dest: *mut zmq_msg_t, src: *mut zmq_msg_t) -> ::std::os::raw::c_int; pub fn zmq_msg_copy(dest: *mut zmq_msg_t, src: *mut zmq_msg_t) -> ::std::os::raw::c_int; pub fn zmq_msg_data(msg: *mut zmq_msg_t) -> *mut ::std::os::raw::c_void; pub fn zmq_msg_size(msg: *mut zmq_msg_t) -> size_t; pub fn zmq_msg_more(msg: *mut zmq_msg_t) -> ::std::os::raw::c_int; pub fn zmq_msg_get(msg: *mut zmq_msg_t, property: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_msg_set(msg: *mut zmq_msg_t, property: ::std::os::raw::c_int, optval: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_msg_gets(msg: *mut zmq_msg_t, property: *const ::std::os::raw::c_char) -> *const ::std::os::raw::c_char; pub fn zmq_socket(arg1: *mut ::std::os::raw::c_void, _type: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn zmq_close(s: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_setsockopt(s: *mut ::std::os::raw::c_void, option: ::std::os::raw::c_int, optval: *const ::std::os::raw::c_void, optvallen: size_t) -> ::std::os::raw::c_int; pub fn zmq_getsockopt(s: *mut ::std::os::raw::c_void, option: ::std::os::raw::c_int, optval: *mut ::std::os::raw::c_void, optvallen: *mut size_t) -> ::std::os::raw::c_int; pub fn zmq_bind(s: *mut ::std::os::raw::c_void, addr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_connect(s: *mut ::std::os::raw::c_void, addr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_unbind(s: *mut ::std::os::raw::c_void, addr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_disconnect(s: *mut ::std::os::raw::c_void, addr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_send(s: *mut ::std::os::raw::c_void, buf: *const ::std::os::raw::c_void, len: size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_send_const(s: *mut ::std::os::raw::c_void, buf: *const ::std::os::raw::c_void, len: size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_recv(s: *mut ::std::os::raw::c_void, buf: *mut ::std::os::raw::c_void, len: size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_socket_monitor(s: *mut ::std::os::raw::c_void, addr: *const ::std::os::raw::c_char, events: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_poll(items: *mut zmq_pollitem_t, nitems: ::std::os::raw::c_int, timeout: ::std::os::raw::c_long) -> ::std::os::raw::c_int; pub fn zmq_proxy(frontend: *mut ::std::os::raw::c_void, backend: *mut ::std::os::raw::c_void, capture: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_proxy_steerable(frontend: *mut ::std::os::raw::c_void, backend: *mut ::std::os::raw::c_void, capture: *mut ::std::os::raw::c_void, control: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_has(capability: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_device(_type: ::std::os::raw::c_int, frontend: *mut ::std::os::raw::c_void, backend: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmq_sendmsg(s: *mut ::std::os::raw::c_void, msg: *mut zmq_msg_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_recvmsg(s: *mut ::std::os::raw::c_void, msg: *mut zmq_msg_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_z85_encode(dest: *mut ::std::os::raw::c_char, data: *const uint8_t, size: size_t) -> *mut ::std::os::raw::c_char; pub fn zmq_z85_decode(dest: *mut uint8_t, string: *const ::std::os::raw::c_char) -> *mut uint8_t; pub fn zmq_curve_keypair(z85_public_key: *mut ::std::os::raw::c_char, z85_secret_key: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmq_sendiov(s: *mut ::std::os::raw::c_void, iov: *mut Struct_iovec, count: size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_recviov(s: *mut ::std::os::raw::c_void, iov: *mut Struct_iovec, count: *mut size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zmq_stopwatch_start() -> *mut ::std::os::raw::c_void; pub fn zmq_stopwatch_stop(watch_: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_ulong; pub fn zmq_sleep(seconds_: ::std::os::raw::c_int); pub fn zmq_threadstart(func: *mut zmq_thread_fn, arg: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zmq_threadclose(thread: *mut ::std::os::raw::c_void); pub fn ___runetype(arg1: __darwin_ct_rune_t) -> ::std::os::raw::c_ulong; pub fn ___tolower(arg1: __darwin_ct_rune_t) -> __darwin_ct_rune_t; pub fn ___toupper(arg1: __darwin_ct_rune_t) -> __darwin_ct_rune_t; pub fn isascii(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn __maskrune(arg1: __darwin_ct_rune_t, arg2: ::std::os::raw::c_ulong) -> ::std::os::raw::c_int; pub fn __istype(_c: __darwin_ct_rune_t, _f: ::std::os::raw::c_ulong) -> ::std::os::raw::c_int; pub fn __isctype(_c: __darwin_ct_rune_t, _f: ::std::os::raw::c_ulong) -> __darwin_ct_rune_t; pub fn __toupper(arg1: __darwin_ct_rune_t) -> __darwin_ct_rune_t; pub fn __tolower(arg1: __darwin_ct_rune_t) -> __darwin_ct_rune_t; pub fn __wcwidth(_c: __darwin_ct_rune_t) -> ::std::os::raw::c_int; pub fn isalnum(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isalpha(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isblank(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn iscntrl(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isdigit(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isgraph(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn islower(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isprint(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ispunct(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isspace(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isupper(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isxdigit(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn toascii(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn tolower(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn toupper(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn digittoint(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ishexnumber(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isideogram(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isnumber(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isphonogram(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isrune(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn isspecial(_c: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn signal(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>) -> ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>)>; pub fn getpriority(arg1: ::std::os::raw::c_int, arg2: id_t) -> ::std::os::raw::c_int; pub fn getiopolicy_np(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getrlimit(arg1: ::std::os::raw::c_int, arg2: *mut Struct_rlimit) -> ::std::os::raw::c_int; pub fn getrusage(arg1: ::std::os::raw::c_int, arg2: *mut Struct_rusage) -> ::std::os::raw::c_int; pub fn setpriority(arg1: ::std::os::raw::c_int, arg2: id_t, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setiopolicy_np(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setrlimit(arg1: ::std::os::raw::c_int, arg2: *const Struct_rlimit) -> ::std::os::raw::c_int; pub fn wait(arg1: *mut ::std::os::raw::c_int) -> pid_t; pub fn waitpid(arg1: pid_t, arg2: *mut ::std::os::raw::c_int, arg3: ::std::os::raw::c_int) -> pid_t; pub fn waitid(arg1: idtype_t, arg2: id_t, arg3: *mut siginfo_t, arg4: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn wait3(arg1: *mut ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: *mut Struct_rusage) -> pid_t; pub fn wait4(arg1: pid_t, arg2: *mut ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *mut Struct_rusage) -> pid_t; pub fn alloca(arg1: size_t) -> *mut ::std::os::raw::c_void; pub fn abort(); pub fn abs(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn atexit(arg1: ::std::option::Option<extern "C" fn()>) -> ::std::os::raw::c_int; pub fn atof(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_double; pub fn atoi(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn atol(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_long; pub fn atoll(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_longlong; pub fn bsearch(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t, arg4: size_t, arg5: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>) -> *mut ::std::os::raw::c_void; pub fn calloc(arg1: size_t, arg2: size_t) -> *mut ::std::os::raw::c_void; pub fn div(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> div_t; pub fn exit(arg1: ::std::os::raw::c_int); pub fn free(arg1: *mut ::std::os::raw::c_void); pub fn getenv(arg1: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn labs(arg1: ::std::os::raw::c_long) -> ::std::os::raw::c_long; pub fn ldiv(arg1: ::std::os::raw::c_long, arg2: ::std::os::raw::c_long) -> ldiv_t; pub fn llabs(arg1: ::std::os::raw::c_longlong) -> ::std::os::raw::c_longlong; pub fn lldiv(arg1: ::std::os::raw::c_longlong, arg2: ::std::os::raw::c_longlong) -> lldiv_t; pub fn malloc(arg1: size_t) -> *mut ::std::os::raw::c_void; pub fn mblen(arg1: *const ::std::os::raw::c_char, arg2: size_t) -> ::std::os::raw::c_int; pub fn mbstowcs(arg1: *mut wchar_t, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> size_t; pub fn mbtowc(arg1: *mut wchar_t, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn posix_memalign(arg1: *mut *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t) -> ::std::os::raw::c_int; pub fn qsort(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>); pub fn rand() -> ::std::os::raw::c_int; pub fn realloc(arg1: *mut ::std::os::raw::c_void, arg2: size_t) -> *mut ::std::os::raw::c_void; pub fn srand(arg1: ::std::os::raw::c_uint); pub fn strtod(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_double; pub fn strtof(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_float; pub fn strtol(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_long; pub fn strtold(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_double; pub fn strtoll(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_longlong; pub fn strtoul(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_ulong; pub fn strtoull(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_ulonglong; pub fn system(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn wcstombs(arg1: *mut ::std::os::raw::c_char, arg2: *const wchar_t, arg3: size_t) -> size_t; pub fn wctomb(arg1: *mut ::std::os::raw::c_char, arg2: wchar_t) -> ::std::os::raw::c_int; pub fn _Exit(arg1: ::std::os::raw::c_int); pub fn a64l(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_long; pub fn drand48() -> ::std::os::raw::c_double; pub fn ecvt(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn erand48(arg1: *mut ::std::os::raw::c_ushort) -> ::std::os::raw::c_double; pub fn fcvt(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn gcvt(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn getsubopt(arg1: *mut *mut ::std::os::raw::c_char, arg2: *const *mut ::std::os::raw::c_char, arg3: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn grantpt(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn initstate(arg1: ::std::os::raw::c_uint, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> *mut ::std::os::raw::c_char; pub fn jrand48(arg1: *mut ::std::os::raw::c_ushort) -> ::std::os::raw::c_long; pub fn l64a(arg1: ::std::os::raw::c_long) -> *mut ::std::os::raw::c_char; pub fn lcong48(arg1: *mut ::std::os::raw::c_ushort); pub fn lrand48() -> ::std::os::raw::c_long; pub fn mktemp(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn mkstemp(arg1: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn mrand48() -> ::std::os::raw::c_long; pub fn nrand48(arg1: *mut ::std::os::raw::c_ushort) -> ::std::os::raw::c_long; pub fn posix_openpt(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ptsname(arg1: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn putenv(arg1: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn random() -> ::std::os::raw::c_long; pub fn rand_r(arg1: *mut ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn realpath(arg1: *const ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn seed48(arg1: *mut ::std::os::raw::c_ushort) -> *mut ::std::os::raw::c_ushort; pub fn setenv(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setkey(arg1: *const ::std::os::raw::c_char); pub fn setstate(arg1: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn srand48(arg1: ::std::os::raw::c_long); pub fn srandom(arg1: ::std::os::raw::c_uint); pub fn unlockpt(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn unsetenv(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn arc4random() -> u_int32_t; pub fn arc4random_addrandom(arg1: *mut ::std::os::raw::c_uchar, arg2: ::std::os::raw::c_int); pub fn arc4random_buf(arg1: *mut ::std::os::raw::c_void, arg2: size_t); pub fn arc4random_stir(); pub fn arc4random_uniform(arg1: u_int32_t) -> u_int32_t; pub fn atexit_b(arg1: ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn bsearch_b(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t, arg4: size_t, arg5: ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn cgetcap(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn cgetclose() -> ::std::os::raw::c_int; pub fn cgetent(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetfirst(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetmatch(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetnext(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetnum(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_long) -> ::std::os::raw::c_int; pub fn cgetset(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetstr(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn cgetustr(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn daemon(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn devname(arg1: dev_t, arg2: mode_t) -> *mut ::std::os::raw::c_char; pub fn devname_r(arg1: dev_t, arg2: mode_t, buf: *mut ::std::os::raw::c_char, len: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn getbsize(arg1: *mut ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_long) -> *mut ::std::os::raw::c_char; pub fn getloadavg(arg1: *mut ::std::os::raw::c_double, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getprogname() -> *const ::std::os::raw::c_char; pub fn heapsort(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>) -> ::std::os::raw::c_int; pub fn heapsort_b(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn mergesort(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>) -> ::std::os::raw::c_int; pub fn mergesort_b(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn psort(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>); pub fn psort_b(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::os::raw::c_void); pub fn psort_r(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: *mut ::std::os::raw::c_void, arg5: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>); pub fn qsort_b(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: ::std::os::raw::c_void); pub fn qsort_r(arg1: *mut ::std::os::raw::c_void, arg2: size_t, arg3: size_t, arg4: *mut ::std::os::raw::c_void, arg5: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int>); pub fn radixsort(arg1: *mut *const ::std::os::raw::c_uchar, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_uchar, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn setprogname(arg1: *const ::std::os::raw::c_char); pub fn sradixsort(arg1: *mut *const ::std::os::raw::c_uchar, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_uchar, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn sranddev(); pub fn srandomdev(); pub fn reallocf(arg1: *mut ::std::os::raw::c_void, arg2: size_t) -> *mut ::std::os::raw::c_void; pub fn strtoq(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_longlong; pub fn strtouq(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_ulonglong; pub fn valloc(arg1: size_t) -> *mut ::std::os::raw::c_void; pub fn memchr(arg1: *const ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: size_t) -> *mut ::std::os::raw::c_void; pub fn memcmp(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t) -> ::std::os::raw::c_int; pub fn memcpy(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t) -> *mut ::std::os::raw::c_void; pub fn memmove(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t) -> *mut ::std::os::raw::c_void; pub fn memset(arg1: *mut ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: size_t) -> *mut ::std::os::raw::c_void; pub fn strcat(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strchr(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn strcmp(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn strcoll(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn strcpy(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strcspn(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> size_t; pub fn strerror(arg1: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn strlen(arg1: *const ::std::os::raw::c_char) -> size_t; pub fn strncat(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> *mut ::std::os::raw::c_char; pub fn strncmp(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn strncpy(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> *mut ::std::os::raw::c_char; pub fn strpbrk(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strrchr(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn strspn(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> size_t; pub fn strstr(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strtok(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strxfrm(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> size_t; pub fn strtok_r(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strerror_r(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn strdup(arg1: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn memccpy(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: ::std::os::raw::c_int, arg4: size_t) -> *mut ::std::os::raw::c_void; pub fn stpcpy(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn stpncpy(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> *mut ::std::os::raw::c_char; pub fn strndup(arg1: *const ::std::os::raw::c_char, arg2: size_t) -> *mut ::std::os::raw::c_char; pub fn strnlen(arg1: *const ::std::os::raw::c_char, arg2: size_t) -> size_t; pub fn strsignal(sig: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn memset_s(arg1: *mut ::std::os::raw::c_void, arg2: rsize_t, arg3: ::std::os::raw::c_int, arg4: rsize_t) -> errno_t; pub fn memmem(arg1: *const ::std::os::raw::c_void, arg2: size_t, arg3: *const ::std::os::raw::c_void, arg4: size_t) -> *mut ::std::os::raw::c_void; pub fn memset_pattern4(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t); pub fn memset_pattern8(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t); pub fn memset_pattern16(arg1: *mut ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t); pub fn strcasestr(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn strnstr(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> *mut ::std::os::raw::c_char; pub fn strlcat(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> size_t; pub fn strlcpy(arg1: *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> size_t; pub fn strmode(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_char); pub fn strsep(arg1: *mut *mut ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn swab(arg1: *const ::std::os::raw::c_void, arg2: *mut ::std::os::raw::c_void, arg3: ssize_t); pub fn bcmp(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, arg3: size_t) -> ::std::os::raw::c_int; pub fn bcopy(arg1: *const ::std::os::raw::c_void, arg2: *mut ::std::os::raw::c_void, arg3: size_t); pub fn bzero(arg1: *mut ::std::os::raw::c_void, arg2: size_t); pub fn index(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn rindex(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn ffs(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn strcasecmp(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn strncasecmp(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn ffsl(arg1: ::std::os::raw::c_long) -> ::std::os::raw::c_int; pub fn ffsll(arg1: ::std::os::raw::c_longlong) -> ::std::os::raw::c_int; pub fn fls(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn flsl(arg1: ::std::os::raw::c_long) -> ::std::os::raw::c_int; pub fn flsll(arg1: ::std::os::raw::c_longlong) -> ::std::os::raw::c_int; pub fn asctime(arg1: *const Struct_tm) -> *mut ::std::os::raw::c_char; pub fn clock() -> clock_t; pub fn ctime(arg1: *const time_t) -> *mut ::std::os::raw::c_char; pub fn difftime(arg1: time_t, arg2: time_t) -> ::std::os::raw::c_double; pub fn getdate(arg1: *const ::std::os::raw::c_char) -> *mut Struct_tm; pub fn gmtime(arg1: *const time_t) -> *mut Struct_tm; pub fn localtime(arg1: *const time_t) -> *mut Struct_tm; pub fn mktime(arg1: *mut Struct_tm) -> time_t; pub fn strftime(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: *const ::std::os::raw::c_char, arg4: *const Struct_tm) -> size_t; pub fn strptime(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *mut Struct_tm) -> *mut ::std::os::raw::c_char; pub fn time(arg1: *mut time_t) -> time_t; pub fn tzset(); pub fn asctime_r(arg1: *const Struct_tm, arg2: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn ctime_r(arg1: *const time_t, arg2: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn gmtime_r(arg1: *const time_t, arg2: *mut Struct_tm) -> *mut Struct_tm; pub fn localtime_r(arg1: *const time_t, arg2: *mut Struct_tm) -> *mut Struct_tm; pub fn posix2time(arg1: time_t) -> time_t; pub fn tzsetwall(); pub fn time2posix(arg1: time_t) -> time_t; pub fn timelocal(arg1: *mut Struct_tm) -> time_t; pub fn timegm(arg1: *mut Struct_tm) -> time_t; pub fn nanosleep(arg1: *const Struct_timespec, arg2: *mut Struct_timespec) -> ::std::os::raw::c_int; pub fn __math_errhandling() -> ::std::os::raw::c_int; pub fn __fpclassifyf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __fpclassifyd(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __fpclassifyl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isfinitef(__x: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __inline_isfinited(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isfinitel(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isinff(__x: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __inline_isinfd(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isinfl(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isnanf(__x: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __inline_isnand(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isnanl(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isnormalf(__x: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __inline_isnormald(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_isnormall(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_signbitf(__x: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn __inline_signbitd(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn __inline_signbitl(__x: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn acosf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn acos(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn acosl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn asinf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn asin(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn asinl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atanf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn atan(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atanl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atan2f(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn atan2(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atan2l(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn cosf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn cos(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn cosl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sinf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn sin(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sinl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tanf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn tan(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tanl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn acoshf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn acosh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn acoshl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn asinhf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn asinh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn asinhl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atanhf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn atanh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn atanhl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn coshf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn cosh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn coshl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sinhf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn sinh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sinhl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tanhf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn tanh(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tanhl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn expf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn exp(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn expl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn exp2f(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn exp2(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn exp2l(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn expm1f(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn expm1(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn expm1l(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn logf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn log(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn logl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log10f(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn log10(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log10l(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log2f(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn log2(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log2l(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log1pf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn log1p(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn log1pl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn logbf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn logb(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn logbl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn modff(arg1: ::std::os::raw::c_float, arg2: *mut ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn modf(arg1: ::std::os::raw::c_double, arg2: *mut ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn modfl(arg1: ::std::os::raw::c_double, arg2: *mut ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn ldexpf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_float; pub fn ldexp(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn ldexpl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn frexpf(arg1: ::std::os::raw::c_float, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_float; pub fn frexp(arg1: ::std::os::raw::c_double, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn frexpl(arg1: ::std::os::raw::c_double, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn ilogbf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_int; pub fn ilogb(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn ilogbl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn scalbnf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_float; pub fn scalbn(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn scalbnl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn scalblnf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_long) -> ::std::os::raw::c_float; pub fn scalbln(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_long) -> ::std::os::raw::c_double; pub fn scalblnl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_long) -> ::std::os::raw::c_double; pub fn fabsf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fabs(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fabsl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn cbrtf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn cbrt(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn cbrtl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn hypotf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn hypot(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn hypotl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn powf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn pow(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn powl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sqrtf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn sqrt(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn sqrtl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn erff(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn erf(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn erfl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn erfcf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn erfc(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn erfcl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn lgammaf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn lgamma(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn lgammal(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tgammaf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn tgamma(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn tgammal(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn ceilf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn ceil(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn ceill(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn floorf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn floor(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn floorl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nearbyintf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn nearbyint(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nearbyintl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn rintf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn rint(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn rintl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn lrintf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_long; pub fn lrint(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn lrintl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn roundf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn round(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn roundl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn lroundf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_long; pub fn lround(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn lroundl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn llrintf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_longlong; pub fn llrint(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_longlong; pub fn llrintl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_longlong; pub fn llroundf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_longlong; pub fn llround(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_longlong; pub fn llroundl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_longlong; pub fn truncf(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn trunc(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn truncl(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmodf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fmod(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmodl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn remainderf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn remainder(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn remainderl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn remquof(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float, arg3: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_float; pub fn remquo(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double, arg3: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn remquol(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double, arg3: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_double; pub fn copysignf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn copysign(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn copysignl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nanf(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_float; pub fn nan(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_double; pub fn nanl(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_double; pub fn nextafterf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn nextafter(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nextafterl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nexttoward(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn nexttowardf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_float; pub fn nexttowardl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fdimf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fdim(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fdiml(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmaxf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fmax(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmaxl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fminf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fmin(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fminl(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmaf(arg1: ::std::os::raw::c_float, arg2: ::std::os::raw::c_float, arg3: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn fma(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double, arg3: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn fmal(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double, arg3: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn __inff() -> ::std::os::raw::c_float; pub fn __inf() -> ::std::os::raw::c_double; pub fn __infl() -> ::std::os::raw::c_double; pub fn __nan() -> ::std::os::raw::c_float; pub fn __exp10f(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn __exp10(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn __sincosf(__x: ::std::os::raw::c_float, __sinp: *mut ::std::os::raw::c_float, __cosp: *mut ::std::os::raw::c_float); pub fn __sincos(__x: ::std::os::raw::c_double, __sinp: *mut ::std::os::raw::c_double, __cosp: *mut ::std::os::raw::c_double); pub fn __cospif(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn __cospi(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn __sinpif(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn __sinpi(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn __tanpif(arg1: ::std::os::raw::c_float) -> ::std::os::raw::c_float; pub fn __tanpi(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn __sincospif(__x: ::std::os::raw::c_float, __sinp: *mut ::std::os::raw::c_float, __cosp: *mut ::std::os::raw::c_float); pub fn __sincospi(__x: ::std::os::raw::c_double, __sinp: *mut ::std::os::raw::c_double, __cosp: *mut ::std::os::raw::c_double); pub fn __sincosf_stret(arg1: ::std::os::raw::c_float) -> Struct___float2; pub fn __sincos_stret(arg1: ::std::os::raw::c_double) -> Struct___double2; pub fn __sincospif_stret(arg1: ::std::os::raw::c_float) -> Struct___float2; pub fn __sincospi_stret(arg1: ::std::os::raw::c_double) -> Struct___double2; pub fn j0(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn j1(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn jn(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn y0(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn y1(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn yn(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn scalb(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn rinttol(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn roundtol(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_long; pub fn drem(arg1: ::std::os::raw::c_double, arg2: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn finite(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_int; pub fn gamma(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn significand(arg1: ::std::os::raw::c_double) -> ::std::os::raw::c_double; pub fn matherr(arg1: *mut Struct_exception) -> ::std::os::raw::c_int; pub fn raise(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn bsd_signal(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>) -> ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>)>; pub fn kill(arg1: pid_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn killpg(arg1: pid_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_kill(arg1: pthread_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_sigmask(arg1: ::std::os::raw::c_int, arg2: *const sigset_t, arg3: *mut sigset_t) -> ::std::os::raw::c_int; pub fn sigaction(arg1: ::std::os::raw::c_int, arg2: *const Struct_sigaction, arg3: *mut Struct_sigaction) -> ::std::os::raw::c_int; pub fn sigaddset(arg1: *mut sigset_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigaltstack(arg1: *const stack_t, arg2: *mut stack_t) -> ::std::os::raw::c_int; pub fn sigdelset(arg1: *mut sigset_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigemptyset(arg1: *mut sigset_t) -> ::std::os::raw::c_int; pub fn sigfillset(arg1: *mut sigset_t) -> ::std::os::raw::c_int; pub fn sighold(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigignore(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn siginterrupt(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigismember(arg1: *const sigset_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigpause(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigpending(arg1: *mut sigset_t) -> ::std::os::raw::c_int; pub fn sigprocmask(arg1: ::std::os::raw::c_int, arg2: *const sigset_t, arg3: *mut sigset_t) -> ::std::os::raw::c_int; pub fn sigrelse(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigset(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>) -> ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int, arg2: ::std::option::Option<extern "C" fn(arg1: ::std::os::raw::c_int)>)>; pub fn sigsuspend(arg1: *const sigset_t) -> ::std::os::raw::c_int; pub fn sigwait(arg1: *const sigset_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn psignal(arg1: ::std::os::raw::c_uint, arg2: *const ::std::os::raw::c_char); pub fn sigblock(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigsetmask(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sigvec(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sigvec, arg3: *mut Struct_sigvec) -> ::std::os::raw::c_int; pub fn __sigbits(__signo: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setjmp(arg1: jmp_buf) -> ::std::os::raw::c_int; pub fn longjmp(arg1: jmp_buf, arg2: ::std::os::raw::c_int); pub fn _setjmp(arg1: jmp_buf) -> ::std::os::raw::c_int; pub fn _longjmp(arg1: jmp_buf, arg2: ::std::os::raw::c_int); pub fn sigsetjmp(arg1: sigjmp_buf, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn siglongjmp(arg1: sigjmp_buf, arg2: ::std::os::raw::c_int); pub fn longjmperror(); pub fn __assert_rtn(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: *const ::std::os::raw::c_char); pub fn open(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, ...) -> ::std::os::raw::c_int; pub fn openat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, ...) -> ::std::os::raw::c_int; pub fn creat(arg1: *const ::std::os::raw::c_char, arg2: mode_t) -> ::std::os::raw::c_int; pub fn fcntl(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, ...) -> ::std::os::raw::c_int; pub fn openx_np(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn open_dprotected_np(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: ::std::os::raw::c_int, ...) -> ::std::os::raw::c_int; pub fn flock(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn filesec_init() -> filesec_t; pub fn filesec_dup(arg1: filesec_t) -> filesec_t; pub fn filesec_free(arg1: filesec_t); pub fn filesec_get_property(arg1: filesec_t, arg2: filesec_property_t, arg3: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn filesec_query_property(arg1: filesec_t, arg2: filesec_property_t, arg3: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn filesec_set_property(arg1: filesec_t, arg2: filesec_property_t, arg3: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn filesec_unset_property(arg1: filesec_t, arg2: filesec_property_t) -> ::std::os::raw::c_int; pub fn accept(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr, arg3: *mut socklen_t) -> ::std::os::raw::c_int; pub fn bind(arg1: ::std::os::raw::c_int, arg2: *const Struct_sockaddr, arg3: socklen_t) -> ::std::os::raw::c_int; pub fn connect(arg1: ::std::os::raw::c_int, arg2: *const Struct_sockaddr, arg3: socklen_t) -> ::std::os::raw::c_int; pub fn getpeername(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr, arg3: *mut socklen_t) -> ::std::os::raw::c_int; pub fn getsockname(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr, arg3: *mut socklen_t) -> ::std::os::raw::c_int; pub fn getsockopt(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_void, arg5: *mut socklen_t) -> ::std::os::raw::c_int; pub fn listen(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn recv(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: size_t, arg4: ::std::os::raw::c_int) -> ssize_t; pub fn recvfrom(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: size_t, arg4: ::std::os::raw::c_int, arg5: *mut Struct_sockaddr, arg6: *mut socklen_t) -> ssize_t; pub fn recvmsg(arg1: ::std::os::raw::c_int, arg2: *mut Struct_msghdr, arg3: ::std::os::raw::c_int) -> ssize_t; pub fn send(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: size_t, arg4: ::std::os::raw::c_int) -> ssize_t; pub fn sendmsg(arg1: ::std::os::raw::c_int, arg2: *const Struct_msghdr, arg3: ::std::os::raw::c_int) -> ssize_t; pub fn sendto(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: size_t, arg4: ::std::os::raw::c_int, arg5: *const Struct_sockaddr, arg6: socklen_t) -> ssize_t; pub fn setsockopt(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *const ::std::os::raw::c_void, arg5: socklen_t) -> ::std::os::raw::c_int; pub fn shutdown(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sockatmark(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn socket(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn socketpair(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sendfile(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: off_t, arg4: *mut off_t, arg5: *mut Struct_sf_hdtr, arg6: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pfctlinput(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr); pub fn connectx(arg1: ::std::os::raw::c_int, arg2: *const sa_endpoints_t, arg3: sae_associd_t, arg4: ::std::os::raw::c_uint, arg5: *const Struct_iovec, arg6: ::std::os::raw::c_uint, arg7: *mut size_t, arg8: *mut sae_connid_t) -> ::std::os::raw::c_int; pub fn disconnectx(arg1: ::std::os::raw::c_int, arg2: sae_associd_t, arg3: sae_connid_t) -> ::std::os::raw::c_int; pub fn setipv4sourcefilter(arg1: ::std::os::raw::c_int, arg2: Struct_in_addr, arg3: Struct_in_addr, arg4: uint32_t, arg5: uint32_t, arg6: *mut Struct_in_addr) -> ::std::os::raw::c_int; pub fn getipv4sourcefilter(arg1: ::std::os::raw::c_int, arg2: Struct_in_addr, arg3: Struct_in_addr, arg4: *mut uint32_t, arg5: *mut uint32_t, arg6: *mut Struct_in_addr) -> ::std::os::raw::c_int; pub fn setsourcefilter(arg1: ::std::os::raw::c_int, arg2: uint32_t, arg3: *mut Struct_sockaddr, arg4: socklen_t, arg5: uint32_t, arg6: uint32_t, arg7: *mut Struct_sockaddr_storage) -> ::std::os::raw::c_int; pub fn getsourcefilter(arg1: ::std::os::raw::c_int, arg2: uint32_t, arg3: *mut Struct_sockaddr, arg4: socklen_t, arg5: *mut uint32_t, arg6: *mut uint32_t, arg7: *mut Struct_sockaddr_storage) -> ::std::os::raw::c_int; pub fn inet6_option_space(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_option_init(arg1: *mut ::std::os::raw::c_void, arg2: *mut *mut Struct_cmsghdr, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_option_append(arg1: *mut Struct_cmsghdr, arg2: *const __uint8_t, arg3: ::std::os::raw::c_int, arg4: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_option_alloc(arg1: *mut Struct_cmsghdr, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: ::std::os::raw::c_int) -> *mut __uint8_t; pub fn inet6_option_next(arg1: *const Struct_cmsghdr, arg2: *mut *mut __uint8_t) -> ::std::os::raw::c_int; pub fn inet6_option_find(arg1: *const Struct_cmsghdr, arg2: *mut *mut __uint8_t, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_rthdr_space(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> size_t; pub fn inet6_rthdr_init(arg1: *mut ::std::os::raw::c_void, arg2: ::std::os::raw::c_int) -> *mut Struct_cmsghdr; pub fn inet6_rthdr_add(arg1: *mut Struct_cmsghdr, arg2: *const Struct_in6_addr, arg3: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn inet6_rthdr_lasthop(arg1: *mut Struct_cmsghdr, arg2: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn inet6_rthdr_segments(arg1: *const Struct_cmsghdr) -> ::std::os::raw::c_int; pub fn inet6_rthdr_getaddr(arg1: *mut Struct_cmsghdr, arg2: ::std::os::raw::c_int) -> *mut Struct_in6_addr; pub fn inet6_rthdr_getflags(arg1: *const Struct_cmsghdr, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_opt_init(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t) -> ::std::os::raw::c_int; pub fn inet6_opt_append(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int, arg4: __uint8_t, arg5: socklen_t, arg6: __uint8_t, arg7: *mut *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn inet6_opt_finish(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn inet6_opt_set_val(arg1: *mut ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_void, arg4: socklen_t) -> ::std::os::raw::c_int; pub fn inet6_opt_next(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int, arg4: *mut __uint8_t, arg5: *mut socklen_t, arg6: *mut *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn inet6_opt_find(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int, arg4: __uint8_t, arg5: *mut socklen_t, arg6: *mut *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn inet6_opt_get_val(arg1: *mut ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_void, arg4: socklen_t) -> ::std::os::raw::c_int; pub fn inet6_rth_space(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> socklen_t; pub fn inet6_rth_init(arg1: *mut ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int, arg4: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn inet6_rth_add(arg1: *mut ::std::os::raw::c_void, arg2: *const Struct_in6_addr) -> ::std::os::raw::c_int; pub fn inet6_rth_reverse(arg1: *const ::std::os::raw::c_void, arg2: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn inet6_rth_segments(arg1: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn inet6_rth_getaddr(arg1: *const ::std::os::raw::c_void, arg2: ::std::os::raw::c_int) -> *mut Struct_in6_addr; pub fn addrsel_policy_init(); pub fn bindresvport(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr_in) -> ::std::os::raw::c_int; pub fn bindresvport_sa(arg1: ::std::os::raw::c_int, arg2: *mut Struct_sockaddr) -> ::std::os::raw::c_int; pub fn endhostent(); pub fn endnetent(); pub fn endprotoent(); pub fn endservent(); pub fn freeaddrinfo(arg1: *mut Struct_addrinfo); pub fn gai_strerror(arg1: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char; pub fn getaddrinfo(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *const Struct_addrinfo, arg4: *mut *mut Struct_addrinfo) -> ::std::os::raw::c_int; pub fn gethostbyaddr(arg1: *const ::std::os::raw::c_void, arg2: socklen_t, arg3: ::std::os::raw::c_int) -> *mut Struct_hostent; pub fn gethostbyname(arg1: *const ::std::os::raw::c_char) -> *mut Struct_hostent; pub fn gethostent() -> *mut Struct_hostent; pub fn getnameinfo(arg1: *const Struct_sockaddr, arg2: socklen_t, arg3: *mut ::std::os::raw::c_char, arg4: socklen_t, arg5: *mut ::std::os::raw::c_char, arg6: socklen_t, arg7: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getnetbyaddr(arg1: uint32_t, arg2: ::std::os::raw::c_int) -> *mut Struct_netent; pub fn getnetbyname(arg1: *const ::std::os::raw::c_char) -> *mut Struct_netent; pub fn getnetent() -> *mut Struct_netent; pub fn getprotobyname(arg1: *const ::std::os::raw::c_char) -> *mut Struct_protoent; pub fn getprotobynumber(arg1: ::std::os::raw::c_int) -> *mut Struct_protoent; pub fn getprotoent() -> *mut Struct_protoent; pub fn getservbyname(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut Struct_servent; pub fn getservbyport(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char) -> *mut Struct_servent; pub fn getservent() -> *mut Struct_servent; pub fn sethostent(arg1: ::std::os::raw::c_int); pub fn setnetent(arg1: ::std::os::raw::c_int); pub fn setprotoent(arg1: ::std::os::raw::c_int); pub fn setservent(arg1: ::std::os::raw::c_int); pub fn freehostent(arg1: *mut Struct_hostent); pub fn gethostbyname2(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut Struct_hostent; pub fn getipnodebyaddr(arg1: *const ::std::os::raw::c_void, arg2: size_t, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> *mut Struct_hostent; pub fn getipnodebyname(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> *mut Struct_hostent; pub fn getrpcbyname(name: *const ::std::os::raw::c_char) -> *mut Struct_rpcent; pub fn getrpcbynumber(number: ::std::os::raw::c_int) -> *mut Struct_rpcent; pub fn getrpcent() -> *mut Struct_rpcent; pub fn setrpcent(stayopen: ::std::os::raw::c_int); pub fn endrpcent(); pub fn herror(arg1: *const ::std::os::raw::c_char); pub fn hstrerror(arg1: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char; pub fn innetgr(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *const ::std::os::raw::c_char, arg4: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn getnetgrent(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut *mut ::std::os::raw::c_char, arg3: *mut *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn endnetgrent(); pub fn setnetgrent(arg1: *const ::std::os::raw::c_char); pub fn getattrlistbulk(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: uint64_t) -> ::std::os::raw::c_int; pub fn faccessat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn fchownat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: uid_t, arg4: gid_t, arg5: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn linkat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: *const ::std::os::raw::c_char, arg5: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn readlinkat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_char, arg4: size_t) -> ssize_t; pub fn symlinkat(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn unlinkat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getattrlistat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_void, arg4: *mut ::std::os::raw::c_void, arg5: size_t, arg6: ::std::os::raw::c_ulong) -> ::std::os::raw::c_int; pub fn _exit(arg1: ::std::os::raw::c_int); pub fn access(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn alarm(arg1: ::std::os::raw::c_uint) -> ::std::os::raw::c_uint; pub fn chdir(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn chown(arg1: *const ::std::os::raw::c_char, arg2: uid_t, arg3: gid_t) -> ::std::os::raw::c_int; pub fn close(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn dup(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn dup2(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn execl(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn execle(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn execlp(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn execv(arg1: *const ::std::os::raw::c_char, arg2: *const *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn execve(arg1: *const ::std::os::raw::c_char, arg2: *const *mut ::std::os::raw::c_char, arg3: *const *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn execvp(arg1: *const ::std::os::raw::c_char, arg2: *const *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn fork() -> pid_t; pub fn fpathconf(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_long; pub fn getcwd(arg1: *mut ::std::os::raw::c_char, arg2: size_t) -> *mut ::std::os::raw::c_char; pub fn getegid() -> gid_t; pub fn geteuid() -> uid_t; pub fn getgid() -> gid_t; pub fn getgroups(arg1: ::std::os::raw::c_int, arg2: *mut gid_t) -> ::std::os::raw::c_int; pub fn getlogin() -> *mut ::std::os::raw::c_char; pub fn getpgrp() -> pid_t; pub fn getpid() -> pid_t; pub fn getppid() -> pid_t; pub fn getuid() -> uid_t; pub fn isatty(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn link(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn lseek(arg1: ::std::os::raw::c_int, arg2: off_t, arg3: ::std::os::raw::c_int) -> off_t; pub fn pathconf(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_long; pub fn pause() -> ::std::os::raw::c_int; pub fn pipe(arg1: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn read(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: size_t) -> ssize_t; pub fn rmdir(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn setgid(arg1: gid_t) -> ::std::os::raw::c_int; pub fn setpgid(arg1: pid_t, arg2: pid_t) -> ::std::os::raw::c_int; pub fn setsid() -> pid_t; pub fn setuid(arg1: uid_t) -> ::std::os::raw::c_int; pub fn sleep(arg1: ::std::os::raw::c_uint) -> ::std::os::raw::c_uint; pub fn sysconf(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_long; pub fn tcgetpgrp(arg1: ::std::os::raw::c_int) -> pid_t; pub fn tcsetpgrp(arg1: ::std::os::raw::c_int, arg2: pid_t) -> ::std::os::raw::c_int; pub fn ttyname(arg1: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn ttyname_r(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn unlink(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn write(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: size_t) -> ssize_t; pub fn confstr(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> size_t; pub fn getopt(arg1: ::std::os::raw::c_int, arg2: *const *mut ::std::os::raw::c_char, arg3: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn brk(arg1: *const ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn chroot(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn crypt(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn encrypt(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int); pub fn fchdir(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn gethostid() -> ::std::os::raw::c_long; pub fn getpgid(arg1: pid_t) -> pid_t; pub fn getsid(arg1: pid_t) -> pid_t; pub fn getdtablesize() -> ::std::os::raw::c_int; pub fn getpagesize() -> ::std::os::raw::c_int; pub fn getpass(arg1: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn getwd(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn lchown(arg1: *const ::std::os::raw::c_char, arg2: uid_t, arg3: gid_t) -> ::std::os::raw::c_int; pub fn lockf(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int, arg3: off_t) -> ::std::os::raw::c_int; pub fn nice(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pread(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: size_t, arg4: off_t) -> ssize_t; pub fn pwrite(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: size_t, arg4: off_t) -> ssize_t; pub fn sbrk(arg1: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn setpgrp() -> pid_t; pub fn setregid(arg1: gid_t, arg2: gid_t) -> ::std::os::raw::c_int; pub fn setreuid(arg1: uid_t, arg2: uid_t) -> ::std::os::raw::c_int; pub fn sync(); pub fn truncate(arg1: *const ::std::os::raw::c_char, arg2: off_t) -> ::std::os::raw::c_int; pub fn ualarm(arg1: useconds_t, arg2: useconds_t) -> useconds_t; pub fn usleep(arg1: useconds_t) -> ::std::os::raw::c_int; pub fn vfork() -> pid_t; pub fn fsync(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ftruncate(arg1: ::std::os::raw::c_int, arg2: off_t) -> ::std::os::raw::c_int; pub fn getlogin_r(arg1: *mut ::std::os::raw::c_char, arg2: size_t) -> ::std::os::raw::c_int; pub fn fchown(arg1: ::std::os::raw::c_int, arg2: uid_t, arg3: gid_t) -> ::std::os::raw::c_int; pub fn gethostname(arg1: *mut ::std::os::raw::c_char, arg2: size_t) -> ::std::os::raw::c_int; pub fn readlink(arg1: *const ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> ssize_t; pub fn setegid(arg1: gid_t) -> ::std::os::raw::c_int; pub fn seteuid(arg1: uid_t) -> ::std::os::raw::c_int; pub fn symlink(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn pselect(arg1: ::std::os::raw::c_int, arg2: *mut fd_set, arg3: *mut fd_set, arg4: *mut fd_set, arg5: *const Struct_timespec, arg6: *const sigset_t) -> ::std::os::raw::c_int; pub fn select(arg1: ::std::os::raw::c_int, arg2: *mut fd_set, arg3: *mut fd_set, arg4: *mut fd_set, arg5: *mut Struct_timeval) -> ::std::os::raw::c_int; pub fn accessx_np(arg1: *const Struct_accessx_descriptor, arg2: size_t, arg3: *mut ::std::os::raw::c_int, arg4: uid_t) -> ::std::os::raw::c_int; pub fn acct(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn add_profil(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: ::std::os::raw::c_ulong, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn endusershell(); pub fn execvP(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: *const *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn fflagstostr(arg1: ::std::os::raw::c_ulong) -> *mut ::std::os::raw::c_char; pub fn getdomainname(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn getgrouplist(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn gethostuuid(arg1: uuid_t, arg2: *const Struct_timespec) -> ::std::os::raw::c_int; pub fn getmode(arg1: *const ::std::os::raw::c_void, arg2: mode_t) -> mode_t; pub fn getpeereid(arg1: ::std::os::raw::c_int, arg2: *mut uid_t, arg3: *mut gid_t) -> ::std::os::raw::c_int; pub fn getsgroups_np(arg1: *mut ::std::os::raw::c_int, arg2: uuid_t) -> ::std::os::raw::c_int; pub fn getusershell() -> *mut ::std::os::raw::c_char; pub fn getwgroups_np(arg1: *mut ::std::os::raw::c_int, arg2: uuid_t) -> ::std::os::raw::c_int; pub fn initgroups(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn iruserok(arg1: ::std::os::raw::c_ulong, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_char, arg4: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn iruserok_sa(arg1: *const ::std::os::raw::c_void, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int, arg4: *const ::std::os::raw::c_char, arg5: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn issetugid() -> ::std::os::raw::c_int; pub fn mkdtemp(arg1: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn mknod(arg1: *const ::std::os::raw::c_char, arg2: mode_t, arg3: dev_t) -> ::std::os::raw::c_int; pub fn mkpath_np(path: *const ::std::os::raw::c_char, omode: mode_t) -> ::std::os::raw::c_int; pub fn mkstemps(arg1: *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn nfssvc(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn profil(arg1: *mut ::std::os::raw::c_char, arg2: size_t, arg3: ::std::os::raw::c_ulong, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn pthread_setugid_np(arg1: uid_t, arg2: gid_t) -> ::std::os::raw::c_int; pub fn pthread_getugid_np(arg1: *mut uid_t, arg2: *mut gid_t) -> ::std::os::raw::c_int; pub fn rcmd(arg1: *mut *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_char, arg4: *const ::std::os::raw::c_char, arg5: *const ::std::os::raw::c_char, arg6: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn rcmd_af(arg1: *mut *mut ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_char, arg4: *const ::std::os::raw::c_char, arg5: *const ::std::os::raw::c_char, arg6: *mut ::std::os::raw::c_int, arg7: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn reboot(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn revoke(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn rresvport(arg1: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn rresvport_af(arg1: *mut ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ruserok(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: *const ::std::os::raw::c_char, arg4: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn setdomainname(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setgroups(arg1: ::std::os::raw::c_int, arg2: *const gid_t) -> ::std::os::raw::c_int; pub fn sethostid(arg1: ::std::os::raw::c_long); pub fn sethostname(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn setlogin(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn setmode(arg1: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_void; pub fn setrgid(arg1: gid_t) -> ::std::os::raw::c_int; pub fn setruid(arg1: uid_t) -> ::std::os::raw::c_int; pub fn setsgroups_np(arg1: ::std::os::raw::c_int, arg2: uuid_t) -> ::std::os::raw::c_int; pub fn setusershell(); pub fn setwgroups_np(arg1: ::std::os::raw::c_int, arg2: uuid_t) -> ::std::os::raw::c_int; pub fn strtofflags(arg1: *mut *mut ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_ulong, arg3: *mut ::std::os::raw::c_ulong) -> ::std::os::raw::c_int; pub fn swapon(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn syscall(arg1: ::std::os::raw::c_int, ...) -> ::std::os::raw::c_int; pub fn ttyslot() -> ::std::os::raw::c_int; pub fn undelete(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn unwhiteout(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn fgetattrlist(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn fsetattrlist(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn getattrlist(arg1: *const ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn setattrlist(arg1: *const ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn exchangedata(arg1: *const ::std::os::raw::c_char, arg2: *const ::std::os::raw::c_char, arg3: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn getdirentriesattr(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_void, arg4: size_t, arg5: *mut ::std::os::raw::c_uint, arg6: *mut ::std::os::raw::c_uint, arg7: *mut ::std::os::raw::c_uint, arg8: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn searchfs(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_fssearchblock, arg3: *mut ::std::os::raw::c_ulong, arg4: ::std::os::raw::c_uint, arg5: ::std::os::raw::c_uint, arg6: *mut Struct_searchstate) -> ::std::os::raw::c_int; pub fn fsctl(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_ulong, arg3: *mut ::std::os::raw::c_void, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn ffsctl(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_ulong, arg3: *mut ::std::os::raw::c_void, arg4: ::std::os::raw::c_uint) -> ::std::os::raw::c_int; pub fn fsync_volume_np(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sync_volume_np(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sched_yield() -> ::std::os::raw::c_int; pub fn sched_get_priority_min(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn sched_get_priority_max(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn qos_class_self() -> qos_class_t; pub fn qos_class_main() -> qos_class_t; pub fn pthread_attr_set_qos_class_np(__attr: *mut pthread_attr_t, __qos_class: qos_class_t, __relative_priority: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_get_qos_class_np(__attr: *mut pthread_attr_t, __qos_class: *mut qos_class_t, __relative_priority: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_set_qos_class_self_np(__qos_class: qos_class_t, __relative_priority: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_get_qos_class_np(__pthread: pthread_t, __qos_class: *mut qos_class_t, __relative_priority: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_override_qos_class_start_np(__pthread: pthread_t, __qos_class: qos_class_t, __relative_priority: ::std::os::raw::c_int) -> pthread_override_t; pub fn pthread_override_qos_class_end_np(__override: pthread_override_t) -> ::std::os::raw::c_int; pub fn pthread_atfork(arg1: ::std::option::Option<extern "C" fn()>, arg2: ::std::option::Option<extern "C" fn()>, arg3: ::std::option::Option<extern "C" fn()>) -> ::std::os::raw::c_int; pub fn pthread_attr_destroy(arg1: *mut pthread_attr_t) -> ::std::os::raw::c_int; pub fn pthread_attr_getdetachstate(arg1: *const pthread_attr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_getguardsize(arg1: *const pthread_attr_t, arg2: *mut size_t) -> ::std::os::raw::c_int; pub fn pthread_attr_getinheritsched(arg1: *const pthread_attr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_getschedparam(arg1: *const pthread_attr_t, arg2: *mut Struct_sched_param) -> ::std::os::raw::c_int; pub fn pthread_attr_getschedpolicy(arg1: *const pthread_attr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_getscope(arg1: *const pthread_attr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_getstack(arg1: *const pthread_attr_t, arg2: *mut *mut ::std::os::raw::c_void, arg3: *mut size_t) -> ::std::os::raw::c_int; pub fn pthread_attr_getstackaddr(arg1: *const pthread_attr_t, arg2: *mut *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_attr_getstacksize(arg1: *const pthread_attr_t, arg2: *mut size_t) -> ::std::os::raw::c_int; pub fn pthread_attr_init(arg1: *mut pthread_attr_t) -> ::std::os::raw::c_int; pub fn pthread_attr_setdetachstate(arg1: *mut pthread_attr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_setguardsize(arg1: *mut pthread_attr_t, arg2: size_t) -> ::std::os::raw::c_int; pub fn pthread_attr_setinheritsched(arg1: *mut pthread_attr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_setschedparam(arg1: *mut pthread_attr_t, arg2: *const Struct_sched_param) -> ::std::os::raw::c_int; pub fn pthread_attr_setschedpolicy(arg1: *mut pthread_attr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_setscope(arg1: *mut pthread_attr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_attr_setstack(arg1: *mut pthread_attr_t, arg2: *mut ::std::os::raw::c_void, arg3: size_t) -> ::std::os::raw::c_int; pub fn pthread_attr_setstackaddr(arg1: *mut pthread_attr_t, arg2: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_attr_setstacksize(arg1: *mut pthread_attr_t, arg2: size_t) -> ::std::os::raw::c_int; pub fn pthread_cancel(arg1: pthread_t) -> ::std::os::raw::c_int; pub fn pthread_cond_broadcast(arg1: *mut pthread_cond_t) -> ::std::os::raw::c_int; pub fn pthread_cond_destroy(arg1: *mut pthread_cond_t) -> ::std::os::raw::c_int; pub fn pthread_cond_init(arg1: *mut pthread_cond_t, arg2: *const pthread_condattr_t) -> ::std::os::raw::c_int; pub fn pthread_cond_signal(arg1: *mut pthread_cond_t) -> ::std::os::raw::c_int; pub fn pthread_cond_timedwait(arg1: *mut pthread_cond_t, arg2: *mut pthread_mutex_t, arg3: *const Struct_timespec) -> ::std::os::raw::c_int; pub fn pthread_cond_wait(arg1: *mut pthread_cond_t, arg2: *mut pthread_mutex_t) -> ::std::os::raw::c_int; pub fn pthread_condattr_destroy(arg1: *mut pthread_condattr_t) -> ::std::os::raw::c_int; pub fn pthread_condattr_init(arg1: *mut pthread_condattr_t) -> ::std::os::raw::c_int; pub fn pthread_condattr_getpshared(arg1: *const pthread_condattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_condattr_setpshared(arg1: *mut pthread_condattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_create(arg1: *mut pthread_t, arg2: *const pthread_attr_t, arg3: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void>, arg4: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_detach(arg1: pthread_t) -> ::std::os::raw::c_int; pub fn pthread_equal(arg1: pthread_t, arg2: pthread_t) -> ::std::os::raw::c_int; pub fn pthread_exit(arg1: *mut ::std::os::raw::c_void); pub fn pthread_getconcurrency() -> ::std::os::raw::c_int; pub fn pthread_getschedparam(arg1: pthread_t, arg2: *mut ::std::os::raw::c_int, arg3: *mut Struct_sched_param) -> ::std::os::raw::c_int; pub fn pthread_getspecific(arg1: pthread_key_t) -> *mut ::std::os::raw::c_void; pub fn pthread_join(arg1: pthread_t, arg2: *mut *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_key_create(arg1: *mut pthread_key_t, arg2: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void)>) -> ::std::os::raw::c_int; pub fn pthread_key_delete(arg1: pthread_key_t) -> ::std::os::raw::c_int; pub fn pthread_mutex_destroy(arg1: *mut pthread_mutex_t) -> ::std::os::raw::c_int; pub fn pthread_mutex_getprioceiling(arg1: *const pthread_mutex_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutex_init(arg1: *mut pthread_mutex_t, arg2: *const pthread_mutexattr_t) -> ::std::os::raw::c_int; pub fn pthread_mutex_lock(arg1: *mut pthread_mutex_t) -> ::std::os::raw::c_int; pub fn pthread_mutex_setprioceiling(arg1: *mut pthread_mutex_t, arg2: ::std::os::raw::c_int, arg3: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutex_trylock(arg1: *mut pthread_mutex_t) -> ::std::os::raw::c_int; pub fn pthread_mutex_unlock(arg1: *mut pthread_mutex_t) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_destroy(arg1: *mut pthread_mutexattr_t) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_getprioceiling(arg1: *const pthread_mutexattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_getprotocol(arg1: *const pthread_mutexattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_getpshared(arg1: *const pthread_mutexattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_gettype(arg1: *const pthread_mutexattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_init(arg1: *mut pthread_mutexattr_t) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_setprioceiling(arg1: *mut pthread_mutexattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_setprotocol(arg1: *mut pthread_mutexattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_setpshared(arg1: *mut pthread_mutexattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_mutexattr_settype(arg1: *mut pthread_mutexattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_once(arg1: *mut pthread_once_t, arg2: ::std::option::Option<extern "C" fn()>) -> ::std::os::raw::c_int; pub fn pthread_rwlock_destroy(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_init(arg1: *mut pthread_rwlock_t, arg2: *const pthread_rwlockattr_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_rdlock(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_tryrdlock(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_trywrlock(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_wrlock(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlock_unlock(arg1: *mut pthread_rwlock_t) -> ::std::os::raw::c_int; pub fn pthread_rwlockattr_destroy(arg1: *mut pthread_rwlockattr_t) -> ::std::os::raw::c_int; pub fn pthread_rwlockattr_getpshared(arg1: *const pthread_rwlockattr_t, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_rwlockattr_init(arg1: *mut pthread_rwlockattr_t) -> ::std::os::raw::c_int; pub fn pthread_rwlockattr_setpshared(arg1: *mut pthread_rwlockattr_t, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_self() -> pthread_t; pub fn pthread_setcancelstate(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_setcanceltype(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_setconcurrency(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn pthread_setschedparam(arg1: pthread_t, arg2: ::std::os::raw::c_int, arg3: *const Struct_sched_param) -> ::std::os::raw::c_int; pub fn pthread_setspecific(arg1: pthread_key_t, arg2: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_testcancel(); pub fn pthread_is_threaded_np() -> ::std::os::raw::c_int; pub fn pthread_threadid_np(arg1: pthread_t, arg2: *mut __uint64_t) -> ::std::os::raw::c_int; pub fn pthread_getname_np(arg1: pthread_t, arg2: *mut ::std::os::raw::c_char, arg3: size_t) -> ::std::os::raw::c_int; pub fn pthread_setname_np(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn pthread_main_np() -> ::std::os::raw::c_int; pub fn pthread_mach_thread_np(arg1: pthread_t) -> mach_port_t; pub fn pthread_get_stacksize_np(arg1: pthread_t) -> size_t; pub fn pthread_get_stackaddr_np(arg1: pthread_t) -> *mut ::std::os::raw::c_void; pub fn pthread_cond_signal_thread_np(arg1: *mut pthread_cond_t, arg2: pthread_t) -> ::std::os::raw::c_int; pub fn pthread_cond_timedwait_relative_np(arg1: *mut pthread_cond_t, arg2: *mut pthread_mutex_t, arg3: *const Struct_timespec) -> ::std::os::raw::c_int; pub fn pthread_create_suspended_np(arg1: *mut pthread_t, arg2: *const pthread_attr_t, arg3: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void>, arg4: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn pthread_from_mach_thread_np(arg1: mach_port_t) -> pthread_t; pub fn pthread_yield_np(); pub fn closedir(arg1: *mut DIR) -> ::std::os::raw::c_int; pub fn opendir(arg1: *const ::std::os::raw::c_char) -> *mut DIR; pub fn readdir(arg1: *mut DIR) -> *mut Struct_dirent; pub fn readdir_r(arg1: *mut DIR, arg2: *mut Struct_dirent, arg3: *mut *mut Struct_dirent) -> ::std::os::raw::c_int; pub fn rewinddir(arg1: *mut DIR); pub fn seekdir(arg1: *mut DIR, arg2: ::std::os::raw::c_long); pub fn telldir(arg1: *mut DIR) -> ::std::os::raw::c_long; pub fn fdopendir(arg1: ::std::os::raw::c_int) -> *mut DIR; pub fn alphasort(arg1: *mut *const Struct_dirent, arg2: *mut *const Struct_dirent) -> ::std::os::raw::c_int; pub fn dirfd(dirp: *mut DIR) -> ::std::os::raw::c_int; pub fn scandir(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut *mut Struct_dirent, arg3: ::std::option::Option<unsafe extern "C" fn(arg1: *const Struct_dirent) -> ::std::os::raw::c_int>, arg4: ::std::option::Option<unsafe extern "C" fn(arg1: *mut *const Struct_dirent, arg2: *mut *const Struct_dirent) -> ::std::os::raw::c_int>) -> ::std::os::raw::c_int; pub fn scandir_b(arg1: *const ::std::os::raw::c_char, arg2: *mut *mut *mut Struct_dirent, arg3: ::std::os::raw::c_void, arg4: ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn getdirentries(arg1: ::std::os::raw::c_int, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_long) -> ::std::os::raw::c_int; pub fn __opendir2(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int) -> *mut DIR; pub fn getpwuid(arg1: uid_t) -> *mut Struct_passwd; pub fn getpwnam(arg1: *const ::std::os::raw::c_char) -> *mut Struct_passwd; pub fn getpwuid_r(arg1: uid_t, arg2: *mut Struct_passwd, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_passwd) -> ::std::os::raw::c_int; pub fn getpwnam_r(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_passwd, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_passwd) -> ::std::os::raw::c_int; pub fn getpwent() -> *mut Struct_passwd; pub fn setpwent(); pub fn endpwent(); pub fn uuid_clear(uu: uuid_t); pub fn uuid_compare(uu1: uuid_t, uu2: uuid_t) -> ::std::os::raw::c_int; pub fn uuid_copy(dst: uuid_t, src: uuid_t); pub fn uuid_generate(out: uuid_t); pub fn uuid_generate_random(out: uuid_t); pub fn uuid_generate_time(out: uuid_t); pub fn uuid_is_null(uu: uuid_t) -> ::std::os::raw::c_int; pub fn uuid_parse(_in: uuid_string_t, uu: uuid_t) -> ::std::os::raw::c_int; pub fn uuid_unparse(uu: uuid_t, out: uuid_string_t); pub fn uuid_unparse_lower(uu: uuid_t, out: uuid_string_t); pub fn uuid_unparse_upper(uu: uuid_t, out: uuid_string_t); pub fn setpassent(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn user_from_uid(arg1: uid_t, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn getpwuuid(arg1: uuid_t) -> *mut Struct_passwd; pub fn getpwuuid_r(arg1: uuid_t, arg2: *mut Struct_passwd, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_passwd) -> ::std::os::raw::c_int; pub fn getgrgid(arg1: gid_t) -> *mut Struct_group; pub fn getgrnam(arg1: *const ::std::os::raw::c_char) -> *mut Struct_group; pub fn getgrgid_r(arg1: gid_t, arg2: *mut Struct_group, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_group) -> ::std::os::raw::c_int; pub fn getgrnam_r(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_group, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_group) -> ::std::os::raw::c_int; pub fn getgrent() -> *mut Struct_group; pub fn setgrent(); pub fn endgrent(); pub fn group_from_gid(arg1: gid_t, arg2: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn getgruuid(arg1: uuid_t) -> *mut Struct_group; pub fn getgruuid_r(arg1: uuid_t, arg2: *mut Struct_group, arg3: *mut ::std::os::raw::c_char, arg4: size_t, arg5: *mut *mut Struct_group) -> ::std::os::raw::c_int; pub fn setgrfile(arg1: *const ::std::os::raw::c_char); pub fn setgroupent(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn utime(arg1: *const ::std::os::raw::c_char, arg2: *const Struct_utimbuf) -> ::std::os::raw::c_int; pub fn imaxabs(j: intmax_t) -> intmax_t; pub fn imaxdiv(__numer: intmax_t, __denom: intmax_t) -> imaxdiv_t; pub fn strtoimax(__nptr: *const ::std::os::raw::c_char, __endptr: *mut *mut ::std::os::raw::c_char, __base: ::std::os::raw::c_int) -> intmax_t; pub fn strtoumax(__nptr: *const ::std::os::raw::c_char, __endptr: *mut *mut ::std::os::raw::c_char, __base: ::std::os::raw::c_int) -> uintmax_t; pub fn wcstoimax(__nptr: *const wchar_t, __endptr: *mut *mut wchar_t, __base: ::std::os::raw::c_int) -> intmax_t; pub fn wcstoumax(__nptr: *const wchar_t, __endptr: *mut *mut wchar_t, __base: ::std::os::raw::c_int) -> uintmax_t; pub fn closelog(); pub fn openlog(arg1: *const ::std::os::raw::c_char, arg2: ::std::os::raw::c_int, arg3: ::std::os::raw::c_int); pub fn setlogmask(arg1: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn syslog(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, ...); pub fn vsyslog(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: __darwin_va_list); pub fn adjtime(arg1: *const Struct_timeval, arg2: *mut Struct_timeval) -> ::std::os::raw::c_int; pub fn futimes(arg1: ::std::os::raw::c_int, arg2: *const Struct_timeval) -> ::std::os::raw::c_int; pub fn lutimes(arg1: *const ::std::os::raw::c_char, arg2: *const Struct_timeval) -> ::std::os::raw::c_int; pub fn settimeofday(arg1: *const Struct_timeval, arg2: *const Struct_timezone) -> ::std::os::raw::c_int; pub fn getitimer(arg1: ::std::os::raw::c_int, arg2: *mut Struct_itimerval) -> ::std::os::raw::c_int; pub fn gettimeofday(arg1: *mut Struct_timeval, arg2: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn setitimer(arg1: ::std::os::raw::c_int, arg2: *const Struct_itimerval, arg3: *mut Struct_itimerval) -> ::std::os::raw::c_int; pub fn utimes(arg1: *const ::std::os::raw::c_char, arg2: *const Struct_timeval) -> ::std::os::raw::c_int; pub fn chmod(arg1: *const ::std::os::raw::c_char, arg2: mode_t) -> ::std::os::raw::c_int; pub fn fchmod(arg1: ::std::os::raw::c_int, arg2: mode_t) -> ::std::os::raw::c_int; pub fn fstat(arg1: ::std::os::raw::c_int, arg2: *mut Struct_stat) -> ::std::os::raw::c_int; pub fn lstat(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat) -> ::std::os::raw::c_int; pub fn mkdir(arg1: *const ::std::os::raw::c_char, arg2: mode_t) -> ::std::os::raw::c_int; pub fn mkfifo(arg1: *const ::std::os::raw::c_char, arg2: mode_t) -> ::std::os::raw::c_int; pub fn stat(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat) -> ::std::os::raw::c_int; pub fn umask(arg1: mode_t) -> mode_t; pub fn fchmodat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: mode_t, arg4: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn fstatat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut Struct_stat, arg4: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn mkdirat(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: mode_t) -> ::std::os::raw::c_int; pub fn chflags(arg1: *const ::std::os::raw::c_char, arg2: __uint32_t) -> ::std::os::raw::c_int; pub fn chmodx_np(arg1: *const ::std::os::raw::c_char, arg2: filesec_t) -> ::std::os::raw::c_int; pub fn fchflags(arg1: ::std::os::raw::c_int, arg2: __uint32_t) -> ::std::os::raw::c_int; pub fn fchmodx_np(arg1: ::std::os::raw::c_int, arg2: filesec_t) -> ::std::os::raw::c_int; pub fn fstatx_np(arg1: ::std::os::raw::c_int, arg2: *mut Struct_stat, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn lchflags(arg1: *const ::std::os::raw::c_char, arg2: __uint32_t) -> ::std::os::raw::c_int; pub fn lchmod(arg1: *const ::std::os::raw::c_char, arg2: mode_t) -> ::std::os::raw::c_int; pub fn lstatx_np(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn mkdirx_np(arg1: *const ::std::os::raw::c_char, arg2: filesec_t) -> ::std::os::raw::c_int; pub fn mkfifox_np(arg1: *const ::std::os::raw::c_char, arg2: filesec_t) -> ::std::os::raw::c_int; pub fn statx_np(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn umaskx_np(arg1: filesec_t) -> ::std::os::raw::c_int; pub fn fstatx64_np(arg1: ::std::os::raw::c_int, arg2: *mut Struct_stat64, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn lstatx64_np(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat64, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn statx64_np(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat64, arg3: filesec_t) -> ::std::os::raw::c_int; pub fn fstat64(arg1: ::std::os::raw::c_int, arg2: *mut Struct_stat64) -> ::std::os::raw::c_int; pub fn lstat64(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat64) -> ::std::os::raw::c_int; pub fn stat64(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_stat64) -> ::std::os::raw::c_int; pub fn ioctl(arg1: ::std::os::raw::c_int, arg2: ::std::os::raw::c_ulong, ...) -> ::std::os::raw::c_int; pub fn readv(arg1: ::std::os::raw::c_int, arg2: *const Struct_iovec, arg3: ::std::os::raw::c_int) -> ssize_t; pub fn writev(arg1: ::std::os::raw::c_int, arg2: *const Struct_iovec, arg3: ::std::os::raw::c_int) -> ssize_t; pub fn getifaddrs(arg1: *mut *mut Struct_ifaddrs) -> ::std::os::raw::c_int; pub fn freeifaddrs(arg1: *mut Struct_ifaddrs); pub fn getifmaddrs(arg1: *mut *mut Struct_ifmaddrs) -> ::std::os::raw::c_int; pub fn freeifmaddrs(arg1: *mut Struct_ifmaddrs); pub fn inet_addr(arg1: *const ::std::os::raw::c_char) -> in_addr_t; pub fn inet_ntoa(arg1: Struct_in_addr) -> *mut ::std::os::raw::c_char; pub fn inet_ntop(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: *mut ::std::os::raw::c_char, arg4: socklen_t) -> *const ::std::os::raw::c_char; pub fn inet_pton(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn ascii2addr(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn addr2ascii(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn inet_aton(arg1: *const ::std::os::raw::c_char, arg2: *mut Struct_in_addr) -> ::std::os::raw::c_int; pub fn inet_lnaof(arg1: Struct_in_addr) -> in_addr_t; pub fn inet_makeaddr(arg1: in_addr_t, arg2: in_addr_t) -> Struct_in_addr; pub fn inet_netof(arg1: Struct_in_addr) -> in_addr_t; pub fn inet_network(arg1: *const ::std::os::raw::c_char) -> in_addr_t; pub fn inet_net_ntop(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_void, arg3: ::std::os::raw::c_int, arg4: *mut ::std::os::raw::c_char, arg5: __darwin_size_t) -> *mut ::std::os::raw::c_char; pub fn inet_net_pton(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_char, arg3: *mut ::std::os::raw::c_void, arg4: __darwin_size_t) -> ::std::os::raw::c_int; pub fn inet_neta(arg1: in_addr_t, arg2: *mut ::std::os::raw::c_char, arg3: __darwin_size_t) -> *mut ::std::os::raw::c_char; pub fn inet_nsap_addr(arg1: *const ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_uchar, arg3: ::std::os::raw::c_int) -> ::std::os::raw::c_uint; pub fn inet_nsap_ntoa(arg1: ::std::os::raw::c_int, arg2: *const ::std::os::raw::c_uchar, arg3: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn mach_msg_overwrite(msg: *mut mach_msg_header_t, option: mach_msg_option_t, send_size: mach_msg_size_t, rcv_size: mach_msg_size_t, rcv_name: mach_port_name_t, timeout: mach_msg_timeout_t, notify: mach_port_name_t, rcv_msg: *mut mach_msg_header_t, rcv_limit: mach_msg_size_t) -> mach_msg_return_t; pub fn mach_msg(msg: *mut mach_msg_header_t, option: mach_msg_option_t, send_size: mach_msg_size_t, rcv_size: mach_msg_size_t, rcv_name: mach_port_name_t, timeout: mach_msg_timeout_t, notify: mach_port_name_t) -> mach_msg_return_t; pub fn mach_voucher_deallocate(voucher: mach_port_name_t) -> kern_return_t; pub fn mig_get_reply_port() -> mach_port_t; pub fn mig_dealloc_reply_port(reply_port: mach_port_t); pub fn mig_put_reply_port(reply_port: mach_port_t); pub fn mig_strncpy(dest: *mut ::std::os::raw::c_char, src: *const ::std::os::raw::c_char, len: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn mig_allocate(arg1: *mut vm_address_t, arg2: vm_size_t); pub fn mig_deallocate(arg1: vm_address_t, arg2: vm_size_t); pub fn clock_get_time(clock_serv: clock_serv_t, cur_time: *mut mach_timespec_t) -> kern_return_t; pub fn clock_get_attributes(clock_serv: clock_serv_t, flavor: clock_flavor_t, clock_attr: clock_attr_t, clock_attrCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn clock_alarm(clock_serv: clock_serv_t, alarm_type: alarm_type_t, alarm_time: mach_timespec_t, alarm_port: clock_reply_t) -> kern_return_t; pub fn clock_set_time(clock_ctrl: clock_ctrl_t, new_time: mach_timespec_t) -> kern_return_t; pub fn clock_set_attributes(clock_ctrl: clock_ctrl_t, flavor: clock_flavor_t, clock_attr: clock_attr_t, clock_attrCnt: mach_msg_type_number_t) -> kern_return_t; pub fn host_get_boot_info(host_priv: host_priv_t, boot_info: kernel_boot_info_t) -> kern_return_t; pub fn host_reboot(host_priv: host_priv_t, options: ::std::os::raw::c_int) -> kern_return_t; pub fn host_priv_statistics(host_priv: host_priv_t, flavor: host_flavor_t, host_info_out: host_info_t, host_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_default_memory_manager(host_priv: host_priv_t, default_manager: *mut memory_object_default_t, cluster_size: memory_object_cluster_size_t) -> kern_return_t; pub fn vm_wire(host_priv: host_priv_t, task: vm_map_t, address: vm_address_t, size: vm_size_t, desired_access: vm_prot_t) -> kern_return_t; pub fn thread_wire(host_priv: host_priv_t, thread: thread_act_t, wired: boolean_t) -> kern_return_t; pub fn vm_allocate_cpm(host_priv: host_priv_t, task: vm_map_t, address: *mut vm_address_t, size: vm_size_t, flags: ::std::os::raw::c_int) -> kern_return_t; pub fn host_processors(host_priv: host_priv_t, out_processor_list: *mut processor_array_t, out_processor_listCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_get_clock_control(host_priv: host_priv_t, clock_id: clock_id_t, clock_ctrl: *mut clock_ctrl_t) -> kern_return_t; pub fn kmod_create(host_priv: host_priv_t, info: vm_address_t, module: *mut kmod_t) -> kern_return_t; pub fn kmod_destroy(host_priv: host_priv_t, module: kmod_t) -> kern_return_t; pub fn kmod_control(host_priv: host_priv_t, module: kmod_t, flavor: kmod_control_flavor_t, data: *mut kmod_args_t, dataCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_get_special_port(host_priv: host_priv_t, node: ::std::os::raw::c_int, which: ::std::os::raw::c_int, port: *mut mach_port_t) -> kern_return_t; pub fn host_set_special_port(host_priv: host_priv_t, which: ::std::os::raw::c_int, port: mach_port_t) -> kern_return_t; pub fn host_set_exception_ports(host_priv: host_priv_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t) -> kern_return_t; pub fn host_get_exception_ports(host_priv: host_priv_t, exception_mask: exception_mask_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlers: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn host_swap_exception_ports(host_priv: host_priv_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlerss: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn mach_vm_wire(host_priv: host_priv_t, task: vm_map_t, address: mach_vm_address_t, size: mach_vm_size_t, desired_access: vm_prot_t) -> kern_return_t; pub fn host_processor_sets(host_priv: host_priv_t, processor_sets: *mut processor_set_name_array_t, processor_setsCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_processor_set_priv(host_priv: host_priv_t, set_name: processor_set_name_t, set: *mut processor_set_t) -> kern_return_t; pub fn set_dp_control_port(host: host_priv_t, control_port: mach_port_t) -> kern_return_t; pub fn get_dp_control_port(host: host_priv_t, contorl_port: *mut mach_port_t) -> kern_return_t; pub fn host_set_UNDServer(host: host_priv_t, server: UNDServerRef) -> kern_return_t; pub fn host_get_UNDServer(host: host_priv_t, server: *mut UNDServerRef) -> kern_return_t; pub fn kext_request(host_priv: host_priv_t, user_log_flags: uint32_t, request_data: vm_offset_t, request_dataCnt: mach_msg_type_number_t, response_data: *mut vm_offset_t, response_dataCnt: *mut mach_msg_type_number_t, log_data: *mut vm_offset_t, log_dataCnt: *mut mach_msg_type_number_t, op_result: *mut kern_return_t) -> kern_return_t; pub fn host_security_create_task_token(host_security: host_security_t, parent_task: task_t, sec_token: security_token_t, audit_token: audit_token_t, host: host_t, ledgers: ledger_array_t, ledgersCnt: mach_msg_type_number_t, inherit_memory: boolean_t, child_task: *mut task_t) -> kern_return_t; pub fn host_security_set_task_token(host_security: host_security_t, target_task: task_t, sec_token: security_token_t, audit_token: audit_token_t, host: host_t) -> kern_return_t; pub fn lock_acquire(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_release(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_try(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_make_stable(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_handoff(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_handoff_accept(lock_set: lock_set_t, lock_id: ::std::os::raw::c_int) -> kern_return_t; pub fn processor_start(processor: processor_t) -> kern_return_t; pub fn processor_exit(processor: processor_t) -> kern_return_t; pub fn processor_info(processor: processor_t, flavor: processor_flavor_t, host: *mut host_t, processor_info_out: processor_info_t, processor_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn processor_control(processor: processor_t, processor_cmd: processor_info_t, processor_cmdCnt: mach_msg_type_number_t) -> kern_return_t; pub fn processor_assign(processor: processor_t, new_set: processor_set_t, wait: boolean_t) -> kern_return_t; pub fn processor_get_assignment(processor: processor_t, assigned_set: *mut processor_set_name_t) -> kern_return_t; pub fn processor_set_statistics(pset: processor_set_name_t, flavor: processor_set_flavor_t, info_out: processor_set_info_t, info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn processor_set_destroy(set: processor_set_t) -> kern_return_t; pub fn processor_set_max_priority(processor_set: processor_set_t, max_priority: ::std::os::raw::c_int, change_threads: boolean_t) -> kern_return_t; pub fn processor_set_policy_enable(processor_set: processor_set_t, policy: ::std::os::raw::c_int) -> kern_return_t; pub fn processor_set_policy_disable(processor_set: processor_set_t, policy: ::std::os::raw::c_int, change_threads: boolean_t) -> kern_return_t; pub fn processor_set_tasks(processor_set: processor_set_t, task_list: *mut task_array_t, task_listCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn processor_set_threads(processor_set: processor_set_t, thread_list: *mut thread_act_array_t, thread_listCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn processor_set_policy_control(pset: processor_set_t, flavor: processor_set_flavor_t, policy_info: processor_set_info_t, policy_infoCnt: mach_msg_type_number_t, change: boolean_t) -> kern_return_t; pub fn processor_set_stack_usage(pset: processor_set_t, ltotal: *mut ::std::os::raw::c_uint, space: *mut vm_size_t, resident: *mut vm_size_t, maxusage: *mut vm_size_t, maxstack: *mut vm_offset_t) -> kern_return_t; pub fn processor_set_info(set_name: processor_set_name_t, flavor: ::std::os::raw::c_int, host: *mut host_t, info_out: processor_set_info_t, info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn semaphore_signal(semaphore: semaphore_t) -> kern_return_t; pub fn semaphore_signal_all(semaphore: semaphore_t) -> kern_return_t; pub fn semaphore_wait(semaphore: semaphore_t) -> kern_return_t; pub fn semaphore_timedwait(semaphore: semaphore_t, wait_time: mach_timespec_t) -> kern_return_t; pub fn semaphore_timedwait_signal(wait_semaphore: semaphore_t, signal_semaphore: semaphore_t, wait_time: mach_timespec_t) -> kern_return_t; pub fn semaphore_wait_signal(wait_semaphore: semaphore_t, signal_semaphore: semaphore_t) -> kern_return_t; pub fn semaphore_signal_thread(semaphore: semaphore_t, thread: thread_t) -> kern_return_t; pub fn task_create(target_task: task_t, ledgers: ledger_array_t, ledgersCnt: mach_msg_type_number_t, inherit_memory: boolean_t, child_task: *mut task_t) -> kern_return_t; pub fn task_terminate(target_task: task_t) -> kern_return_t; pub fn task_threads(target_task: task_t, act_list: *mut thread_act_array_t, act_listCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_ports_register(target_task: task_t, init_port_set: mach_port_array_t, init_port_setCnt: mach_msg_type_number_t) -> kern_return_t; pub fn mach_ports_lookup(target_task: task_t, init_port_set: *mut mach_port_array_t, init_port_setCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn task_info(target_task: task_name_t, flavor: task_flavor_t, task_info_out: task_info_t, task_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn task_set_info(target_task: task_t, flavor: task_flavor_t, task_info_in: task_info_t, task_info_inCnt: mach_msg_type_number_t) -> kern_return_t; pub fn task_suspend(target_task: task_t) -> kern_return_t; pub fn task_resume(target_task: task_t) -> kern_return_t; pub fn task_get_special_port(task: task_t, which_port: ::std::os::raw::c_int, special_port: *mut mach_port_t) -> kern_return_t; pub fn task_set_special_port(task: task_t, which_port: ::std::os::raw::c_int, special_port: mach_port_t) -> kern_return_t; pub fn thread_create(parent_task: task_t, child_act: *mut thread_act_t) -> kern_return_t; pub fn thread_create_running(parent_task: task_t, flavor: thread_state_flavor_t, new_state: thread_state_t, new_stateCnt: mach_msg_type_number_t, child_act: *mut thread_act_t) -> kern_return_t; pub fn task_set_exception_ports(task: task_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t) -> kern_return_t; pub fn task_get_exception_ports(task: task_t, exception_mask: exception_mask_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlers: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn task_swap_exception_ports(task: task_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlerss: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn lock_set_create(task: task_t, new_lock_set: *mut lock_set_t, n_ulocks: ::std::os::raw::c_int, policy: ::std::os::raw::c_int) -> kern_return_t; pub fn lock_set_destroy(task: task_t, lock_set: lock_set_t) -> kern_return_t; pub fn semaphore_create(task: task_t, semaphore: *mut semaphore_t, policy: ::std::os::raw::c_int, value: ::std::os::raw::c_int) -> kern_return_t; pub fn semaphore_destroy(task: task_t, semaphore: semaphore_t) -> kern_return_t; pub fn task_policy_set(task: task_t, flavor: task_policy_flavor_t, policy_info: task_policy_t, policy_infoCnt: mach_msg_type_number_t) -> kern_return_t; pub fn task_policy_get(task: task_t, flavor: task_policy_flavor_t, policy_info: task_policy_t, policy_infoCnt: *mut mach_msg_type_number_t, get_default: *mut boolean_t) -> kern_return_t; pub fn task_sample(task: task_t, reply: mach_port_t) -> kern_return_t; pub fn task_policy(task: task_t, policy: policy_t, base: policy_base_t, baseCnt: mach_msg_type_number_t, set_limit: boolean_t, change: boolean_t) -> kern_return_t; pub fn task_set_emulation(target_port: task_t, routine_entry_pt: vm_address_t, routine_number: ::std::os::raw::c_int) -> kern_return_t; pub fn task_get_emulation_vector(task: task_t, vector_start: *mut ::std::os::raw::c_int, emulation_vector: *mut emulation_vector_t, emulation_vectorCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn task_set_emulation_vector(task: task_t, vector_start: ::std::os::raw::c_int, emulation_vector: emulation_vector_t, emulation_vectorCnt: mach_msg_type_number_t) -> kern_return_t; pub fn task_set_ras_pc(target_task: task_t, basepc: vm_address_t, boundspc: vm_address_t) -> kern_return_t; pub fn task_zone_info(target_task: task_t, names: *mut mach_zone_name_array_t, namesCnt: *mut mach_msg_type_number_t, info: *mut task_zone_info_array_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn task_assign(task: task_t, new_set: processor_set_t, assign_threads: boolean_t) -> kern_return_t; pub fn task_assign_default(task: task_t, assign_threads: boolean_t) -> kern_return_t; pub fn task_get_assignment(task: task_t, assigned_set: *mut processor_set_name_t) -> kern_return_t; pub fn task_set_policy(task: task_t, pset: processor_set_t, policy: policy_t, base: policy_base_t, baseCnt: mach_msg_type_number_t, limit: policy_limit_t, limitCnt: mach_msg_type_number_t, change: boolean_t) -> kern_return_t; pub fn task_get_state(task: task_t, flavor: thread_state_flavor_t, old_state: thread_state_t, old_stateCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn task_set_state(task: task_t, flavor: thread_state_flavor_t, new_state: thread_state_t, new_stateCnt: mach_msg_type_number_t) -> kern_return_t; pub fn task_set_phys_footprint_limit(task: task_t, new_limit: ::std::os::raw::c_int, old_limit: *mut ::std::os::raw::c_int) -> kern_return_t; pub fn task_suspend2(target_task: task_t, suspend_token: *mut task_suspension_token_t) -> kern_return_t; pub fn task_resume2(suspend_token: task_suspension_token_t) -> kern_return_t; pub fn task_purgable_info(task: task_t, stats: *mut task_purgable_info_t) -> kern_return_t; pub fn task_get_mach_voucher(task: task_t, which: mach_voucher_selector_t, voucher: *mut ipc_voucher_t) -> kern_return_t; pub fn task_set_mach_voucher(task: task_t, voucher: ipc_voucher_t) -> kern_return_t; pub fn task_swap_mach_voucher(task: task_t, new_voucher: ipc_voucher_t, old_voucher: *mut ipc_voucher_t) -> kern_return_t; pub fn thread_terminate(target_act: thread_act_t) -> kern_return_t; pub fn act_get_state(target_act: thread_act_t, flavor: ::std::os::raw::c_int, old_state: thread_state_t, old_stateCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn act_set_state(target_act: thread_act_t, flavor: ::std::os::raw::c_int, new_state: thread_state_t, new_stateCnt: mach_msg_type_number_t) -> kern_return_t; pub fn thread_get_state(target_act: thread_act_t, flavor: thread_state_flavor_t, old_state: thread_state_t, old_stateCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn thread_set_state(target_act: thread_act_t, flavor: thread_state_flavor_t, new_state: thread_state_t, new_stateCnt: mach_msg_type_number_t) -> kern_return_t; pub fn thread_suspend(target_act: thread_act_t) -> kern_return_t; pub fn thread_resume(target_act: thread_act_t) -> kern_return_t; pub fn thread_abort(target_act: thread_act_t) -> kern_return_t; pub fn thread_abort_safely(target_act: thread_act_t) -> kern_return_t; pub fn thread_depress_abort(thread: thread_act_t) -> kern_return_t; pub fn thread_get_special_port(thr_act: thread_act_t, which_port: ::std::os::raw::c_int, special_port: *mut mach_port_t) -> kern_return_t; pub fn thread_set_special_port(thr_act: thread_act_t, which_port: ::std::os::raw::c_int, special_port: mach_port_t) -> kern_return_t; pub fn thread_info(target_act: thread_act_t, flavor: thread_flavor_t, thread_info_out: thread_info_t, thread_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn thread_set_exception_ports(thread: thread_act_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t) -> kern_return_t; pub fn thread_get_exception_ports(thread: thread_act_t, exception_mask: exception_mask_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlers: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn thread_swap_exception_ports(thread: thread_act_t, exception_mask: exception_mask_t, new_port: mach_port_t, behavior: exception_behavior_t, new_flavor: thread_state_flavor_t, masks: exception_mask_array_t, masksCnt: *mut mach_msg_type_number_t, old_handlers: exception_handler_array_t, old_behaviors: exception_behavior_array_t, old_flavors: exception_flavor_array_t) -> kern_return_t; pub fn thread_policy(thr_act: thread_act_t, policy: policy_t, base: policy_base_t, baseCnt: mach_msg_type_number_t, set_limit: boolean_t) -> kern_return_t; pub fn thread_policy_set(thread: thread_act_t, flavor: thread_policy_flavor_t, policy_info: thread_policy_t, policy_infoCnt: mach_msg_type_number_t) -> kern_return_t; pub fn thread_policy_get(thread: thread_act_t, flavor: thread_policy_flavor_t, policy_info: thread_policy_t, policy_infoCnt: *mut mach_msg_type_number_t, get_default: *mut boolean_t) -> kern_return_t; pub fn thread_sample(thread: thread_act_t, reply: mach_port_t) -> kern_return_t; pub fn etap_trace_thread(target_act: thread_act_t, trace_status: boolean_t) -> kern_return_t; pub fn thread_assign(thread: thread_act_t, new_set: processor_set_t) -> kern_return_t; pub fn thread_assign_default(thread: thread_act_t) -> kern_return_t; pub fn thread_get_assignment(thread: thread_act_t, assigned_set: *mut processor_set_name_t) -> kern_return_t; pub fn thread_set_policy(thr_act: thread_act_t, pset: processor_set_t, policy: policy_t, base: policy_base_t, baseCnt: mach_msg_type_number_t, limit: policy_limit_t, limitCnt: mach_msg_type_number_t) -> kern_return_t; pub fn thread_get_mach_voucher(thr_act: thread_act_t, which: mach_voucher_selector_t, voucher: *mut ipc_voucher_t) -> kern_return_t; pub fn thread_set_mach_voucher(thr_act: thread_act_t, voucher: ipc_voucher_t) -> kern_return_t; pub fn thread_swap_mach_voucher(thr_act: thread_act_t, new_voucher: ipc_voucher_t, old_voucher: *mut ipc_voucher_t) -> kern_return_t; pub fn vm_region(target_task: vm_map_t, address: *mut vm_address_t, size: *mut vm_size_t, flavor: vm_region_flavor_t, info: vm_region_info_t, infoCnt: *mut mach_msg_type_number_t, object_name: *mut mach_port_t) -> kern_return_t; pub fn vm_allocate(target_task: vm_map_t, address: *mut vm_address_t, size: vm_size_t, flags: ::std::os::raw::c_int) -> kern_return_t; pub fn vm_deallocate(target_task: vm_map_t, address: vm_address_t, size: vm_size_t) -> kern_return_t; pub fn vm_protect(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, set_maximum: boolean_t, new_protection: vm_prot_t) -> kern_return_t; pub fn vm_inherit(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, new_inheritance: vm_inherit_t) -> kern_return_t; pub fn vm_read(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, data: *mut vm_offset_t, dataCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn vm_read_list(target_task: vm_map_t, data_list: vm_read_entry_t, count: natural_t) -> kern_return_t; pub fn vm_write(target_task: vm_map_t, address: vm_address_t, data: vm_offset_t, dataCnt: mach_msg_type_number_t) -> kern_return_t; pub fn vm_copy(target_task: vm_map_t, source_address: vm_address_t, size: vm_size_t, dest_address: vm_address_t) -> kern_return_t; pub fn vm_read_overwrite(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, data: vm_address_t, outsize: *mut vm_size_t) -> kern_return_t; pub fn vm_msync(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, sync_flags: vm_sync_t) -> kern_return_t; pub fn vm_behavior_set(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, new_behavior: vm_behavior_t) -> kern_return_t; pub fn vm_map(target_task: vm_map_t, address: *mut vm_address_t, size: vm_size_t, mask: vm_address_t, flags: ::std::os::raw::c_int, object: mem_entry_name_port_t, offset: vm_offset_t, copy: boolean_t, cur_protection: vm_prot_t, max_protection: vm_prot_t, inheritance: vm_inherit_t) -> kern_return_t; pub fn vm_machine_attribute(target_task: vm_map_t, address: vm_address_t, size: vm_size_t, attribute: vm_machine_attribute_t, value: *mut vm_machine_attribute_val_t) -> kern_return_t; pub fn vm_remap(target_task: vm_map_t, target_address: *mut vm_address_t, size: vm_size_t, mask: vm_address_t, flags: ::std::os::raw::c_int, src_task: vm_map_t, src_address: vm_address_t, copy: boolean_t, cur_protection: *mut vm_prot_t, max_protection: *mut vm_prot_t, inheritance: vm_inherit_t) -> kern_return_t; pub fn task_wire(target_task: vm_map_t, must_wire: boolean_t) -> kern_return_t; pub fn mach_make_memory_entry(target_task: vm_map_t, size: *mut vm_size_t, offset: vm_offset_t, permission: vm_prot_t, object_handle: *mut mem_entry_name_port_t, parent_entry: mem_entry_name_port_t) -> kern_return_t; pub fn vm_map_page_query(target_map: vm_map_t, offset: vm_offset_t, disposition: *mut integer_t, ref_count: *mut integer_t) -> kern_return_t; pub fn mach_vm_region_info(task: vm_map_t, address: vm_address_t, region: *mut vm_info_region_t, objects: *mut vm_info_object_array_t, objectsCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn vm_mapped_pages_info(task: vm_map_t, pages: *mut page_address_array_t, pagesCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn vm_region_recurse(target_task: vm_map_t, address: *mut vm_address_t, size: *mut vm_size_t, nesting_depth: *mut natural_t, info: vm_region_recurse_info_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn vm_region_recurse_64(target_task: vm_map_t, address: *mut vm_address_t, size: *mut vm_size_t, nesting_depth: *mut natural_t, info: vm_region_recurse_info_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_vm_region_info_64(task: vm_map_t, address: vm_address_t, region: *mut vm_info_region_64_t, objects: *mut vm_info_object_array_t, objectsCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn vm_region_64(target_task: vm_map_t, address: *mut vm_address_t, size: *mut vm_size_t, flavor: vm_region_flavor_t, info: vm_region_info_t, infoCnt: *mut mach_msg_type_number_t, object_name: *mut mach_port_t) -> kern_return_t; pub fn mach_make_memory_entry_64(target_task: vm_map_t, size: *mut memory_object_size_t, offset: memory_object_offset_t, permission: vm_prot_t, object_handle: *mut mach_port_t, parent_entry: mem_entry_name_port_t) -> kern_return_t; pub fn vm_map_64(target_task: vm_map_t, address: *mut vm_address_t, size: vm_size_t, mask: vm_address_t, flags: ::std::os::raw::c_int, object: mem_entry_name_port_t, offset: memory_object_offset_t, copy: boolean_t, cur_protection: vm_prot_t, max_protection: vm_prot_t, inheritance: vm_inherit_t) -> kern_return_t; pub fn vm_purgable_control(target_task: vm_map_t, address: vm_address_t, control: vm_purgable_t, state: *mut ::std::os::raw::c_int) -> kern_return_t; pub fn mach_port_names(task: ipc_space_t, names: *mut mach_port_name_array_t, namesCnt: *mut mach_msg_type_number_t, types: *mut mach_port_type_array_t, typesCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_type(task: ipc_space_t, name: mach_port_name_t, ptype: *mut mach_port_type_t) -> kern_return_t; pub fn mach_port_rename(task: ipc_space_t, old_name: mach_port_name_t, new_name: mach_port_name_t) -> kern_return_t; pub fn mach_port_allocate_name(task: ipc_space_t, right: mach_port_right_t, name: mach_port_name_t) -> kern_return_t; pub fn mach_port_allocate(task: ipc_space_t, right: mach_port_right_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn mach_port_destroy(task: ipc_space_t, name: mach_port_name_t) -> kern_return_t; pub fn mach_port_deallocate(task: ipc_space_t, name: mach_port_name_t) -> kern_return_t; pub fn mach_port_get_refs(task: ipc_space_t, name: mach_port_name_t, right: mach_port_right_t, refs: *mut mach_port_urefs_t) -> kern_return_t; pub fn mach_port_mod_refs(task: ipc_space_t, name: mach_port_name_t, right: mach_port_right_t, delta: mach_port_delta_t) -> kern_return_t; pub fn mach_port_peek(task: ipc_space_t, name: mach_port_name_t, trailer_type: mach_msg_trailer_type_t, request_seqnop: *mut mach_port_seqno_t, msg_sizep: *mut mach_msg_size_t, msg_idp: *mut mach_msg_id_t, trailer_infop: mach_msg_trailer_info_t, trailer_infopCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_set_mscount(task: ipc_space_t, name: mach_port_name_t, mscount: mach_port_mscount_t) -> kern_return_t; pub fn mach_port_get_set_status(task: ipc_space_t, name: mach_port_name_t, members: *mut mach_port_name_array_t, membersCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_move_member(task: ipc_space_t, member: mach_port_name_t, after: mach_port_name_t) -> kern_return_t; pub fn mach_port_request_notification(task: ipc_space_t, name: mach_port_name_t, msgid: mach_msg_id_t, sync: mach_port_mscount_t, notify: mach_port_t, notifyPoly: mach_msg_type_name_t, previous: *mut mach_port_t) -> kern_return_t; pub fn mach_port_insert_right(task: ipc_space_t, name: mach_port_name_t, poly: mach_port_t, polyPoly: mach_msg_type_name_t) -> kern_return_t; pub fn mach_port_extract_right(task: ipc_space_t, name: mach_port_name_t, msgt_name: mach_msg_type_name_t, poly: *mut mach_port_t, polyPoly: *mut mach_msg_type_name_t) -> kern_return_t; pub fn mach_port_set_seqno(task: ipc_space_t, name: mach_port_name_t, seqno: mach_port_seqno_t) -> kern_return_t; pub fn mach_port_get_attributes(task: ipc_space_t, name: mach_port_name_t, flavor: mach_port_flavor_t, port_info_out: mach_port_info_t, port_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_set_attributes(task: ipc_space_t, name: mach_port_name_t, flavor: mach_port_flavor_t, port_info: mach_port_info_t, port_infoCnt: mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_allocate_qos(task: ipc_space_t, right: mach_port_right_t, qos: *mut mach_port_qos_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn mach_port_allocate_full(task: ipc_space_t, right: mach_port_right_t, proto: mach_port_t, qos: *mut mach_port_qos_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn task_set_port_space(task: ipc_space_t, table_entries: ::std::os::raw::c_int) -> kern_return_t; pub fn mach_port_get_srights(task: ipc_space_t, name: mach_port_name_t, srights: *mut mach_port_rights_t) -> kern_return_t; pub fn mach_port_space_info(task: ipc_space_t, space_info: *mut ipc_info_space_t, table_info: *mut ipc_info_name_array_t, table_infoCnt: *mut mach_msg_type_number_t, tree_info: *mut ipc_info_tree_name_array_t, tree_infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_port_dnrequest_info(task: ipc_space_t, name: mach_port_name_t, dnr_total: *mut ::std::os::raw::c_uint, dnr_used: *mut ::std::os::raw::c_uint) -> kern_return_t; pub fn mach_port_kernel_object(task: ipc_space_t, name: mach_port_name_t, object_type: *mut ::std::os::raw::c_uint, object_addr: *mut ::std::os::raw::c_uint) -> kern_return_t; pub fn mach_port_insert_member(task: ipc_space_t, name: mach_port_name_t, pset: mach_port_name_t) -> kern_return_t; pub fn mach_port_extract_member(task: ipc_space_t, name: mach_port_name_t, pset: mach_port_name_t) -> kern_return_t; pub fn mach_port_get_context(task: ipc_space_t, name: mach_port_name_t, context: *mut mach_port_context_t) -> kern_return_t; pub fn mach_port_set_context(task: ipc_space_t, name: mach_port_name_t, context: mach_port_context_t) -> kern_return_t; pub fn mach_port_kobject(task: ipc_space_t, name: mach_port_name_t, object_type: *mut natural_t, object_addr: *mut mach_vm_address_t) -> kern_return_t; pub fn mach_port_construct(task: ipc_space_t, options: mach_port_options_ptr_t, context: mach_port_context_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn mach_port_destruct(task: ipc_space_t, name: mach_port_name_t, srdelta: mach_port_delta_t, guard: mach_port_context_t) -> kern_return_t; pub fn mach_port_guard(task: ipc_space_t, name: mach_port_name_t, guard: mach_port_context_t, strict: boolean_t) -> kern_return_t; pub fn mach_port_unguard(task: ipc_space_t, name: mach_port_name_t, guard: mach_port_context_t) -> kern_return_t; pub fn mach_port_space_basic_info(task: ipc_space_t, basic_info: *mut ipc_info_space_basic_t) -> kern_return_t; pub fn mach_host_self() -> mach_port_t; pub fn mach_thread_self() -> mach_port_t; pub fn host_page_size(arg1: host_t, arg2: *mut vm_size_t) -> kern_return_t; pub fn clock_sleep_trap(clock_name: mach_port_name_t, sleep_type: sleep_type_t, sleep_sec: ::std::os::raw::c_int, sleep_nsec: ::std::os::raw::c_int, wakeup_time: *mut mach_timespec_t) -> kern_return_t; pub fn _kernelrpc_mach_vm_allocate_trap(target: mach_port_name_t, addr: *mut mach_vm_offset_t, size: mach_vm_size_t, flags: ::std::os::raw::c_int) -> kern_return_t; pub fn _kernelrpc_mach_vm_deallocate_trap(target: mach_port_name_t, address: mach_vm_address_t, size: mach_vm_size_t) -> kern_return_t; pub fn _kernelrpc_mach_vm_protect_trap(target: mach_port_name_t, address: mach_vm_address_t, size: mach_vm_size_t, set_maximum: boolean_t, new_protection: vm_prot_t) -> kern_return_t; pub fn _kernelrpc_mach_vm_map_trap(target: mach_port_name_t, address: *mut mach_vm_offset_t, size: mach_vm_size_t, mask: mach_vm_offset_t, flags: ::std::os::raw::c_int, cur_protection: vm_prot_t) -> kern_return_t; pub fn _kernelrpc_mach_port_allocate_trap(target: mach_port_name_t, right: mach_port_right_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_destroy_trap(target: mach_port_name_t, name: mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_deallocate_trap(target: mach_port_name_t, name: mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_mod_refs_trap(target: mach_port_name_t, name: mach_port_name_t, right: mach_port_right_t, delta: mach_port_delta_t) -> kern_return_t; pub fn _kernelrpc_mach_port_move_member_trap(target: mach_port_name_t, member: mach_port_name_t, after: mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_insert_right_trap(target: mach_port_name_t, name: mach_port_name_t, poly: mach_port_name_t, polyPoly: mach_msg_type_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_insert_member_trap(target: mach_port_name_t, name: mach_port_name_t, pset: mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_extract_member_trap(target: mach_port_name_t, name: mach_port_name_t, pset: mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_construct_trap(target: mach_port_name_t, options: *mut mach_port_options_t, context: uint64_t, name: *mut mach_port_name_t) -> kern_return_t; pub fn _kernelrpc_mach_port_destruct_trap(target: mach_port_name_t, name: mach_port_name_t, srdelta: mach_port_delta_t, guard: uint64_t) -> kern_return_t; pub fn _kernelrpc_mach_port_guard_trap(target: mach_port_name_t, name: mach_port_name_t, guard: uint64_t, strict: boolean_t) -> kern_return_t; pub fn _kernelrpc_mach_port_unguard_trap(target: mach_port_name_t, name: mach_port_name_t, guard: uint64_t) -> kern_return_t; pub fn macx_swapon(filename: uint64_t, flags: ::std::os::raw::c_int, size: ::std::os::raw::c_int, priority: ::std::os::raw::c_int) -> kern_return_t; pub fn macx_swapoff(filename: uint64_t, flags: ::std::os::raw::c_int) -> kern_return_t; pub fn macx_triggers(hi_water: ::std::os::raw::c_int, low_water: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, alert_port: mach_port_t) -> kern_return_t; pub fn macx_backing_store_suspend(suspend: boolean_t) -> kern_return_t; pub fn macx_backing_store_recovery(pid: ::std::os::raw::c_int) -> kern_return_t; pub fn swtch_pri(pri: ::std::os::raw::c_int) -> boolean_t; pub fn swtch() -> boolean_t; pub fn thread_switch(thread_name: mach_port_name_t, option: ::std::os::raw::c_int, option_time: mach_msg_timeout_t) -> kern_return_t; pub fn task_self_trap() -> mach_port_name_t; pub fn task_for_pid(target_tport: mach_port_name_t, pid: ::std::os::raw::c_int, t: *mut mach_port_name_t) -> kern_return_t; pub fn task_name_for_pid(target_tport: mach_port_name_t, pid: ::std::os::raw::c_int, tn: *mut mach_port_name_t) -> kern_return_t; pub fn pid_for_task(t: mach_port_name_t, x: *mut ::std::os::raw::c_int) -> kern_return_t; pub fn host_info(host: host_t, flavor: host_flavor_t, host_info_out: host_info_t, host_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_kernel_version(host: host_t, kernel_version: kernel_version_t) -> kern_return_t; pub fn _host_page_size(host: host_t, out_page_size: *mut vm_size_t) -> kern_return_t; pub fn mach_memory_object_memory_entry(host: host_t, internal: boolean_t, size: vm_size_t, permission: vm_prot_t, pager: memory_object_t, entry_handle: *mut mach_port_t) -> kern_return_t; pub fn host_processor_info(host: host_t, flavor: processor_flavor_t, out_processor_count: *mut natural_t, out_processor_info: *mut processor_info_array_t, out_processor_infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_get_io_master(host: host_t, io_master: *mut io_master_t) -> kern_return_t; pub fn host_get_clock_service(host: host_t, clock_id: clock_id_t, clock_serv: *mut clock_serv_t) -> kern_return_t; pub fn kmod_get_info(host: host_t, modules: *mut kmod_args_t, modulesCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_zone_info(host: host_priv_t, names: *mut zone_name_array_t, namesCnt: *mut mach_msg_type_number_t, info: *mut zone_info_array_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_virtual_physical_table_info(host: host_t, info: *mut hash_info_bucket_array_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn processor_set_default(host: host_t, default_set: *mut processor_set_name_t) -> kern_return_t; pub fn processor_set_create(host: host_t, new_set: *mut processor_set_t, new_name: *mut processor_set_name_t) -> kern_return_t; pub fn mach_memory_object_memory_entry_64(host: host_t, internal: boolean_t, size: memory_object_size_t, permission: vm_prot_t, pager: memory_object_t, entry_handle: *mut mach_port_t) -> kern_return_t; pub fn host_statistics(host_priv: host_t, flavor: host_flavor_t, host_info_out: host_info_t, host_info_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_request_notification(host: host_t, notify_type: host_flavor_t, notify_port: mach_port_t) -> kern_return_t; pub fn host_lockgroup_info(host: host_t, lockgroup_info: *mut lockgroup_info_array_t, lockgroup_infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_statistics64(host_priv: host_t, flavor: host_flavor_t, host_info64_out: host_info64_t, host_info64_outCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn mach_zone_info(host: host_priv_t, names: *mut mach_zone_name_array_t, namesCnt: *mut mach_msg_type_number_t, info: *mut mach_zone_info_array_t, infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_create_mach_voucher(host: host_t, recipes: mach_voucher_attr_raw_recipe_array_t, recipesCnt: mach_msg_type_number_t, voucher: *mut ipc_voucher_t) -> kern_return_t; pub fn host_register_mach_voucher_attr_manager(host: host_t, attr_manager: mach_voucher_attr_manager_t, default_value: mach_voucher_attr_value_handle_t, new_key: *mut mach_voucher_attr_key_t, new_attr_control: *mut ipc_voucher_attr_control_t) -> kern_return_t; pub fn host_register_well_known_mach_voucher_attr_manager(host: host_t, attr_manager: mach_voucher_attr_manager_t, default_value: mach_voucher_attr_value_handle_t, key: mach_voucher_attr_key_t, new_attr_control: *mut ipc_voucher_attr_control_t) -> kern_return_t; pub fn host_set_atm_diagnostic_flag(host_priv: host_priv_t, diagnostic_flag: uint32_t) -> kern_return_t; pub fn host_get_atm_diagnostic_flag(host: host_t, diagnostic_flag: *mut uint32_t) -> kern_return_t; pub fn mach_memory_info(host: host_priv_t, names: *mut mach_zone_name_array_t, namesCnt: *mut mach_msg_type_number_t, info: *mut mach_zone_info_array_t, infoCnt: *mut mach_msg_type_number_t, memory_info: *mut mach_memory_info_array_t, memory_infoCnt: *mut mach_msg_type_number_t) -> kern_return_t; pub fn host_set_multiuser_config_flags(host_priv: host_priv_t, multiuser_flags: uint32_t) -> kern_return_t; pub fn host_get_multiuser_config_flags(host: host_t, multiuser_flags: *mut uint32_t) -> kern_return_t; pub fn host_check_multiuser_mode(host: host_t, multiuser_mode: *mut uint32_t) -> kern_return_t; pub fn mach_error_string(error_value: mach_error_t) -> *mut ::std::os::raw::c_char; pub fn mach_error(str: *const ::std::os::raw::c_char, error_value: mach_error_t); pub fn mach_error_type(error_value: mach_error_t) -> *mut ::std::os::raw::c_char; pub fn panic_init(arg1: mach_port_t); pub fn panic(arg1: *const ::std::os::raw::c_char, ...); pub fn safe_gets(arg1: *mut ::std::os::raw::c_char, arg2: *mut ::std::os::raw::c_char, arg3: ::std::os::raw::c_int); pub fn slot_name(arg1: cpu_type_t, arg2: cpu_subtype_t, arg3: *mut *mut ::std::os::raw::c_char, arg4: *mut *mut ::std::os::raw::c_char); pub fn mig_reply_setup(arg1: *mut mach_msg_header_t, arg2: *mut mach_msg_header_t); pub fn mach_msg_destroy(arg1: *mut mach_msg_header_t); pub fn mach_msg_receive(arg1: *mut mach_msg_header_t) -> mach_msg_return_t; pub fn mach_msg_send(arg1: *mut mach_msg_header_t) -> mach_msg_return_t; pub fn mach_msg_server_once(arg1: ::std::option::Option<unsafe extern "C" fn(arg1: *mut mach_msg_header_t, arg2: *mut mach_msg_header_t) -> boolean_t>, arg2: mach_msg_size_t, arg3: mach_port_t, arg4: mach_msg_options_t) -> mach_msg_return_t; pub fn mach_msg_server(arg1: ::std::option::Option<unsafe extern "C" fn(arg1: *mut mach_msg_header_t, arg2: *mut mach_msg_header_t) -> boolean_t>, arg2: mach_msg_size_t, arg3: mach_port_t, arg4: mach_msg_options_t) -> mach_msg_return_t; pub fn mach_msg_server_importance(arg1: ::std::option::Option<unsafe extern "C" fn(arg1: *mut mach_msg_header_t, arg2: *mut mach_msg_header_t) -> boolean_t>, arg2: mach_msg_size_t, arg3: mach_port_t, arg4: mach_msg_options_t) -> mach_msg_return_t; pub fn clock_get_res(arg1: mach_port_t, arg2: *mut clock_res_t) -> kern_return_t; pub fn clock_set_res(arg1: mach_port_t, arg2: clock_res_t) -> kern_return_t; pub fn clock_sleep(arg1: mach_port_t, arg2: ::std::os::raw::c_int, arg3: mach_timespec_t, arg4: *mut mach_timespec_t) -> kern_return_t; pub fn voucher_mach_msg_set(msg: *mut mach_msg_header_t) -> boolean_t; pub fn voucher_mach_msg_clear(msg: *mut mach_msg_header_t); pub fn voucher_mach_msg_adopt(msg: *mut mach_msg_header_t) -> voucher_mach_msg_state_t; pub fn voucher_mach_msg_revert(state: voucher_mach_msg_state_t); pub fn _NSGetArgv() -> *mut *mut *mut ::std::os::raw::c_char; pub fn _NSGetArgc() -> *mut ::std::os::raw::c_int; pub fn _NSGetEnviron() -> *mut *mut *mut ::std::os::raw::c_char; pub fn _NSGetProgname() -> *mut *mut ::std::os::raw::c_char; pub fn _NSGetMachExecuteHeader() -> *mut Struct_mach_header_64; pub fn if_nametoindex(arg1: *const ::std::os::raw::c_char) -> ::std::os::raw::c_uint; pub fn if_indextoname(arg1: ::std::os::raw::c_uint, arg2: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn if_nameindex() -> *mut Struct_if_nameindex; pub fn if_freenameindex(arg1: *mut Struct_if_nameindex); pub fn zactor_new(task: zactor_fn, args: *mut ::std::os::raw::c_void) -> *mut zactor_t; pub fn zactor_destroy(self_p: *mut *mut zactor_t); pub fn zactor_send(_self: *mut zactor_t, msg_p: *mut *mut zmsg_t) -> ::std::os::raw::c_int; pub fn zactor_recv(_self: *mut zactor_t) -> *mut zmsg_t; pub fn zactor_is(_self: *mut ::std::os::raw::c_void) -> u8; pub fn zactor_resolve(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zactor_sock(_self: *mut zactor_t) -> *mut zsock_t; pub fn zactor_test(verbose: u8); pub fn zarmour_new() -> *mut zarmour_t; pub fn zarmour_destroy(self_p: *mut *mut zarmour_t); pub fn zarmour_encode(_self: *mut zarmour_t, data: *const byte, size: size_t) -> *mut ::std::os::raw::c_char; pub fn zarmour_decode(_self: *mut zarmour_t, data: *const ::std::os::raw::c_char) -> *mut zchunk_t; pub fn zarmour_mode(_self: *mut zarmour_t) -> ::std::os::raw::c_int; pub fn zarmour_mode_str(_self: *mut zarmour_t) -> *const ::std::os::raw::c_char; pub fn zarmour_set_mode(_self: *mut zarmour_t, mode: ::std::os::raw::c_int); pub fn zarmour_pad(_self: *mut zarmour_t) -> u8; pub fn zarmour_set_pad(_self: *mut zarmour_t, pad: u8); pub fn zarmour_pad_char(_self: *mut zarmour_t) -> ::std::os::raw::c_char; pub fn zarmour_set_pad_char(_self: *mut zarmour_t, pad_char: ::std::os::raw::c_char); pub fn zarmour_line_breaks(_self: *mut zarmour_t) -> u8; pub fn zarmour_set_line_breaks(_self: *mut zarmour_t, line_breaks: u8); pub fn zarmour_line_length(_self: *mut zarmour_t) -> size_t; pub fn zarmour_set_line_length(_self: *mut zarmour_t, line_length: size_t); pub fn zarmour_print(_self: *mut zarmour_t); pub fn zarmour_test(verbose: u8); pub fn zcert_new() -> *mut zcert_t; pub fn zcert_new_from(public_key: *const byte, secret_key: *const byte) -> *mut zcert_t; pub fn zcert_load(filename: *const ::std::os::raw::c_char) -> *mut zcert_t; pub fn zcert_destroy(self_p: *mut *mut zcert_t); pub fn zcert_public_key(_self: *mut zcert_t) -> *const byte; pub fn zcert_secret_key(_self: *mut zcert_t) -> *const byte; pub fn zcert_public_txt(_self: *mut zcert_t) -> *const ::std::os::raw::c_char; pub fn zcert_secret_txt(_self: *mut zcert_t) -> *const ::std::os::raw::c_char; pub fn zcert_set_meta(_self: *mut zcert_t, name: *const ::std::os::raw::c_char, format: *const ::std::os::raw::c_char, ...); pub fn zcert_meta(_self: *mut zcert_t, name: *const ::std::os::raw::c_char) -> *const ::std::os::raw::c_char; pub fn zcert_meta_keys(_self: *mut zcert_t) -> *mut zlist_t; pub fn zcert_save(_self: *mut zcert_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zcert_save_public(_self: *mut zcert_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zcert_save_secret(_self: *mut zcert_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zcert_apply(_self: *mut zcert_t, socket: *mut ::std::os::raw::c_void); pub fn zcert_dup(_self: *mut zcert_t) -> *mut zcert_t; pub fn zcert_eq(_self: *mut zcert_t, compare: *mut zcert_t) -> u8; pub fn zcert_print(_self: *mut zcert_t); pub fn zcert_fprint(_self: *mut zcert_t, file: *mut FILE); pub fn zcert_test(verbose: u8); pub fn zcert_unset_meta(_self: *mut zcert_t, name: *const ::std::os::raw::c_char); pub fn zcertstore_new(location: *const ::std::os::raw::c_char) -> *mut zcertstore_t; pub fn zcertstore_destroy(self_p: *mut *mut zcertstore_t); pub fn zcertstore_lookup(_self: *mut zcertstore_t, public_key: *const ::std::os::raw::c_char) -> *mut zcert_t; pub fn zcertstore_insert(_self: *mut zcertstore_t, cert_p: *mut *mut zcert_t); pub fn zcertstore_print(_self: *mut zcertstore_t); pub fn zcertstore_fprint(_self: *mut zcertstore_t, file: *mut FILE); pub fn zcertstore_test(verbose: u8); pub fn zcertstore_set_loader(_self: *mut zcertstore_t, loader: zcertstore_loader, destructor: zcertstore_destructor, state: *mut ::std::os::raw::c_void); pub fn zcertstore_empty(_self: *mut zcertstore_t); pub fn zchunk_new(data: *const ::std::os::raw::c_void, size: size_t) -> *mut zchunk_t; pub fn zchunk_destroy(self_p: *mut *mut zchunk_t); pub fn zchunk_resize(_self: *mut zchunk_t, size: size_t); pub fn zchunk_size(_self: *mut zchunk_t) -> size_t; pub fn zchunk_max_size(_self: *mut zchunk_t) -> size_t; pub fn zchunk_data(_self: *mut zchunk_t) -> *mut byte; pub fn zchunk_set(_self: *mut zchunk_t, data: *const ::std::os::raw::c_void, size: size_t) -> size_t; pub fn zchunk_fill(_self: *mut zchunk_t, filler: byte, size: size_t) -> size_t; pub fn zchunk_append(_self: *mut zchunk_t, data: *const ::std::os::raw::c_void, size: size_t) -> size_t; pub fn zchunk_extend(_self: *mut zchunk_t, data: *const ::std::os::raw::c_void, size: size_t) -> size_t; pub fn zchunk_consume(_self: *mut zchunk_t, source: *mut zchunk_t) -> size_t; pub fn zchunk_exhausted(_self: *mut zchunk_t) -> u8; pub fn zchunk_read(handle: *mut FILE, bytes: size_t) -> *mut zchunk_t; pub fn zchunk_write(_self: *mut zchunk_t, handle: *mut FILE) -> ::std::os::raw::c_int; pub fn zchunk_slurp(filename: *const ::std::os::raw::c_char, maxsize: size_t) -> *mut zchunk_t; pub fn zchunk_dup(_self: *mut zchunk_t) -> *mut zchunk_t; pub fn zchunk_strhex(_self: *mut zchunk_t) -> *mut ::std::os::raw::c_char; pub fn zchunk_strdup(_self: *mut zchunk_t) -> *mut ::std::os::raw::c_char; pub fn zchunk_streq(_self: *mut zchunk_t, string: *const ::std::os::raw::c_char) -> u8; pub fn zchunk_pack(_self: *mut zchunk_t) -> *mut zframe_t; pub fn zchunk_unpack(frame: *mut zframe_t) -> *mut zchunk_t; pub fn zchunk_digest(_self: *mut zchunk_t) -> *const ::std::os::raw::c_char; pub fn zchunk_fprint(_self: *mut zchunk_t, file: *mut FILE); pub fn zchunk_print(_self: *mut zchunk_t); pub fn zchunk_is(_self: *mut ::std::os::raw::c_void) -> u8; pub fn zchunk_test(verbose: u8); pub fn zclock_sleep(msecs: ::std::os::raw::c_int); pub fn zclock_time() -> int64_t; pub fn zclock_mono() -> int64_t; pub fn zclock_usecs() -> int64_t; pub fn zclock_timestr() -> *mut ::std::os::raw::c_char; pub fn zclock_test(verbose: u8); pub fn zclock_log(format: *const ::std::os::raw::c_char, ...); pub fn zconfig_new(name: *const ::std::os::raw::c_char, parent: *mut zconfig_t) -> *mut zconfig_t; pub fn zconfig_load(filename: *const ::std::os::raw::c_char) -> *mut zconfig_t; pub fn zconfig_loadf(format: *const ::std::os::raw::c_char, ...) -> *mut zconfig_t; pub fn zconfig_destroy(self_p: *mut *mut zconfig_t); pub fn zconfig_name(_self: *mut zconfig_t) -> *mut ::std::os::raw::c_char; pub fn zconfig_value(_self: *mut zconfig_t) -> *mut ::std::os::raw::c_char; pub fn zconfig_put(_self: *mut zconfig_t, path: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char); pub fn zconfig_putf(_self: *mut zconfig_t, path: *const ::std::os::raw::c_char, format: *const ::std::os::raw::c_char, ...); pub fn zconfig_get(_self: *mut zconfig_t, path: *const ::std::os::raw::c_char, default_value: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char; pub fn zconfig_set_name(_self: *mut zconfig_t, name: *const ::std::os::raw::c_char); pub fn zconfig_set_value(_self: *mut zconfig_t, format: *const ::std::os::raw::c_char, ...); pub fn zconfig_child(_self: *mut zconfig_t) -> *mut zconfig_t; pub fn zconfig_next(_self: *mut zconfig_t) -> *mut zconfig_t; pub fn zconfig_locate(_self: *mut zconfig_t, path: *const ::std::os::raw::c_char) -> *mut zconfig_t; pub fn zconfig_at_depth(_self: *mut zconfig_t, level: ::std::os::raw::c_int) -> *mut zconfig_t; pub fn zconfig_execute(_self: *mut zconfig_t, handler: zconfig_fct, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zconfig_set_comment(_self: *mut zconfig_t, format: *const ::std::os::raw::c_char, ...); pub fn zconfig_comments(_self: *mut zconfig_t) -> *mut zlist_t; pub fn zconfig_save(_self: *mut zconfig_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zconfig_savef(_self: *mut zconfig_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zconfig_filename(_self: *mut zconfig_t) -> *const ::std::os::raw::c_char; pub fn zconfig_reload(self_p: *mut *mut zconfig_t) -> ::std::os::raw::c_int; pub fn zconfig_chunk_load(chunk: *mut zchunk_t) -> *mut zconfig_t; pub fn zconfig_chunk_save(_self: *mut zconfig_t) -> *mut zchunk_t; pub fn zconfig_str_load(string: *const ::std::os::raw::c_char) -> *mut zconfig_t; pub fn zconfig_str_save(_self: *mut zconfig_t) -> *mut ::std::os::raw::c_char; pub fn zconfig_has_changed(_self: *mut zconfig_t) -> u8; pub fn zconfig_fprint(_self: *mut zconfig_t, file: *mut FILE); pub fn zconfig_print(_self: *mut zconfig_t); pub fn zconfig_test(verbose: u8); pub fn zdigest_new() -> *mut zdigest_t; pub fn zdigest_destroy(self_p: *mut *mut zdigest_t); pub fn zdigest_update(_self: *mut zdigest_t, buffer: *const byte, length: size_t); pub fn zdigest_data(_self: *mut zdigest_t) -> *const byte; pub fn zdigest_size(_self: *mut zdigest_t) -> size_t; pub fn zdigest_string(_self: *mut zdigest_t) -> *mut ::std::os::raw::c_char; pub fn zdigest_test(verbose: u8); pub fn zdir_new(path: *const ::std::os::raw::c_char, parent: *const ::std::os::raw::c_char) -> *mut zdir_t; pub fn zdir_destroy(self_p: *mut *mut zdir_t); pub fn zdir_path(_self: *mut zdir_t) -> *const ::std::os::raw::c_char; pub fn zdir_modified(_self: *mut zdir_t) -> time_t; pub fn zdir_cursize(_self: *mut zdir_t) -> off_t; pub fn zdir_count(_self: *mut zdir_t) -> size_t; pub fn zdir_list(_self: *mut zdir_t) -> *mut zlist_t; pub fn zdir_remove(_self: *mut zdir_t, force: u8); pub fn zdir_diff(older: *mut zdir_t, newer: *mut zdir_t, alias: *const ::std::os::raw::c_char) -> *mut zlist_t; pub fn zdir_resync(_self: *mut zdir_t, alias: *const ::std::os::raw::c_char) -> *mut zlist_t; pub fn zdir_cache(_self: *mut zdir_t) -> *mut zhash_t; pub fn zdir_fprint(_self: *mut zdir_t, file: *mut FILE, indent: ::std::os::raw::c_int); pub fn zdir_print(_self: *mut zdir_t, indent: ::std::os::raw::c_int); pub fn zdir_watch(pipe: *mut zsock_t, unused: *mut ::std::os::raw::c_void); pub fn zdir_test(verbose: u8); pub fn zdir_flatten(_self: *mut zdir_t) -> *mut *mut zfile_t; pub fn zdir_flatten_free(files_p: *mut *mut *mut zfile_t); pub fn zdir_patch_new(path: *const ::std::os::raw::c_char, file: *mut zfile_t, op: ::std::os::raw::c_int, alias: *const ::std::os::raw::c_char) -> *mut zdir_patch_t; pub fn zdir_patch_destroy(self_p: *mut *mut zdir_patch_t); pub fn zdir_patch_dup(_self: *mut zdir_patch_t) -> *mut zdir_patch_t; pub fn zdir_patch_path(_self: *mut zdir_patch_t) -> *const ::std::os::raw::c_char; pub fn zdir_patch_file(_self: *mut zdir_patch_t) -> *mut zfile_t; pub fn zdir_patch_op(_self: *mut zdir_patch_t) -> ::std::os::raw::c_int; pub fn zdir_patch_vpath(_self: *mut zdir_patch_t) -> *const ::std::os::raw::c_char; pub fn zdir_patch_digest_set(_self: *mut zdir_patch_t); pub fn zdir_patch_digest(_self: *mut zdir_patch_t) -> *const ::std::os::raw::c_char; pub fn zdir_patch_test(verbose: u8); pub fn zfile_new(path: *const ::std::os::raw::c_char, name: *const ::std::os::raw::c_char) -> *mut zfile_t; pub fn zfile_destroy(self_p: *mut *mut zfile_t); pub fn zfile_dup(_self: *mut zfile_t) -> *mut zfile_t; pub fn zfile_filename(_self: *mut zfile_t, path: *const ::std::os::raw::c_char) -> *const ::std::os::raw::c_char; pub fn zfile_restat(_self: *mut zfile_t); pub fn zfile_modified(_self: *mut zfile_t) -> time_t; pub fn zfile_cursize(_self: *mut zfile_t) -> off_t; pub fn zfile_is_directory(_self: *mut zfile_t) -> u8; pub fn zfile_is_regular(_self: *mut zfile_t) -> u8; pub fn zfile_is_readable(_self: *mut zfile_t) -> u8; pub fn zfile_is_writeable(_self: *mut zfile_t) -> u8; pub fn zfile_is_stable(_self: *mut zfile_t) -> u8; pub fn zfile_has_changed(_self: *mut zfile_t) -> u8; pub fn zfile_remove(_self: *mut zfile_t); pub fn zfile_input(_self: *mut zfile_t) -> ::std::os::raw::c_int; pub fn zfile_output(_self: *mut zfile_t) -> ::std::os::raw::c_int; pub fn zfile_read(_self: *mut zfile_t, bytes: size_t, offset: off_t) -> *mut zchunk_t; pub fn zfile_eof(_self: *mut zfile_t) -> u8; pub fn zfile_write(_self: *mut zfile_t, chunk: *mut zchunk_t, offset: off_t) -> ::std::os::raw::c_int; pub fn zfile_readln(_self: *mut zfile_t) -> *const ::std::os::raw::c_char; pub fn zfile_close(_self: *mut zfile_t); pub fn zfile_handle(_self: *mut zfile_t) -> *mut FILE; pub fn zfile_digest(_self: *mut zfile_t) -> *const ::std::os::raw::c_char; pub fn zfile_test(verbose: u8); pub fn zfile_exists(filename: *const ::std::os::raw::c_char) -> u8; pub fn zfile_size(filename: *const ::std::os::raw::c_char) -> ssize_t; pub fn zfile_mode(filename: *const ::std::os::raw::c_char) -> mode_t; pub fn zfile_delete(filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zfile_stable(filename: *const ::std::os::raw::c_char) -> u8; pub fn zfile_mkdir(pathname: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zfile_rmdir(pathname: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zfile_mode_private(); pub fn zfile_mode_default(); pub fn zframe_new(data: *const ::std::os::raw::c_void, size: size_t) -> *mut zframe_t; pub fn zframe_new_empty() -> *mut zframe_t; pub fn zframe_from(string: *const ::std::os::raw::c_char) -> *mut zframe_t; pub fn zframe_recv(source: *mut ::std::os::raw::c_void) -> *mut zframe_t; pub fn zframe_destroy(self_p: *mut *mut zframe_t); pub fn zframe_send(self_p: *mut *mut zframe_t, dest: *mut ::std::os::raw::c_void, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zframe_size(_self: *mut zframe_t) -> size_t; pub fn zframe_data(_self: *mut zframe_t) -> *mut byte; pub fn zframe_meta(_self: *mut zframe_t, property: *const ::std::os::raw::c_char) -> *const ::std::os::raw::c_char; pub fn zframe_dup(_self: *mut zframe_t) -> *mut zframe_t; pub fn zframe_strhex(_self: *mut zframe_t) -> *mut ::std::os::raw::c_char; pub fn zframe_strdup(_self: *mut zframe_t) -> *mut ::std::os::raw::c_char; pub fn zframe_streq(_self: *mut zframe_t, string: *const ::std::os::raw::c_char) -> u8; pub fn zframe_more(_self: *mut zframe_t) -> ::std::os::raw::c_int; pub fn zframe_set_more(_self: *mut zframe_t, more: ::std::os::raw::c_int); pub fn zframe_eq(_self: *mut zframe_t, other: *mut zframe_t) -> u8; pub fn zframe_reset(_self: *mut zframe_t, data: *const ::std::os::raw::c_void, size: size_t); pub fn zframe_print(_self: *mut zframe_t, prefix: *const ::std::os::raw::c_char); pub fn zframe_is(_self: *mut ::std::os::raw::c_void) -> u8; pub fn zframe_test(verbose: u8); pub fn zframe_routing_id(_self: *mut zframe_t) -> uint32_t; pub fn zframe_set_routing_id(_self: *mut zframe_t, routing_id: uint32_t); pub fn zframe_group(_self: *mut zframe_t) -> *const ::std::os::raw::c_char; pub fn zframe_set_group(_self: *mut zframe_t, group: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zframe_recv_nowait(source: *mut ::std::os::raw::c_void) -> *mut zframe_t; pub fn zframe_fprint(_self: *mut zframe_t, prefix: *const ::std::os::raw::c_char, file: *mut FILE); pub fn zhash_new() -> *mut zhash_t; pub fn zhash_unpack(frame: *mut zframe_t) -> *mut zhash_t; pub fn zhash_destroy(self_p: *mut *mut zhash_t); pub fn zhash_insert(_self: *mut zhash_t, key: *const ::std::os::raw::c_char, item: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zhash_update(_self: *mut zhash_t, key: *const ::std::os::raw::c_char, item: *mut ::std::os::raw::c_void); pub fn zhash_delete(_self: *mut zhash_t, key: *const ::std::os::raw::c_char); pub fn zhash_lookup(_self: *mut zhash_t, key: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_void; pub fn zhash_rename(_self: *mut zhash_t, old_key: *const ::std::os::raw::c_char, new_key: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zhash_freefn(_self: *mut zhash_t, key: *const ::std::os::raw::c_char, free_fn: zhash_free_fn) -> *mut ::std::os::raw::c_void; pub fn zhash_size(_self: *mut zhash_t) -> size_t; pub fn zhash_dup(_self: *mut zhash_t) -> *mut zhash_t; pub fn zhash_keys(_self: *mut zhash_t) -> *mut zlist_t; pub fn zhash_first(_self: *mut zhash_t) -> *mut ::std::os::raw::c_void; pub fn zhash_next(_self: *mut zhash_t) -> *mut ::std::os::raw::c_void; pub fn zhash_cursor(_self: *mut zhash_t) -> *const ::std::os::raw::c_char; pub fn zhash_comment(_self: *mut zhash_t, format: *const ::std::os::raw::c_char, ...); pub fn zhash_pack(_self: *mut zhash_t) -> *mut zframe_t; pub fn zhash_save(_self: *mut zhash_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zhash_load(_self: *mut zhash_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zhash_refresh(_self: *mut zhash_t) -> ::std::os::raw::c_int; pub fn zhash_autofree(_self: *mut zhash_t); pub fn zhash_foreach(_self: *mut zhash_t, callback: zhash_foreach_fn, argument: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zhash_test(verbose: u8); pub fn zhashx_new() -> *mut zhashx_t; pub fn zhashx_unpack(frame: *mut zframe_t) -> *mut zhashx_t; pub fn zhashx_destroy(self_p: *mut *mut zhashx_t); pub fn zhashx_insert(_self: *mut zhashx_t, key: *const ::std::os::raw::c_void, item: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zhashx_update(_self: *mut zhashx_t, key: *const ::std::os::raw::c_void, item: *mut ::std::os::raw::c_void); pub fn zhashx_delete(_self: *mut zhashx_t, key: *const ::std::os::raw::c_void); pub fn zhashx_purge(_self: *mut zhashx_t); pub fn zhashx_lookup(_self: *mut zhashx_t, key: *const ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zhashx_rename(_self: *mut zhashx_t, old_key: *const ::std::os::raw::c_void, new_key: *const ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zhashx_freefn(_self: *mut zhashx_t, key: *const ::std::os::raw::c_void, free_fn: zhashx_free_fn) -> *mut ::std::os::raw::c_void; pub fn zhashx_size(_self: *mut zhashx_t) -> size_t; pub fn zhashx_keys(_self: *mut zhashx_t) -> *mut zlistx_t; pub fn zhashx_values(_self: *mut zhashx_t) -> *mut zlistx_t; pub fn zhashx_first(_self: *mut zhashx_t) -> *mut ::std::os::raw::c_void; pub fn zhashx_next(_self: *mut zhashx_t) -> *mut ::std::os::raw::c_void; pub fn zhashx_cursor(_self: *mut zhashx_t) -> *const ::std::os::raw::c_void; pub fn zhashx_comment(_self: *mut zhashx_t, format: *const ::std::os::raw::c_char, ...); pub fn zhashx_save(_self: *mut zhashx_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zhashx_load(_self: *mut zhashx_t, filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zhashx_refresh(_self: *mut zhashx_t) -> ::std::os::raw::c_int; pub fn zhashx_pack(_self: *mut zhashx_t) -> *mut zframe_t; pub fn zhashx_dup(_self: *mut zhashx_t) -> *mut zhashx_t; pub fn zhashx_set_destructor(_self: *mut zhashx_t, destructor: zhashx_destructor_fn); pub fn zhashx_set_duplicator(_self: *mut zhashx_t, duplicator: zhashx_duplicator_fn); pub fn zhashx_set_key_destructor(_self: *mut zhashx_t, destructor: zhashx_destructor_fn); pub fn zhashx_set_key_duplicator(_self: *mut zhashx_t, duplicator: zhashx_duplicator_fn); pub fn zhashx_set_key_comparator(_self: *mut zhashx_t, comparator: zhashx_comparator_fn); pub fn zhashx_set_key_hasher(_self: *mut zhashx_t, hasher: zhashx_hash_fn); pub fn zhashx_dup_v2(_self: *mut zhashx_t) -> *mut zhashx_t; pub fn zhashx_autofree(_self: *mut zhashx_t); pub fn zhashx_foreach(_self: *mut zhashx_t, callback: zhashx_foreach_fn, argument: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zhashx_test(verbose: u8); pub fn ziflist_new() -> *mut ziflist_t; pub fn ziflist_destroy(self_p: *mut *mut ziflist_t); pub fn ziflist_reload(_self: *mut ziflist_t); pub fn ziflist_size(_self: *mut ziflist_t) -> size_t; pub fn ziflist_first(_self: *mut ziflist_t) -> *const ::std::os::raw::c_char; pub fn ziflist_next(_self: *mut ziflist_t) -> *const ::std::os::raw::c_char; pub fn ziflist_address(_self: *mut ziflist_t) -> *const ::std::os::raw::c_char; pub fn ziflist_broadcast(_self: *mut ziflist_t) -> *const ::std::os::raw::c_char; pub fn ziflist_netmask(_self: *mut ziflist_t) -> *const ::std::os::raw::c_char; pub fn ziflist_print(_self: *mut ziflist_t); pub fn ziflist_test(verbose: u8); pub fn zlist_new() -> *mut zlist_t; pub fn zlist_destroy(self_p: *mut *mut zlist_t); pub fn zlist_first(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_next(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_last(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_head(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_tail(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_item(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_append(_self: *mut zlist_t, item: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zlist_push(_self: *mut zlist_t, item: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zlist_pop(_self: *mut zlist_t) -> *mut ::std::os::raw::c_void; pub fn zlist_exists(_self: *mut zlist_t, item: *mut ::std::os::raw::c_void) -> u8; pub fn zlist_remove(_self: *mut zlist_t, item: *mut ::std::os::raw::c_void); pub fn zlist_dup(_self: *mut zlist_t) -> *mut zlist_t; pub fn zlist_purge(_self: *mut zlist_t); pub fn zlist_size(_self: *mut zlist_t) -> size_t; pub fn zlist_sort(_self: *mut zlist_t, compare: zlist_compare_fn); pub fn zlist_autofree(_self: *mut zlist_t); pub fn zlist_comparefn(_self: *mut zlist_t, _fn: zlist_compare_fn); pub fn zlist_freefn(_self: *mut zlist_t, item: *mut ::std::os::raw::c_void, _fn: zlist_free_fn, at_tail: u8) -> *mut ::std::os::raw::c_void; pub fn zlist_test(verbose: u8); pub fn zlistx_new() -> *mut zlistx_t; pub fn zlistx_destroy(self_p: *mut *mut zlistx_t); pub fn zlistx_add_start(_self: *mut zlistx_t, item: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zlistx_add_end(_self: *mut zlistx_t, item: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zlistx_size(_self: *mut zlistx_t) -> size_t; pub fn zlistx_head(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_tail(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_first(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_next(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_prev(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_last(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_item(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_cursor(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_handle_item(handle: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zlistx_find(_self: *mut zlistx_t, item: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zlistx_detach(_self: *mut zlistx_t, handle: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zlistx_detach_cur(_self: *mut zlistx_t) -> *mut ::std::os::raw::c_void; pub fn zlistx_delete(_self: *mut zlistx_t, handle: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zlistx_move_start(_self: *mut zlistx_t, handle: *mut ::std::os::raw::c_void); pub fn zlistx_move_end(_self: *mut zlistx_t, handle: *mut ::std::os::raw::c_void); pub fn zlistx_purge(_self: *mut zlistx_t); pub fn zlistx_sort(_self: *mut zlistx_t); pub fn zlistx_insert(_self: *mut zlistx_t, item: *mut ::std::os::raw::c_void, low_value: u8) -> *mut ::std::os::raw::c_void; pub fn zlistx_reorder(_self: *mut zlistx_t, handle: *mut ::std::os::raw::c_void, low_value: u8); pub fn zlistx_dup(_self: *mut zlistx_t) -> *mut zlistx_t; pub fn zlistx_set_destructor(_self: *mut zlistx_t, destructor: zlistx_destructor_fn); pub fn zlistx_set_duplicator(_self: *mut zlistx_t, duplicator: zlistx_duplicator_fn); pub fn zlistx_set_comparator(_self: *mut zlistx_t, comparator: zlistx_comparator_fn); pub fn zlistx_test(verbose: u8); pub fn zloop_new() -> *mut zloop_t; pub fn zloop_destroy(self_p: *mut *mut zloop_t); pub fn zloop_reader(_self: *mut zloop_t, sock: *mut zsock_t, handler: zloop_reader_fn, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zloop_reader_end(_self: *mut zloop_t, sock: *mut zsock_t); pub fn zloop_reader_set_tolerant(_self: *mut zloop_t, sock: *mut zsock_t); pub fn zloop_poller(_self: *mut zloop_t, item: *mut zmq_pollitem_t, handler: zloop_fn, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zloop_poller_end(_self: *mut zloop_t, item: *mut zmq_pollitem_t); pub fn zloop_poller_set_tolerant(_self: *mut zloop_t, item: *mut zmq_pollitem_t); pub fn zloop_timer(_self: *mut zloop_t, delay: size_t, times: size_t, handler: zloop_timer_fn, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zloop_timer_end(_self: *mut zloop_t, timer_id: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zloop_ticket(_self: *mut zloop_t, handler: zloop_timer_fn, arg: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zloop_ticket_reset(_self: *mut zloop_t, handle: *mut ::std::os::raw::c_void); pub fn zloop_ticket_delete(_self: *mut zloop_t, handle: *mut ::std::os::raw::c_void); pub fn zloop_set_ticket_delay(_self: *mut zloop_t, ticket_delay: size_t); pub fn zloop_set_max_timers(_self: *mut zloop_t, max_timers: size_t); pub fn zloop_set_verbose(_self: *mut zloop_t, verbose: u8); pub fn zloop_start(_self: *mut zloop_t) -> ::std::os::raw::c_int; pub fn zloop_test(verbose: u8); pub fn zloop_set_nonstop(_self: *mut zloop_t, nonstop: u8); pub fn zmsg_new() -> *mut zmsg_t; pub fn zmsg_recv(source: *mut ::std::os::raw::c_void) -> *mut zmsg_t; pub fn zmsg_load(file: *mut FILE) -> *mut zmsg_t; pub fn zmsg_decode(frame: *mut zframe_t) -> *mut zmsg_t; pub fn zmsg_new_signal(status: byte) -> *mut zmsg_t; pub fn zmsg_destroy(self_p: *mut *mut zmsg_t); pub fn zmsg_send(self_p: *mut *mut zmsg_t, dest: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmsg_sendm(self_p: *mut *mut zmsg_t, dest: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zmsg_size(_self: *mut zmsg_t) -> size_t; pub fn zmsg_content_size(_self: *mut zmsg_t) -> size_t; pub fn zmsg_prepend(_self: *mut zmsg_t, frame_p: *mut *mut zframe_t) -> ::std::os::raw::c_int; pub fn zmsg_append(_self: *mut zmsg_t, frame_p: *mut *mut zframe_t) -> ::std::os::raw::c_int; pub fn zmsg_pop(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_pushmem(_self: *mut zmsg_t, data: *const ::std::os::raw::c_void, size: size_t) -> ::std::os::raw::c_int; pub fn zmsg_addmem(_self: *mut zmsg_t, data: *const ::std::os::raw::c_void, size: size_t) -> ::std::os::raw::c_int; pub fn zmsg_pushstr(_self: *mut zmsg_t, string: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmsg_addstr(_self: *mut zmsg_t, string: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zmsg_pushstrf(_self: *mut zmsg_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zmsg_addstrf(_self: *mut zmsg_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zmsg_popstr(_self: *mut zmsg_t) -> *mut ::std::os::raw::c_char; pub fn zmsg_addmsg(_self: *mut zmsg_t, msg_p: *mut *mut zmsg_t) -> ::std::os::raw::c_int; pub fn zmsg_popmsg(_self: *mut zmsg_t) -> *mut zmsg_t; pub fn zmsg_remove(_self: *mut zmsg_t, frame: *mut zframe_t); pub fn zmsg_first(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_next(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_last(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_save(_self: *mut zmsg_t, file: *mut FILE) -> ::std::os::raw::c_int; pub fn zmsg_encode(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_dup(_self: *mut zmsg_t) -> *mut zmsg_t; pub fn zmsg_print(_self: *mut zmsg_t); pub fn zmsg_eq(_self: *mut zmsg_t, other: *mut zmsg_t) -> u8; pub fn zmsg_signal(_self: *mut zmsg_t) -> ::std::os::raw::c_int; pub fn zmsg_is(_self: *mut ::std::os::raw::c_void) -> u8; pub fn zmsg_test(verbose: u8); pub fn zmsg_routing_id(_self: *mut zmsg_t) -> uint32_t; pub fn zmsg_set_routing_id(_self: *mut zmsg_t, routing_id: uint32_t); pub fn zmsg_unwrap(_self: *mut zmsg_t) -> *mut zframe_t; pub fn zmsg_recv_nowait(source: *mut ::std::os::raw::c_void) -> *mut zmsg_t; pub fn zmsg_wrap(_self: *mut zmsg_t, frame: *mut zframe_t); pub fn zmsg_push(_self: *mut zmsg_t, frame: *mut zframe_t) -> ::std::os::raw::c_int; pub fn zmsg_add(_self: *mut zmsg_t, frame: *mut zframe_t) -> ::std::os::raw::c_int; pub fn zmsg_fprint(_self: *mut zmsg_t, file: *mut FILE); pub fn zpoller_new(reader: *mut ::std::os::raw::c_void, ...) -> *mut zpoller_t; pub fn zpoller_destroy(self_p: *mut *mut zpoller_t); pub fn zpoller_add(_self: *mut zpoller_t, reader: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zpoller_remove(_self: *mut zpoller_t, reader: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zpoller_wait(_self: *mut zpoller_t, timeout: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn zpoller_expired(_self: *mut zpoller_t) -> u8; pub fn zpoller_terminated(_self: *mut zpoller_t) -> u8; pub fn zpoller_test(verbose: u8); pub fn zpoller_set_nonstop(_self: *mut zpoller_t, nonstop: u8); pub fn zsock_new(_type: ::std::os::raw::c_int) -> *mut zsock_t; pub fn zsock_new_pub(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_sub(endpoint: *const ::std::os::raw::c_char, subscribe: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_req(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_rep(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_dealer(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_router(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_push(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_pull(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_xpub(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_xsub(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_pair(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_stream(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_destroy(self_p: *mut *mut zsock_t); pub fn zsock_bind(_self: *mut zsock_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_endpoint(_self: *mut zsock_t) -> *const ::std::os::raw::c_char; pub fn zsock_unbind(_self: *mut zsock_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_connect(_self: *mut zsock_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_disconnect(_self: *mut zsock_t, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_attach(_self: *mut zsock_t, endpoints: *const ::std::os::raw::c_char, serverish: u8) -> ::std::os::raw::c_int; pub fn zsock_type_str(_self: *mut zsock_t) -> *const ::std::os::raw::c_char; pub fn zsock_send(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_vsend(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, argptr: va_list) -> ::std::os::raw::c_int; pub fn zsock_recv(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_vrecv(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, argptr: va_list) -> ::std::os::raw::c_int; pub fn zsock_bsend(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_brecv(_self: *mut ::std::os::raw::c_void, picture: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsock_set_unbounded(_self: *mut ::std::os::raw::c_void); pub fn zsock_signal(_self: *mut ::std::os::raw::c_void, status: byte) -> ::std::os::raw::c_int; pub fn zsock_wait(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_flush(_self: *mut ::std::os::raw::c_void); pub fn zsock_is(_self: *mut ::std::os::raw::c_void) -> u8; pub fn zsock_resolve(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zsock_tos(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_tos(_self: *mut ::std::os::raw::c_void, tos: ::std::os::raw::c_int); pub fn zsock_set_router_handover(_self: *mut ::std::os::raw::c_void, router_handover: ::std::os::raw::c_int); pub fn zsock_set_router_mandatory(_self: *mut ::std::os::raw::c_void, router_mandatory: ::std::os::raw::c_int); pub fn zsock_set_probe_router(_self: *mut ::std::os::raw::c_void, probe_router: ::std::os::raw::c_int); pub fn zsock_set_req_relaxed(_self: *mut ::std::os::raw::c_void, req_relaxed: ::std::os::raw::c_int); pub fn zsock_set_req_correlate(_self: *mut ::std::os::raw::c_void, req_correlate: ::std::os::raw::c_int); pub fn zsock_set_conflate(_self: *mut ::std::os::raw::c_void, conflate: ::std::os::raw::c_int); pub fn zsock_zap_domain(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_zap_domain(_self: *mut ::std::os::raw::c_void, zap_domain: *const ::std::os::raw::c_char); pub fn zsock_mechanism(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_plain_server(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_plain_server(_self: *mut ::std::os::raw::c_void, plain_server: ::std::os::raw::c_int); pub fn zsock_plain_username(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_plain_username(_self: *mut ::std::os::raw::c_void, plain_username: *const ::std::os::raw::c_char); pub fn zsock_plain_password(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_plain_password(_self: *mut ::std::os::raw::c_void, plain_password: *const ::std::os::raw::c_char); pub fn zsock_curve_server(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_curve_server(_self: *mut ::std::os::raw::c_void, curve_server: ::std::os::raw::c_int); pub fn zsock_curve_publickey(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_curve_publickey(_self: *mut ::std::os::raw::c_void, curve_publickey: *const ::std::os::raw::c_char); pub fn zsock_set_curve_publickey_bin(_self: *mut ::std::os::raw::c_void, curve_publickey: *const byte); pub fn zsock_curve_secretkey(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_curve_secretkey(_self: *mut ::std::os::raw::c_void, curve_secretkey: *const ::std::os::raw::c_char); pub fn zsock_set_curve_secretkey_bin(_self: *mut ::std::os::raw::c_void, curve_secretkey: *const byte); pub fn zsock_curve_serverkey(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_curve_serverkey(_self: *mut ::std::os::raw::c_void, curve_serverkey: *const ::std::os::raw::c_char); pub fn zsock_set_curve_serverkey_bin(_self: *mut ::std::os::raw::c_void, curve_serverkey: *const byte); pub fn zsock_gssapi_server(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_gssapi_server(_self: *mut ::std::os::raw::c_void, gssapi_server: ::std::os::raw::c_int); pub fn zsock_gssapi_plaintext(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_gssapi_plaintext(_self: *mut ::std::os::raw::c_void, gssapi_plaintext: ::std::os::raw::c_int); pub fn zsock_gssapi_principal(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_gssapi_principal(_self: *mut ::std::os::raw::c_void, gssapi_principal: *const ::std::os::raw::c_char); pub fn zsock_gssapi_service_principal(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_gssapi_service_principal(_self: *mut ::std::os::raw::c_void, gssapi_service_principal: *const ::std::os::raw::c_char); pub fn zsock_ipv6(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_ipv6(_self: *mut ::std::os::raw::c_void, ipv6: ::std::os::raw::c_int); pub fn zsock_immediate(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_immediate(_self: *mut ::std::os::raw::c_void, immediate: ::std::os::raw::c_int); pub fn zsock_set_router_raw(_self: *mut ::std::os::raw::c_void, router_raw: ::std::os::raw::c_int); pub fn zsock_ipv4only(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_ipv4only(_self: *mut ::std::os::raw::c_void, ipv4only: ::std::os::raw::c_int); pub fn zsock_set_delay_attach_on_connect(_self: *mut ::std::os::raw::c_void, delay_attach_on_connect: ::std::os::raw::c_int); pub fn zsock_type(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_sndhwm(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_sndhwm(_self: *mut ::std::os::raw::c_void, sndhwm: ::std::os::raw::c_int); pub fn zsock_rcvhwm(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_rcvhwm(_self: *mut ::std::os::raw::c_void, rcvhwm: ::std::os::raw::c_int); pub fn zsock_affinity(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_affinity(_self: *mut ::std::os::raw::c_void, affinity: ::std::os::raw::c_int); pub fn zsock_set_subscribe(_self: *mut ::std::os::raw::c_void, subscribe: *const ::std::os::raw::c_char); pub fn zsock_set_unsubscribe(_self: *mut ::std::os::raw::c_void, unsubscribe: *const ::std::os::raw::c_char); pub fn zsock_identity(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_identity(_self: *mut ::std::os::raw::c_void, identity: *const ::std::os::raw::c_char); pub fn zsock_rate(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_rate(_self: *mut ::std::os::raw::c_void, rate: ::std::os::raw::c_int); pub fn zsock_recovery_ivl(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_recovery_ivl(_self: *mut ::std::os::raw::c_void, recovery_ivl: ::std::os::raw::c_int); pub fn zsock_sndbuf(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_sndbuf(_self: *mut ::std::os::raw::c_void, sndbuf: ::std::os::raw::c_int); pub fn zsock_rcvbuf(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_rcvbuf(_self: *mut ::std::os::raw::c_void, rcvbuf: ::std::os::raw::c_int); pub fn zsock_linger(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_linger(_self: *mut ::std::os::raw::c_void, linger: ::std::os::raw::c_int); pub fn zsock_reconnect_ivl(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_reconnect_ivl(_self: *mut ::std::os::raw::c_void, reconnect_ivl: ::std::os::raw::c_int); pub fn zsock_reconnect_ivl_max(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_reconnect_ivl_max(_self: *mut ::std::os::raw::c_void, reconnect_ivl_max: ::std::os::raw::c_int); pub fn zsock_backlog(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_backlog(_self: *mut ::std::os::raw::c_void, backlog: ::std::os::raw::c_int); pub fn zsock_maxmsgsize(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_maxmsgsize(_self: *mut ::std::os::raw::c_void, maxmsgsize: ::std::os::raw::c_int); pub fn zsock_multicast_hops(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_multicast_hops(_self: *mut ::std::os::raw::c_void, multicast_hops: ::std::os::raw::c_int); pub fn zsock_rcvtimeo(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_rcvtimeo(_self: *mut ::std::os::raw::c_void, rcvtimeo: ::std::os::raw::c_int); pub fn zsock_sndtimeo(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_sndtimeo(_self: *mut ::std::os::raw::c_void, sndtimeo: ::std::os::raw::c_int); pub fn zsock_set_xpub_verbose(_self: *mut ::std::os::raw::c_void, xpub_verbose: ::std::os::raw::c_int); pub fn zsock_tcp_keepalive(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_tcp_keepalive(_self: *mut ::std::os::raw::c_void, tcp_keepalive: ::std::os::raw::c_int); pub fn zsock_tcp_keepalive_idle(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_tcp_keepalive_idle(_self: *mut ::std::os::raw::c_void, tcp_keepalive_idle: ::std::os::raw::c_int); pub fn zsock_tcp_keepalive_cnt(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_tcp_keepalive_cnt(_self: *mut ::std::os::raw::c_void, tcp_keepalive_cnt: ::std::os::raw::c_int); pub fn zsock_tcp_keepalive_intvl(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_tcp_keepalive_intvl(_self: *mut ::std::os::raw::c_void, tcp_keepalive_intvl: ::std::os::raw::c_int); pub fn zsock_tcp_accept_filter(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_set_tcp_accept_filter(_self: *mut ::std::os::raw::c_void, tcp_accept_filter: *const ::std::os::raw::c_char); pub fn zsock_rcvmore(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_fd(_self: *mut ::std::os::raw::c_void) -> SOCKET; pub fn zsock_events(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_last_endpoint(_self: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsock_test(verbose: u8); pub fn zsock_new_server(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_client(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_radio(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_dish(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_gather(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_new_scatter(endpoint: *const ::std::os::raw::c_char) -> *mut zsock_t; pub fn zsock_routing_id(_self: *mut zsock_t) -> uint32_t; pub fn zsock_set_routing_id(_self: *mut zsock_t, routing_id: uint32_t); pub fn zsock_join(_self: *mut ::std::os::raw::c_void, group: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsock_leave(_self: *mut ::std::os::raw::c_void, group: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsock_heartbeat_ivl(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_heartbeat_ivl(_self: *mut ::std::os::raw::c_void, heartbeat_ivl: ::std::os::raw::c_int); pub fn zsock_heartbeat_ttl(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_heartbeat_ttl(_self: *mut ::std::os::raw::c_void, heartbeat_ttl: ::std::os::raw::c_int); pub fn zsock_heartbeat_timeout(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_heartbeat_timeout(_self: *mut ::std::os::raw::c_void, heartbeat_timeout: ::std::os::raw::c_int); pub fn zsock_use_fd(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsock_set_use_fd(_self: *mut ::std::os::raw::c_void, use_fd: ::std::os::raw::c_int); pub fn zsock_new_checked(_type: ::std::os::raw::c_int, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_destroy_checked(self_p: *mut *mut zsock_t, filename: *const ::std::os::raw::c_char, line_nbr: size_t); pub fn zsock_new_pub_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_sub_checked(endpoint: *const ::std::os::raw::c_char, subscribe: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_req_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_rep_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_dealer_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_router_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_push_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_pull_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_xpub_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_xsub_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_pair_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_stream_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_server_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_client_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_radio_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_dish_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_gather_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zsock_new_scatter_checked(endpoint: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut zsock_t; pub fn zstr_recv(source: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zstr_recvx(source: *mut ::std::os::raw::c_void, string_p: *mut *mut ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zstr_send(dest: *mut ::std::os::raw::c_void, string: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zstr_sendm(dest: *mut ::std::os::raw::c_void, string: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zstr_sendf(dest: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zstr_sendfm(dest: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zstr_sendx(dest: *mut ::std::os::raw::c_void, string: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zstr_free(string_p: *mut *mut ::std::os::raw::c_char); pub fn zstr_test(verbose: u8); pub fn zstr_str(source: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zstr_recv_nowait(source: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zuuid_new() -> *mut zuuid_t; pub fn zuuid_new_from(source: *const byte) -> *mut zuuid_t; pub fn zuuid_destroy(self_p: *mut *mut zuuid_t); pub fn zuuid_set(_self: *mut zuuid_t, source: *const byte); pub fn zuuid_set_str(_self: *mut zuuid_t, source: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zuuid_data(_self: *mut zuuid_t) -> *const byte; pub fn zuuid_size(_self: *mut zuuid_t) -> size_t; pub fn zuuid_str(_self: *mut zuuid_t) -> *const ::std::os::raw::c_char; pub fn zuuid_str_canonical(_self: *mut zuuid_t) -> *const ::std::os::raw::c_char; pub fn zuuid_export(_self: *mut zuuid_t, target: *mut byte); pub fn zuuid_eq(_self: *mut zuuid_t, compare: *const byte) -> u8; pub fn zuuid_neq(_self: *mut zuuid_t, compare: *const byte) -> u8; pub fn zuuid_dup(_self: *mut zuuid_t) -> *mut zuuid_t; pub fn zuuid_test(verbose: u8); pub fn zauth(pipe: *mut zsock_t, certstore: *mut ::std::os::raw::c_void); pub fn zauth_test(verbose: u8); pub fn zbeacon(pipe: *mut zsock_t, unused: *mut ::std::os::raw::c_void); pub fn zbeacon_test(verbose: u8); pub fn zgossip(pipe: *mut zsock_t, args: *mut ::std::os::raw::c_void); pub fn zgossip_test(verbose: u8); pub fn zmonitor(pipe: *mut zsock_t, sock: *mut ::std::os::raw::c_void); pub fn zmonitor_test(verbose: u8); pub fn zproxy(pipe: *mut zsock_t, unused: *mut ::std::os::raw::c_void); pub fn zproxy_test(verbose: u8); pub fn zrex_new(expression: *const ::std::os::raw::c_char) -> *mut zrex_t; pub fn zrex_destroy(self_p: *mut *mut zrex_t); pub fn zrex_valid(_self: *mut zrex_t) -> u8; pub fn zrex_strerror(_self: *mut zrex_t) -> *const ::std::os::raw::c_char; pub fn zrex_matches(_self: *mut zrex_t, text: *const ::std::os::raw::c_char) -> u8; pub fn zrex_eq(_self: *mut zrex_t, text: *const ::std::os::raw::c_char, expression: *const ::std::os::raw::c_char) -> u8; pub fn zrex_hits(_self: *mut zrex_t) -> ::std::os::raw::c_int; pub fn zrex_hit(_self: *mut zrex_t, index: _uint) -> *const ::std::os::raw::c_char; pub fn zrex_fetch(_self: *mut zrex_t, string_p: *mut *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zrex_test(verbose: u8); pub fn zsys_init() -> *mut ::std::os::raw::c_void; pub fn zsys_shutdown(); pub fn zsys_socket(_type: ::std::os::raw::c_int, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> *mut ::std::os::raw::c_void; pub fn zsys_close(handle: *mut ::std::os::raw::c_void, filename: *const ::std::os::raw::c_char, line_nbr: size_t) -> ::std::os::raw::c_int; pub fn zsys_sockname(socktype: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_char; pub fn zsys_create_pipe(backend_p: *mut *mut zsock_t) -> *mut zsock_t; pub fn zsys_handler_set(handler_fn: *mut zsys_handler_fn); pub fn zsys_handler_reset(); pub fn zsys_catch_interrupts(); pub fn zsys_file_exists(filename: *const ::std::os::raw::c_char) -> u8; pub fn zsys_file_size(filename: *const ::std::os::raw::c_char) -> ssize_t; pub fn zsys_file_modified(filename: *const ::std::os::raw::c_char) -> time_t; pub fn zsys_file_mode(filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsys_file_delete(filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsys_file_stable(filename: *const ::std::os::raw::c_char) -> u8; pub fn zsys_dir_create(pathname: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsys_dir_delete(pathname: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsys_dir_change(pathname: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsys_file_mode_private(); pub fn zsys_file_mode_default(); pub fn zsys_version(major: *mut ::std::os::raw::c_int, minor: *mut ::std::os::raw::c_int, patch: *mut ::std::os::raw::c_int); pub fn zsys_sprintf(format: *const ::std::os::raw::c_char, ...) -> *mut ::std::os::raw::c_char; pub fn zsys_vprintf(format: *const ::std::os::raw::c_char, argptr: va_list) -> *mut ::std::os::raw::c_char; pub fn zsys_udp_new(routable: u8) -> SOCKET; pub fn zsys_udp_close(handle: SOCKET) -> ::std::os::raw::c_int; pub fn zsys_udp_send(udpsock: SOCKET, frame: *mut zframe_t, address: *mut inaddr_t, addrlen: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zsys_udp_recv(udpsock: SOCKET, peername: *mut ::std::os::raw::c_char, peerlen: ::std::os::raw::c_int) -> *mut zframe_t; pub fn zsys_socket_error(reason: *const ::std::os::raw::c_char); pub fn zsys_hostname() -> *mut ::std::os::raw::c_char; pub fn zsys_daemonize(workdir: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsys_run_as(lockfile: *const ::std::os::raw::c_char, group: *const ::std::os::raw::c_char, user: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn zsys_has_curve() -> u8; pub fn zsys_set_io_threads(io_threads: size_t); pub fn zsys_set_max_sockets(max_sockets: size_t); pub fn zsys_socket_limit() -> size_t; pub fn zsys_set_linger(linger: size_t); pub fn zsys_set_sndhwm(sndhwm: size_t); pub fn zsys_set_rcvhwm(rcvhwm: size_t); pub fn zsys_set_pipehwm(pipehwm: size_t); pub fn zsys_pipehwm() -> size_t; pub fn zsys_set_ipv6(ipv6: ::std::os::raw::c_int); pub fn zsys_ipv6() -> ::std::os::raw::c_int; pub fn zsys_set_interface(value: *const ::std::os::raw::c_char); pub fn zsys_interface() -> *const ::std::os::raw::c_char; pub fn zsys_set_ipv6_address(value: *const ::std::os::raw::c_char); pub fn zsys_ipv6_address() -> *const ::std::os::raw::c_char; pub fn zsys_set_ipv6_mcast_address(value: *const ::std::os::raw::c_char); pub fn zsys_ipv6_mcast_address() -> *const ::std::os::raw::c_char; pub fn zsys_set_auto_use_fd(auto_use_fd: ::std::os::raw::c_int); pub fn zsys_auto_use_fd() -> ::std::os::raw::c_int; pub fn zsys_set_logident(value: *const ::std::os::raw::c_char); pub fn zsys_set_logstream(stream: *mut FILE); pub fn zsys_set_logsender(endpoint: *const ::std::os::raw::c_char); pub fn zsys_set_logsystem(logsystem: u8); pub fn zsys_error(format: *const ::std::os::raw::c_char, ...); pub fn zsys_warning(format: *const ::std::os::raw::c_char, ...); pub fn zsys_notice(format: *const ::std::os::raw::c_char, ...); pub fn zsys_info(format: *const ::std::os::raw::c_char, ...); pub fn zsys_debug(format: *const ::std::os::raw::c_char, ...); pub fn zsys_test(verbose: u8); pub fn zauth_new(ctx: *mut zctx_t) -> *mut zauth_t; pub fn zauth_destroy(self_p: *mut *mut zauth_t); pub fn zauth_allow(_self: *mut zauth_t, address: *const ::std::os::raw::c_char); pub fn zauth_deny(_self: *mut zauth_t, address: *const ::std::os::raw::c_char); pub fn zauth_configure_plain(_self: *mut zauth_t, domain: *const ::std::os::raw::c_char, filename: *const ::std::os::raw::c_char); pub fn zauth_configure_curve(_self: *mut zauth_t, domain: *const ::std::os::raw::c_char, location: *const ::std::os::raw::c_char); pub fn zauth_configure_gssapi(_self: *mut zauth_t, domain: *mut ::std::os::raw::c_char); pub fn zauth_set_verbose(_self: *mut zauth_t, verbose: u8); pub fn zauth_v2_test(verbose: u8); pub fn zbeacon_new(ctx: *mut zctx_t, port_nbr: ::std::os::raw::c_int) -> *mut zbeacon_t; pub fn zbeacon_destroy(self_p: *mut *mut zbeacon_t); pub fn zbeacon_hostname(_self: *mut zbeacon_t) -> *mut ::std::os::raw::c_char; pub fn zbeacon_set_interval(_self: *mut zbeacon_t, interval: ::std::os::raw::c_int); pub fn zbeacon_noecho(_self: *mut zbeacon_t); pub fn zbeacon_publish(_self: *mut zbeacon_t, transmit: *mut byte, size: size_t); pub fn zbeacon_silence(_self: *mut zbeacon_t); pub fn zbeacon_subscribe(_self: *mut zbeacon_t, filter: *mut byte, size: size_t); pub fn zbeacon_unsubscribe(_self: *mut zbeacon_t); pub fn zbeacon_socket(_self: *mut zbeacon_t) -> *mut ::std::os::raw::c_void; pub fn zbeacon_v2_test(verbose: u8); pub fn zctx_new() -> *mut zctx_t; pub fn zctx_destroy(self_p: *mut *mut zctx_t); pub fn zctx_shadow(_self: *mut zctx_t) -> *mut zctx_t; pub fn zctx_shadow_zmq_ctx(zmqctx: *mut ::std::os::raw::c_void) -> *mut zctx_t; pub fn zctx_set_iothreads(_self: *mut zctx_t, iothreads: ::std::os::raw::c_int); pub fn zctx_set_linger(_self: *mut zctx_t, linger: ::std::os::raw::c_int); pub fn zctx_set_pipehwm(_self: *mut zctx_t, pipehwm: ::std::os::raw::c_int); pub fn zctx_set_sndhwm(_self: *mut zctx_t, sndhwm: ::std::os::raw::c_int); pub fn zctx_set_rcvhwm(_self: *mut zctx_t, rcvhwm: ::std::os::raw::c_int); pub fn zctx_underlying(_self: *mut zctx_t) -> *mut ::std::os::raw::c_void; pub fn zctx_test(verbose: u8); pub fn zctx__socket_new(_self: *mut zctx_t, _type: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn zctx__socket_pipe(_self: *mut zctx_t) -> *mut ::std::os::raw::c_void; pub fn zctx__socket_destroy(_self: *mut zctx_t, socket: *mut ::std::os::raw::c_void); pub fn zctx__initialize_underlying(_self: *mut zctx_t); pub fn zmonitor_new(ctx: *mut zctx_t, socket: *mut ::std::os::raw::c_void, events: ::std::os::raw::c_int) -> *mut zmonitor_t; pub fn zmonitor_destroy(self_p: *mut *mut zmonitor_t); pub fn zmonitor_recv(_self: *mut zmonitor_t) -> *mut zmsg_t; pub fn zmonitor_socket(_self: *mut zmonitor_t) -> *mut ::std::os::raw::c_void; pub fn zmonitor_set_verbose(_self: *mut zmonitor_t, verbose: u8); pub fn zmonitor_v2_test(verbose: u8); pub fn zmutex_new() -> *mut zmutex_t; pub fn zmutex_destroy(self_p: *mut *mut zmutex_t); pub fn zmutex_lock(_self: *mut zmutex_t); pub fn zmutex_unlock(_self: *mut zmutex_t); pub fn zmutex_try_lock(_self: *mut zmutex_t) -> ::std::os::raw::c_int; pub fn zmutex_test(verbose: u8); pub fn zproxy_new(ctx: *mut zctx_t, frontend: *mut ::std::os::raw::c_void, backend: *mut ::std::os::raw::c_void) -> *mut zproxy_t; pub fn zproxy_destroy(self_p: *mut *mut zproxy_t); pub fn zproxy_capture(_self: *mut zproxy_t, endpoint: *const ::std::os::raw::c_char); pub fn zproxy_pause(_self: *mut zproxy_t); pub fn zproxy_resume(_self: *mut zproxy_t); pub fn zproxy_v2_test(verbose: u8); pub fn zsocket_new(_self: *mut zctx_t, _type: ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void; pub fn zsocket_destroy(ctx: *mut zctx_t, _self: *mut ::std::os::raw::c_void); pub fn zsocket_bind(_self: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsocket_unbind(_self: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsocket_connect(_self: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsocket_disconnect(_self: *mut ::std::os::raw::c_void, format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; pub fn zsocket_poll(_self: *mut ::std::os::raw::c_void, msecs: ::std::os::raw::c_int) -> u8; pub fn zsocket_type_str(_self: *mut ::std::os::raw::c_void) -> *const ::std::os::raw::c_char; pub fn zsocket_sendmem(_self: *mut ::std::os::raw::c_void, data: *const ::std::os::raw::c_void, size: size_t, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn zsocket_signal(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_wait(_self: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_test(verbose: u8); pub fn zsocket_set_hwm(_self: *mut ::std::os::raw::c_void, hwm: ::std::os::raw::c_int); pub fn zsocket_heartbeat_ivl(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_heartbeat_ttl(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_heartbeat_timeout(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_use_fd(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tos(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_zap_domain(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_mechanism(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_plain_server(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_plain_username(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_plain_password(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_curve_server(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_curve_publickey(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_curve_secretkey(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_curve_serverkey(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_gssapi_server(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_gssapi_plaintext(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_gssapi_principal(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_gssapi_service_principal(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_ipv6(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_immediate(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_ipv4only(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_type(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_sndhwm(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_rcvhwm(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_affinity(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_identity(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_rate(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_recovery_ivl(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_sndbuf(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_rcvbuf(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_linger(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_reconnect_ivl(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_reconnect_ivl_max(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_backlog(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_maxmsgsize(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_multicast_hops(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_rcvtimeo(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_sndtimeo(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tcp_keepalive(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tcp_keepalive_idle(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tcp_keepalive_cnt(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tcp_keepalive_intvl(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_tcp_accept_filter(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_rcvmore(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_fd(zocket: *mut ::std::os::raw::c_void) -> SOCKET; pub fn zsocket_events(zocket: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zsocket_last_endpoint(zocket: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_char; pub fn zsocket_set_heartbeat_ivl(zocket: *mut ::std::os::raw::c_void, heartbeat_ivl: ::std::os::raw::c_int); pub fn zsocket_set_heartbeat_ttl(zocket: *mut ::std::os::raw::c_void, heartbeat_ttl: ::std::os::raw::c_int); pub fn zsocket_set_heartbeat_timeout(zocket: *mut ::std::os::raw::c_void, heartbeat_timeout: ::std::os::raw::c_int); pub fn zsocket_set_use_fd(zocket: *mut ::std::os::raw::c_void, use_fd: ::std::os::raw::c_int); pub fn zsocket_set_tos(zocket: *mut ::std::os::raw::c_void, tos: ::std::os::raw::c_int); pub fn zsocket_set_router_handover(zocket: *mut ::std::os::raw::c_void, router_handover: ::std::os::raw::c_int); pub fn zsocket_set_router_mandatory(zocket: *mut ::std::os::raw::c_void, router_mandatory: ::std::os::raw::c_int); pub fn zsocket_set_probe_router(zocket: *mut ::std::os::raw::c_void, probe_router: ::std::os::raw::c_int); pub fn zsocket_set_req_relaxed(zocket: *mut ::std::os::raw::c_void, req_relaxed: ::std::os::raw::c_int); pub fn zsocket_set_req_correlate(zocket: *mut ::std::os::raw::c_void, req_correlate: ::std::os::raw::c_int); pub fn zsocket_set_conflate(zocket: *mut ::std::os::raw::c_void, conflate: ::std::os::raw::c_int); pub fn zsocket_set_zap_domain(zocket: *mut ::std::os::raw::c_void, zap_domain: *const ::std::os::raw::c_char); pub fn zsocket_set_plain_server(zocket: *mut ::std::os::raw::c_void, plain_server: ::std::os::raw::c_int); pub fn zsocket_set_plain_username(zocket: *mut ::std::os::raw::c_void, plain_username: *const ::std::os::raw::c_char); pub fn zsocket_set_plain_password(zocket: *mut ::std::os::raw::c_void, plain_password: *const ::std::os::raw::c_char); pub fn zsocket_set_curve_server(zocket: *mut ::std::os::raw::c_void, curve_server: ::std::os::raw::c_int); pub fn zsocket_set_curve_publickey(zocket: *mut ::std::os::raw::c_void, curve_publickey: *const ::std::os::raw::c_char); pub fn zsocket_set_curve_publickey_bin(zocket: *mut ::std::os::raw::c_void, curve_publickey: *const byte); pub fn zsocket_set_curve_secretkey(zocket: *mut ::std::os::raw::c_void, curve_secretkey: *const ::std::os::raw::c_char); pub fn zsocket_set_curve_secretkey_bin(zocket: *mut ::std::os::raw::c_void, curve_secretkey: *const byte); pub fn zsocket_set_curve_serverkey(zocket: *mut ::std::os::raw::c_void, curve_serverkey: *const ::std::os::raw::c_char); pub fn zsocket_set_curve_serverkey_bin(zocket: *mut ::std::os::raw::c_void, curve_serverkey: *const byte); pub fn zsocket_set_gssapi_server(zocket: *mut ::std::os::raw::c_void, gssapi_server: ::std::os::raw::c_int); pub fn zsocket_set_gssapi_plaintext(zocket: *mut ::std::os::raw::c_void, gssapi_plaintext: ::std::os::raw::c_int); pub fn zsocket_set_gssapi_principal(zocket: *mut ::std::os::raw::c_void, gssapi_principal: *const ::std::os::raw::c_char); pub fn zsocket_set_gssapi_service_principal(zocket: *mut ::std::os::raw::c_void, gssapi_service_principal: *const ::std::os::raw::c_char); pub fn zsocket_set_ipv6(zocket: *mut ::std::os::raw::c_void, ipv6: ::std::os::raw::c_int); pub fn zsocket_set_immediate(zocket: *mut ::std::os::raw::c_void, immediate: ::std::os::raw::c_int); pub fn zsocket_set_router_raw(zocket: *mut ::std::os::raw::c_void, router_raw: ::std::os::raw::c_int); pub fn zsocket_set_ipv4only(zocket: *mut ::std::os::raw::c_void, ipv4only: ::std::os::raw::c_int); pub fn zsocket_set_delay_attach_on_connect(zocket: *mut ::std::os::raw::c_void, delay_attach_on_connect: ::std::os::raw::c_int); pub fn zsocket_set_sndhwm(zocket: *mut ::std::os::raw::c_void, sndhwm: ::std::os::raw::c_int); pub fn zsocket_set_rcvhwm(zocket: *mut ::std::os::raw::c_void, rcvhwm: ::std::os::raw::c_int); pub fn zsocket_set_affinity(zocket: *mut ::std::os::raw::c_void, affinity: ::std::os::raw::c_int); pub fn zsocket_set_subscribe(zocket: *mut ::std::os::raw::c_void, subscribe: *const ::std::os::raw::c_char); pub fn zsocket_set_unsubscribe(zocket: *mut ::std::os::raw::c_void, unsubscribe: *const ::std::os::raw::c_char); pub fn zsocket_set_identity(zocket: *mut ::std::os::raw::c_void, identity: *const ::std::os::raw::c_char); pub fn zsocket_set_rate(zocket: *mut ::std::os::raw::c_void, rate: ::std::os::raw::c_int); pub fn zsocket_set_recovery_ivl(zocket: *mut ::std::os::raw::c_void, recovery_ivl: ::std::os::raw::c_int); pub fn zsocket_set_sndbuf(zocket: *mut ::std::os::raw::c_void, sndbuf: ::std::os::raw::c_int); pub fn zsocket_set_rcvbuf(zocket: *mut ::std::os::raw::c_void, rcvbuf: ::std::os::raw::c_int); pub fn zsocket_set_linger(zocket: *mut ::std::os::raw::c_void, linger: ::std::os::raw::c_int); pub fn zsocket_set_reconnect_ivl(zocket: *mut ::std::os::raw::c_void, reconnect_ivl: ::std::os::raw::c_int); pub fn zsocket_set_reconnect_ivl_max(zocket: *mut ::std::os::raw::c_void, reconnect_ivl_max: ::std::os::raw::c_int); pub fn zsocket_set_backlog(zocket: *mut ::std::os::raw::c_void, backlog: ::std::os::raw::c_int); pub fn zsocket_set_maxmsgsize(zocket: *mut ::std::os::raw::c_void, maxmsgsize: ::std::os::raw::c_int); pub fn zsocket_set_multicast_hops(zocket: *mut ::std::os::raw::c_void, multicast_hops: ::std::os::raw::c_int); pub fn zsocket_set_rcvtimeo(zocket: *mut ::std::os::raw::c_void, rcvtimeo: ::std::os::raw::c_int); pub fn zsocket_set_sndtimeo(zocket: *mut ::std::os::raw::c_void, sndtimeo: ::std::os::raw::c_int); pub fn zsocket_set_xpub_verbose(zocket: *mut ::std::os::raw::c_void, xpub_verbose: ::std::os::raw::c_int); pub fn zsocket_set_tcp_keepalive(zocket: *mut ::std::os::raw::c_void, tcp_keepalive: ::std::os::raw::c_int); pub fn zsocket_set_tcp_keepalive_idle(zocket: *mut ::std::os::raw::c_void, tcp_keepalive_idle: ::std::os::raw::c_int); pub fn zsocket_set_tcp_keepalive_cnt(zocket: *mut ::std::os::raw::c_void, tcp_keepalive_cnt: ::std::os::raw::c_int); pub fn zsocket_set_tcp_keepalive_intvl(zocket: *mut ::std::os::raw::c_void, tcp_keepalive_intvl: ::std::os::raw::c_int); pub fn zsocket_set_tcp_accept_filter(zocket: *mut ::std::os::raw::c_void, tcp_accept_filter: *const ::std::os::raw::c_char); pub fn zsockopt_test(verbose: u8); pub fn zthread_new(thread_fn: *mut zthread_detached_fn, args: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn zthread_fork(ctx: *mut zctx_t, thread_fn: *mut zthread_attached_fn, args: *mut ::std::os::raw::c_void) -> *mut ::std::os::raw::c_void; pub fn zthread_test(verbose: u8); pub fn zproc_czmq_version() -> ::std::os::raw::c_int; pub fn zproc_interrupted() -> u8; pub fn zproc_has_curve() -> u8; pub fn zproc_hostname() -> *mut ::std::os::raw::c_char; pub fn zproc_daemonize(workdir: *const ::std::os::raw::c_char); pub fn zproc_run_as(lockfile: *const ::std::os::raw::c_char, group: *const ::std::os::raw::c_char, user: *const ::std::os::raw::c_char); pub fn zproc_set_io_threads(io_threads: size_t); pub fn zproc_set_max_sockets(max_sockets: size_t); pub fn zproc_set_biface(value: *const ::std::os::raw::c_char); pub fn zproc_biface() -> *const ::std::os::raw::c_char; pub fn zproc_set_log_ident(value: *const ::std::os::raw::c_char); pub fn zproc_set_log_sender(endpoint: *const ::std::os::raw::c_char); pub fn zproc_set_log_system(logsystem: u8); pub fn zproc_log_error(format: *const ::std::os::raw::c_char, ...); pub fn zproc_log_warning(format: *const ::std::os::raw::c_char, ...); pub fn zproc_log_notice(format: *const ::std::os::raw::c_char, ...); pub fn zproc_log_info(format: *const ::std::os::raw::c_char, ...); pub fn zproc_log_debug(format: *const ::std::os::raw::c_char, ...); pub fn zproc_test(verbose: u8); pub fn ztimerset_new() -> *mut ztimerset_t; pub fn ztimerset_destroy(self_p: *mut *mut ztimerset_t); pub fn ztimerset_add(_self: *mut ztimerset_t, interval: size_t, handler: ztimerset_fn, arg: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int; pub fn ztimerset_cancel(_self: *mut ztimerset_t, timer_id: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ztimerset_set_interval(_self: *mut ztimerset_t, timer_id: ::std::os::raw::c_int, interval: size_t) -> ::std::os::raw::c_int; pub fn ztimerset_reset(_self: *mut ztimerset_t, timer_id: ::std::os::raw::c_int) -> ::std::os::raw::c_int; pub fn ztimerset_timeout(_self: *mut ztimerset_t) -> ::std::os::raw::c_int; pub fn ztimerset_execute(_self: *mut ztimerset_t) -> ::std::os::raw::c_int; pub fn ztimerset_test(verbose: u8); pub fn ztrie_new(delimiter: ::std::os::raw::c_char) -> *mut ztrie_t; pub fn ztrie_destroy(self_p: *mut *mut ztrie_t); pub fn ztrie_insert_route(_self: *mut ztrie_t, path: *const ::std::os::raw::c_char, data: *mut ::std::os::raw::c_void, destroy_data_fn: ztrie_destroy_data_fn) -> ::std::os::raw::c_int; pub fn ztrie_remove_route(_self: *mut ztrie_t, path: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; pub fn ztrie_matches(_self: *mut ztrie_t, path: *const ::std::os::raw::c_char) -> u8; pub fn ztrie_hit_data(_self: *mut ztrie_t) -> *mut ::std::os::raw::c_void; pub fn ztrie_hit_parameter_count(_self: *mut ztrie_t) -> size_t; pub fn ztrie_hit_parameters(_self: *mut ztrie_t) -> *mut zhashx_t; pub fn ztrie_hit_asterisk_match(_self: *mut ztrie_t) -> *const ::std::os::raw::c_char; pub fn ztrie_print(_self: *mut ztrie_t); pub fn ztrie_test(verbose: u8); pub fn zgossip_msg_new() -> *mut zgossip_msg_t; pub fn zgossip_msg_destroy(self_p: *mut *mut zgossip_msg_t); pub fn zgossip_msg_recv(_self: *mut zgossip_msg_t, input: *mut zsock_t) -> ::std::os::raw::c_int; pub fn zgossip_msg_send(_self: *mut zgossip_msg_t, output: *mut zsock_t) -> ::std::os::raw::c_int; pub fn zgossip_msg_print(_self: *mut zgossip_msg_t); pub fn zgossip_msg_routing_id(_self: *mut zgossip_msg_t) -> *mut zframe_t; pub fn zgossip_msg_set_routing_id(_self: *mut zgossip_msg_t, routing_id: *mut zframe_t); pub fn zgossip_msg_id(_self: *mut zgossip_msg_t) -> ::std::os::raw::c_int; pub fn zgossip_msg_set_id(_self: *mut zgossip_msg_t, id: ::std::os::raw::c_int); pub fn zgossip_msg_command(_self: *mut zgossip_msg_t) -> *const ::std::os::raw::c_char; pub fn zgossip_msg_key(_self: *mut zgossip_msg_t) -> *const ::std::os::raw::c_char; pub fn zgossip_msg_set_key(_self: *mut zgossip_msg_t, key: *const ::std::os::raw::c_char); pub fn zgossip_msg_value(_self: *mut zgossip_msg_t) -> *const ::std::os::raw::c_char; pub fn zgossip_msg_set_value(_self: *mut zgossip_msg_t, value: *const ::std::os::raw::c_char); pub fn zgossip_msg_ttl(_self: *mut zgossip_msg_t) -> uint32_t; pub fn zgossip_msg_set_ttl(_self: *mut zgossip_msg_t, ttl: uint32_t); pub fn zgossip_msg_test(verbose: u8); }
40.36002
118
0.629107
e24866013ae2645b8887d9e91a72c0bd6f217a1d
462
use crate::core::Parser; use crate::extension::parser::ConversionParser; use crate::extension::parsers::ConversionParsers; use crate::internal::ParsersImpl; use std::fmt::Debug; impl<'a, I, A> ConversionParser<'a> for Parser<'a, I, A> { fn map_res<B, E, F>(self, f: F) -> Self::P<'a, Self::Input, B> where F: Fn(Self::Output) -> Result<B, E> + 'a, E: Debug, Self::Output: Debug + 'a, B: Debug + 'a, { ParsersImpl::map_res(self, f) } }
27.176471
64
0.623377
1aa6143e3592bde64eae482820d19d548d12d8f3
217,181
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![allow(warnings)] use futures::future; use futures::Future; use rusoto_core::credential::ProvideAwsCredentials; use rusoto_core::region; use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest}; use rusoto_core::{Client, RusotoError, RusotoFuture}; use std::error::Error; use std::fmt; use rusoto_core::param::{Params, ServiceParams}; use rusoto_core::proto; use rusoto_core::signature::SignedRequest; use serde_json; #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct AcceptInvitationRequest { /// <p>The unique ID of the detector of the GuardDuty member account.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>This value is used to validate the master account to the member account.</p> #[serde(rename = "InvitationId")] pub invitation_id: String, /// <p>The account ID of the master GuardDuty account whose invitation you're accepting.</p> #[serde(rename = "MasterId")] pub master_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct AcceptInvitationResponse {} /// <p>Contains information about the access keys.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct AccessKeyDetails { /// <p>Access key ID of the user.</p> #[serde(rename = "AccessKeyId")] #[serde(skip_serializing_if = "Option::is_none")] pub access_key_id: Option<String>, /// <p>The principal ID of the user.</p> #[serde(rename = "PrincipalId")] #[serde(skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, /// <p>The name of the user.</p> #[serde(rename = "UserName")] #[serde(skip_serializing_if = "Option::is_none")] pub user_name: Option<String>, /// <p>The type of the user.</p> #[serde(rename = "UserType")] #[serde(skip_serializing_if = "Option::is_none")] pub user_type: Option<String>, } /// <p>Contains information about the account.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct AccountDetail { /// <p>Member account ID.</p> #[serde(rename = "AccountId")] pub account_id: String, /// <p>Member account's email address.</p> #[serde(rename = "Email")] pub email: String, } /// <p>Contains information about action.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Action { /// <p>GuardDuty Finding activity type.</p> #[serde(rename = "ActionType")] #[serde(skip_serializing_if = "Option::is_none")] pub action_type: Option<String>, /// <p>Information about the AWS_API_CALL action described in this finding.</p> #[serde(rename = "AwsApiCallAction")] #[serde(skip_serializing_if = "Option::is_none")] pub aws_api_call_action: Option<AwsApiCallAction>, /// <p>Information about the DNS_REQUEST action described in this finding.</p> #[serde(rename = "DnsRequestAction")] #[serde(skip_serializing_if = "Option::is_none")] pub dns_request_action: Option<DnsRequestAction>, /// <p>Information about the NETWORK_CONNECTION action described in this finding.</p> #[serde(rename = "NetworkConnectionAction")] #[serde(skip_serializing_if = "Option::is_none")] pub network_connection_action: Option<NetworkConnectionAction>, /// <p>Information about the PORT_PROBE action described in this finding.</p> #[serde(rename = "PortProbeAction")] #[serde(skip_serializing_if = "Option::is_none")] pub port_probe_action: Option<PortProbeAction>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ArchiveFindingsRequest { /// <p>The ID of the detector that specifies the GuardDuty service whose findings you want to archive.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>IDs of the findings that you want to archive.</p> #[serde(rename = "FindingIds")] pub finding_ids: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ArchiveFindingsResponse {} /// <p>Contains information about the API operation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct AwsApiCallAction { /// <p>AWS API name.</p> #[serde(rename = "Api")] #[serde(skip_serializing_if = "Option::is_none")] pub api: Option<String>, /// <p>AWS API caller type.</p> #[serde(rename = "CallerType")] #[serde(skip_serializing_if = "Option::is_none")] pub caller_type: Option<String>, /// <p>Domain information for the AWS API call.</p> #[serde(rename = "DomainDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub domain_details: Option<DomainDetails>, /// <p>Remote IP information of the connection.</p> #[serde(rename = "RemoteIpDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub remote_ip_details: Option<RemoteIpDetails>, /// <p>AWS service name whose API was invoked.</p> #[serde(rename = "ServiceName")] #[serde(skip_serializing_if = "Option::is_none")] pub service_name: Option<String>, } /// <p>Contains information about the city associated with the IP address.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct City { /// <p>City name of the remote IP address.</p> #[serde(rename = "CityName")] #[serde(skip_serializing_if = "Option::is_none")] pub city_name: Option<String>, } /// <p>Contains information about the condition.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Condition { /// <p>Represents an <b>equal</b> condition to be applied to a single field when querying for findings.</p> #[serde(rename = "Equals")] #[serde(skip_serializing_if = "Option::is_none")] pub equals: Option<Vec<String>>, /// <p>Represents a greater than condition to be applied to a single field when querying for findings.</p> #[serde(rename = "GreaterThan")] #[serde(skip_serializing_if = "Option::is_none")] pub greater_than: Option<i64>, /// <p>Represents a greater than equal condition to be applied to a single field when querying for findings.</p> #[serde(rename = "GreaterThanOrEqual")] #[serde(skip_serializing_if = "Option::is_none")] pub greater_than_or_equal: Option<i64>, /// <p>Represents a less than condition to be applied to a single field when querying for findings.</p> #[serde(rename = "LessThan")] #[serde(skip_serializing_if = "Option::is_none")] pub less_than: Option<i64>, /// <p>Represents a less than equal condition to be applied to a single field when querying for findings.</p> #[serde(rename = "LessThanOrEqual")] #[serde(skip_serializing_if = "Option::is_none")] pub less_than_or_equal: Option<i64>, /// <p>Represents an <b>not equal</b> condition to be applied to a single field when querying for findings.</p> #[serde(rename = "NotEquals")] #[serde(skip_serializing_if = "Option::is_none")] pub not_equals: Option<Vec<String>>, } /// <p>Contains information about the country.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Country { /// <p>Country code of the remote IP address.</p> #[serde(rename = "CountryCode")] #[serde(skip_serializing_if = "Option::is_none")] pub country_code: Option<String>, /// <p>Country name of the remote IP address.</p> #[serde(rename = "CountryName")] #[serde(skip_serializing_if = "Option::is_none")] pub country_name: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateDetectorRequest { /// <p>The idempotency token for the create request.</p> #[serde(rename = "ClientToken")] #[serde(skip_serializing_if = "Option::is_none")] pub client_token: Option<String>, /// <p>A boolean value that specifies whether the detector is to be enabled.</p> #[serde(rename = "Enable")] pub enable: bool, /// <p>A enum value that specifies how frequently customer got Finding updates published.</p> #[serde(rename = "FindingPublishingFrequency")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_publishing_frequency: Option<String>, /// <p>The tags to be added to a new detector resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateDetectorResponse { /// <p>The unique ID of the created detector.</p> #[serde(rename = "DetectorId")] #[serde(skip_serializing_if = "Option::is_none")] pub detector_id: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateFilterRequest { /// <p>Specifies the action that is to be applied to the findings that match the filter.</p> #[serde(rename = "Action")] #[serde(skip_serializing_if = "Option::is_none")] pub action: Option<String>, /// <p>The idempotency token for the create request.</p> #[serde(rename = "ClientToken")] #[serde(skip_serializing_if = "Option::is_none")] pub client_token: Option<String>, /// <p>The description of the filter.</p> #[serde(rename = "Description")] #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// <p>The unique ID of the detector of the GuardDuty account for which you want to create a filter.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Represents the criteria to be used in the filter for querying findings.</p> #[serde(rename = "FindingCriteria")] pub finding_criteria: FindingCriteria, /// <p>The name of the filter.</p> #[serde(rename = "Name")] pub name: String, /// <p>Specifies the position of the filter in the list of current filters. Also specifies the order in which this filter is applied to the findings.</p> #[serde(rename = "Rank")] #[serde(skip_serializing_if = "Option::is_none")] pub rank: Option<i64>, /// <p>The tags to be added to a new filter resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateFilterResponse { /// <p>The name of the successfully created filter.</p> #[serde(rename = "Name")] pub name: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateIPSetRequest { /// <p>A boolean value that indicates whether GuardDuty is to start using the uploaded IPSet.</p> #[serde(rename = "Activate")] pub activate: bool, /// <p>The idempotency token for the create request.</p> #[serde(rename = "ClientToken")] #[serde(skip_serializing_if = "Option::is_none")] pub client_token: Option<String>, /// <p>The unique ID of the detector of the GuardDuty account for which you want to create an IPSet.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The format of the file that contains the IPSet.</p> #[serde(rename = "Format")] pub format: String, /// <p>The URI of the file that contains the IPSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key)</p> #[serde(rename = "Location")] pub location: String, /// <p>The user friendly name to identify the IPSet. This name is displayed in all findings that are triggered by activity that involves IP addresses included in this IPSet.</p> #[serde(rename = "Name")] pub name: String, /// <p>The tags to be added to a new IP set resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateIPSetResponse { /// <p>The ID of the IPSet resource.</p> #[serde(rename = "IpSetId")] pub ip_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateMembersRequest { /// <p>A list of account ID and email address pairs of the accounts that you want to associate with the master GuardDuty account.</p> #[serde(rename = "AccountDetails")] pub account_details: Vec<AccountDetail>, /// <p>The unique ID of the detector of the GuardDuty account with which you want to associate member accounts.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateMembersResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateSampleFindingsRequest { /// <p>The ID of the detector to create sample findings for.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Types of sample findings that you want to generate.</p> #[serde(rename = "FindingTypes")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_types: Option<Vec<String>>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateSampleFindingsResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct CreateThreatIntelSetRequest { /// <p>A boolean value that indicates whether GuardDuty is to start using the uploaded ThreatIntelSet.</p> #[serde(rename = "Activate")] pub activate: bool, /// <p>The idempotency token for the create request.</p> #[serde(rename = "ClientToken")] #[serde(skip_serializing_if = "Option::is_none")] pub client_token: Option<String>, /// <p>The unique ID of the detector of the GuardDuty account for which you want to create a threatIntelSet.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The format of the file that contains the ThreatIntelSet.</p> #[serde(rename = "Format")] pub format: String, /// <p>The URI of the file that contains the ThreatIntelSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).</p> #[serde(rename = "Location")] pub location: String, /// <p>A user-friendly ThreatIntelSet name that is displayed in all finding generated by activity that involves IP addresses included in this ThreatIntelSet.</p> #[serde(rename = "Name")] pub name: String, /// <p>The tags to be added to a new Threat List resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct CreateThreatIntelSetResponse { /// <p>The ID of the ThreatIntelSet resource.</p> #[serde(rename = "ThreatIntelSetId")] pub threat_intel_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeclineInvitationsRequest { /// <p>A list of account IDs of the AWS accounts that sent invitations to the current member account that you want to decline invitations from.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeclineInvitationsResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteDetectorRequest { /// <p>The unique ID of the detector that you want to delete.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteDetectorResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteFilterRequest { /// <p>The unique ID of the detector the filter is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The name of the filter you want to delete.</p> #[serde(rename = "FilterName")] pub filter_name: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteFilterResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteIPSetRequest { /// <p>The unique ID of the detector the ipSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The unique ID of the ipSet you want to delete.</p> #[serde(rename = "IpSetId")] pub ip_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteIPSetResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteInvitationsRequest { /// <p>A list of account IDs of the AWS accounts that sent invitations to the current member account that you want to delete invitations from.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteInvitationsResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteMembersRequest { /// <p>A list of account IDs of the GuardDuty member accounts that you want to delete.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account whose members you want to delete.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteMembersResponse { /// <p>The accounts that could not be processed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DeleteThreatIntelSetRequest { /// <p>The unique ID of the detector the threatIntelSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The unique ID of the threatIntelSet you want to delete.</p> #[serde(rename = "ThreatIntelSetId")] pub threat_intel_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DeleteThreatIntelSetResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DisassociateFromMasterAccountRequest { /// <p>The unique ID of the detector of the GuardDuty member account.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DisassociateFromMasterAccountResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct DisassociateMembersRequest { /// <p>A list of account IDs of the GuardDuty member accounts that you want to disassociate from master.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account whose members you want to disassociate from master.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DisassociateMembersResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } /// <p>Contains information about the DNS request.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DnsRequestAction { /// <p>Domain information for the DNS request.</p> #[serde(rename = "Domain")] #[serde(skip_serializing_if = "Option::is_none")] pub domain: Option<String>, } /// <p>Contains information about the domain.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DomainDetails { /// <p>Domain information for the AWS API call.</p> #[serde(rename = "Domain")] #[serde(skip_serializing_if = "Option::is_none")] pub domain: Option<String>, } /// <p>Contains information about the reason that the finding was generated.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Evidence { /// <p>A list of threat intelligence details related to the evidence.</p> #[serde(rename = "ThreatIntelligenceDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub threat_intelligence_details: Option<Vec<ThreatIntelligenceDetail>>, } /// <p>Contains information about the finding.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Finding { /// <p>The ID of the account in which the finding was generated.</p> #[serde(rename = "AccountId")] pub account_id: String, /// <p>The ARN for the finding.</p> #[serde(rename = "Arn")] pub arn: String, /// <p>The confidence score for the finding.</p> #[serde(rename = "Confidence")] #[serde(skip_serializing_if = "Option::is_none")] pub confidence: Option<f64>, /// <p>The time and date at which the finding was created.</p> #[serde(rename = "CreatedAt")] pub created_at: String, /// <p>The description of the finding.</p> #[serde(rename = "Description")] #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// <p>The ID of the finding.</p> #[serde(rename = "Id")] pub id: String, /// <p>The partition associated with the finding.</p> #[serde(rename = "Partition")] #[serde(skip_serializing_if = "Option::is_none")] pub partition: Option<String>, /// <p>The Region in which the finding was generated.</p> #[serde(rename = "Region")] pub region: String, #[serde(rename = "Resource")] pub resource: Resource, /// <p>The version of the schema used for the finding.</p> #[serde(rename = "SchemaVersion")] pub schema_version: String, #[serde(rename = "Service")] #[serde(skip_serializing_if = "Option::is_none")] pub service: Option<Service>, /// <p>The severity of the finding.</p> #[serde(rename = "Severity")] pub severity: f64, /// <p>The title for the finding.</p> #[serde(rename = "Title")] #[serde(skip_serializing_if = "Option::is_none")] pub title: Option<String>, /// <p>The type of the finding.</p> #[serde(rename = "Type")] pub type_: String, /// <p>The time and date at which the finding was laste updated.</p> #[serde(rename = "UpdatedAt")] pub updated_at: String, } /// <p>Contains finding criteria information.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FindingCriteria { /// <p>Represents a map of finding properties that match specified conditions and values when querying findings.</p> #[serde(rename = "Criterion")] #[serde(skip_serializing_if = "Option::is_none")] pub criterion: Option<::std::collections::HashMap<String, Condition>>, } /// <p>Contains information about finding statistics.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct FindingStatistics { /// <p>Represents a map of severity to count statistic for a set of findings</p> #[serde(rename = "CountBySeverity")] #[serde(skip_serializing_if = "Option::is_none")] pub count_by_severity: Option<::std::collections::HashMap<String, i64>>, } /// <p>Contains information about the </p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GeoLocation { /// <p>Latitude information of remote IP address.</p> #[serde(rename = "Lat")] #[serde(skip_serializing_if = "Option::is_none")] pub lat: Option<f64>, /// <p>Longitude information of remote IP address.</p> #[serde(rename = "Lon")] #[serde(skip_serializing_if = "Option::is_none")] pub lon: Option<f64>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetDetectorRequest { /// <p>The unique ID of the detector that you want to get.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetDetectorResponse { /// <p>Detector creation timestamp.</p> #[serde(rename = "CreatedAt")] #[serde(skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, /// <p>Finding publishing frequency.</p> #[serde(rename = "FindingPublishingFrequency")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_publishing_frequency: Option<String>, /// <p>The GuardDuty service role.</p> #[serde(rename = "ServiceRole")] pub service_role: String, /// <p>The detector status.</p> #[serde(rename = "Status")] pub status: String, /// <p>The tags of the detector resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, /// <p>Detector last update timestamp.</p> #[serde(rename = "UpdatedAt")] #[serde(skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetFilterRequest { /// <p>The unique ID of the detector the filter is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The name of the filter you want to get.</p> #[serde(rename = "FilterName")] pub filter_name: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetFilterResponse { /// <p>Specifies the action that is to be applied to the findings that match the filter.</p> #[serde(rename = "Action")] pub action: String, /// <p>The description of the filter.</p> #[serde(rename = "Description")] #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// <p>Represents the criteria to be used in the filter for querying findings.</p> #[serde(rename = "FindingCriteria")] pub finding_criteria: FindingCriteria, /// <p>The name of the filter.</p> #[serde(rename = "Name")] pub name: String, /// <p>Specifies the position of the filter in the list of current filters. Also specifies the order in which this filter is applied to the findings.</p> #[serde(rename = "Rank")] #[serde(skip_serializing_if = "Option::is_none")] pub rank: Option<i64>, /// <p>The tags of the filter resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetFindingsRequest { /// <p>The ID of the detector that specifies the GuardDuty service whose findings you want to retrieve.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>IDs of the findings that you want to retrieve.</p> #[serde(rename = "FindingIds")] pub finding_ids: Vec<String>, /// <p>Represents the criteria used for sorting findings.</p> #[serde(rename = "SortCriteria")] #[serde(skip_serializing_if = "Option::is_none")] pub sort_criteria: Option<SortCriteria>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetFindingsResponse { /// <p>A list of findings.</p> #[serde(rename = "Findings")] pub findings: Vec<Finding>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetFindingsStatisticsRequest { /// <p>The ID of the detector that specifies the GuardDuty service whose findings' statistics you want to retrieve.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Represents the criteria used for querying findings.</p> #[serde(rename = "FindingCriteria")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_criteria: Option<FindingCriteria>, /// <p>Types of finding statistics to retrieve.</p> #[serde(rename = "FindingStatisticTypes")] pub finding_statistic_types: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetFindingsStatisticsResponse { /// <p>Finding statistics object.</p> #[serde(rename = "FindingStatistics")] pub finding_statistics: FindingStatistics, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetIPSetRequest { /// <p>The unique ID of the detector the ipSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The unique ID of the ipSet you want to get.</p> #[serde(rename = "IpSetId")] pub ip_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetIPSetResponse { /// <p>The format of the file that contains the IPSet.</p> #[serde(rename = "Format")] pub format: String, /// <p>The URI of the file that contains the IPSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key)</p> #[serde(rename = "Location")] pub location: String, /// <p>The user friendly name to identify the IPSet. This name is displayed in all findings that are triggered by activity that involves IP addresses included in this IPSet.</p> #[serde(rename = "Name")] pub name: String, /// <p>The status of ipSet file uploaded.</p> #[serde(rename = "Status")] pub status: String, /// <p>The tags of the IP set resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetInvitationsCountRequest {} #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetInvitationsCountResponse { /// <p>The number of received invitations.</p> #[serde(rename = "InvitationsCount")] #[serde(skip_serializing_if = "Option::is_none")] pub invitations_count: Option<i64>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetMasterAccountRequest { /// <p>The unique ID of the detector of the GuardDuty member account.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetMasterAccountResponse { /// <p>Master account details.</p> #[serde(rename = "Master")] pub master: Master, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetMembersRequest { /// <p>A list of account IDs of the GuardDuty member accounts that you want to describe.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account whose members you want to retrieve.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetMembersResponse { /// <p>A list of members.</p> #[serde(rename = "Members")] pub members: Vec<Member>, /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct GetThreatIntelSetRequest { /// <p>The unique ID of the detector the threatIntelSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The unique ID of the threatIntelSet you want to get.</p> #[serde(rename = "ThreatIntelSetId")] pub threat_intel_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetThreatIntelSetResponse { /// <p>The format of the threatIntelSet.</p> #[serde(rename = "Format")] pub format: String, /// <p>The URI of the file that contains the ThreatIntelSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).</p> #[serde(rename = "Location")] pub location: String, /// <p>A user-friendly ThreatIntelSet name that is displayed in all finding generated by activity that involves IP addresses included in this ThreatIntelSet.</p> #[serde(rename = "Name")] pub name: String, /// <p>The status of threatIntelSet file uploaded.</p> #[serde(rename = "Status")] pub status: String, /// <p>The tags of the Threat List resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } /// <p>Contains information about the instance profile.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct IamInstanceProfile { /// <p>AWS EC2 instance profile ARN.</p> #[serde(rename = "Arn")] #[serde(skip_serializing_if = "Option::is_none")] pub arn: Option<String>, /// <p>AWS EC2 instance profile ID.</p> #[serde(rename = "Id")] #[serde(skip_serializing_if = "Option::is_none")] pub id: Option<String>, } /// <p>Contains information about the details of an instance.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct InstanceDetails { /// <p>The availability zone of the EC2 instance.</p> #[serde(rename = "AvailabilityZone")] #[serde(skip_serializing_if = "Option::is_none")] pub availability_zone: Option<String>, /// <p>The profile information of the EC2 instance.</p> #[serde(rename = "IamInstanceProfile")] #[serde(skip_serializing_if = "Option::is_none")] pub iam_instance_profile: Option<IamInstanceProfile>, /// <p>The image description of the EC2 instance.</p> #[serde(rename = "ImageDescription")] #[serde(skip_serializing_if = "Option::is_none")] pub image_description: Option<String>, /// <p>The image ID of the EC2 instance.</p> #[serde(rename = "ImageId")] #[serde(skip_serializing_if = "Option::is_none")] pub image_id: Option<String>, /// <p>The ID of the EC2 instance.</p> #[serde(rename = "InstanceId")] #[serde(skip_serializing_if = "Option::is_none")] pub instance_id: Option<String>, /// <p>The state of the EC2 instance.</p> #[serde(rename = "InstanceState")] #[serde(skip_serializing_if = "Option::is_none")] pub instance_state: Option<String>, /// <p>The type of the EC2 instance.</p> #[serde(rename = "InstanceType")] #[serde(skip_serializing_if = "Option::is_none")] pub instance_type: Option<String>, /// <p>The launch time of the EC2 instance.</p> #[serde(rename = "LaunchTime")] #[serde(skip_serializing_if = "Option::is_none")] pub launch_time: Option<String>, /// <p>The network interface information of the EC2 instance.</p> #[serde(rename = "NetworkInterfaces")] #[serde(skip_serializing_if = "Option::is_none")] pub network_interfaces: Option<Vec<NetworkInterface>>, /// <p>The platform of the EC2 instance.</p> #[serde(rename = "Platform")] #[serde(skip_serializing_if = "Option::is_none")] pub platform: Option<String>, /// <p>The product code of the EC2 instance.</p> #[serde(rename = "ProductCodes")] #[serde(skip_serializing_if = "Option::is_none")] pub product_codes: Option<Vec<ProductCode>>, /// <p>The tags of the EC2 instance.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<Vec<Tag>>, } /// <p>Contains information about the invitation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Invitation { /// <p>Inviter account ID</p> #[serde(rename = "AccountId")] #[serde(skip_serializing_if = "Option::is_none")] pub account_id: Option<String>, /// <p>This value is used to validate the inviter account to the member account.</p> #[serde(rename = "InvitationId")] #[serde(skip_serializing_if = "Option::is_none")] pub invitation_id: Option<String>, /// <p>Timestamp at which the invitation was sent</p> #[serde(rename = "InvitedAt")] #[serde(skip_serializing_if = "Option::is_none")] pub invited_at: Option<String>, /// <p>The status of the relationship between the inviter and invitee accounts.</p> #[serde(rename = "RelationshipStatus")] #[serde(skip_serializing_if = "Option::is_none")] pub relationship_status: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct InviteMembersRequest { /// <p>A list of account IDs of the accounts that you want to invite to GuardDuty as members.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account with which you want to invite members.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>A boolean value that specifies whether you want to disable email notification to the accounts that you’re inviting to GuardDuty as members.</p> #[serde(rename = "DisableEmailNotification")] #[serde(skip_serializing_if = "Option::is_none")] pub disable_email_notification: Option<bool>, /// <p>The invitation message that you want to send to the accounts that you’re inviting to GuardDuty as members.</p> #[serde(rename = "Message")] #[serde(skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct InviteMembersResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListDetectorsRequest { /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListDetectorsResponse { /// <p>A list of detector Ids.</p> #[serde(rename = "DetectorIds")] pub detector_ids: Vec<String>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListFiltersRequest { /// <p>The unique ID of the detector the filter is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListFiltersResponse { /// <p>A list of filter names</p> #[serde(rename = "FilterNames")] pub filter_names: Vec<String>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListFindingsRequest { /// <p>The ID of the detector that specifies the GuardDuty service whose findings you want to list.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Represents the criteria used for querying findings.</p> #[serde(rename = "FindingCriteria")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_criteria: Option<FindingCriteria>, /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, /// <p>Represents the criteria used for sorting findings.</p> #[serde(rename = "SortCriteria")] #[serde(skip_serializing_if = "Option::is_none")] pub sort_criteria: Option<SortCriteria>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListFindingsResponse { /// <p>The IDs of the findings you are listing.</p> #[serde(rename = "FindingIds")] pub finding_ids: Vec<String>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListIPSetsRequest { /// <p>The unique ID of the detector the ipSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListIPSetsResponse { /// <p>The IDs of the IPSet resources.</p> #[serde(rename = "IpSetIds")] pub ip_set_ids: Vec<String>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListInvitationsRequest { /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListInvitationsResponse { /// <p>A list of invitation descriptions.</p> #[serde(rename = "Invitations")] #[serde(skip_serializing_if = "Option::is_none")] pub invitations: Option<Vec<Invitation>>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListMembersRequest { /// <p>The unique ID of the detector the member is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, /// <p>Specifies whether to only return associated members or to return all members (including members which haven't been invited yet or have been disassociated).</p> #[serde(rename = "OnlyAssociated")] #[serde(skip_serializing_if = "Option::is_none")] pub only_associated: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListMembersResponse { /// <p>A list of members.</p> #[serde(rename = "Members")] #[serde(skip_serializing_if = "Option::is_none")] pub members: Option<Vec<Member>>, /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListTagsForResourceRequest { /// <p>The Amazon Resource Name (ARN) for the given GuardDuty resource </p> #[serde(rename = "ResourceArn")] pub resource_arn: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListTagsForResourceResponse { /// <p>The tags associated with the resource.</p> #[serde(rename = "Tags")] #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, String>>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct ListThreatIntelSetsRequest { /// <p>The unique ID of the detector the threatIntelSet is associated with.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>You can use this parameter to indicate the maximum number of items you want in the response. The default value is 50. The maximum value is 50.</p> #[serde(rename = "MaxResults")] #[serde(skip_serializing_if = "Option::is_none")] pub max_results: Option<i64>, /// <p>You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListThreatIntelSetsResponse { /// <p>Pagination parameter to be used on the next list operation to retrieve more items.</p> #[serde(rename = "NextToken")] #[serde(skip_serializing_if = "Option::is_none")] pub next_token: Option<String>, /// <p>The IDs of the ThreatIntelSet resources.</p> #[serde(rename = "ThreatIntelSetIds")] pub threat_intel_set_ids: Vec<String>, } /// <p>Contains information about the port for the local connection.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct LocalPortDetails { /// <p>Port number of the local connection.</p> #[serde(rename = "Port")] #[serde(skip_serializing_if = "Option::is_none")] pub port: Option<i64>, /// <p>Port name of the local connection.</p> #[serde(rename = "PortName")] #[serde(skip_serializing_if = "Option::is_none")] pub port_name: Option<String>, } /// <p>Contains information about the Master account and invitation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Master { /// <p>The ID of the account used as the Master account.</p> #[serde(rename = "AccountId")] #[serde(skip_serializing_if = "Option::is_none")] pub account_id: Option<String>, /// <p>This value is used to validate the master account to the member account.</p> #[serde(rename = "InvitationId")] #[serde(skip_serializing_if = "Option::is_none")] pub invitation_id: Option<String>, /// <p>Timestamp at which the invitation was sent.</p> #[serde(rename = "InvitedAt")] #[serde(skip_serializing_if = "Option::is_none")] pub invited_at: Option<String>, /// <p>The status of the relationship between the master and member accounts.</p> #[serde(rename = "RelationshipStatus")] #[serde(skip_serializing_if = "Option::is_none")] pub relationship_status: Option<String>, } /// <p>Continas information about the member account </p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Member { /// <p>Member account ID.</p> #[serde(rename = "AccountId")] pub account_id: String, /// <p>Member account's detector ID.</p> #[serde(rename = "DetectorId")] #[serde(skip_serializing_if = "Option::is_none")] pub detector_id: Option<String>, /// <p>Member account's email address.</p> #[serde(rename = "Email")] pub email: String, /// <p>Timestamp at which the invitation was sent</p> #[serde(rename = "InvitedAt")] #[serde(skip_serializing_if = "Option::is_none")] pub invited_at: Option<String>, /// <p>Master account ID.</p> #[serde(rename = "MasterId")] pub master_id: String, /// <p>The status of the relationship between the member and the master.</p> #[serde(rename = "RelationshipStatus")] pub relationship_status: String, /// <p>Member last updated timestamp.</p> #[serde(rename = "UpdatedAt")] pub updated_at: String, } /// <p>Contains information about the network connection.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct NetworkConnectionAction { /// <p>Network connection blocked information.</p> #[serde(rename = "Blocked")] #[serde(skip_serializing_if = "Option::is_none")] pub blocked: Option<bool>, /// <p>Network connection direction.</p> #[serde(rename = "ConnectionDirection")] #[serde(skip_serializing_if = "Option::is_none")] pub connection_direction: Option<String>, /// <p>Local port information of the connection.</p> #[serde(rename = "LocalPortDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub local_port_details: Option<LocalPortDetails>, /// <p>Network connection protocol.</p> #[serde(rename = "Protocol")] #[serde(skip_serializing_if = "Option::is_none")] pub protocol: Option<String>, /// <p>Remote IP information of the connection.</p> #[serde(rename = "RemoteIpDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub remote_ip_details: Option<RemoteIpDetails>, /// <p>Remote port information of the connection.</p> #[serde(rename = "RemotePortDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub remote_port_details: Option<RemotePortDetails>, } /// <p>Contains information about the network interface.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct NetworkInterface { /// <p>A list of EC2 instance IPv6 address information.</p> #[serde(rename = "Ipv6Addresses")] #[serde(skip_serializing_if = "Option::is_none")] pub ipv_6_addresses: Option<Vec<String>>, /// <p>The ID of the network interface</p> #[serde(rename = "NetworkInterfaceId")] #[serde(skip_serializing_if = "Option::is_none")] pub network_interface_id: Option<String>, /// <p>Private DNS name of the EC2 instance.</p> #[serde(rename = "PrivateDnsName")] #[serde(skip_serializing_if = "Option::is_none")] pub private_dns_name: Option<String>, /// <p>Private IP address of the EC2 instance.</p> #[serde(rename = "PrivateIpAddress")] #[serde(skip_serializing_if = "Option::is_none")] pub private_ip_address: Option<String>, /// <p>Other private IP address information of the EC2 instance.</p> #[serde(rename = "PrivateIpAddresses")] #[serde(skip_serializing_if = "Option::is_none")] pub private_ip_addresses: Option<Vec<PrivateIpAddressDetails>>, /// <p>Public DNS name of the EC2 instance.</p> #[serde(rename = "PublicDnsName")] #[serde(skip_serializing_if = "Option::is_none")] pub public_dns_name: Option<String>, /// <p>Public IP address of the EC2 instance.</p> #[serde(rename = "PublicIp")] #[serde(skip_serializing_if = "Option::is_none")] pub public_ip: Option<String>, /// <p>Security groups associated with the EC2 instance.</p> #[serde(rename = "SecurityGroups")] #[serde(skip_serializing_if = "Option::is_none")] pub security_groups: Option<Vec<SecurityGroup>>, /// <p>The subnet ID of the EC2 instance.</p> #[serde(rename = "SubnetId")] #[serde(skip_serializing_if = "Option::is_none")] pub subnet_id: Option<String>, /// <p>The VPC ID of the EC2 instance.</p> #[serde(rename = "VpcId")] #[serde(skip_serializing_if = "Option::is_none")] pub vpc_id: Option<String>, } /// <p>Continas information about the organization.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Organization { /// <p>Autonomous system number of the internet provider of the remote IP address.</p> #[serde(rename = "Asn")] #[serde(skip_serializing_if = "Option::is_none")] pub asn: Option<String>, /// <p>Organization that registered this ASN.</p> #[serde(rename = "AsnOrg")] #[serde(skip_serializing_if = "Option::is_none")] pub asn_org: Option<String>, /// <p>ISP information for the internet provider.</p> #[serde(rename = "Isp")] #[serde(skip_serializing_if = "Option::is_none")] pub isp: Option<String>, /// <p>Name of the internet provider.</p> #[serde(rename = "Org")] #[serde(skip_serializing_if = "Option::is_none")] pub org: Option<String>, } /// <p>Contains information about the port probe.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct PortProbeAction { /// <p>Port probe blocked information.</p> #[serde(rename = "Blocked")] #[serde(skip_serializing_if = "Option::is_none")] pub blocked: Option<bool>, /// <p>A list of port probe details objects.</p> #[serde(rename = "PortProbeDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub port_probe_details: Option<Vec<PortProbeDetail>>, } /// <p>Contains information about the port probe details.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct PortProbeDetail { /// <p>Local port information of the connection.</p> #[serde(rename = "LocalPortDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub local_port_details: Option<LocalPortDetails>, /// <p>Remote IP information of the connection.</p> #[serde(rename = "RemoteIpDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub remote_ip_details: Option<RemoteIpDetails>, } /// <p>Contains information about the private IP address.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct PrivateIpAddressDetails { /// <p>Private DNS name of the EC2 instance.</p> #[serde(rename = "PrivateDnsName")] #[serde(skip_serializing_if = "Option::is_none")] pub private_dns_name: Option<String>, /// <p>Private IP address of the EC2 instance.</p> #[serde(rename = "PrivateIpAddress")] #[serde(skip_serializing_if = "Option::is_none")] pub private_ip_address: Option<String>, } /// <p>Contains information about the product code.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ProductCode { /// <p>Product code information.</p> #[serde(rename = "Code")] #[serde(skip_serializing_if = "Option::is_none")] pub code: Option<String>, /// <p>Product code type.</p> #[serde(rename = "ProductType")] #[serde(skip_serializing_if = "Option::is_none")] pub product_type: Option<String>, } /// <p>Continas information about the remote IP address.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct RemoteIpDetails { /// <p>City information of the remote IP address.</p> #[serde(rename = "City")] #[serde(skip_serializing_if = "Option::is_none")] pub city: Option<City>, /// <p>Country code of the remote IP address.</p> #[serde(rename = "Country")] #[serde(skip_serializing_if = "Option::is_none")] pub country: Option<Country>, /// <p>Location information of the remote IP address.</p> #[serde(rename = "GeoLocation")] #[serde(skip_serializing_if = "Option::is_none")] pub geo_location: Option<GeoLocation>, /// <p>IPV4 remote address of the connection.</p> #[serde(rename = "IpAddressV4")] #[serde(skip_serializing_if = "Option::is_none")] pub ip_address_v4: Option<String>, /// <p>ISP Organization information of the remote IP address.</p> #[serde(rename = "Organization")] #[serde(skip_serializing_if = "Option::is_none")] pub organization: Option<Organization>, } /// <p>Contains information about the remote port.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct RemotePortDetails { /// <p>Port number of the remote connection.</p> #[serde(rename = "Port")] #[serde(skip_serializing_if = "Option::is_none")] pub port: Option<i64>, /// <p>Port name of the remote connection.</p> #[serde(rename = "PortName")] #[serde(skip_serializing_if = "Option::is_none")] pub port_name: Option<String>, } /// <p>Contains information about the resource.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Resource { /// <p>The IAM access key details (IAM user information) of a user that engaged in the activity that prompted GuardDuty to generate a finding.</p> #[serde(rename = "AccessKeyDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub access_key_details: Option<AccessKeyDetails>, /// <p>The information about the EC2 instance associated with the activity that prompted GuardDuty to generate a finding.</p> #[serde(rename = "InstanceDetails")] #[serde(skip_serializing_if = "Option::is_none")] pub instance_details: Option<InstanceDetails>, /// <p>The type of the AWS resource.</p> #[serde(rename = "ResourceType")] #[serde(skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, } /// <p>Contains information about the security group.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct SecurityGroup { /// <p>EC2 instance's security group ID.</p> #[serde(rename = "GroupId")] #[serde(skip_serializing_if = "Option::is_none")] pub group_id: Option<String>, /// <p>EC2 instance's security group name.</p> #[serde(rename = "GroupName")] #[serde(skip_serializing_if = "Option::is_none")] pub group_name: Option<String>, } /// <p>Contains information about the service.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Service { /// <p>Information about the activity described in a finding.</p> #[serde(rename = "Action")] #[serde(skip_serializing_if = "Option::is_none")] pub action: Option<Action>, /// <p>Indicates whether this finding is archived.</p> #[serde(rename = "Archived")] #[serde(skip_serializing_if = "Option::is_none")] pub archived: Option<bool>, /// <p>Total count of the occurrences of this finding type.</p> #[serde(rename = "Count")] #[serde(skip_serializing_if = "Option::is_none")] pub count: Option<i64>, /// <p>Detector ID for the GuardDuty service.</p> #[serde(rename = "DetectorId")] #[serde(skip_serializing_if = "Option::is_none")] pub detector_id: Option<String>, /// <p>First seen timestamp of the activity that prompted GuardDuty to generate this finding.</p> #[serde(rename = "EventFirstSeen")] #[serde(skip_serializing_if = "Option::is_none")] pub event_first_seen: Option<String>, /// <p>Last seen timestamp of the activity that prompted GuardDuty to generate this finding.</p> #[serde(rename = "EventLastSeen")] #[serde(skip_serializing_if = "Option::is_none")] pub event_last_seen: Option<String>, /// <p>An evidence object associated with the service.</p> #[serde(rename = "Evidence")] #[serde(skip_serializing_if = "Option::is_none")] pub evidence: Option<Evidence>, /// <p>Resource role information for this finding.</p> #[serde(rename = "ResourceRole")] #[serde(skip_serializing_if = "Option::is_none")] pub resource_role: Option<String>, /// <p>The name of the AWS service (GuardDuty) that generated a finding.</p> #[serde(rename = "ServiceName")] #[serde(skip_serializing_if = "Option::is_none")] pub service_name: Option<String>, /// <p>Feedback left about the finding.</p> #[serde(rename = "UserFeedback")] #[serde(skip_serializing_if = "Option::is_none")] pub user_feedback: Option<String>, } /// <p>Contains information about the criteria for sorting.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct SortCriteria { /// <p>Represents the finding attribute (for example, accountId) by which to sort findings.</p> #[serde(rename = "AttributeName")] #[serde(skip_serializing_if = "Option::is_none")] pub attribute_name: Option<String>, /// <p>Order by which the sorted findings are to be displayed.</p> #[serde(rename = "OrderBy")] #[serde(skip_serializing_if = "Option::is_none")] pub order_by: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct StartMonitoringMembersRequest { /// <p>A list of account IDs of the GuardDuty member accounts whose findings you want the master account to monitor.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account whom you want to re-enable to monitor members' findings.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct StartMonitoringMembersResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct StopMonitoringMembersRequest { /// <p>A list of account IDs of the GuardDuty member accounts whose findings you want the master account to stop monitoring.</p> #[serde(rename = "AccountIds")] pub account_ids: Vec<String>, /// <p>The unique ID of the detector of the GuardDuty account that you want to stop from monitor members' findings.</p> #[serde(rename = "DetectorId")] pub detector_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct StopMonitoringMembersResponse { /// <p>A list of objects containing the unprocessed account and a result string explaining why it was unprocessed.</p> #[serde(rename = "UnprocessedAccounts")] pub unprocessed_accounts: Vec<UnprocessedAccount>, } /// <p>Contains information about the tag associated with the resource.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Tag { /// <p>EC2 instance tag key.</p> #[serde(rename = "Key")] #[serde(skip_serializing_if = "Option::is_none")] pub key: Option<String>, /// <p>EC2 instance tag value.</p> #[serde(rename = "Value")] #[serde(skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct TagResourceRequest { /// <p>The Amazon Resource Name (ARN) for the given GuardDuty resource </p> #[serde(rename = "ResourceArn")] pub resource_arn: String, /// <p>The tags to be added to a resource.</p> #[serde(rename = "Tags")] pub tags: ::std::collections::HashMap<String, String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct TagResourceResponse {} /// <p>An instance of a threat intelligence detail that constitutes evidence for the finding.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ThreatIntelligenceDetail { /// <p>The name of the threat intelligence list that triggered the finding.</p> #[serde(rename = "ThreatListName")] #[serde(skip_serializing_if = "Option::is_none")] pub threat_list_name: Option<String>, /// <p>A list of names of the threats in the threat intelligence list that triggered the finding.</p> #[serde(rename = "ThreatNames")] #[serde(skip_serializing_if = "Option::is_none")] pub threat_names: Option<Vec<String>>, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UnarchiveFindingsRequest { /// <p>The ID of the detector that specifies the GuardDuty service whose findings you want to unarchive.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>IDs of the findings that you want to unarchive.</p> #[serde(rename = "FindingIds")] pub finding_ids: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UnarchiveFindingsResponse {} /// <p>Contains information about the accounts that were not processed.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UnprocessedAccount { /// <p>AWS Account ID.</p> #[serde(rename = "AccountId")] pub account_id: String, /// <p>A reason why the account hasn't been processed.</p> #[serde(rename = "Result")] pub result: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UntagResourceRequest { /// <p>The Amazon Resource Name (ARN) for the given GuardDuty resource </p> #[serde(rename = "ResourceArn")] pub resource_arn: String, /// <p>The tag keys to remove from a resource.</p> #[serde(rename = "TagKeys")] pub tag_keys: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UntagResourceResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UpdateDetectorRequest { /// <p>The unique ID of the detector that you want to update.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Updated boolean value for the detector that specifies whether the detector is enabled.</p> #[serde(rename = "Enable")] #[serde(skip_serializing_if = "Option::is_none")] pub enable: Option<bool>, /// <p>A enum value that specifies how frequently customer got Finding updates published.</p> #[serde(rename = "FindingPublishingFrequency")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_publishing_frequency: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UpdateDetectorResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UpdateFilterRequest { /// <p>Specifies the action that is to be applied to the findings that match the filter.</p> #[serde(rename = "Action")] #[serde(skip_serializing_if = "Option::is_none")] pub action: Option<String>, /// <p>The description of the filter.</p> #[serde(rename = "Description")] #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// <p>The unique ID of the detector that specifies the GuardDuty service where you want to update a filter.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The name of the filter.</p> #[serde(rename = "FilterName")] pub filter_name: String, /// <p>Represents the criteria to be used in the filter for querying findings.</p> #[serde(rename = "FindingCriteria")] #[serde(skip_serializing_if = "Option::is_none")] pub finding_criteria: Option<FindingCriteria>, /// <p>Specifies the position of the filter in the list of current filters. Also specifies the order in which this filter is applied to the findings.</p> #[serde(rename = "Rank")] #[serde(skip_serializing_if = "Option::is_none")] pub rank: Option<i64>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UpdateFilterResponse { /// <p>The name of the filter.</p> #[serde(rename = "Name")] pub name: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UpdateFindingsFeedbackRequest { /// <p>Additional feedback about the GuardDuty findings.</p> #[serde(rename = "Comments")] #[serde(skip_serializing_if = "Option::is_none")] pub comments: Option<String>, /// <p>The ID of the detector that specifies the GuardDuty service whose findings you want to mark as useful or not useful.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>Valid values: USEFUL | NOT_USEFUL</p> #[serde(rename = "Feedback")] pub feedback: String, /// <p>IDs of the findings that you want to mark as useful or not useful.</p> #[serde(rename = "FindingIds")] pub finding_ids: Vec<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UpdateFindingsFeedbackResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UpdateIPSetRequest { /// <p>The updated boolean value that specifies whether the IPSet is active or not.</p> #[serde(rename = "Activate")] #[serde(skip_serializing_if = "Option::is_none")] pub activate: Option<bool>, /// <p>The detectorID that specifies the GuardDuty service whose IPSet you want to update.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The unique ID that specifies the IPSet that you want to update.</p> #[serde(rename = "IpSetId")] pub ip_set_id: String, /// <p>The updated URI of the file that contains the IPSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).</p> #[serde(rename = "Location")] #[serde(skip_serializing_if = "Option::is_none")] pub location: Option<String>, /// <p>The unique ID that specifies the IPSet that you want to update.</p> #[serde(rename = "Name")] #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UpdateIPSetResponse {} #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub struct UpdateThreatIntelSetRequest { /// <p>The updated boolean value that specifies whether the ThreateIntelSet is active or not.</p> #[serde(rename = "Activate")] #[serde(skip_serializing_if = "Option::is_none")] pub activate: Option<bool>, /// <p>The detectorID that specifies the GuardDuty service whose ThreatIntelSet you want to update.</p> #[serde(rename = "DetectorId")] pub detector_id: String, /// <p>The updated URI of the file that contains the ThreateIntelSet. For example (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key)</p> #[serde(rename = "Location")] #[serde(skip_serializing_if = "Option::is_none")] pub location: Option<String>, /// <p>The unique ID that specifies the ThreatIntelSet that you want to update.</p> #[serde(rename = "Name")] #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// <p>The unique ID that specifies the ThreatIntelSet that you want to update.</p> #[serde(rename = "ThreatIntelSetId")] pub threat_intel_set_id: String, } #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct UpdateThreatIntelSetResponse {} /// Errors returned by AcceptInvitation #[derive(Debug, PartialEq)] pub enum AcceptInvitationError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl AcceptInvitationError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<AcceptInvitationError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(AcceptInvitationError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(AcceptInvitationError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for AcceptInvitationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for AcceptInvitationError { fn description(&self) -> &str { match *self { AcceptInvitationError::BadRequest(ref cause) => cause, AcceptInvitationError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ArchiveFindings #[derive(Debug, PartialEq)] pub enum ArchiveFindingsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ArchiveFindingsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ArchiveFindingsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ArchiveFindingsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ArchiveFindingsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ArchiveFindingsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ArchiveFindingsError { fn description(&self) -> &str { match *self { ArchiveFindingsError::BadRequest(ref cause) => cause, ArchiveFindingsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateDetector #[derive(Debug, PartialEq)] pub enum CreateDetectorError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateDetectorError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateDetectorError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateDetectorError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateDetectorError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateDetectorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateDetectorError { fn description(&self) -> &str { match *self { CreateDetectorError::BadRequest(ref cause) => cause, CreateDetectorError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateFilter #[derive(Debug, PartialEq)] pub enum CreateFilterError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateFilterError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateFilterError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateFilterError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateFilterError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateFilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateFilterError { fn description(&self) -> &str { match *self { CreateFilterError::BadRequest(ref cause) => cause, CreateFilterError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateIPSet #[derive(Debug, PartialEq)] pub enum CreateIPSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateIPSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateIPSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateIPSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateIPSetError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateIPSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateIPSetError { fn description(&self) -> &str { match *self { CreateIPSetError::BadRequest(ref cause) => cause, CreateIPSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateMembers #[derive(Debug, PartialEq)] pub enum CreateMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateMembersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateMembersError { fn description(&self) -> &str { match *self { CreateMembersError::BadRequest(ref cause) => cause, CreateMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateSampleFindings #[derive(Debug, PartialEq)] pub enum CreateSampleFindingsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateSampleFindingsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateSampleFindingsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateSampleFindingsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateSampleFindingsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateSampleFindingsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateSampleFindingsError { fn description(&self) -> &str { match *self { CreateSampleFindingsError::BadRequest(ref cause) => cause, CreateSampleFindingsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by CreateThreatIntelSet #[derive(Debug, PartialEq)] pub enum CreateThreatIntelSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl CreateThreatIntelSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateThreatIntelSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(CreateThreatIntelSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(CreateThreatIntelSetError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for CreateThreatIntelSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for CreateThreatIntelSetError { fn description(&self) -> &str { match *self { CreateThreatIntelSetError::BadRequest(ref cause) => cause, CreateThreatIntelSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeclineInvitations #[derive(Debug, PartialEq)] pub enum DeclineInvitationsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeclineInvitationsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeclineInvitationsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeclineInvitationsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeclineInvitationsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeclineInvitationsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeclineInvitationsError { fn description(&self) -> &str { match *self { DeclineInvitationsError::BadRequest(ref cause) => cause, DeclineInvitationsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteDetector #[derive(Debug, PartialEq)] pub enum DeleteDetectorError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteDetectorError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteDetectorError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteDetectorError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteDetectorError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteDetectorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteDetectorError { fn description(&self) -> &str { match *self { DeleteDetectorError::BadRequest(ref cause) => cause, DeleteDetectorError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteFilter #[derive(Debug, PartialEq)] pub enum DeleteFilterError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteFilterError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteFilterError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteFilterError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteFilterError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteFilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteFilterError { fn description(&self) -> &str { match *self { DeleteFilterError::BadRequest(ref cause) => cause, DeleteFilterError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteIPSet #[derive(Debug, PartialEq)] pub enum DeleteIPSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteIPSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteIPSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteIPSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteIPSetError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteIPSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteIPSetError { fn description(&self) -> &str { match *self { DeleteIPSetError::BadRequest(ref cause) => cause, DeleteIPSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteInvitations #[derive(Debug, PartialEq)] pub enum DeleteInvitationsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteInvitationsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteInvitationsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteInvitationsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteInvitationsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteInvitationsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteInvitationsError { fn description(&self) -> &str { match *self { DeleteInvitationsError::BadRequest(ref cause) => cause, DeleteInvitationsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteMembers #[derive(Debug, PartialEq)] pub enum DeleteMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteMembersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteMembersError { fn description(&self) -> &str { match *self { DeleteMembersError::BadRequest(ref cause) => cause, DeleteMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DeleteThreatIntelSet #[derive(Debug, PartialEq)] pub enum DeleteThreatIntelSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DeleteThreatIntelSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteThreatIntelSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DeleteThreatIntelSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DeleteThreatIntelSetError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DeleteThreatIntelSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DeleteThreatIntelSetError { fn description(&self) -> &str { match *self { DeleteThreatIntelSetError::BadRequest(ref cause) => cause, DeleteThreatIntelSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DisassociateFromMasterAccount #[derive(Debug, PartialEq)] pub enum DisassociateFromMasterAccountError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DisassociateFromMasterAccountError { pub fn from_response( res: BufferedHttpResponse, ) -> RusotoError<DisassociateFromMasterAccountError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DisassociateFromMasterAccountError::BadRequest( err.msg, )) } "InternalServerErrorException" => { return RusotoError::Service( DisassociateFromMasterAccountError::InternalServerError(err.msg), ) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DisassociateFromMasterAccountError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DisassociateFromMasterAccountError { fn description(&self) -> &str { match *self { DisassociateFromMasterAccountError::BadRequest(ref cause) => cause, DisassociateFromMasterAccountError::InternalServerError(ref cause) => cause, } } } /// Errors returned by DisassociateMembers #[derive(Debug, PartialEq)] pub enum DisassociateMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl DisassociateMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DisassociateMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(DisassociateMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(DisassociateMembersError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DisassociateMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for DisassociateMembersError { fn description(&self) -> &str { match *self { DisassociateMembersError::BadRequest(ref cause) => cause, DisassociateMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetDetector #[derive(Debug, PartialEq)] pub enum GetDetectorError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetDetectorError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetDetectorError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetDetectorError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetDetectorError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetDetectorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetDetectorError { fn description(&self) -> &str { match *self { GetDetectorError::BadRequest(ref cause) => cause, GetDetectorError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetFilter #[derive(Debug, PartialEq)] pub enum GetFilterError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetFilterError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetFilterError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetFilterError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetFilterError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetFilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetFilterError { fn description(&self) -> &str { match *self { GetFilterError::BadRequest(ref cause) => cause, GetFilterError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetFindings #[derive(Debug, PartialEq)] pub enum GetFindingsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetFindingsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetFindingsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetFindingsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetFindingsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetFindingsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetFindingsError { fn description(&self) -> &str { match *self { GetFindingsError::BadRequest(ref cause) => cause, GetFindingsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetFindingsStatistics #[derive(Debug, PartialEq)] pub enum GetFindingsStatisticsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetFindingsStatisticsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetFindingsStatisticsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetFindingsStatisticsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetFindingsStatisticsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetFindingsStatisticsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetFindingsStatisticsError { fn description(&self) -> &str { match *self { GetFindingsStatisticsError::BadRequest(ref cause) => cause, GetFindingsStatisticsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetIPSet #[derive(Debug, PartialEq)] pub enum GetIPSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetIPSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetIPSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetIPSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetIPSetError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetIPSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetIPSetError { fn description(&self) -> &str { match *self { GetIPSetError::BadRequest(ref cause) => cause, GetIPSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetInvitationsCount #[derive(Debug, PartialEq)] pub enum GetInvitationsCountError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetInvitationsCountError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetInvitationsCountError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetInvitationsCountError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetInvitationsCountError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetInvitationsCountError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetInvitationsCountError { fn description(&self) -> &str { match *self { GetInvitationsCountError::BadRequest(ref cause) => cause, GetInvitationsCountError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetMasterAccount #[derive(Debug, PartialEq)] pub enum GetMasterAccountError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetMasterAccountError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetMasterAccountError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetMasterAccountError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetMasterAccountError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetMasterAccountError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetMasterAccountError { fn description(&self) -> &str { match *self { GetMasterAccountError::BadRequest(ref cause) => cause, GetMasterAccountError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetMembers #[derive(Debug, PartialEq)] pub enum GetMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetMembersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetMembersError { fn description(&self) -> &str { match *self { GetMembersError::BadRequest(ref cause) => cause, GetMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by GetThreatIntelSet #[derive(Debug, PartialEq)] pub enum GetThreatIntelSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl GetThreatIntelSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetThreatIntelSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(GetThreatIntelSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(GetThreatIntelSetError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetThreatIntelSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for GetThreatIntelSetError { fn description(&self) -> &str { match *self { GetThreatIntelSetError::BadRequest(ref cause) => cause, GetThreatIntelSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by InviteMembers #[derive(Debug, PartialEq)] pub enum InviteMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl InviteMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<InviteMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(InviteMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(InviteMembersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for InviteMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for InviteMembersError { fn description(&self) -> &str { match *self { InviteMembersError::BadRequest(ref cause) => cause, InviteMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListDetectors #[derive(Debug, PartialEq)] pub enum ListDetectorsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListDetectorsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListDetectorsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListDetectorsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListDetectorsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListDetectorsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListDetectorsError { fn description(&self) -> &str { match *self { ListDetectorsError::BadRequest(ref cause) => cause, ListDetectorsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListFilters #[derive(Debug, PartialEq)] pub enum ListFiltersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListFiltersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListFiltersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListFiltersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListFiltersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListFiltersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListFiltersError { fn description(&self) -> &str { match *self { ListFiltersError::BadRequest(ref cause) => cause, ListFiltersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListFindings #[derive(Debug, PartialEq)] pub enum ListFindingsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListFindingsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListFindingsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListFindingsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListFindingsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListFindingsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListFindingsError { fn description(&self) -> &str { match *self { ListFindingsError::BadRequest(ref cause) => cause, ListFindingsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListIPSets #[derive(Debug, PartialEq)] pub enum ListIPSetsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListIPSetsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListIPSetsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListIPSetsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListIPSetsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListIPSetsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListIPSetsError { fn description(&self) -> &str { match *self { ListIPSetsError::BadRequest(ref cause) => cause, ListIPSetsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListInvitations #[derive(Debug, PartialEq)] pub enum ListInvitationsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListInvitationsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListInvitationsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListInvitationsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListInvitationsError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListInvitationsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListInvitationsError { fn description(&self) -> &str { match *self { ListInvitationsError::BadRequest(ref cause) => cause, ListInvitationsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListMembers #[derive(Debug, PartialEq)] pub enum ListMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListMembersError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListMembersError { fn description(&self) -> &str { match *self { ListMembersError::BadRequest(ref cause) => cause, ListMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListTagsForResource #[derive(Debug, PartialEq)] pub enum ListTagsForResourceError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListTagsForResourceError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListTagsForResourceError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListTagsForResourceError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListTagsForResourceError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListTagsForResourceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListTagsForResourceError { fn description(&self) -> &str { match *self { ListTagsForResourceError::BadRequest(ref cause) => cause, ListTagsForResourceError::InternalServerError(ref cause) => cause, } } } /// Errors returned by ListThreatIntelSets #[derive(Debug, PartialEq)] pub enum ListThreatIntelSetsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl ListThreatIntelSetsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListThreatIntelSetsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(ListThreatIntelSetsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(ListThreatIntelSetsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListThreatIntelSetsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for ListThreatIntelSetsError { fn description(&self) -> &str { match *self { ListThreatIntelSetsError::BadRequest(ref cause) => cause, ListThreatIntelSetsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by StartMonitoringMembers #[derive(Debug, PartialEq)] pub enum StartMonitoringMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl StartMonitoringMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<StartMonitoringMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(StartMonitoringMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(StartMonitoringMembersError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for StartMonitoringMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for StartMonitoringMembersError { fn description(&self) -> &str { match *self { StartMonitoringMembersError::BadRequest(ref cause) => cause, StartMonitoringMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by StopMonitoringMembers #[derive(Debug, PartialEq)] pub enum StopMonitoringMembersError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl StopMonitoringMembersError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<StopMonitoringMembersError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(StopMonitoringMembersError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(StopMonitoringMembersError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for StopMonitoringMembersError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for StopMonitoringMembersError { fn description(&self) -> &str { match *self { StopMonitoringMembersError::BadRequest(ref cause) => cause, StopMonitoringMembersError::InternalServerError(ref cause) => cause, } } } /// Errors returned by TagResource #[derive(Debug, PartialEq)] pub enum TagResourceError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl TagResourceError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<TagResourceError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(TagResourceError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(TagResourceError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for TagResourceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for TagResourceError { fn description(&self) -> &str { match *self { TagResourceError::BadRequest(ref cause) => cause, TagResourceError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UnarchiveFindings #[derive(Debug, PartialEq)] pub enum UnarchiveFindingsError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UnarchiveFindingsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UnarchiveFindingsError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UnarchiveFindingsError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UnarchiveFindingsError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UnarchiveFindingsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UnarchiveFindingsError { fn description(&self) -> &str { match *self { UnarchiveFindingsError::BadRequest(ref cause) => cause, UnarchiveFindingsError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UntagResource #[derive(Debug, PartialEq)] pub enum UntagResourceError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UntagResourceError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UntagResourceError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UntagResourceError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UntagResourceError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UntagResourceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UntagResourceError { fn description(&self) -> &str { match *self { UntagResourceError::BadRequest(ref cause) => cause, UntagResourceError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UpdateDetector #[derive(Debug, PartialEq)] pub enum UpdateDetectorError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UpdateDetectorError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateDetectorError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UpdateDetectorError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UpdateDetectorError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UpdateDetectorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UpdateDetectorError { fn description(&self) -> &str { match *self { UpdateDetectorError::BadRequest(ref cause) => cause, UpdateDetectorError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UpdateFilter #[derive(Debug, PartialEq)] pub enum UpdateFilterError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UpdateFilterError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateFilterError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UpdateFilterError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UpdateFilterError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UpdateFilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UpdateFilterError { fn description(&self) -> &str { match *self { UpdateFilterError::BadRequest(ref cause) => cause, UpdateFilterError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UpdateFindingsFeedback #[derive(Debug, PartialEq)] pub enum UpdateFindingsFeedbackError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UpdateFindingsFeedbackError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateFindingsFeedbackError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UpdateFindingsFeedbackError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UpdateFindingsFeedbackError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UpdateFindingsFeedbackError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UpdateFindingsFeedbackError { fn description(&self) -> &str { match *self { UpdateFindingsFeedbackError::BadRequest(ref cause) => cause, UpdateFindingsFeedbackError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UpdateIPSet #[derive(Debug, PartialEq)] pub enum UpdateIPSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UpdateIPSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateIPSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UpdateIPSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UpdateIPSetError::InternalServerError(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UpdateIPSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UpdateIPSetError { fn description(&self) -> &str { match *self { UpdateIPSetError::BadRequest(ref cause) => cause, UpdateIPSetError::InternalServerError(ref cause) => cause, } } } /// Errors returned by UpdateThreatIntelSet #[derive(Debug, PartialEq)] pub enum UpdateThreatIntelSetError { /// <p>Bad request exception object.</p> BadRequest(String), /// <p>Internal server error exception object.</p> InternalServerError(String), } impl UpdateThreatIntelSetError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateThreatIntelSetError> { if let Some(err) = proto::json::Error::parse_rest(&res) { match err.typ.as_str() { "BadRequestException" => { return RusotoError::Service(UpdateThreatIntelSetError::BadRequest(err.msg)) } "InternalServerErrorException" => { return RusotoError::Service(UpdateThreatIntelSetError::InternalServerError( err.msg, )) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for UpdateThreatIntelSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for UpdateThreatIntelSetError { fn description(&self) -> &str { match *self { UpdateThreatIntelSetError::BadRequest(ref cause) => cause, UpdateThreatIntelSetError::InternalServerError(ref cause) => cause, } } } /// Trait representing the capabilities of the Amazon GuardDuty API. Amazon GuardDuty clients implement this trait. pub trait GuardDuty { /// <p>Accepts the invitation to be monitored by a master GuardDuty account.</p> fn accept_invitation( &self, input: AcceptInvitationRequest, ) -> RusotoFuture<AcceptInvitationResponse, AcceptInvitationError>; /// <p><p>Archives GuardDuty findings specified by the list of finding IDs.</p> <note> <p>Only the master account can archive findings. Member accounts do not have permission to archive findings from their accounts.</p> </note></p> fn archive_findings( &self, input: ArchiveFindingsRequest, ) -> RusotoFuture<ArchiveFindingsResponse, ArchiveFindingsError>; /// <p>Creates a single Amazon GuardDuty detector. A detector is a resource that represents the GuardDuty service. To start using GuardDuty, you must create a detector in each region that you enable the service. You can have only one detector per account per region.</p> fn create_detector( &self, input: CreateDetectorRequest, ) -> RusotoFuture<CreateDetectorResponse, CreateDetectorError>; /// <p>Creates a filter using the specified finding criteria.</p> fn create_filter( &self, input: CreateFilterRequest, ) -> RusotoFuture<CreateFilterResponse, CreateFilterError>; /// <p>Creates a new IPSet - a list of trusted IP addresses that have been whitelisted for secure communication with AWS infrastructure and applications.</p> fn create_ip_set( &self, input: CreateIPSetRequest, ) -> RusotoFuture<CreateIPSetResponse, CreateIPSetError>; /// <p>Creates member accounts of the current AWS account by specifying a list of AWS account IDs. The current AWS account can then invite these members to manage GuardDuty in their accounts.</p> fn create_members( &self, input: CreateMembersRequest, ) -> RusotoFuture<CreateMembersResponse, CreateMembersError>; /// <p>Generates example findings of types specified by the list of finding types. If 'NULL' is specified for findingTypes, the API generates example findings of all supported finding types.</p> fn create_sample_findings( &self, input: CreateSampleFindingsRequest, ) -> RusotoFuture<CreateSampleFindingsResponse, CreateSampleFindingsError>; /// <p>Create a new ThreatIntelSet. ThreatIntelSets consist of known malicious IP addresses. GuardDuty generates findings based on ThreatIntelSets.</p> fn create_threat_intel_set( &self, input: CreateThreatIntelSetRequest, ) -> RusotoFuture<CreateThreatIntelSetResponse, CreateThreatIntelSetError>; /// <p>Declines invitations sent to the current member account by AWS account specified by their account IDs.</p> fn decline_invitations( &self, input: DeclineInvitationsRequest, ) -> RusotoFuture<DeclineInvitationsResponse, DeclineInvitationsError>; /// <p>Deletes a Amazon GuardDuty detector specified by the detector ID.</p> fn delete_detector( &self, input: DeleteDetectorRequest, ) -> RusotoFuture<DeleteDetectorResponse, DeleteDetectorError>; /// <p>Deletes the filter specified by the filter name.</p> fn delete_filter( &self, input: DeleteFilterRequest, ) -> RusotoFuture<DeleteFilterResponse, DeleteFilterError>; /// <p>Deletes the IPSet specified by the IPSet ID.</p> fn delete_ip_set( &self, input: DeleteIPSetRequest, ) -> RusotoFuture<DeleteIPSetResponse, DeleteIPSetError>; /// <p>Deletes invitations sent to the current member account by AWS accounts specified by their account IDs.</p> fn delete_invitations( &self, input: DeleteInvitationsRequest, ) -> RusotoFuture<DeleteInvitationsResponse, DeleteInvitationsError>; /// <p>Deletes GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn delete_members( &self, input: DeleteMembersRequest, ) -> RusotoFuture<DeleteMembersResponse, DeleteMembersError>; /// <p>Deletes ThreatIntelSet specified by the ThreatIntelSet ID.</p> fn delete_threat_intel_set( &self, input: DeleteThreatIntelSetRequest, ) -> RusotoFuture<DeleteThreatIntelSetResponse, DeleteThreatIntelSetError>; /// <p>Disassociates the current GuardDuty member account from its master account.</p> fn disassociate_from_master_account( &self, input: DisassociateFromMasterAccountRequest, ) -> RusotoFuture<DisassociateFromMasterAccountResponse, DisassociateFromMasterAccountError>; /// <p>Disassociates GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn disassociate_members( &self, input: DisassociateMembersRequest, ) -> RusotoFuture<DisassociateMembersResponse, DisassociateMembersError>; /// <p>Retrieves an Amazon GuardDuty detector specified by the detectorId.</p> fn get_detector( &self, input: GetDetectorRequest, ) -> RusotoFuture<GetDetectorResponse, GetDetectorError>; /// <p>Returns the details of the filter specified by the filter name.</p> fn get_filter( &self, input: GetFilterRequest, ) -> RusotoFuture<GetFilterResponse, GetFilterError>; /// <p>Describes Amazon GuardDuty findings specified by finding IDs.</p> fn get_findings( &self, input: GetFindingsRequest, ) -> RusotoFuture<GetFindingsResponse, GetFindingsError>; /// <p>Lists Amazon GuardDuty findings' statistics for the specified detector ID.</p> fn get_findings_statistics( &self, input: GetFindingsStatisticsRequest, ) -> RusotoFuture<GetFindingsStatisticsResponse, GetFindingsStatisticsError>; /// <p>Retrieves the IPSet specified by the IPSet ID.</p> fn get_ip_set(&self, input: GetIPSetRequest) -> RusotoFuture<GetIPSetResponse, GetIPSetError>; /// <p>Returns the count of all GuardDuty membership invitations that were sent to the current member account except the currently accepted invitation.</p> fn get_invitations_count( &self, ) -> RusotoFuture<GetInvitationsCountResponse, GetInvitationsCountError>; /// <p>Provides the details for the GuardDuty master account associated with the current GuardDuty member account.</p> fn get_master_account( &self, input: GetMasterAccountRequest, ) -> RusotoFuture<GetMasterAccountResponse, GetMasterAccountError>; /// <p>Retrieves GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn get_members( &self, input: GetMembersRequest, ) -> RusotoFuture<GetMembersResponse, GetMembersError>; /// <p>Retrieves the ThreatIntelSet that is specified by the ThreatIntelSet ID.</p> fn get_threat_intel_set( &self, input: GetThreatIntelSetRequest, ) -> RusotoFuture<GetThreatIntelSetResponse, GetThreatIntelSetError>; /// <p>Invites other AWS accounts (created as members of the current AWS account by CreateMembers) to enable GuardDuty and allow the current AWS account to view and manage these accounts' GuardDuty findings on their behalf as the master account.</p> fn invite_members( &self, input: InviteMembersRequest, ) -> RusotoFuture<InviteMembersResponse, InviteMembersError>; /// <p>Lists detectorIds of all the existing Amazon GuardDuty detector resources.</p> fn list_detectors( &self, input: ListDetectorsRequest, ) -> RusotoFuture<ListDetectorsResponse, ListDetectorsError>; /// <p>Returns a paginated list of the current filters.</p> fn list_filters( &self, input: ListFiltersRequest, ) -> RusotoFuture<ListFiltersResponse, ListFiltersError>; /// <p>Lists Amazon GuardDuty findings for the specified detector ID.</p> fn list_findings( &self, input: ListFindingsRequest, ) -> RusotoFuture<ListFindingsResponse, ListFindingsError>; /// <p>Lists the IPSets of the GuardDuty service specified by the detector ID.</p> fn list_ip_sets( &self, input: ListIPSetsRequest, ) -> RusotoFuture<ListIPSetsResponse, ListIPSetsError>; /// <p>Lists all GuardDuty membership invitations that were sent to the current AWS account.</p> fn list_invitations( &self, input: ListInvitationsRequest, ) -> RusotoFuture<ListInvitationsResponse, ListInvitationsError>; /// <p>Lists details about all member accounts for the current GuardDuty master account.</p> fn list_members( &self, input: ListMembersRequest, ) -> RusotoFuture<ListMembersResponse, ListMembersError>; /// <p>Lists tags for a resource. Tagging is currently supported for detectors, finding filters, IP sets, and Threat Intel sets, with a limit of 50 tags per resource. When invoked, this operation returns all assigned tags for a given resource..</p> fn list_tags_for_resource( &self, input: ListTagsForResourceRequest, ) -> RusotoFuture<ListTagsForResourceResponse, ListTagsForResourceError>; /// <p>Lists the ThreatIntelSets of the GuardDuty service specified by the detector ID.</p> fn list_threat_intel_sets( &self, input: ListThreatIntelSetsRequest, ) -> RusotoFuture<ListThreatIntelSetsResponse, ListThreatIntelSetsError>; /// <p>Re-enables GuardDuty to monitor findings of the member accounts specified by the account IDs. A master GuardDuty account can run this command after disabling GuardDuty from monitoring these members' findings by running StopMonitoringMembers.</p> fn start_monitoring_members( &self, input: StartMonitoringMembersRequest, ) -> RusotoFuture<StartMonitoringMembersResponse, StartMonitoringMembersError>; /// <p>Disables GuardDuty from monitoring findings of the member accounts specified by the account IDs. After running this command, a master GuardDuty account can run StartMonitoringMembers to re-enable GuardDuty to monitor these members’ findings.</p> fn stop_monitoring_members( &self, input: StopMonitoringMembersRequest, ) -> RusotoFuture<StopMonitoringMembersResponse, StopMonitoringMembersError>; /// <p>Adds tags to a resource.</p> fn tag_resource( &self, input: TagResourceRequest, ) -> RusotoFuture<TagResourceResponse, TagResourceError>; /// <p>Unarchives Amazon GuardDuty findings specified by the list of finding IDs.</p> fn unarchive_findings( &self, input: UnarchiveFindingsRequest, ) -> RusotoFuture<UnarchiveFindingsResponse, UnarchiveFindingsError>; /// <p>Removes tags from a resource.</p> fn untag_resource( &self, input: UntagResourceRequest, ) -> RusotoFuture<UntagResourceResponse, UntagResourceError>; /// <p>Updates an Amazon GuardDuty detector specified by the detectorId.</p> fn update_detector( &self, input: UpdateDetectorRequest, ) -> RusotoFuture<UpdateDetectorResponse, UpdateDetectorError>; /// <p>Updates the filter specified by the filter name.</p> fn update_filter( &self, input: UpdateFilterRequest, ) -> RusotoFuture<UpdateFilterResponse, UpdateFilterError>; /// <p>Marks specified Amazon GuardDuty findings as useful or not useful.</p> fn update_findings_feedback( &self, input: UpdateFindingsFeedbackRequest, ) -> RusotoFuture<UpdateFindingsFeedbackResponse, UpdateFindingsFeedbackError>; /// <p>Updates the IPSet specified by the IPSet ID.</p> fn update_ip_set( &self, input: UpdateIPSetRequest, ) -> RusotoFuture<UpdateIPSetResponse, UpdateIPSetError>; /// <p>Updates the ThreatIntelSet specified by ThreatIntelSet ID.</p> fn update_threat_intel_set( &self, input: UpdateThreatIntelSetRequest, ) -> RusotoFuture<UpdateThreatIntelSetResponse, UpdateThreatIntelSetError>; } /// A client for the Amazon GuardDuty API. #[derive(Clone)] pub struct GuardDutyClient { client: Client, region: region::Region, } impl GuardDutyClient { /// Creates a client backed by the default tokio event loop. /// /// The client will use the default credentials provider and tls client. pub fn new(region: region::Region) -> GuardDutyClient { Self::new_with_client(Client::shared(), region) } pub fn new_with<P, D>( request_dispatcher: D, credentials_provider: P, region: region::Region, ) -> GuardDutyClient where P: ProvideAwsCredentials + Send + Sync + 'static, P::Future: Send, D: DispatchSignedRequest + Send + Sync + 'static, D::Future: Send, { Self::new_with_client( Client::new_with(credentials_provider, request_dispatcher), region, ) } pub fn new_with_client(client: Client, region: region::Region) -> GuardDutyClient { GuardDutyClient { client, region } } } impl fmt::Debug for GuardDutyClient { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GuardDutyClient") .field("region", &self.region) .finish() } } impl GuardDuty for GuardDutyClient { /// <p>Accepts the invitation to be monitored by a master GuardDuty account.</p> fn accept_invitation( &self, input: AcceptInvitationRequest, ) -> RusotoFuture<AcceptInvitationResponse, AcceptInvitationError> { let request_uri = format!( "/detector/{detector_id}/master", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<AcceptInvitationResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(AcceptInvitationError::from_response(response))), ) } }) } /// <p><p>Archives GuardDuty findings specified by the list of finding IDs.</p> <note> <p>Only the master account can archive findings. Member accounts do not have permission to archive findings from their accounts.</p> </note></p> fn archive_findings( &self, input: ArchiveFindingsRequest, ) -> RusotoFuture<ArchiveFindingsResponse, ArchiveFindingsError> { let request_uri = format!( "/detector/{detector_id}/findings/archive", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ArchiveFindingsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ArchiveFindingsError::from_response(response))), ) } }) } /// <p>Creates a single Amazon GuardDuty detector. A detector is a resource that represents the GuardDuty service. To start using GuardDuty, you must create a detector in each region that you enable the service. You can have only one detector per account per region.</p> fn create_detector( &self, input: CreateDetectorRequest, ) -> RusotoFuture<CreateDetectorResponse, CreateDetectorError> { let request_uri = "/detector"; let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateDetectorResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(CreateDetectorError::from_response(response))), ) } }) } /// <p>Creates a filter using the specified finding criteria.</p> fn create_filter( &self, input: CreateFilterRequest, ) -> RusotoFuture<CreateFilterResponse, CreateFilterError> { let request_uri = format!( "/detector/{detector_id}/filter", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateFilterResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(CreateFilterError::from_response(response))), ) } }) } /// <p>Creates a new IPSet - a list of trusted IP addresses that have been whitelisted for secure communication with AWS infrastructure and applications.</p> fn create_ip_set( &self, input: CreateIPSetRequest, ) -> RusotoFuture<CreateIPSetResponse, CreateIPSetError> { let request_uri = format!( "/detector/{detector_id}/ipset", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateIPSetResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(CreateIPSetError::from_response(response))), ) } }) } /// <p>Creates member accounts of the current AWS account by specifying a list of AWS account IDs. The current AWS account can then invite these members to manage GuardDuty in their accounts.</p> fn create_members( &self, input: CreateMembersRequest, ) -> RusotoFuture<CreateMembersResponse, CreateMembersError> { let request_uri = format!( "/detector/{detector_id}/member", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateMembersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(CreateMembersError::from_response(response))), ) } }) } /// <p>Generates example findings of types specified by the list of finding types. If 'NULL' is specified for findingTypes, the API generates example findings of all supported finding types.</p> fn create_sample_findings( &self, input: CreateSampleFindingsRequest, ) -> RusotoFuture<CreateSampleFindingsResponse, CreateSampleFindingsError> { let request_uri = format!( "/detector/{detector_id}/findings/create", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateSampleFindingsResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(CreateSampleFindingsError::from_response(response)) }), ) } }) } /// <p>Create a new ThreatIntelSet. ThreatIntelSets consist of known malicious IP addresses. GuardDuty generates findings based on ThreatIntelSets.</p> fn create_threat_intel_set( &self, input: CreateThreatIntelSetRequest, ) -> RusotoFuture<CreateThreatIntelSetResponse, CreateThreatIntelSetError> { let request_uri = format!( "/detector/{detector_id}/threatintelset", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<CreateThreatIntelSetResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(CreateThreatIntelSetError::from_response(response)) }), ) } }) } /// <p>Declines invitations sent to the current member account by AWS account specified by their account IDs.</p> fn decline_invitations( &self, input: DeclineInvitationsRequest, ) -> RusotoFuture<DeclineInvitationsResponse, DeclineInvitationsError> { let request_uri = "/invitation/decline"; let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeclineInvitationsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeclineInvitationsError::from_response(response))), ) } }) } /// <p>Deletes a Amazon GuardDuty detector specified by the detector ID.</p> fn delete_detector( &self, input: DeleteDetectorRequest, ) -> RusotoFuture<DeleteDetectorResponse, DeleteDetectorError> { let request_uri = format!("/detector/{detector_id}", detector_id = input.detector_id); let mut request = SignedRequest::new("DELETE", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteDetectorResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeleteDetectorError::from_response(response))), ) } }) } /// <p>Deletes the filter specified by the filter name.</p> fn delete_filter( &self, input: DeleteFilterRequest, ) -> RusotoFuture<DeleteFilterResponse, DeleteFilterError> { let request_uri = format!( "/detector/{detector_id}/filter/{filter_name}", detector_id = input.detector_id, filter_name = input.filter_name ); let mut request = SignedRequest::new("DELETE", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteFilterResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeleteFilterError::from_response(response))), ) } }) } /// <p>Deletes the IPSet specified by the IPSet ID.</p> fn delete_ip_set( &self, input: DeleteIPSetRequest, ) -> RusotoFuture<DeleteIPSetResponse, DeleteIPSetError> { let request_uri = format!( "/detector/{detector_id}/ipset/{ip_set_id}", detector_id = input.detector_id, ip_set_id = input.ip_set_id ); let mut request = SignedRequest::new("DELETE", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteIPSetResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeleteIPSetError::from_response(response))), ) } }) } /// <p>Deletes invitations sent to the current member account by AWS accounts specified by their account IDs.</p> fn delete_invitations( &self, input: DeleteInvitationsRequest, ) -> RusotoFuture<DeleteInvitationsResponse, DeleteInvitationsError> { let request_uri = "/invitation/delete"; let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteInvitationsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeleteInvitationsError::from_response(response))), ) } }) } /// <p>Deletes GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn delete_members( &self, input: DeleteMembersRequest, ) -> RusotoFuture<DeleteMembersResponse, DeleteMembersError> { let request_uri = format!( "/detector/{detector_id}/member/delete", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteMembersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DeleteMembersError::from_response(response))), ) } }) } /// <p>Deletes ThreatIntelSet specified by the ThreatIntelSet ID.</p> fn delete_threat_intel_set( &self, input: DeleteThreatIntelSetRequest, ) -> RusotoFuture<DeleteThreatIntelSetResponse, DeleteThreatIntelSetError> { let request_uri = format!( "/detector/{detector_id}/threatintelset/{threat_intel_set_id}", detector_id = input.detector_id, threat_intel_set_id = input.threat_intel_set_id ); let mut request = SignedRequest::new("DELETE", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DeleteThreatIntelSetResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(DeleteThreatIntelSetError::from_response(response)) }), ) } }) } /// <p>Disassociates the current GuardDuty member account from its master account.</p> fn disassociate_from_master_account( &self, input: DisassociateFromMasterAccountRequest, ) -> RusotoFuture<DisassociateFromMasterAccountResponse, DisassociateFromMasterAccountError> { let request_uri = format!( "/detector/{detector_id}/master/disassociate", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DisassociateFromMasterAccountResponse, _>()?; Ok(result) })) } else { Box::new(response.buffer().from_err().and_then(|response| { Err(DisassociateFromMasterAccountError::from_response(response)) })) } }) } /// <p>Disassociates GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn disassociate_members( &self, input: DisassociateMembersRequest, ) -> RusotoFuture<DisassociateMembersResponse, DisassociateMembersError> { let request_uri = format!( "/detector/{detector_id}/member/disassociate", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<DisassociateMembersResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(DisassociateMembersError::from_response(response)) }), ) } }) } /// <p>Retrieves an Amazon GuardDuty detector specified by the detectorId.</p> fn get_detector( &self, input: GetDetectorRequest, ) -> RusotoFuture<GetDetectorResponse, GetDetectorError> { let request_uri = format!("/detector/{detector_id}", detector_id = input.detector_id); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetDetectorResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetDetectorError::from_response(response))), ) } }) } /// <p>Returns the details of the filter specified by the filter name.</p> fn get_filter( &self, input: GetFilterRequest, ) -> RusotoFuture<GetFilterResponse, GetFilterError> { let request_uri = format!( "/detector/{detector_id}/filter/{filter_name}", detector_id = input.detector_id, filter_name = input.filter_name ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetFilterResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetFilterError::from_response(response))), ) } }) } /// <p>Describes Amazon GuardDuty findings specified by finding IDs.</p> fn get_findings( &self, input: GetFindingsRequest, ) -> RusotoFuture<GetFindingsResponse, GetFindingsError> { let request_uri = format!( "/detector/{detector_id}/findings/get", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetFindingsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetFindingsError::from_response(response))), ) } }) } /// <p>Lists Amazon GuardDuty findings' statistics for the specified detector ID.</p> fn get_findings_statistics( &self, input: GetFindingsStatisticsRequest, ) -> RusotoFuture<GetFindingsStatisticsResponse, GetFindingsStatisticsError> { let request_uri = format!( "/detector/{detector_id}/findings/statistics", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetFindingsStatisticsResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(GetFindingsStatisticsError::from_response(response)) }), ) } }) } /// <p>Retrieves the IPSet specified by the IPSet ID.</p> fn get_ip_set(&self, input: GetIPSetRequest) -> RusotoFuture<GetIPSetResponse, GetIPSetError> { let request_uri = format!( "/detector/{detector_id}/ipset/{ip_set_id}", detector_id = input.detector_id, ip_set_id = input.ip_set_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetIPSetResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetIPSetError::from_response(response))), ) } }) } /// <p>Returns the count of all GuardDuty membership invitations that were sent to the current member account except the currently accepted invitation.</p> fn get_invitations_count( &self, ) -> RusotoFuture<GetInvitationsCountResponse, GetInvitationsCountError> { let request_uri = "/invitation/count"; let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetInvitationsCountResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(GetInvitationsCountError::from_response(response)) }), ) } }) } /// <p>Provides the details for the GuardDuty master account associated with the current GuardDuty member account.</p> fn get_master_account( &self, input: GetMasterAccountRequest, ) -> RusotoFuture<GetMasterAccountResponse, GetMasterAccountError> { let request_uri = format!( "/detector/{detector_id}/master", detector_id = input.detector_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetMasterAccountResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetMasterAccountError::from_response(response))), ) } }) } /// <p>Retrieves GuardDuty member accounts (to the current GuardDuty master account) specified by the account IDs.</p> fn get_members( &self, input: GetMembersRequest, ) -> RusotoFuture<GetMembersResponse, GetMembersError> { let request_uri = format!( "/detector/{detector_id}/member/get", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetMembersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetMembersError::from_response(response))), ) } }) } /// <p>Retrieves the ThreatIntelSet that is specified by the ThreatIntelSet ID.</p> fn get_threat_intel_set( &self, input: GetThreatIntelSetRequest, ) -> RusotoFuture<GetThreatIntelSetResponse, GetThreatIntelSetError> { let request_uri = format!( "/detector/{detector_id}/threatintelset/{threat_intel_set_id}", detector_id = input.detector_id, threat_intel_set_id = input.threat_intel_set_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<GetThreatIntelSetResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetThreatIntelSetError::from_response(response))), ) } }) } /// <p>Invites other AWS accounts (created as members of the current AWS account by CreateMembers) to enable GuardDuty and allow the current AWS account to view and manage these accounts' GuardDuty findings on their behalf as the master account.</p> fn invite_members( &self, input: InviteMembersRequest, ) -> RusotoFuture<InviteMembersResponse, InviteMembersError> { let request_uri = format!( "/detector/{detector_id}/member/invite", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<InviteMembersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(InviteMembersError::from_response(response))), ) } }) } /// <p>Lists detectorIds of all the existing Amazon GuardDuty detector resources.</p> fn list_detectors( &self, input: ListDetectorsRequest, ) -> RusotoFuture<ListDetectorsResponse, ListDetectorsError> { let request_uri = "/detector"; let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListDetectorsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListDetectorsError::from_response(response))), ) } }) } /// <p>Returns a paginated list of the current filters.</p> fn list_filters( &self, input: ListFiltersRequest, ) -> RusotoFuture<ListFiltersResponse, ListFiltersError> { let request_uri = format!( "/detector/{detector_id}/filter", detector_id = input.detector_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListFiltersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListFiltersError::from_response(response))), ) } }) } /// <p>Lists Amazon GuardDuty findings for the specified detector ID.</p> fn list_findings( &self, input: ListFindingsRequest, ) -> RusotoFuture<ListFindingsResponse, ListFindingsError> { let request_uri = format!( "/detector/{detector_id}/findings", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListFindingsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListFindingsError::from_response(response))), ) } }) } /// <p>Lists the IPSets of the GuardDuty service specified by the detector ID.</p> fn list_ip_sets( &self, input: ListIPSetsRequest, ) -> RusotoFuture<ListIPSetsResponse, ListIPSetsError> { let request_uri = format!( "/detector/{detector_id}/ipset", detector_id = input.detector_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListIPSetsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListIPSetsError::from_response(response))), ) } }) } /// <p>Lists all GuardDuty membership invitations that were sent to the current AWS account.</p> fn list_invitations( &self, input: ListInvitationsRequest, ) -> RusotoFuture<ListInvitationsResponse, ListInvitationsError> { let request_uri = "/invitation"; let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListInvitationsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListInvitationsError::from_response(response))), ) } }) } /// <p>Lists details about all member accounts for the current GuardDuty master account.</p> fn list_members( &self, input: ListMembersRequest, ) -> RusotoFuture<ListMembersResponse, ListMembersError> { let request_uri = format!( "/detector/{detector_id}/member", detector_id = input.detector_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } if let Some(ref x) = input.only_associated { params.put("onlyAssociated", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListMembersResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListMembersError::from_response(response))), ) } }) } /// <p>Lists tags for a resource. Tagging is currently supported for detectors, finding filters, IP sets, and Threat Intel sets, with a limit of 50 tags per resource. When invoked, this operation returns all assigned tags for a given resource..</p> fn list_tags_for_resource( &self, input: ListTagsForResourceRequest, ) -> RusotoFuture<ListTagsForResourceResponse, ListTagsForResourceError> { let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListTagsForResourceResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(ListTagsForResourceError::from_response(response)) }), ) } }) } /// <p>Lists the ThreatIntelSets of the GuardDuty service specified by the detector ID.</p> fn list_threat_intel_sets( &self, input: ListThreatIntelSetsRequest, ) -> RusotoFuture<ListThreatIntelSetsResponse, ListThreatIntelSetsError> { let request_uri = format!( "/detector/{detector_id}/threatintelset", detector_id = input.detector_id ); let mut request = SignedRequest::new("GET", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); if let Some(ref x) = input.max_results { params.put("maxResults", x); } if let Some(ref x) = input.next_token { params.put("nextToken", x); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<ListThreatIntelSetsResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(ListThreatIntelSetsError::from_response(response)) }), ) } }) } /// <p>Re-enables GuardDuty to monitor findings of the member accounts specified by the account IDs. A master GuardDuty account can run this command after disabling GuardDuty from monitoring these members' findings by running StopMonitoringMembers.</p> fn start_monitoring_members( &self, input: StartMonitoringMembersRequest, ) -> RusotoFuture<StartMonitoringMembersResponse, StartMonitoringMembersError> { let request_uri = format!( "/detector/{detector_id}/member/start", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<StartMonitoringMembersResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(StartMonitoringMembersError::from_response(response)) }), ) } }) } /// <p>Disables GuardDuty from monitoring findings of the member accounts specified by the account IDs. After running this command, a master GuardDuty account can run StartMonitoringMembers to re-enable GuardDuty to monitor these members’ findings.</p> fn stop_monitoring_members( &self, input: StopMonitoringMembersRequest, ) -> RusotoFuture<StopMonitoringMembersResponse, StopMonitoringMembersError> { let request_uri = format!( "/detector/{detector_id}/member/stop", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<StopMonitoringMembersResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(StopMonitoringMembersError::from_response(response)) }), ) } }) } /// <p>Adds tags to a resource.</p> fn tag_resource( &self, input: TagResourceRequest, ) -> RusotoFuture<TagResourceResponse, TagResourceError> { let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 204 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<TagResourceResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(TagResourceError::from_response(response))), ) } }) } /// <p>Unarchives Amazon GuardDuty findings specified by the list of finding IDs.</p> fn unarchive_findings( &self, input: UnarchiveFindingsRequest, ) -> RusotoFuture<UnarchiveFindingsResponse, UnarchiveFindingsError> { let request_uri = format!( "/detector/{detector_id}/findings/unarchive", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UnarchiveFindingsResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(UnarchiveFindingsError::from_response(response))), ) } }) } /// <p>Removes tags from a resource.</p> fn untag_resource( &self, input: UntagResourceRequest, ) -> RusotoFuture<UntagResourceResponse, UntagResourceError> { let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn); let mut request = SignedRequest::new("DELETE", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let mut params = Params::new(); for item in input.tag_keys.iter() { params.put("tagKeys", item); } request.set_params(params); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 204 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UntagResourceResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(UntagResourceError::from_response(response))), ) } }) } /// <p>Updates an Amazon GuardDuty detector specified by the detectorId.</p> fn update_detector( &self, input: UpdateDetectorRequest, ) -> RusotoFuture<UpdateDetectorResponse, UpdateDetectorError> { let request_uri = format!("/detector/{detector_id}", detector_id = input.detector_id); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UpdateDetectorResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(UpdateDetectorError::from_response(response))), ) } }) } /// <p>Updates the filter specified by the filter name.</p> fn update_filter( &self, input: UpdateFilterRequest, ) -> RusotoFuture<UpdateFilterResponse, UpdateFilterError> { let request_uri = format!( "/detector/{detector_id}/filter/{filter_name}", detector_id = input.detector_id, filter_name = input.filter_name ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UpdateFilterResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(UpdateFilterError::from_response(response))), ) } }) } /// <p>Marks specified Amazon GuardDuty findings as useful or not useful.</p> fn update_findings_feedback( &self, input: UpdateFindingsFeedbackRequest, ) -> RusotoFuture<UpdateFindingsFeedbackResponse, UpdateFindingsFeedbackError> { let request_uri = format!( "/detector/{detector_id}/findings/feedback", detector_id = input.detector_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UpdateFindingsFeedbackResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(UpdateFindingsFeedbackError::from_response(response)) }), ) } }) } /// <p>Updates the IPSet specified by the IPSet ID.</p> fn update_ip_set( &self, input: UpdateIPSetRequest, ) -> RusotoFuture<UpdateIPSetResponse, UpdateIPSetError> { let request_uri = format!( "/detector/{detector_id}/ipset/{ip_set_id}", detector_id = input.detector_id, ip_set_id = input.ip_set_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UpdateIPSetResponse, _>()?; Ok(result) })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(UpdateIPSetError::from_response(response))), ) } }) } /// <p>Updates the ThreatIntelSet specified by ThreatIntelSet ID.</p> fn update_threat_intel_set( &self, input: UpdateThreatIntelSetRequest, ) -> RusotoFuture<UpdateThreatIntelSetResponse, UpdateThreatIntelSetError> { let request_uri = format!( "/detector/{detector_id}/threatintelset/{threat_intel_set_id}", detector_id = input.detector_id, threat_intel_set_id = input.threat_intel_set_id ); let mut request = SignedRequest::new("POST", "guardduty", &self.region, &request_uri); request.set_content_type("application/x-amz-json-1.1".to_owned()); let encoded = Some(serde_json::to_vec(&input).unwrap()); request.set_payload(encoded); self.client.sign_and_dispatch(request, |response| { if response.status.as_u16() == 200 { Box::new(response.buffer().from_err().and_then(|response| { let result = proto::json::ResponsePayload::new(&response) .deserialize::<UpdateThreatIntelSetResponse, _>()?; Ok(result) })) } else { Box::new( response.buffer().from_err().and_then(|response| { Err(UpdateThreatIntelSetError::from_response(response)) }), ) } }) } }
40.151784
291
0.621878
11b0879bf55f1c62db4c6d0c1c0ad343e7d09468
2,511
// Copyright (c) 2017-2018 Stefan Lankes, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Architecture dependent interface to initialize a task use crate::arch::processor::halt; use crate::consts::*; use crate::logging::*; use crate::scheduler::task::*; use crate::scheduler::{do_exit, get_current_taskid}; use core::mem::size_of; use core::ptr::write_bytes; #[repr(C, packed)] struct State { /// GS register gs: u64, /// FS register fs: u64, /// R15 register r15: u64, /// R14 register r14: u64, /// R13 register r13: u64, /// R12 register r12: u64, /// R11 register r11: u64, /// R10 register r10: u64, /// R9 register r9: u64, /// R8 register r8: u64, /// RDI register rdi: u64, /// RSI register rsi: u64, /// RBP register rbp: u64, /// (pseudo) RSP register rsp: u64, /// RBX register rbx: u64, /// RDX register rdx: u64, /// RCX register rcx: u64, /// RAX register rax: u64, /// status flags rflags: u64, /// instruction pointer rip: u64, } extern "C" fn leave_task() -> ! { debug!("finish task {}", get_current_taskid()); do_exit(); loop { halt(); } } impl TaskFrame for Task { fn create_stack_frame(&mut self, func: extern "C" fn()) { unsafe { let mut stack: *mut u64 = ((*self.stack).top()) as *mut u64; write_bytes((*self.stack).bottom() as *mut u8, 0xCD, STACK_SIZE); /* Only marker for debugging purposes, ... */ *stack = 0xDEADBEEFu64; stack = (stack as usize - size_of::<u64>()) as *mut u64; /* the first-function-to-be-called's arguments, ... */ //TODO: add arguments /* and the "caller" we shall return to. * This procedure cleans the task after exit. */ *stack = (leave_task as *const ()) as u64; stack = (stack as usize - size_of::<State>()) as *mut u64; let state: *mut State = stack as *mut State; write_bytes(state, 0x00, 1); (*state).rsp = (stack as usize + size_of::<State>()) as u64; (*state).rbp = (*state).rsp + size_of::<u64>() as u64; (*state).gs = ((*self.stack).top()) as u64; (*state).rip = (func as *const ()) as u64; (*state).rflags = 0x1202u64; /* Set the task's stack pointer entry to the stack we have crafted right now. */ self.last_stack_pointer = stack as usize; } } }
23.688679
83
0.637595
f8fc1eda1080e6bf3ad3aed723ac553d6bf5daa3
6,357
// Pruned copy of crate rust log, without global logger // https://github.com/rust-lang-nursery/log #7a60286 // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may not use this file except in accordance with one or both of these // licenses. //! Log traits live here, which are called throughout the library to provide useful information for //! debugging purposes. //! //! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g "max_level_off". //! The second one, client-side by implementing check against Record Level field. //! Each module may have its own Logger or share one. use core::cmp; use core::fmt; static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"]; /// An enum representing the available verbosity levels of the logger. #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub enum Level { /// Designates extremely verbose information, including gossip-induced messages Gossip, /// Designates very low priority, often extremely verbose, information Trace, /// Designates lower priority information Debug, /// Designates useful information Info, /// Designates hazardous situations Warn, /// Designates very serious errors Error, } impl PartialOrd for Level { #[inline] fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> { Some(self.cmp(other)) } #[inline] fn lt(&self, other: &Level) -> bool { (*self as usize) < *other as usize } #[inline] fn le(&self, other: &Level) -> bool { *self as usize <= *other as usize } #[inline] fn gt(&self, other: &Level) -> bool { *self as usize > *other as usize } #[inline] fn ge(&self, other: &Level) -> bool { *self as usize >= *other as usize } } impl Ord for Level { #[inline] fn cmp(&self, other: &Level) -> cmp::Ordering { (*self as usize).cmp(&(*other as usize)) } } impl fmt::Display for Level { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.pad(LOG_LEVEL_NAMES[*self as usize]) } } impl Level { /// Returns the most verbose logging level. #[inline] pub fn max() -> Level { Level::Gossip } } /// A Record, unit of logging output with Metadata to enable filtering /// Module_path, file, line to inform on log's source #[derive(Clone, Debug)] pub struct Record<'a> { /// The verbosity level of the message. pub level: Level, #[cfg(not(c_bindings))] /// The message body. pub args: fmt::Arguments<'a>, #[cfg(c_bindings)] /// The message body. pub args: String, /// The module path of the message. pub module_path: &'static str, /// The source file containing the message. pub file: &'static str, /// The line containing the message. pub line: u32, #[cfg(c_bindings)] /// We don't actually use the lifetime parameter in C bindings (as there is no good way to /// communicate a lifetime to a C, or worse, Java user). _phantom: core::marker::PhantomData<&'a ()>, } impl<'a> Record<'a> { /// Returns a new Record. /// (C-not exported) as fmt can't be used in C #[inline] pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32) -> Record<'a> { Record { level, #[cfg(not(c_bindings))] args, #[cfg(c_bindings)] args: format!("{}", args), module_path, file, line, #[cfg(c_bindings)] _phantom: core::marker::PhantomData, } } } /// A trait encapsulating the operations required of a logger pub trait Logger { /// Logs the `Record` fn log(&self, record: &Record); } /// Wrapper for logging byte slices in hex format. /// (C-not exported) as fmt can't be used in C #[doc(hidden)] pub struct DebugBytes<'a>(pub &'a [u8]); impl<'a> core::fmt::Display for DebugBytes<'a> { fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for i in self.0 { write!(f, "{:02x}", i)?; } Ok(()) } } #[cfg(test)] mod tests { use util::logger::{Logger, Level}; use util::test_utils::TestLogger; use sync::Arc; #[test] fn test_level_show() { assert_eq!("INFO", Level::Info.to_string()); assert_eq!("ERROR", Level::Error.to_string()); assert_ne!("WARN", Level::Error.to_string()); } struct WrapperLog { logger: Arc<Logger> } impl WrapperLog { fn new(logger: Arc<Logger>) -> WrapperLog { WrapperLog { logger, } } fn call_macros(&self) { log_error!(self.logger, "This is an error"); log_warn!(self.logger, "This is a warning"); log_info!(self.logger, "This is an info"); log_debug!(self.logger, "This is a debug"); log_trace!(self.logger, "This is a trace"); log_gossip!(self.logger, "This is a gossip"); } } #[test] fn test_logging_macros() { let mut logger = TestLogger::new(); logger.enable(Level::Gossip); let logger : Arc<Logger> = Arc::new(logger); let wrapper = WrapperLog::new(Arc::clone(&logger)); wrapper.call_macros(); } #[test] fn test_log_ordering() { assert!(Level::Error > Level::Warn); assert!(Level::Error >= Level::Warn); assert!(Level::Error >= Level::Error); assert!(Level::Warn > Level::Info); assert!(Level::Warn >= Level::Info); assert!(Level::Warn >= Level::Warn); assert!(Level::Info > Level::Debug); assert!(Level::Info >= Level::Debug); assert!(Level::Info >= Level::Info); assert!(Level::Debug > Level::Trace); assert!(Level::Debug >= Level::Trace); assert!(Level::Debug >= Level::Debug); assert!(Level::Trace > Level::Gossip); assert!(Level::Trace >= Level::Gossip); assert!(Level::Trace >= Level::Trace); assert!(Level::Gossip >= Level::Gossip); assert!(Level::Error <= Level::Error); assert!(Level::Warn < Level::Error); assert!(Level::Warn <= Level::Error); assert!(Level::Warn <= Level::Warn); assert!(Level::Info < Level::Warn); assert!(Level::Info <= Level::Warn); assert!(Level::Info <= Level::Info); assert!(Level::Debug < Level::Info); assert!(Level::Debug <= Level::Info); assert!(Level::Debug <= Level::Debug); assert!(Level::Trace < Level::Debug); assert!(Level::Trace <= Level::Debug); assert!(Level::Trace <= Level::Trace); assert!(Level::Gossip < Level::Trace); assert!(Level::Gossip <= Level::Trace); assert!(Level::Gossip <= Level::Gossip); } }
27.519481
125
0.657857
e41548fa3f668c7d35f2775332e9411533b1c530
1,297
use assert2::check; use assert2::let_assert; use syn::Expr; use syn::Ident; mod keywords { syn::custom_keyword!(lebowski); } #[derive(crate::Parse)] enum EnumWithMixedVariants { TwoExpressionsSeparatedByKeyword { first: syn::Expr, _the_dude: keywords::lebowski, second: syn::Expr, }, IdentifierPlusPlus(Ident, syn::token::Add, syn::token::Add), } #[test] fn parsing_struct_like_variants_work() { let variant = syn::parse_str::<EnumWithMixedVariants>("jeffrey() lebowski el.duderino(&his_dudeness)") .unwrap(); let expected_first = syn::parse_str::<Expr>("jeffrey()").unwrap(); let expected_second = syn::parse_str::<Expr>("el.duderino(&his_dudeness)").unwrap(); let_assert!( EnumWithMixedVariants::TwoExpressionsSeparatedByKeyword { first, _the_dude, second } = variant ); check!(first == expected_first); check!(second == expected_second); } #[test] fn parsing_stuple_like_variants_work() { let variant = syn::parse_str::<EnumWithMixedVariants>("C++").unwrap(); let expected_ident = syn::parse_str::<Ident>("C").unwrap(); let_assert!(EnumWithMixedVariants::IdentifierPlusPlus(ident, _, _) = variant); check!(ident == expected_ident); }
28.822222
96
0.655359
c1274ec06d155b8094ff0c2f0eba17e236f5ea3c
64,775
//! Generic data structure serialization framework. //! //! The two most important traits in this module are [`Serialize`] and //! [`Serializer`]. //! //! - **A type that implements `Serialize` is a data structure** that can be //! serialized to any data format supported by Serde, and conversely //! - **A type that implements `Serializer` is a data format** that can //! serialize any data structure supported by Serde. //! //! # The Serialize trait //! //! Serde provides [`Serialize`] implementations for many Rust primitive and //! standard library types. The complete list is below. All of these can be //! serialized using Serde out of the box. //! //! Additionally, Serde provides a procedural macro called [`serde_derive`] to //! automatically generate [`Serialize`] implementations for structs and enums //! in your program. See the [derive section of the manual] for how to use this. //! //! In rare cases it may be necessary to implement [`Serialize`] manually for //! some type in your program. See the [Implementing `Serialize`] section of the //! manual for more about this. //! //! Third-party crates may provide [`Serialize`] implementations for types that //! they expose. For example the [`linked-hash-map`] crate provides a //! [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate //! provides an implementation of [`Serialize`] for it. //! //! # The Serializer trait //! //! [`Serializer`] implementations are provided by third-party crates, for //! example [`serde_json`], [`serde_yaml`] and [`bincode`]. //! //! A partial list of well-maintained formats is given on the [Serde //! website][data formats]. //! //! # Implementations of Serialize provided by Serde //! //! - **Primitive types**: //! - bool //! - i8, i16, i32, i64, i128, isize //! - u8, u16, u32, u64, u128, usize //! - f32, f64 //! - char //! - str //! - &T and &mut T //! - **Compound types**: //! - \[T\] //! - \[T; 0\] through \[T; 32\] //! - tuples up to size 16 //! - **Common standard library types**: //! - String //! - Option\<T\> //! - Result\<T, E\> //! - PhantomData\<T\> //! - **Wrapper types**: //! - Box\<T\> //! - Cow\<'a, T\> //! - Cell\<T\> //! - RefCell\<T\> //! - Mutex\<T\> //! - RwLock\<T\> //! - Rc\<T\>&emsp;*(if* features = ["rc"] *is enabled)* //! - Arc\<T\>&emsp;*(if* features = ["rc"] *is enabled)* //! - **Collection types**: //! - BTreeMap\<K, V\> //! - BTreeSet\<T\> //! - BinaryHeap\<T\> //! - HashMap\<K, V, H\> //! - HashSet\<T, H\> //! - LinkedList\<T\> //! - VecDeque\<T\> //! - Vec\<T\> //! - **FFI types**: //! - CStr //! - CString //! - OsStr //! - OsString //! - **Miscellaneous standard library types**: //! - Duration //! - SystemTime //! - Path //! - PathBuf //! - Range\<T\> //! - RangeInclusive\<T\> //! - Bound\<T\> //! - num::NonZero* //! - `!` *(unstable)* //! - **Net types**: //! - IpAddr //! - Ipv4Addr //! - Ipv6Addr //! - SocketAddr //! - SocketAddrV4 //! - SocketAddrV6 //! //! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html //! [`Serialize`]: ../trait.Serialize.html //! [`Serializer`]: ../trait.Serializer.html //! [`bincode`]: https://github.com/TyOverby/bincode //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map //! [`serde_derive`]: https://crates.io/crates/serde_derive //! [`serde_json`]: https://github.com/serde-rs/json //! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml //! [derive section of the manual]: https://serde.rs/derive.html //! [data formats]: https://serde.rs/#data-formats use lib::*; mod impls; mod impossible; pub use self::impossible::Impossible; //////////////////////////////////////////////////////////////////////////////// macro_rules! declare_error_trait { (Error: Sized $(+ $($supertrait:ident)::+)*) => { /// Trait used by `Serialize` implementations to generically construct /// errors belonging to the `Serializer` against which they are /// currently running. /// /// # Example implementation /// /// The [example data format] presented on the website shows an error /// type appropriate for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait Error: Sized $(+ $($supertrait)::+)* { /// Used when a [`Serialize`] implementation encounters any error /// while serializing a type. /// /// The message should not be capitalized and should not end with a /// period. /// /// For example, a filesystem [`Path`] may refuse to serialize /// itself if it contains invalid UTF-8 data. /// /// ```edition2018 /// # struct Path; /// # /// # impl Path { /// # fn to_str(&self) -> Option<&str> { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{self, Serialize, Serializer}; /// /// impl Serialize for Path { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match self.to_str() { /// Some(s) => serializer.serialize_str(s), /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")), /// } /// } /// } /// ``` /// /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html /// [`Serialize`]: ../trait.Serialize.html fn custom<T>(msg: T) -> Self where T: Display; } } } #[cfg(feature = "std")] declare_error_trait!(Error: Sized + error::Error); #[cfg(not(feature = "std"))] declare_error_trait!(Error: Sized + Debug + Display); //////////////////////////////////////////////////////////////////////////////// /// A **data structure** that can be serialized into any data format supported /// by Serde. /// /// Serde provides `Serialize` implementations for many Rust primitive and /// standard library types. The complete list is [here][ser]. All of these can /// be serialized using Serde out of the box. /// /// Additionally, Serde provides a procedural macro called [`serde_derive`] to /// automatically generate `Serialize` implementations for structs and enums in /// your program. See the [derive section of the manual] for how to use this. /// /// In rare cases it may be necessary to implement `Serialize` manually for some /// type in your program. See the [Implementing `Serialize`] section of the /// manual for more about this. /// /// Third-party crates may provide `Serialize` implementations for types that /// they expose. For example the [`linked-hash-map`] crate provides a /// [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate /// provides an implementation of `Serialize` for it. /// /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html /// [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html /// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map /// [`serde_derive`]: https://crates.io/crates/serde_derive /// [derive section of the manual]: https://serde.rs/derive.html /// [ser]: https://docs.serde.rs/serde/ser/index.html pub trait Serialize { /// Serialize this value into the given Serde serializer. /// /// See the [Implementing `Serialize`] section of the manual for more /// information about how to implement this method. /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeStruct, Serializer}; /// /// struct Person { /// name: String, /// age: u8, /// phones: Vec<String>, /// } /// /// // This is what #[derive(Serialize)] would generate. /// impl Serialize for Person { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut s = serializer.serialize_struct("Person", 3)?; /// s.serialize_field("name", &self.name)?; /// s.serialize_field("age", &self.age)?; /// s.serialize_field("phones", &self.phones)?; /// s.end() /// } /// } /// ``` /// /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer; } //////////////////////////////////////////////////////////////////////////////// /// A **data format** that can serialize any data structure supported by Serde. /// /// The role of this trait is to define the serialization half of the [Serde /// data model], which is a way to categorize every Rust data structure into one /// of 29 possible types. Each method of the `Serializer` trait corresponds to /// one of the types of the data model. /// /// Implementations of `Serialize` map themselves into this data model by /// invoking exactly one of the `Serializer` methods. /// /// The types that make up the Serde data model are: /// /// - **14 primitive types** /// - bool /// - i8, i16, i32, i64, i128 /// - u8, u16, u32, u64, u128 /// - f32, f64 /// - char /// - **string** /// - UTF-8 bytes with a length and no null terminator. /// - When serializing, all strings are handled equally. When deserializing, /// there are three flavors of strings: transient, owned, and borrowed. /// - **byte array** - \[u8\] /// - Similar to strings, during deserialization byte arrays can be /// transient, owned, or borrowed. /// - **option** /// - Either none or some value. /// - **unit** /// - The type of `()` in Rust. It represents an anonymous value containing /// no data. /// - **unit_struct** /// - For example `struct Unit` or `PhantomData<T>`. It represents a named /// value containing no data. /// - **unit_variant** /// - For example the `E::A` and `E::B` in `enum E { A, B }`. /// - **newtype_struct** /// - For example `struct Millimeters(u8)`. /// - **newtype_variant** /// - For example the `E::N` in `enum E { N(u8) }`. /// - **seq** /// - A variably sized heterogeneous sequence of values, for example /// `Vec<T>` or `HashSet<T>`. When serializing, the length may or may not /// be known before iterating through all the data. When deserializing, /// the length is determined by looking at the serialized data. /// - **tuple** /// - A statically sized heterogeneous sequence of values for which the /// length will be known at deserialization time without looking at the /// serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or /// `[u64; 10]`. /// - **tuple_struct** /// - A named tuple, for example `struct Rgb(u8, u8, u8)`. /// - **tuple_variant** /// - For example the `E::T` in `enum E { T(u8, u8) }`. /// - **map** /// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`. /// - **struct** /// - A heterogeneous key-value pairing in which the keys are strings and /// will be known at deserialization time without looking at the /// serialized data, for example `struct S { r: u8, g: u8, b: u8 }`. /// - **struct_variant** /// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. /// /// Many Serde serializers produce text or binary data as output, for example /// JSON or Bincode. This is not a requirement of the `Serializer` trait, and /// there are serializers that do not produce text or binary output. One example /// is the `serde_json::value::Serializer` (distinct from the main `serde_json` /// serializer) that produces a `serde_json::Value` data structure in memory as /// output. /// /// [Serde data model]: https://serde.rs/data-model.html /// /// # Example implementation /// /// The [example data format] presented on the website contains example code for /// a basic JSON `Serializer`. /// /// [example data format]: https://serde.rs/data-format.html pub trait Serializer: Sized { /// The output type produced by this `Serializer` during successful /// serialization. Most serializers that produce text or binary output /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer /// contained within the `Serializer` instance. Serializers that build /// in-memory data structures may be simplified by using `Ok` to propagate /// the data structure around. /// /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html type Ok; /// The error type when some error occurs during serialization. type Error: Error; /// Type returned from [`serialize_seq`] for serializing the content of the /// sequence. /// /// [`serialize_seq`]: #tymethod.serialize_seq type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_tuple`] for serializing the content of /// the tuple. /// /// [`serialize_tuple`]: #tymethod.serialize_tuple type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_tagged`] for serializing the content of /// the tagged. Added by us /// /// [`serialize_tagged`]: #tymethod.serialize_tagged type SerializeTagged: SerializeTagged<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_tuple_struct`] for serializing the /// content of the tuple struct. /// /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_tuple_variant`] for serializing the /// content of the tuple variant. /// /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_map`] for serializing the content of the /// map. /// /// [`serialize_map`]: #tymethod.serialize_map type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_struct`] for serializing the content of /// the struct. /// /// [`serialize_struct`]: #tymethod.serialize_struct type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>; /// Type returned from [`serialize_struct_variant`] for serializing the /// content of the struct variant. /// /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>; /// Serialize a `bool` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for bool { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_bool(*self) /// } /// } /// ``` fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>; /// Serialize an `i8` value. /// /// If the format does not differentiate between `i8` and `i64`, a /// reasonable implementation would be to cast the value to `i64` and /// forward to `serialize_i64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for i8 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_i8(*self) /// } /// } /// ``` fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>; /// Serialize an `i16` value. /// /// If the format does not differentiate between `i16` and `i64`, a /// reasonable implementation would be to cast the value to `i64` and /// forward to `serialize_i64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for i16 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_i16(*self) /// } /// } /// ``` fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>; /// Serialize an `i32` value. /// /// If the format does not differentiate between `i32` and `i64`, a /// reasonable implementation would be to cast the value to `i64` and /// forward to `serialize_i64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for i32 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_i32(*self) /// } /// } /// ``` fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>; /// Serialize an `i64` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for i64 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_i64(*self) /// } /// } /// ``` fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>; serde_if_integer128! { /// Serialize an `i128` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for i128 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_i128(*self) /// } /// } /// ``` /// /// This method is available only on Rust compiler versions >=1.26. The /// default behavior unconditionally returns an error. fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> { let _ = v; Err(Error::custom("i128 is not supported")) } } /// Serialize a `u8` value. /// /// If the format does not differentiate between `u8` and `u64`, a /// reasonable implementation would be to cast the value to `u64` and /// forward to `serialize_u64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for u8 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_u8(*self) /// } /// } /// ``` fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>; /// Serialize a `u16` value. /// /// If the format does not differentiate between `u16` and `u64`, a /// reasonable implementation would be to cast the value to `u64` and /// forward to `serialize_u64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for u16 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_u16(*self) /// } /// } /// ``` fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>; /// Serialize a `u32` value. /// /// If the format does not differentiate between `u32` and `u64`, a /// reasonable implementation would be to cast the value to `u64` and /// forward to `serialize_u64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for u32 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_u32(*self) /// } /// } /// ``` fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>; /// Serialize a `u64` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for u64 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_u64(*self) /// } /// } /// ``` fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>; serde_if_integer128! { /// Serialize a `u128` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for u128 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_u128(*self) /// } /// } /// ``` /// /// This method is available only on Rust compiler versions >=1.26. The /// default behavior unconditionally returns an error. fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> { let _ = v; Err(Error::custom("u128 is not supported")) } } /// Serialize an `f32` value. /// /// If the format does not differentiate between `f32` and `f64`, a /// reasonable implementation would be to cast the value to `f64` and /// forward to `serialize_f64`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for f32 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_f32(*self) /// } /// } /// ``` fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>; /// Serialize an `f64` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for f64 { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_f64(*self) /// } /// } /// ``` fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>; /// Serialize a character. /// /// If the format does not support characters, it is reasonable to serialize /// it as a single element `str` or a `u32`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for char { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_char(*self) /// } /// } /// ``` fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>; /// Serialize a `&str`. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for str { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_str(self) /// } /// } /// ``` fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>; /// Serialize a chunk of raw byte data. /// /// Enables serializers to serialize byte slices more compactly or more /// efficiently than other types of slices. If no efficient implementation /// is available, a reasonable implementation would be to forward to /// `serialize_seq`. If forwarded, the implementation looks usually just /// like this: /// /// ```edition2018 /// # use serde::ser::{Serializer, SerializeSeq}; /// # use serde::private::ser::Error; /// # /// # struct MySerializer; /// # /// # impl Serializer for MySerializer { /// # type Ok = (); /// # type Error = Error; /// # /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { /// let mut seq = self.serialize_seq(Some(v.len()))?; /// for b in v { /// seq.serialize_element(b)?; /// } /// seq.end() /// } /// # /// # serde::__serialize_unimplemented! { /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some /// # unit unit_struct unit_variant newtype_struct newtype_variant /// # seq tuple tuple_struct tuple_variant map struct struct_variant /// # } /// # } /// ``` fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>; /// Serialize a [`None`] value. /// /// ```edition2018 /// # use serde::{Serialize, Serializer}; /// # /// # enum Option<T> { /// # Some(T), /// # None, /// # } /// # /// # use self::Option::{Some, None}; /// # /// impl<T> Serialize for Option<T> /// where /// T: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// Some(ref value) => serializer.serialize_some(value), /// None => serializer.serialize_none(), /// } /// } /// } /// # /// # fn main() {} /// ``` /// /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None fn serialize_none(self) -> Result<Self::Ok, Self::Error>; /// Serialize a [`Some(T)`] value. /// /// ```edition2018 /// # use serde::{Serialize, Serializer}; /// # /// # enum Option<T> { /// # Some(T), /// # None, /// # } /// # /// # use self::Option::{Some, None}; /// # /// impl<T> Serialize for Option<T> /// where /// T: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// Some(ref value) => serializer.serialize_some(value), /// None => serializer.serialize_none(), /// } /// } /// } /// # /// # fn main() {} /// ``` /// /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Serialize; /// Serialize a `()` value. /// /// ```edition2018 /// # use serde::Serializer; /// # /// # serde::__private_serialize!(); /// # /// impl Serialize for () { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_unit() /// } /// } /// ``` fn serialize_unit(self) -> Result<Self::Ok, Self::Error>; /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`. /// /// A reasonable implementation would be to forward to `serialize_unit`. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// /// struct Nothing; /// /// impl Serialize for Nothing { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_unit_struct("Nothing") /// } /// } /// ``` fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>; /// Serialize a unit variant like `E::A` in `enum E { A, B }`. /// /// The `name` is the name of the enum, the `variant_index` is the index of /// this variant within the enum, and the `variant` is the name of the /// variant. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// /// enum E { /// A, /// B, /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::A => serializer.serialize_unit_variant("E", 0, "A"), /// E::B => serializer.serialize_unit_variant("E", 1, "B"), /// } /// } /// } /// ``` fn serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result<Self::Ok, Self::Error>; /// Serialize a newtype struct like `struct Millimeters(u8)`. /// /// Serializers are encouraged to treat newtype structs as insignificant /// wrappers around the data they contain. A reasonable implementation would /// be to forward to `value.serialize(self)`. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// /// struct Millimeters(u8); /// /// impl Serialize for Millimeters { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.serialize_newtype_struct("Millimeters", &self.0) /// } /// } /// ``` fn serialize_newtype_struct<T: ?Sized>( self, name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize; /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. /// /// The `name` is the name of the enum, the `variant_index` is the index of /// this variant within the enum, and the `variant` is the name of the /// variant. The `value` is the data contained within this newtype variant. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// /// enum E { /// M(String), /// N(u8), /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), /// } /// } /// } /// ``` fn serialize_newtype_variant<T: ?Sized>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize; /// Begin to serialize a variably sized sequence. This call must be /// followed by zero or more calls to `serialize_element`, then a call to /// `end`. /// /// The argument is the number of elements in the sequence, which may or may /// not be computable before the sequence is iterated. Some serializers only /// support sequences whose length is known up front. /// /// ```edition2018 /// # use std::marker::PhantomData; /// # /// # struct Vec<T>(PhantomData<T>); /// # /// # impl<T> Vec<T> { /// # fn len(&self) -> usize { /// # unimplemented!() /// # } /// # } /// # /// # impl<'a, T> IntoIterator for &'a Vec<T> { /// # type Item = &'a T; /// # type IntoIter = Box<Iterator<Item = &'a T>>; /// # /// # fn into_iter(self) -> Self::IntoIter { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{Serialize, Serializer, SerializeSeq}; /// /// impl<T> Serialize for Vec<T> /// where /// T: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut seq = serializer.serialize_seq(Some(self.len()))?; /// for element in self { /// seq.serialize_element(element)?; /// } /// seq.end() /// } /// } /// ``` fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>; /// Begin to serialize a statically sized sequence whose length will be /// known at deserialization time without looking at the serialized data. /// This call must be followed by zero or more calls to `serialize_element`, /// then a call to `end`. /// /// ```edition2018 /// use serde::ser::{Serialize, Serializer, SerializeTuple}; /// /// # mod fool { /// # trait Serialize {} /// impl<A, B, C> Serialize for (A, B, C) /// # {} /// # } /// # /// # struct Tuple3<A, B, C>(A, B, C); /// # /// # impl<A, B, C> Serialize for Tuple3<A, B, C> /// where /// A: Serialize, /// B: Serialize, /// C: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut tup = serializer.serialize_tuple(3)?; /// tup.serialize_element(&self.0)?; /// tup.serialize_element(&self.1)?; /// tup.serialize_element(&self.2)?; /// tup.end() /// } /// } /// ``` /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeTuple, Serializer}; /// /// const VRAM_SIZE: usize = 386; /// struct Vram([u16; VRAM_SIZE]); /// /// impl Serialize for Vram { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; /// for element in &self.0[..] { /// seq.serialize_element(element)?; /// } /// seq.end() /// } /// } /// ``` fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>; ///Serialize Tagged value (added by us) /// fn serialize_tagged(self) -> Result<Self::SerializeTagged, Self::Error>; /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This /// call must be followed by zero or more calls to `serialize_field`, then a /// call to `end`. /// /// The `name` is the name of the tuple struct and the `len` is the number /// of data fields that will be serialized. /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; /// /// struct Rgb(u8, u8, u8); /// /// impl Serialize for Rgb { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; /// ts.serialize_field(&self.0)?; /// ts.serialize_field(&self.1)?; /// ts.serialize_field(&self.2)?; /// ts.end() /// } /// } /// ``` fn serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>; /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) /// }`. This call must be followed by zero or more calls to /// `serialize_field`, then a call to `end`. /// /// The `name` is the name of the enum, the `variant_index` is the index of /// this variant within the enum, the `variant` is the name of the variant, /// and the `len` is the number of data fields that will be serialized. /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; /// /// enum E { /// T(u8, u8), /// U(String, u32, u32), /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::T(ref a, ref b) => { /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; /// tv.serialize_field(a)?; /// tv.serialize_field(b)?; /// tv.end() /// } /// E::U(ref a, ref b, ref c) => { /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; /// tv.serialize_field(a)?; /// tv.serialize_field(b)?; /// tv.serialize_field(c)?; /// tv.end() /// } /// } /// } /// } /// ``` fn serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>; /// Begin to serialize a map. This call must be followed by zero or more /// calls to `serialize_key` and `serialize_value`, then a call to `end`. /// /// The argument is the number of elements in the map, which may or may not /// be computable before the map is iterated. Some serializers only support /// maps whose length is known up front. /// /// ```edition2018 /// # use std::marker::PhantomData; /// # /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); /// # /// # impl<K, V> HashMap<K, V> { /// # fn len(&self) -> usize { /// # unimplemented!() /// # } /// # } /// # /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { /// # type Item = (&'a K, &'a V); /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; /// # /// # fn into_iter(self) -> Self::IntoIter { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{Serialize, Serializer, SerializeMap}; /// /// impl<K, V> Serialize for HashMap<K, V> /// where /// K: Serialize, /// V: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut map = serializer.serialize_map(Some(self.len()))?; /// for (k, v) in self { /// map.serialize_entry(k, v)?; /// } /// map.end() /// } /// } /// ``` fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>; /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. /// This call must be followed by zero or more calls to `serialize_field`, /// then a call to `end`. /// /// The `name` is the name of the struct and the `len` is the number of /// data fields that will be serialized. /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeStruct, Serializer}; /// /// struct Rgb { /// r: u8, /// g: u8, /// b: u8, /// } /// /// impl Serialize for Rgb { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; /// rgb.serialize_field("r", &self.r)?; /// rgb.serialize_field("g", &self.g)?; /// rgb.serialize_field("b", &self.b)?; /// rgb.end() /// } /// } /// ``` fn serialize_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, Self::Error>; /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to /// `serialize_field`, then a call to `end`. /// /// The `name` is the name of the enum, the `variant_index` is the index of /// this variant within the enum, the `variant` is the name of the variant, /// and the `len` is the number of data fields that will be serialized. /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; /// /// enum E { /// S { r: u8, g: u8, b: u8 }, /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::S { /// ref r, /// ref g, /// ref b, /// } => { /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; /// sv.serialize_field("r", r)?; /// sv.serialize_field("g", g)?; /// sv.serialize_field("b", b)?; /// sv.end() /// } /// } /// } /// } /// ``` fn serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>; /// Collect an iterator as a sequence. /// /// The default implementation serializes each item yielded by the iterator /// using [`serialize_seq`]. Implementors should not need to override this /// method. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// /// struct SecretlyOneHigher { /// data: Vec<i32>, /// } /// /// impl Serialize for SecretlyOneHigher { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.collect_seq(self.data.iter().map(|x| x + 1)) /// } /// } /// ``` /// /// [`serialize_seq`]: #tymethod.serialize_seq fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where I: IntoIterator, <I as IntoIterator>::Item: Serialize, { let iter = iter.into_iter(); let mut serializer = try!(self.serialize_seq(iter.len_hint())); for item in iter { try!(serializer.serialize_element(&item)); } serializer.end() } /// Collect an iterator as a map. /// /// The default implementation serializes each pair yielded by the iterator /// using [`serialize_map`]. Implementors should not need to override this /// method. /// /// ```edition2018 /// use serde::{Serialize, Serializer}; /// use std::collections::BTreeSet; /// /// struct MapToUnit { /// keys: BTreeSet<i32>, /// } /// /// // Serializes as a map in which the values are all unit. /// impl Serialize for MapToUnit { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.collect_map(self.keys.iter().map(|k| (k, ()))) /// } /// } /// ``` /// /// [`serialize_map`]: #tymethod.serialize_map fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> where K: Serialize, V: Serialize, I: IntoIterator<Item = (K, V)>, { let iter = iter.into_iter(); let mut serializer = try!(self.serialize_map(iter.len_hint())); for (key, value) in iter { try!(serializer.serialize_entry(&key, &value)); } serializer.end() } /// Serialize a string produced by an implementation of `Display`. /// /// The default implementation builds a heap-allocated [`String`] and /// delegates to [`serialize_str`]. Serializers are encouraged to provide a /// more efficient implementation if possible. /// /// ```edition2018 /// # struct DateTime; /// # /// # impl DateTime { /// # fn naive_local(&self) -> () { () } /// # fn offset(&self) -> () { () } /// # } /// # /// use serde::{Serialize, Serializer}; /// /// impl Serialize for DateTime { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.collect_str(&format_args!("{:?}{:?}", /// self.naive_local(), /// self.offset())) /// } /// } /// ``` /// /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html /// [`serialize_str`]: #tymethod.serialize_str #[cfg(any(feature = "std", feature = "alloc"))] fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display, { use lib::fmt::Write; let mut string = String::new(); write!(string, "{}", value).unwrap(); self.serialize_str(&string) } /// Serialize a string produced by an implementation of `Display`. /// /// Serializers that use `no_std` are required to provide an implementation /// of this method. If no more sensible behavior is possible, the /// implementation is expected to return an error. /// /// ```edition2018 /// # struct DateTime; /// # /// # impl DateTime { /// # fn naive_local(&self) -> () { () } /// # fn offset(&self) -> () { () } /// # } /// # /// use serde::{Serialize, Serializer}; /// /// impl Serialize for DateTime { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// serializer.collect_str(&format_args!("{:?}{:?}", /// self.naive_local(), /// self.offset())) /// } /// } /// ``` #[cfg(not(any(feature = "std", feature = "alloc")))] fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display; /// Determine whether `Serialize` implementations should serialize in /// human-readable form. /// /// Some types have a human-readable form that may be somewhat expensive to /// construct, as well as a binary form that is compact and efficient. /// Generally text-based formats like JSON and YAML will prefer to use the /// human-readable one and binary formats like Bincode will prefer the /// compact one. /// /// ```edition2018 /// # use std::fmt::{self, Display}; /// # /// # struct Timestamp; /// # /// # impl Timestamp { /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } /// # } /// # /// # impl Display for Timestamp { /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { /// # unimplemented!() /// # } /// # } /// # /// use serde::{Serialize, Serializer}; /// /// impl Serialize for Timestamp { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// if serializer.is_human_readable() { /// // Serialize to a human-readable string "2015-05-15T17:01:00Z". /// self.to_string().serialize(serializer) /// } else { /// // Serialize to a compact binary representation. /// self.seconds_since_epoch().serialize(serializer) /// } /// } /// } /// ``` /// /// The default implementation of this method returns `true`. Data formats /// may override this to `false` to request a compact form for types that /// support one. Note that modifying this method to change a format from /// human-readable to compact or vice versa should be regarded as a breaking /// change, as a value serialized in human-readable mode is not required to /// deserialize from the same data in compact mode. #[inline] fn is_human_readable(&self) -> bool { true } } /// Returned from `Serializer::serialize_seq`. /// /// # Example use /// /// ```edition2018 /// # use std::marker::PhantomData; /// # /// # struct Vec<T>(PhantomData<T>); /// # /// # impl<T> Vec<T> { /// # fn len(&self) -> usize { /// # unimplemented!() /// # } /// # } /// # /// # impl<'a, T> IntoIterator for &'a Vec<T> { /// # type Item = &'a T; /// # type IntoIter = Box<Iterator<Item = &'a T>>; /// # fn into_iter(self) -> Self::IntoIter { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{Serialize, Serializer, SerializeSeq}; /// /// impl<T> Serialize for Vec<T> /// where /// T: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut seq = serializer.serialize_seq(Some(self.len()))?; /// for element in self { /// seq.serialize_element(element)?; /// } /// seq.end() /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeSeq` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeSeq { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a sequence element. fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; /// Finish serializing a sequence. fn end(self) -> Result<Self::Ok, Self::Error>; } /// Returned from `Serializer::serialize_tuple`. /// /// # Example use /// /// ```edition2018 /// use serde::ser::{Serialize, Serializer, SerializeTuple}; /// /// # mod fool { /// # trait Serialize {} /// impl<A, B, C> Serialize for (A, B, C) /// # {} /// # } /// # /// # struct Tuple3<A, B, C>(A, B, C); /// # /// # impl<A, B, C> Serialize for Tuple3<A, B, C> /// where /// A: Serialize, /// B: Serialize, /// C: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut tup = serializer.serialize_tuple(3)?; /// tup.serialize_element(&self.0)?; /// tup.serialize_element(&self.1)?; /// tup.serialize_element(&self.2)?; /// tup.end() /// } /// } /// ``` /// /// ```edition2018 /// # use std::marker::PhantomData; /// # /// # struct Array<T>(PhantomData<T>); /// # /// # impl<T> Array<T> { /// # fn len(&self) -> usize { /// # unimplemented!() /// # } /// # } /// # /// # impl<'a, T> IntoIterator for &'a Array<T> { /// # type Item = &'a T; /// # type IntoIter = Box<Iterator<Item = &'a T>>; /// # fn into_iter(self) -> Self::IntoIter { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{Serialize, Serializer, SerializeTuple}; /// /// # mod fool { /// # trait Serialize {} /// impl<T> Serialize for [T; 16] /// # {} /// # } /// # /// # impl<T> Serialize for Array<T> /// where /// T: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut seq = serializer.serialize_tuple(16)?; /// for element in self { /// seq.serialize_element(element)?; /// } /// seq.end() /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeTuple` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeTuple { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a tuple element. fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; /// Finish serializing a tuple. fn end(self) -> Result<Self::Ok, Self::Error>; } ///trait for tagged pub trait SerializeTagged { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; ///Assign tag information fn set_tag<T: ?Sized>(&mut self, value: &T) ->Result<(), Self::Error>; /// Serialize a tagged element. fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; } /// Returned from `Serializer::serialize_tuple_struct`. /// /// # Example use /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; /// /// struct Rgb(u8, u8, u8); /// /// impl Serialize for Rgb { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; /// ts.serialize_field(&self.0)?; /// ts.serialize_field(&self.1)?; /// ts.serialize_field(&self.2)?; /// ts.end() /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeTupleStruct` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeTupleStruct { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a tuple struct field. fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; /// Finish serializing a tuple struct. fn end(self) -> Result<Self::Ok, Self::Error>; } /// Returned from `Serializer::serialize_tuple_variant`. /// /// # Example use /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; /// /// enum E { /// T(u8, u8), /// U(String, u32, u32), /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::T(ref a, ref b) => { /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; /// tv.serialize_field(a)?; /// tv.serialize_field(b)?; /// tv.end() /// } /// E::U(ref a, ref b, ref c) => { /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; /// tv.serialize_field(a)?; /// tv.serialize_field(b)?; /// tv.serialize_field(c)?; /// tv.end() /// } /// } /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeTupleVariant` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeTupleVariant { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a tuple variant field. fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; /// Finish serializing a tuple variant. fn end(self) -> Result<Self::Ok, Self::Error>; } /// Returned from `Serializer::serialize_map`. /// /// # Example use /// /// ```edition2018 /// # use std::marker::PhantomData; /// # /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); /// # /// # impl<K, V> HashMap<K, V> { /// # fn len(&self) -> usize { /// # unimplemented!() /// # } /// # } /// # /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { /// # type Item = (&'a K, &'a V); /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; /// # /// # fn into_iter(self) -> Self::IntoIter { /// # unimplemented!() /// # } /// # } /// # /// use serde::ser::{Serialize, Serializer, SerializeMap}; /// /// impl<K, V> Serialize for HashMap<K, V> /// where /// K: Serialize, /// V: Serialize, /// { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut map = serializer.serialize_map(Some(self.len()))?; /// for (k, v) in self { /// map.serialize_entry(k, v)?; /// } /// map.end() /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeMap` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeMap { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a map key. /// /// If possible, `Serialize` implementations are encouraged to use /// `serialize_entry` instead as it may be implemented more efficiently in /// some formats compared to a pair of calls to `serialize_key` and /// `serialize_value`. fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize; /// Serialize a map value. /// /// # Panics /// /// Calling `serialize_value` before `serialize_key` is incorrect and is /// allowed to panic or produce bogus results. fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize; /// Serialize a map entry consisting of a key and a value. /// /// Some [`Serialize`] types are not able to hold a key and value in memory /// at the same time so `SerializeMap` implementations are required to /// support [`serialize_key`] and [`serialize_value`] individually. The /// `serialize_entry` method allows serializers to optimize for the case /// where key and value are both available. [`Serialize`] implementations /// are encouraged to use `serialize_entry` if possible. /// /// The default implementation delegates to [`serialize_key`] and /// [`serialize_value`]. This is appropriate for serializers that do not /// care about performance or are not able to optimize `serialize_entry` any /// better than this. /// /// [`Serialize`]: ../trait.Serialize.html /// [`serialize_key`]: #tymethod.serialize_key /// [`serialize_value`]: #tymethod.serialize_value fn serialize_entry<K: ?Sized, V: ?Sized>( &mut self, key: &K, value: &V, ) -> Result<(), Self::Error> where K: Serialize, V: Serialize, { try!(self.serialize_key(key)); self.serialize_value(value) } /// Finish serializing a map. fn end(self) -> Result<Self::Ok, Self::Error>; } /// Returned from `Serializer::serialize_struct`. /// /// # Example use /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeStruct, Serializer}; /// /// struct Rgb { /// r: u8, /// g: u8, /// b: u8, /// } /// /// impl Serialize for Rgb { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; /// rgb.serialize_field("r", &self.r)?; /// rgb.serialize_field("g", &self.g)?; /// rgb.serialize_field("b", &self.b)?; /// rgb.end() /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeStruct` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeStruct { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a struct field. fn serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize; /// Indicate that a struct field has been skipped. #[inline] fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { let _ = key; Ok(()) } /// Finish serializing a struct. fn end(self) -> Result<Self::Ok, Self::Error>; } /// Returned from `Serializer::serialize_struct_variant`. /// /// # Example use /// /// ```edition2018 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer}; /// /// enum E { /// S { r: u8, g: u8, b: u8 }, /// } /// /// impl Serialize for E { /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// where /// S: Serializer, /// { /// match *self { /// E::S { /// ref r, /// ref g, /// ref b, /// } => { /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; /// sv.serialize_field("r", r)?; /// sv.serialize_field("g", g)?; /// sv.serialize_field("b", b)?; /// sv.end() /// } /// } /// } /// } /// ``` /// /// # Example implementation /// /// The [example data format] presented on the website demonstrates an /// implementation of `SerializeStructVariant` for a basic JSON data format. /// /// [example data format]: https://serde.rs/data-format.html pub trait SerializeStructVariant { /// Must match the `Ok` type of our `Serializer`. type Ok; /// Must match the `Error` type of our `Serializer`. type Error: Error; /// Serialize a struct variant field. fn serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize; /// Indicate that a struct variant field has been skipped. #[inline] fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { let _ = key; Ok(()) } /// Finish serializing a struct variant. fn end(self) -> Result<Self::Ok, Self::Error>; } trait LenHint: Iterator { fn len_hint(&self) -> Option<usize>; } impl<I> LenHint for I where I: Iterator, { #[cfg(not(feature = "unstable"))] fn len_hint(&self) -> Option<usize> { iterator_len_hint(self) } #[cfg(feature = "unstable")] default fn len_hint(&self) -> Option<usize> { iterator_len_hint(self) } } #[cfg(feature = "unstable")] impl<I> LenHint for I where I: ExactSizeIterator, { fn len_hint(&self) -> Option<usize> { Some(self.len()) } } fn iterator_len_hint<I>(iter: &I) -> Option<usize> where I: Iterator, { match iter.size_hint() { (lo, Some(hi)) if lo == hi => Some(lo), _ => None, } }
32.114527
104
0.52775
e5ce9b2c92ec4bae91788f4ff0703bc329c64f39
858
#[derive(Clone, Default, Debug)] pub struct Security { lock_revision: bool, lock_structure: bool, lock_windows: bool, revisions_password: String, workbook_password: String, } impl Security { pub(crate) fn is_security_enabled(&self) -> bool { if self.lock_revision { true } else if self.lock_structure { true } else { self.lock_windows } } pub fn get_lock_revision(&self) -> &bool { &self.lock_revision } pub fn get_lock_structure(&self) -> &bool { &self.lock_structure } pub fn get_lock_windows(&self) -> &bool { &self.lock_windows } pub fn get_revisions_password(&self) -> &str { &self.revisions_password } pub fn get_workbook_password(&self) -> &str { &self.workbook_password } }
24.514286
54
0.59324
019ed3bd4b2fb675c6487f362b0a2b3d8a815539
3,118
use crate::ray::Ray; use rand::Rng; use crate::vec3::Real; use crate::vec3::Vec3; pub trait Material: Sync { fn scatter(&self, r_in: &Ray, point: Vec3, normal: Vec3) -> Option<(Vec3, Ray)>; } // the lambertian class does not make sense pub struct Lambertian { pub albedo: Vec3, } impl Material for Lambertian { fn scatter(&self, _r_in: &Ray, point: Vec3, normal: Vec3) -> Option<(Vec3, Ray)> { let target = point + normal + crate::random_in_unit_sphere(); let attenuation = self.albedo; let scattered = Ray::new(point, target - point); Some((attenuation, scattered)) } } fn reflect(v: Vec3, n: Vec3) -> Vec3 { v - 2. * v.dot(&n) * n } pub struct Metal { albedo: Vec3, fuzz: Real, } impl Metal { pub fn new(albedo: Vec3, fuzz: Real) -> Self { Metal { albedo, fuzz: fuzz.min(1.), } } pub fn boxed(albedo: Vec3, fuzz: Real) -> Box<Self> { Box::new(Metal::new(albedo, fuzz)) } } impl Material for Metal { fn scatter(&self, r_in: &Ray, point: Vec3, normal: Vec3) -> Option<(Vec3, Ray)> { let reflected = reflect(r_in.direction().unit_vec(), normal); let attenuation = self.albedo; let scattered = Ray::new( point, reflected + self.fuzz * crate::random_in_unit_sphere(), ); if scattered.direction().dot(&normal) > 0. { Some((attenuation, scattered)) } else { None } } } fn refract(v: Vec3, n: Vec3, ni_over_nt: Real) -> Option<Vec3> { let uv = v.unit_vec(); let dt = uv.dot(&n); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1. - dt * dt); if discriminant > 0. { let refracted = ni_over_nt * (uv - n * dt) - n * discriminant.sqrt(); Some(refracted) } else { None } } fn schlick(cosine: Real, ref_idx: Real) -> Real { let mut r0 = (1. - ref_idx) / (1. + ref_idx); r0 *= r0; r0 + (1. - r0) * (1. - cosine).powi(5) } pub struct Dielectric { pub ref_idx: Real, } impl Material for Dielectric { fn scatter(&self, r_in: &Ray, point: Vec3, normal: Vec3) -> Option<(Vec3, Ray)> { let reflected = reflect(r_in.direction(), normal); let attenuation = Vec3::new(1., 1., 1.); let cosine = self.ref_idx * r_in.direction().dot(&normal) / r_in.direction().length(); let (outward_normal, ni_over_nt, cosine) = if r_in.direction().dot(&normal) > 0. { (-normal, self.ref_idx, cosine) } else { (normal, 1. / self.ref_idx, -cosine) }; let scattered = if let Some(refracted) = refract(r_in.direction(), outward_normal, ni_over_nt) { let reflect_prob = schlick(cosine, self.ref_idx); if rand::thread_rng().gen::<Real>() < reflect_prob { Ray::new(point, reflected) } else { Ray::new(point, refracted) } } else { Ray::new(point, reflected) }; Some((attenuation, scattered)) } }
28.87037
94
0.546825
4b4cb20f4089b6eab8170a0ce72ea88254ef0b86
2,629
use border_tch_agent::{model::SubModel, util::OutDim}; use serde::{Deserialize, Serialize}; use tch::{nn, nn::Module, Device, Tensor}; #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] pub struct CNNConfig { n_stack: i64, out_dim: i64, } impl OutDim for CNNConfig { fn get_out_dim(&self) -> i64 { self.out_dim } fn set_out_dim(&mut self, v: i64) { self.out_dim = v; } } // impl CNNConfig { // pub fn new(n_stack: i64, out_dim: i64) -> Self { // Self { // n_stack, // out_dim, // } // } // } #[allow(clippy::upper_case_acronyms)] // Convolutional neural network pub struct CNN { n_stack: i64, out_dim: i64, device: Device, seq: nn::Sequential, } impl CNN { fn stride(s: i64) -> nn::ConvConfig { nn::ConvConfig { stride: s, ..Default::default() } } fn create_net(var_store: &nn::VarStore, n_stack: i64, out_dim: i64) -> nn::Sequential { let p = &var_store.root(); nn::seq() .add_fn(|xs| xs.squeeze_dim(2).internal_cast_float(true) / 255) .add(nn::conv2d(p / "c1", n_stack, 32, 8, Self::stride(4))) .add_fn(|xs| xs.relu()) .add(nn::conv2d(p / "c2", 32, 64, 4, Self::stride(2))) .add_fn(|xs| xs.relu()) .add(nn::conv2d(p / "c3", 64, 64, 3, Self::stride(1))) .add_fn(|xs| xs.relu().flat_view()) .add(nn::linear(p / "l1", 3136, 512, Default::default())) .add_fn(|xs| xs.relu()) .add(nn::linear(p / "l2", 512, out_dim as _, Default::default())) } } impl SubModel for CNN { type Config = CNNConfig; type Input = Tensor; type Output = Tensor; fn forward(&self, x: &Self::Input) -> Tensor { self.seq.forward(&x.to(self.device)) } fn build(var_store: &nn::VarStore, config: Self::Config) -> Self { let n_stack = config.n_stack; let out_dim = config.out_dim; let device = var_store.device(); let seq = Self::create_net(var_store, n_stack, out_dim); Self { n_stack, out_dim, device, seq, } } fn clone_with_var_store(&self, var_store: &nn::VarStore) -> Self { let n_stack = self.n_stack; let out_dim = self.out_dim; let device = var_store.device(); let seq = Self::create_net(&var_store, n_stack, out_dim); Self { n_stack, out_dim, device, seq, } } }
26.029703
91
0.534804
2650f50e2f3a3d2fcb35c7a5c1a10a747e464882
432
//! # 提供了异步运行时需要的队列和锁 //! use std::hint::spin_loop; pub mod mpmc_deque; pub mod mpsc_deque; pub mod steal_deque; pub mod spin_lock; pub mod mutex_lock; pub mod rw_lock; /* * 根据指定值进行自旋,返回下次自旋的值 */ #[inline] pub(crate) fn spin(mut len: u32) -> u32 { if len < 1 { len = 1; } else if len > 10 { len = 10; } for _ in 0..(1 << len) { spin_loop() } len + 1 }
14.896552
42
0.523148
f40fe3e8186e879f6202a0b7eb0d80870eb8706c
1,436
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(non_camel_case_types)] struct cat { meows : usize, how_hungry : isize, name : String, } impl cat { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1_usize; if self.meows % 5_usize == 0_usize { self.how_hungry += 1; } } } fn cat(in_x : usize, in_y : isize, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0_usize, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in 1_usize..10_usize { nyan.speak(); }; assert!((nyan.eat())); }
23.540984
68
0.579387
d65ec50c65a55f1078edf32b69195928cdbf96e9
937
use crate::handlers::proof_presentation::prover::states::finished::FinishedState; use crate::messages::error::ProblemReport; use crate::messages::proof_presentation::presentation::Presentation; use crate::messages::proof_presentation::presentation_request::PresentationRequest; use crate::messages::status::Status; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PresentationPreparationFailedState { pub presentation_request: PresentationRequest, pub problem_report: ProblemReport, } impl From<PresentationPreparationFailedState> for FinishedState { fn from(state: PresentationPreparationFailedState) -> Self { trace!("transit state from PresentationPreparationFailedState to FinishedState"); FinishedState { presentation_request: Some(state.presentation_request), presentation: None, status: Status::Failed(state.problem_report), } } }
40.73913
89
0.759872
5616971e9d1f54ff50197e1e8f920778f9c94e96
40,534
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::ImportDirectiveSubclass::*; use {AmbiguityError, Module, PerNS}; use Namespace::{self, TypeNS, MacroNS}; use {NameBinding, NameBindingKind, PathResult, PrivacyError}; use Resolver; use {names_to_string, module_to_string}; use {resolve_error, ResolutionError}; use rustc::ty; use rustc::lint::builtin::PUB_USE_OF_PRIVATE_EXTERN_CRATE; use rustc::hir::def_id::DefId; use rustc::hir::def::*; use rustc::util::nodemap::{FxHashMap, FxHashSet}; use syntax::ast::{Ident, SpannedIdent, NodeId}; use syntax::ext::base::Determinacy::{self, Determined, Undetermined}; use syntax::ext::hygiene::Mark; use syntax::parse::token; use syntax::symbol::keywords; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::Span; use std::cell::{Cell, RefCell}; use std::mem; /// Contains data for specific types of import directives. #[derive(Clone, Debug)] pub enum ImportDirectiveSubclass<'a> { SingleImport { target: Ident, source: Ident, result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>, type_ns_only: bool, }, GlobImport { is_prelude: bool, max_vis: Cell<ty::Visibility>, // The visibility of the greatest reexport. // n.b. `max_vis` is only used in `finalize_import` to check for reexport errors. }, ExternCrate, MacroUse, } /// One import directive. #[derive(Debug,Clone)] pub struct ImportDirective<'a> { pub id: NodeId, pub parent: Module<'a>, pub module_path: Vec<SpannedIdent>, pub imported_module: Cell<Option<Module<'a>>>, // the resolution of `module_path` pub subclass: ImportDirectiveSubclass<'a>, pub span: Span, pub vis: Cell<ty::Visibility>, pub expansion: Mark, pub used: Cell<bool>, } impl<'a> ImportDirective<'a> { pub fn is_glob(&self) -> bool { match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false } } } #[derive(Clone, Default)] /// Records information about the resolution of a name in a namespace of a module. pub struct NameResolution<'a> { /// The single imports that define the name in the namespace. single_imports: SingleImports<'a>, /// The least shadowable known binding for this name, or None if there are no known bindings. pub binding: Option<&'a NameBinding<'a>>, shadows_glob: Option<&'a NameBinding<'a>>, } #[derive(Clone, Debug)] enum SingleImports<'a> { /// No single imports can define the name in the namespace. None, /// Only the given single import can define the name in the namespace. MaybeOne(&'a ImportDirective<'a>), /// At least one single import will define the name in the namespace. AtLeastOne, } impl<'a> Default for SingleImports<'a> { /// Creates a `SingleImports<'a>` of None type. fn default() -> Self { SingleImports::None } } impl<'a> SingleImports<'a> { fn add_directive(&mut self, directive: &'a ImportDirective<'a>) { match *self { SingleImports::None => *self = SingleImports::MaybeOne(directive), // If two single imports can define the name in the namespace, we can assume that at // least one of them will define it since otherwise both would have to define only one // namespace, leading to a duplicate error. SingleImports::MaybeOne(_) => *self = SingleImports::AtLeastOne, SingleImports::AtLeastOne => {} }; } fn directive_failed(&mut self) { match *self { SingleImports::None => unreachable!(), SingleImports::MaybeOne(_) => *self = SingleImports::None, SingleImports::AtLeastOne => {} } } } impl<'a> NameResolution<'a> { // Returns the binding for the name if it is known or None if it not known. fn binding(&self) -> Option<&'a NameBinding<'a>> { self.binding.and_then(|binding| match self.single_imports { SingleImports::None => Some(binding), _ if !binding.is_glob_import() => Some(binding), _ => None, // The binding could be shadowed by a single import, so it is not known. }) } } impl<'a> Resolver<'a> { fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace) -> &'a RefCell<NameResolution<'a>> { *module.resolutions.borrow_mut().entry((ident.modern(), ns)) .or_insert_with(|| self.arenas.alloc_name_resolution()) } /// Attempts to resolve `ident` in namespaces `ns` of `module`. /// Invariant: if `record_used` is `Some`, import resolution must be complete. pub fn resolve_ident_in_module_unadjusted(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, restricted_shadowing: bool, record_used: bool, path_span: Span) -> Result<&'a NameBinding<'a>, Determinacy> { self.populate_module_if_necessary(module); let resolution = self.resolution(module, ident, ns) .try_borrow_mut() .map_err(|_| Determined)?; // This happens when there is a cycle of imports if record_used { if let Some(binding) = resolution.binding { if let Some(shadowed_glob) = resolution.shadows_glob { let name = ident.name; // Forbid expanded shadowing to avoid time travel. if restricted_shadowing && binding.expansion != Mark::root() && ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing binding.def() != shadowed_glob.def() { self.ambiguity_errors.push(AmbiguityError { span: path_span, name, lexical: false, b1: binding, b2: shadowed_glob, legacy: false, }); } } if self.record_use(ident, ns, binding, path_span) { return Ok(self.dummy_binding); } if !self.is_accessible(binding.vis) { self.privacy_errors.push(PrivacyError(path_span, ident.name, binding)); } } return resolution.binding.ok_or(Determined); } let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| { // `extern crate` are always usable for backwards compatability, see issue #37020. let usable = this.is_accessible(binding.vis) || binding.is_extern_crate(); if usable { Ok(binding) } else { Err(Determined) } }; // Items and single imports are not shadowable. if let Some(binding) = resolution.binding { if !binding.is_glob_import() { return check_usable(self, binding); } } // Check if a single import can still define the name. match resolution.single_imports { SingleImports::AtLeastOne => return Err(Undetermined), SingleImports::MaybeOne(directive) if self.is_accessible(directive.vis.get()) => { let module = match directive.imported_module.get() { Some(module) => module, None => return Err(Undetermined), }; let ident = match directive.subclass { SingleImport { source, .. } => source, _ => unreachable!(), }; match self.resolve_ident_in_module(module, ident, ns, false, false, path_span) { Err(Determined) => {} _ => return Err(Undetermined), } } SingleImports::MaybeOne(_) | SingleImports::None => {}, } let no_unresolved_invocations = restricted_shadowing || module.unresolved_invocations.borrow().is_empty(); match resolution.binding { // In `MacroNS`, expanded bindings do not shadow (enforced in `try_define`). Some(binding) if no_unresolved_invocations || ns == MacroNS => return check_usable(self, binding), None if no_unresolved_invocations => {} _ => return Err(Undetermined), } // Check if the globs are determined if restricted_shadowing && module.def().is_some() { return Err(Determined); } for directive in module.globs.borrow().iter() { if !self.is_accessible(directive.vis.get()) { continue } let module = unwrap_or!(directive.imported_module.get(), return Err(Undetermined)); let (orig_current_module, mut ident) = (self.current_module, ident.modern()); match ident.ctxt.glob_adjust(module.expansion, directive.span.ctxt.modern()) { Some(Some(def)) => self.current_module = self.macro_def_scope(def), Some(None) => {} None => continue, }; let result = self.resolve_ident_in_module_unadjusted( module, ident, ns, false, false, path_span, ); self.current_module = orig_current_module; if let Err(Undetermined) = result { return Err(Undetermined); } } Err(Determined) } // Add an import directive to the current module. pub fn add_import_directive(&mut self, module_path: Vec<SpannedIdent>, subclass: ImportDirectiveSubclass<'a>, span: Span, id: NodeId, vis: ty::Visibility, expansion: Mark) { let current_module = self.current_module; let directive = self.arenas.alloc_import_directive(ImportDirective { parent: current_module, module_path, imported_module: Cell::new(None), subclass, span, id, vis: Cell::new(vis), expansion, used: Cell::new(false), }); self.indeterminate_imports.push(directive); match directive.subclass { SingleImport { target, .. } => { self.per_ns(|this, ns| { let mut resolution = this.resolution(current_module, target, ns).borrow_mut(); resolution.single_imports.add_directive(directive); }); } // We don't add prelude imports to the globs since they only affect lexical scopes, // which are not relevant to import resolution. GlobImport { is_prelude: true, .. } => {} GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive), _ => unreachable!(), } } // Given a binding and an import directive that resolves to it, // return the corresponding binding defined by the import directive. pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>) -> &'a NameBinding<'a> { let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) || // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE` !directive.is_glob() && binding.is_extern_crate() { directive.vis.get() } else { binding.pseudo_vis() }; if let GlobImport { ref max_vis, .. } = directive.subclass { if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) { max_vis.set(vis) } } self.arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Import { binding, directive, used: Cell::new(false), legacy_self_import: false, }, span: directive.span, vis, expansion: directive.expansion, }) } // Define the name or return the existing binding if there is a collision. pub fn try_define(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> { self.update_resolution(module, ident, ns, |this, resolution| { if let Some(old_binding) = resolution.binding { if binding.is_glob_import() { if !old_binding.is_glob_import() && !(ns == MacroNS && old_binding.expansion != Mark::root()) { resolution.shadows_glob = Some(binding); } else if binding.def() != old_binding.def() { resolution.binding = Some(this.ambiguity(old_binding, binding)); } else if !old_binding.vis.is_at_least(binding.vis, &*this) { // We are glob-importing the same item but with greater visibility. resolution.binding = Some(binding); } } else if old_binding.is_glob_import() { if ns == MacroNS && binding.expansion != Mark::root() && binding.def() != old_binding.def() { resolution.binding = Some(this.ambiguity(binding, old_binding)); } else { resolution.binding = Some(binding); resolution.shadows_glob = Some(old_binding); } } else { return Err(old_binding); } } else { resolution.binding = Some(binding); } Ok(()) }) } pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>) -> &'a NameBinding<'a> { self.arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: false }, vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis }, span: b1.span, expansion: Mark::root(), }) } // Use `f` to mutate the resolution of the name in the module. // If the resolution becomes a success, define it in the module's glob importers. fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F) -> T where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T { // Ensure that `resolution` isn't borrowed when defining in the module's glob importers, // during which the resolution might end up getting re-defined via a glob cycle. let (binding, t) = { let resolution = &mut *self.resolution(module, ident, ns).borrow_mut(); let old_binding = resolution.binding(); let t = f(self, resolution); match resolution.binding() { _ if old_binding.is_some() => return t, None => return t, Some(binding) => match old_binding { Some(old_binding) if old_binding as *const _ == binding as *const _ => return t, _ => (binding, t), } } }; // Define `binding` in `module`s glob importers. for directive in module.glob_importers.borrow_mut().iter() { let mut ident = ident.modern(); let scope = match ident.ctxt.reverse_glob_adjust(module.expansion, directive.span.ctxt.modern()) { Some(Some(def)) => self.macro_def_scope(def), Some(None) => directive.parent, None => continue, }; if self.is_accessible_from(binding.vis, scope) { let imported_binding = self.import(binding, directive); let _ = self.try_define(directive.parent, ident, ns, imported_binding); } } t } // Define a "dummy" resolution containing a Def::Err as a placeholder for a // failed resolution fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) { if let SingleImport { target, .. } = directive.subclass { let dummy_binding = self.dummy_binding; let dummy_binding = self.import(dummy_binding, directive); self.per_ns(|this, ns| { let _ = this.try_define(directive.parent, target, ns, dummy_binding); }); } } } pub struct ImportResolver<'a, 'b: 'a> { pub resolver: &'a mut Resolver<'b>, } impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> { type Target = Resolver<'b>; fn deref(&self) -> &Resolver<'b> { self.resolver } } impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> { fn deref_mut(&mut self) -> &mut Resolver<'b> { self.resolver } } impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> { fn parent(self, id: DefId) -> Option<DefId> { self.resolver.parent(id) } } impl<'a, 'b:'a> ImportResolver<'a, 'b> { // Import resolution // // This is a fixed-point algorithm. We resolve imports until our efforts // are stymied by an unresolved import; then we bail out of the current // module and continue. We terminate successfully once no more imports // remain or unsuccessfully when no forward progress in resolving imports // is made. /// Resolves all imports for the crate. This method performs the fixed- /// point iteration. pub fn resolve_imports(&mut self) { let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1; while self.indeterminate_imports.len() < prev_num_indeterminates { prev_num_indeterminates = self.indeterminate_imports.len(); for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) { match self.resolve_import(&import) { true => self.determined_imports.push(import), false => self.indeterminate_imports.push(import), } } } } pub fn finalize_imports(&mut self) { for module in self.arenas.local_modules().iter() { self.finalize_resolutions_in(module); } let mut errors = false; let mut seen_spans = FxHashSet(); for i in 0 .. self.determined_imports.len() { let import = self.determined_imports[i]; if let Some((span, err)) = self.finalize_import(import) { errors = true; if let SingleImport { source, ref result, .. } = import.subclass { if source.name == "self" { // Silence `unresolved import` error if E0429 is already emitted match result.value_ns.get() { Err(Determined) => continue, _ => {}, } } } // If the error is a single failed import then create a "fake" import // resolution for it so that later resolve stages won't complain. self.import_dummy_binding(import); if !seen_spans.contains(&span) { let path = import_path_to_string(&import.module_path[..], &import.subclass, span); let error = ResolutionError::UnresolvedImport(Some((span, &path, &err))); resolve_error(self.resolver, span, error); seen_spans.insert(span); } } } // Report unresolved imports only if no hard error was already reported // to avoid generating multiple errors on the same import. if !errors { if let Some(import) = self.indeterminate_imports.iter().next() { let error = ResolutionError::UnresolvedImport(None); resolve_error(self.resolver, import.span, error); } } } /// Attempts to resolve the given import, returning true if its resolution is determined. /// If successful, the resolved bindings are written into the module. fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool { debug!("(resolving import for module) resolving import `{}::...` in `{}`", names_to_string(&directive.module_path[..]), module_to_string(self.current_module)); self.current_module = directive.parent; let module = if let Some(module) = directive.imported_module.get() { module } else { let vis = directive.vis.get(); // For better failure detection, pretend that the import will not define any names // while resolving its module path. directive.vis.set(ty::Visibility::Invisible); let result = self.resolve_path(&directive.module_path[..], None, false, directive.span); directive.vis.set(vis); match result { PathResult::Module(module) => module, PathResult::Indeterminate => return false, _ => return true, } }; directive.imported_module.set(Some(module)); let (source, target, result, type_ns_only) = match directive.subclass { SingleImport { source, target, ref result, type_ns_only } => (source, target, result, type_ns_only), GlobImport { .. } => { self.resolve_glob_import(directive); return true; } _ => unreachable!(), }; let mut indeterminate = false; self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS { if let Err(Undetermined) = result[ns].get() { result[ns].set(this.resolve_ident_in_module(module, source, ns, false, false, directive.span)); } else { return }; let parent = directive.parent; match result[ns].get() { Err(Undetermined) => indeterminate = true, Err(Determined) => { this.update_resolution(parent, target, ns, |_, resolution| { resolution.single_imports.directive_failed() }); } Ok(binding) if !binding.is_importable() => { let msg = format!("`{}` is not directly importable", target); struct_span_err!(this.session, directive.span, E0253, "{}", &msg) .span_label(directive.span, "cannot be imported directly") .emit(); // Do not import this illegal binding. Import a dummy binding and pretend // everything is fine this.import_dummy_binding(directive); } Ok(binding) => { let imported_binding = this.import(binding, directive); let conflict = this.try_define(parent, target, ns, imported_binding); if let Err(old_binding) = conflict { this.report_conflict(parent, target, ns, imported_binding, old_binding); } } } }); !indeterminate } // If appropriate, returns an error to report. fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> { self.current_module = directive.parent; let ImportDirective { ref module_path, span, .. } = *directive; let module_result = self.resolve_path(&module_path, None, true, span); let module = match module_result { PathResult::Module(module) => module, PathResult::Failed(span, msg, _) => { let (mut self_path, mut self_result) = (module_path.clone(), None); if !self_path.is_empty() && !token::Ident(self_path[0].node).is_path_segment_keyword() { self_path[0].node.name = keywords::SelfValue.name(); self_result = Some(self.resolve_path(&self_path, None, false, span)); } return if let Some(PathResult::Module(..)) = self_result { Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..])))) } else { Some((span, msg)) }; }, _ => return None, }; let (ident, result, type_ns_only) = match directive.subclass { SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only), GlobImport { .. } if module.def_id() == directive.parent.def_id() => { // Importing a module into itself is not allowed. return Some((directive.span, "Cannot glob-import a module into itself.".to_string())); } GlobImport { is_prelude, ref max_vis } => { if !is_prelude && max_vis.get() != ty::Visibility::Invisible && // Allow empty globs. !max_vis.get().is_at_least(directive.vis.get(), &*self) { let msg = "A non-empty glob must import something with the glob's visibility"; self.session.span_err(directive.span, msg); } return None; } _ => unreachable!(), }; let mut all_ns_err = true; let mut legacy_self_import = None; self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS { if let Ok(binding) = result[ns].get() { all_ns_err = false; if this.record_use(ident, ns, binding, directive.span) { this.resolution(module, ident, ns).borrow_mut().binding = Some(this.dummy_binding); } } } else if let Ok(binding) = this.resolve_ident_in_module(module, ident, ns, false, false, directive.span) { legacy_self_import = Some(directive); let binding = this.arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Import { binding, directive, used: Cell::new(false), legacy_self_import: true, }, ..*binding }); let _ = this.try_define(directive.parent, ident, ns, binding); }); if all_ns_err { if let Some(directive) = legacy_self_import { self.warn_legacy_self_import(directive); return None; } let mut all_ns_failed = true; self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS { match this.resolve_ident_in_module(module, ident, ns, false, true, span) { Ok(_) => all_ns_failed = false, _ => {} } }); return if all_ns_failed { let resolutions = module.resolutions.borrow(); let names = resolutions.iter().filter_map(|(&(ref i, _), resolution)| { if *i == ident { return None; } // Never suggest the same name match *resolution.borrow() { NameResolution { binding: Some(name_binding), .. } => { match name_binding.kind { NameBindingKind::Import { binding, .. } => { match binding.kind { // Never suggest the name that has binding error // i.e. the name that cannot be previously resolved NameBindingKind::Def(Def::Err) => return None, _ => Some(&i.name), } }, _ => Some(&i.name), } }, NameResolution { single_imports: SingleImports::None, .. } => None, _ => Some(&i.name), } }); let lev_suggestion = match find_best_match_for_name(names, &ident.name.as_str(), None) { Some(name) => format!(". Did you mean to use `{}`?", name), None => "".to_owned(), }; let module_str = module_to_string(module); let msg = if &module_str == "???" { format!("no `{}` in the root{}", ident, lev_suggestion) } else { format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion) }; Some((span, msg)) } else { // `resolve_ident_in_module` reported a privacy error. self.import_dummy_binding(directive); None } } let mut reexport_error = None; let mut any_successful_reexport = false; self.per_ns(|this, ns| { if let Ok(binding) = result[ns].get() { let vis = directive.vis.get(); if !binding.pseudo_vis().is_at_least(vis, &*this) { reexport_error = Some((ns, binding)); } else { any_successful_reexport = true; } } }); // All namespaces must be re-exported with extra visibility for an error to occur. if !any_successful_reexport { let (ns, binding) = reexport_error.unwrap(); if ns == TypeNS && binding.is_extern_crate() { let msg = format!("extern crate `{}` is private, and cannot be reexported \ (error E0365), consider declaring with `pub`", ident); self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE, directive.id, directive.span, &msg); } else if ns == TypeNS { struct_span_err!(self.session, directive.span, E0365, "`{}` is private, and cannot be reexported", ident) .span_label(directive.span, format!("reexport of private `{}`", ident)) .note(&format!("consider declaring type or module `{}` with `pub`", ident)) .emit(); } else { let msg = format!("`{}` is private, and cannot be reexported", ident); let note_msg = format!("consider marking `{}` as `pub` in the imported module", ident); struct_span_err!(self.session, directive.span, E0364, "{}", &msg) .span_note(directive.span, &note_msg) .emit(); } } // Record what this import resolves to for later uses in documentation, // this may resolve to either a value or a type, but for documentation // purposes it's good enough to just favor one over the other. self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() { this.def_map.entry(directive.id).or_insert(PathResolution::new(binding.def())); }); debug!("(resolving single import) successfully resolved import"); None } fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) { let module = directive.imported_module.get().unwrap(); self.populate_module_if_necessary(module); if let Some(Def::Trait(_)) = module.def() { self.session.span_err(directive.span, "items in traits are not importable."); return; } else if module.def_id() == directive.parent.def_id() { return; } else if let GlobImport { is_prelude: true, .. } = directive.subclass { self.prelude = Some(module); return; } // Add to module's glob_importers module.glob_importers.borrow_mut().push(directive); // Ensure that `resolutions` isn't borrowed during `try_define`, // since it might get updated via a glob cycle. let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| { resolution.borrow().binding().map(|binding| (ident, binding)) }).collect::<Vec<_>>(); for ((mut ident, ns), binding) in bindings { let scope = match ident.ctxt.reverse_glob_adjust(module.expansion, directive.span.ctxt.modern()) { Some(Some(def)) => self.macro_def_scope(def), Some(None) => self.current_module, None => continue, }; if self.is_accessible_from(binding.pseudo_vis(), scope) { let imported_binding = self.import(binding, directive); let _ = self.try_define(directive.parent, ident, ns, imported_binding); } } // Record the destination of this import self.record_def(directive.id, PathResolution::new(module.def().unwrap())); } // Miscellaneous post-processing, including recording reexports, // reporting conflicts, and reporting unresolved imports. fn finalize_resolutions_in(&mut self, module: Module<'b>) { // Since import resolution is finished, globs will not define any more names. *module.globs.borrow_mut() = Vec::new(); let mut reexports = Vec::new(); let mut exported_macro_names = FxHashMap(); if module as *const _ == self.graph_root as *const _ { let macro_exports = mem::replace(&mut self.macro_exports, Vec::new()); for export in macro_exports.into_iter().rev() { if exported_macro_names.insert(export.ident.modern(), export.span).is_none() { reexports.push(export); } } } for (&(ident, ns), resolution) in module.resolutions.borrow().iter() { let resolution = &mut *resolution.borrow_mut(); let binding = match resolution.binding { Some(binding) => binding, None => continue, }; if binding.vis == ty::Visibility::Public && (binding.is_import() || binding.is_macro_def()) { let def = binding.def(); if def != Def::Err { if !def.def_id().is_local() { self.session.cstore.export_macros(def.def_id().krate); } if let Def::Macro(..) = def { if let Some(&span) = exported_macro_names.get(&ident.modern()) { let msg = format!("a macro named `{}` has already been exported", ident); self.session.struct_span_err(span, &msg) .span_label(span, format!("`{}` already exported", ident)) .span_note(binding.span, "previous macro export here") .emit(); } } reexports.push(Export { ident: ident.modern(), def: def, span: binding.span }); } } match binding.kind { NameBindingKind::Import { binding: orig_binding, .. } => { if ns == TypeNS && orig_binding.is_variant() && !orig_binding.vis.is_at_least(binding.vis, &*self) { let msg = format!("variant `{}` is private, and cannot be reexported, \ consider declaring its enum as `pub`", ident); self.session.span_err(binding.span, &msg); } } NameBindingKind::Ambiguity { b1, b2, .. } if b1.is_glob_import() && b2.is_glob_import() => { let (orig_b1, orig_b2) = match (&b1.kind, &b2.kind) { (&NameBindingKind::Import { binding: b1, .. }, &NameBindingKind::Import { binding: b2, .. }) => (b1, b2), _ => continue, }; let (b1, b2) = match (orig_b1.vis, orig_b2.vis) { (ty::Visibility::Public, ty::Visibility::Public) => continue, (ty::Visibility::Public, _) => (b1, b2), (_, ty::Visibility::Public) => (b2, b1), _ => continue, }; resolution.binding = Some(self.arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: true }, ..*b1 })); } _ => {} } } if reexports.len() > 0 { if let Some(def_id) = module.def_id() { let node_id = self.definitions.as_local_node_id(def_id).unwrap(); self.export_map.insert(node_id, reexports); } } } } fn import_path_to_string(names: &[SpannedIdent], subclass: &ImportDirectiveSubclass, span: Span) -> String { let pos = names.iter() .position(|p| span == p.span && p.node.name != keywords::CrateRoot.name()); let global = !names.is_empty() && names[0].node.name == keywords::CrateRoot.name(); if let Some(pos) = pos { let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] }; names_to_string(names) } else { let names = if global { &names[1..] } else { names }; if names.is_empty() { import_directive_subclass_to_string(subclass) } else { (format!("{}::{}", names_to_string(names), import_directive_subclass_to_string(subclass))) } } } fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String { match *subclass { SingleImport { source, .. } => source.to_string(), GlobImport { .. } => "*".to_string(), ExternCrate => "<extern crate>".to_string(), MacroUse => "#[macro_use]".to_string(), } }
43.538131
100
0.516554
75eaf357fdcdceee17a7c6952f14d47bd3a90b14
43
#[cfg(feature = "stdweb")] pub mod stdweb;
14.333333
26
0.651163
bb67dc9bd217cc5ae31f612895229061fe279b6c
3,947
use metric; use collections::hashmap::HashMap; use time; /// Buckets are the main storage of the statsd server. Each bucket is a simple /// hashmap representing the key: value pairs that the statsd clients send to this /// server. /// /// The buckets are cleared out on every flush event. pub struct Buckets { pub counters: HashMap<~str, f64>, pub gauges: HashMap<~str, f64>, pub histograms: HashMap<~str, ~[f64]>, pub timers: HashMap<~str, ~[f64]>, pub server_start_time: time::Timespec, pub last_message: time::Timespec, pub bad_messages: uint, pub total_messages: uint } impl Buckets { pub fn new() -> Buckets { Buckets { counters: HashMap::new(), gauges: HashMap::new(), histograms: HashMap::new(), timers: HashMap::new(), server_start_time: time::get_time(), last_message: time::get_time(), bad_messages: 0, total_messages: 0 } } /// Clear out current buckets pub fn flush(&mut self) { self.counters.clear(); self.gauges.clear(); self.histograms.clear(); self.timers.clear(); } /// Act on a line of text sent to the management server. /// /// Return a tuple of (response_str, end_conn?). If end_conn==true, close /// the connection. pub fn do_management_line(&mut self, line: &str) -> (~str, bool) { let mut words = line.words(); let resp = match words.next().unwrap_or("") { "stats" => { let uptime = time::get_time().sec - self.server_start_time.sec; format!("uptime: {up} s\nbad messages: {bad}total messages: {total}", up=uptime, bad=self.bad_messages, total=self.total_messages) }, "clear" => { match words.next().unwrap_or("") { "counters" => { self.counters.clear(); ~"Counters cleared." }, "gauges" => { self.gauges.clear(); ~"Gauges cleared." }, "histograms" => { self.histograms.clear(); ~"Histograms cleared." }, "timers" => { self.timers.clear(); ~"Timers cleared." }, "" => ~"ERROR: need something to clear!", x => format!("ERROR: Nothing named '{}' to clear.", x) } }, "quit" => { // Terminate the connection. return (~"END", true); }, x => format!("ERROR: Unknown command: {}", x) }; (resp, false) } /// Add `metric` to the proper bucket. pub fn add_metric(&mut self, metric: metric::Metric) { let key = metric.name.clone(); let val = metric.value; match metric.kind { metric::Counter(sample_rate) => { self.counters .insert_or_update_with(key, 0.0, |_, v| { *v += val * (1.0 / sample_rate) } ); }, metric::Gauge => { self.gauges.insert(key, val); }, metric::Timer => { self.timers.insert_or_update_with(key, ~[], |_, v| v.push(val)); }, // Histograms are functionally equivalent to Timers with a // different name. metric::Histogram => { self.histograms.insert_or_update_with(key, ~[], |_, v| v.push(val)); } } self.last_message = time::get_time(); self.total_messages += 1; } }
30.835938
85
0.46567
e65d0edf4aaff1c1c912104f3f32052aa5d45f65
34,934
//! Gadgets implementing Jubjub elliptic curve operations. use ff::Field; use pairing::Engine; use bellman::{ConstraintSystem, SynthesisError}; use bellman::gadgets::Assignment; use bellman::gadgets::num::{AllocatedNum, Num}; use zcash_primitives::jubjub::{edwards, FixedGenerators, JubjubEngine, JubjubParams}; use bellman::gadgets::lookup::lookup3_xy; use bellman::gadgets::boolean::Boolean; #[derive(Clone)] pub struct EdwardsPoint<E: Engine> { x: AllocatedNum<E>, y: AllocatedNum<E>, } /// Perform a fixed-base scalar multiplication with /// `by` being in little-endian bit order. pub fn fixed_base_multiplication<E, CS>( mut cs: CS, base: FixedGenerators, by: &[Boolean], params: &E::Params, ) -> Result<EdwardsPoint<E>, SynthesisError> where CS: ConstraintSystem<E>, E: JubjubEngine, { // Represents the result of the multiplication let mut result = None; for (i, (chunk, window)) in by .chunks(3) .zip(params.circuit_generators(base).iter()) .enumerate() { let chunk_a = chunk .get(0) .cloned() .unwrap_or_else(|| Boolean::constant(false)); let chunk_b = chunk .get(1) .cloned() .unwrap_or_else(|| Boolean::constant(false)); let chunk_c = chunk .get(2) .cloned() .unwrap_or_else(|| Boolean::constant(false)); let (x, y) = lookup3_xy( cs.namespace(|| format!("window table lookup {}", i)), &[chunk_a, chunk_b, chunk_c], window, )?; let p = EdwardsPoint { x, y }; if result.is_none() { result = Some(p); } else { result = Some(result.unwrap().add( cs.namespace(|| format!("addition {}", i)), &p, params, )?); } } Ok(result.get()?.clone()) } impl<E: JubjubEngine> EdwardsPoint<E> { pub fn get_x(&self) -> &AllocatedNum<E> { &self.x } pub fn get_y(&self) -> &AllocatedNum<E> { &self.y } pub fn assert_not_small_order<CS>( &self, mut cs: CS, params: &E::Params, ) -> Result<(), SynthesisError> where CS: ConstraintSystem<E>, { let tmp = self.double(cs.namespace(|| "first doubling"), params)?; let tmp = tmp.double(cs.namespace(|| "second doubling"), params)?; let tmp = tmp.double(cs.namespace(|| "third doubling"), params)?; // (0, -1) is a small order point, but won't ever appear here // because cofactor is 2^3, and we performed three doublings. // (0, 1) is the neutral element, so checking if x is nonzero // is sufficient to prevent small order points here. tmp.x.assert_nonzero(cs.namespace(|| "check x != 0"))?; Ok(()) } pub fn inputize<CS>(&self, mut cs: CS) -> Result<(), SynthesisError> where CS: ConstraintSystem<E>, { self.x.inputize(cs.namespace(|| "x"))?; self.y.inputize(cs.namespace(|| "y"))?; Ok(()) } /// This converts the point into a representation. pub fn repr<CS>(&self, mut cs: CS) -> Result<Vec<Boolean>, SynthesisError> where CS: ConstraintSystem<E>, { let mut tmp = vec![]; let x = self.x.to_bits_le_strict(cs.namespace(|| "unpack x"))?; let y = self.y.to_bits_le_strict(cs.namespace(|| "unpack y"))?; tmp.extend(y); tmp.push(x[0].clone()); Ok(tmp) } /// This 'witnesses' a point inside the constraint system. /// It guarantees the point is on the curve. pub fn witness<Order, CS>( mut cs: CS, p: Option<edwards::Point<E, Order>>, params: &E::Params, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { let p = p.map(|p| p.to_xy()); // Allocate x let x = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(p.get()?.0))?; // Allocate y let y = AllocatedNum::alloc(cs.namespace(|| "y"), || Ok(p.get()?.1))?; Self::interpret(cs.namespace(|| "point interpretation"), &x, &y, params) } /// Returns `self` if condition is true, and the neutral /// element (0, 1) otherwise. pub fn conditionally_select<CS>( &self, mut cs: CS, condition: &Boolean, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // Compute x' = self.x if condition, and 0 otherwise let x_prime = AllocatedNum::alloc(cs.namespace(|| "x'"), || { if *condition.get_value().get()? { Ok(*self.x.get_value().get()?) } else { Ok(E::Fr::zero()) } })?; // condition * x = x' // if condition is 0, x' must be 0 // if condition is 1, x' must be x let one = CS::one(); cs.enforce( || "x' computation", |lc| lc + self.x.get_variable(), |_| condition.lc(one, E::Fr::one()), |lc| lc + x_prime.get_variable(), ); // Compute y' = self.y if condition, and 1 otherwise let y_prime = AllocatedNum::alloc(cs.namespace(|| "y'"), || { if *condition.get_value().get()? { Ok(*self.y.get_value().get()?) } else { Ok(E::Fr::one()) } })?; // condition * y = y' - (1 - condition) // if condition is 0, y' must be 1 // if condition is 1, y' must be y cs.enforce( || "y' computation", |lc| lc + self.y.get_variable(), |_| condition.lc(one, E::Fr::one()), |lc| lc + y_prime.get_variable() - &condition.not().lc(one, E::Fr::one()), ); Ok(EdwardsPoint { x: x_prime, y: y_prime, }) } /// Performs a scalar multiplication of this twisted Edwards /// point by a scalar represented as a sequence of booleans /// in little-endian bit order. pub fn mul<CS>( &self, mut cs: CS, by: &[Boolean], params: &E::Params, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // Represents the current "magnitude" of the base // that we're operating over. Starts at self, // then 2*self, then 4*self, ... let mut curbase = None; // Represents the result of the multiplication let mut result = None; for (i, bit) in by.iter().enumerate() { if curbase.is_none() { curbase = Some(self.clone()); } else { // Double the previous value curbase = Some( curbase .unwrap() .double(cs.namespace(|| format!("doubling {}", i)), params)?, ); } // Represents the select base. If the bit for this magnitude // is true, this will return `curbase`. Otherwise it will // return the neutral element, which will have no effect on // the result. let thisbase = curbase .as_ref() .unwrap() .conditionally_select(cs.namespace(|| format!("selection {}", i)), bit)?; if result.is_none() { result = Some(thisbase); } else { result = Some(result.unwrap().add( cs.namespace(|| format!("addition {}", i)), &thisbase, params, )?); } } Ok(result.get()?.clone()) } pub fn interpret<CS>( mut cs: CS, x: &AllocatedNum<E>, y: &AllocatedNum<E>, params: &E::Params, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // -x^2 + y^2 = 1 + dx^2y^2 let x2 = x.square(cs.namespace(|| "x^2"))?; let y2 = y.square(cs.namespace(|| "y^2"))?; let x2y2 = x2.mul(cs.namespace(|| "x^2 y^2"), &y2)?; let one = CS::one(); cs.enforce( || "on curve check", |lc| lc - x2.get_variable() + y2.get_variable(), |lc| lc + one, |lc| lc + one + (*params.edwards_d(), x2y2.get_variable()), ); Ok(EdwardsPoint { x: x.clone(), y: y.clone(), }) } pub fn double<CS>(&self, mut cs: CS, params: &E::Params) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // Compute T = (x1 + y1) * (x1 + y1) let t = AllocatedNum::alloc(cs.namespace(|| "T"), || { let mut t0 = *self.x.get_value().get()?; t0.add_assign(self.y.get_value().get()?); let mut t1 = *self.x.get_value().get()?; t1.add_assign(self.y.get_value().get()?); t0.mul_assign(&t1); Ok(t0) })?; cs.enforce( || "T computation", |lc| lc + self.x.get_variable() + self.y.get_variable(), |lc| lc + self.x.get_variable() + self.y.get_variable(), |lc| lc + t.get_variable(), ); // Compute A = x1 * y1 let a = self.x.mul(cs.namespace(|| "A computation"), &self.y)?; // Compute C = d*A*A let c = AllocatedNum::alloc(cs.namespace(|| "C"), || { let mut t0 = *a.get_value().get()?; t0.square(); t0.mul_assign(params.edwards_d()); Ok(t0) })?; cs.enforce( || "C computation", |lc| lc + (*params.edwards_d(), a.get_variable()), |lc| lc + a.get_variable(), |lc| lc + c.get_variable(), ); // Compute x3 = (2.A) / (1 + C) let x3 = AllocatedNum::alloc(cs.namespace(|| "x3"), || { let mut t0 = *a.get_value().get()?; t0.double(); let mut t1 = E::Fr::one(); t1.add_assign(c.get_value().get()?); match t1.inverse() { Some(t1) => { t0.mul_assign(&t1); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; let one = CS::one(); cs.enforce( || "x3 computation", |lc| lc + one + c.get_variable(), |lc| lc + x3.get_variable(), |lc| lc + a.get_variable() + a.get_variable(), ); // Compute y3 = (U - 2.A) / (1 - C) let y3 = AllocatedNum::alloc(cs.namespace(|| "y3"), || { let mut t0 = *a.get_value().get()?; t0.double(); t0.negate(); t0.add_assign(t.get_value().get()?); let mut t1 = E::Fr::one(); t1.sub_assign(c.get_value().get()?); match t1.inverse() { Some(t1) => { t0.mul_assign(&t1); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; cs.enforce( || "y3 computation", |lc| lc + one - c.get_variable(), |lc| lc + y3.get_variable(), |lc| lc + t.get_variable() - a.get_variable() - a.get_variable(), ); Ok(EdwardsPoint { x: x3, y: y3 }) } /// Perform addition between any two points pub fn add<CS>( &self, mut cs: CS, other: &Self, params: &E::Params, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // Compute U = (x1 + y1) * (x2 + y2) let u = AllocatedNum::alloc(cs.namespace(|| "U"), || { let mut t0 = *self.x.get_value().get()?; t0.add_assign(self.y.get_value().get()?); let mut t1 = *other.x.get_value().get()?; t1.add_assign(other.y.get_value().get()?); t0.mul_assign(&t1); Ok(t0) })?; cs.enforce( || "U computation", |lc| lc + self.x.get_variable() + self.y.get_variable(), |lc| lc + other.x.get_variable() + other.y.get_variable(), |lc| lc + u.get_variable(), ); // Compute A = y2 * x1 let a = other.y.mul(cs.namespace(|| "A computation"), &self.x)?; // Compute B = x2 * y1 let b = other.x.mul(cs.namespace(|| "B computation"), &self.y)?; // Compute C = d*A*B let c = AllocatedNum::alloc(cs.namespace(|| "C"), || { let mut t0 = *a.get_value().get()?; t0.mul_assign(b.get_value().get()?); t0.mul_assign(params.edwards_d()); Ok(t0) })?; cs.enforce( || "C computation", |lc| lc + (*params.edwards_d(), a.get_variable()), |lc| lc + b.get_variable(), |lc| lc + c.get_variable(), ); // Compute x3 = (A + B) / (1 + C) let x3 = AllocatedNum::alloc(cs.namespace(|| "x3"), || { let mut t0 = *a.get_value().get()?; t0.add_assign(b.get_value().get()?); let mut t1 = E::Fr::one(); t1.add_assign(c.get_value().get()?); match t1.inverse() { Some(t1) => { t0.mul_assign(&t1); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; let one = CS::one(); cs.enforce( || "x3 computation", |lc| lc + one + c.get_variable(), |lc| lc + x3.get_variable(), |lc| lc + a.get_variable() + b.get_variable(), ); // Compute y3 = (U - A - B) / (1 - C) let y3 = AllocatedNum::alloc(cs.namespace(|| "y3"), || { let mut t0 = *u.get_value().get()?; t0.sub_assign(a.get_value().get()?); t0.sub_assign(b.get_value().get()?); let mut t1 = E::Fr::one(); t1.sub_assign(c.get_value().get()?); match t1.inverse() { Some(t1) => { t0.mul_assign(&t1); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; cs.enforce( || "y3 computation", |lc| lc + one - c.get_variable(), |lc| lc + y3.get_variable(), |lc| lc + u.get_variable() - a.get_variable() - b.get_variable(), ); Ok(EdwardsPoint { x: x3, y: y3 }) } } pub struct MontgomeryPoint<E: Engine> { x: Num<E>, y: Num<E>, } impl<E: JubjubEngine> MontgomeryPoint<E> { /// Converts an element in the prime order subgroup into /// a point in the birationally equivalent twisted /// Edwards curve. pub fn into_edwards<CS>( self, mut cs: CS, params: &E::Params, ) -> Result<EdwardsPoint<E>, SynthesisError> where CS: ConstraintSystem<E>, { // Compute u = (scale*x) / y let u = AllocatedNum::alloc(cs.namespace(|| "u"), || { let mut t0 = *self.x.get_value().get()?; t0.mul_assign(params.scale()); match self.y.get_value().get()?.inverse() { Some(invy) => { t0.mul_assign(&invy); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; cs.enforce( || "u computation", |lc| lc + &self.y.lc(E::Fr::one()), |lc| lc + u.get_variable(), |lc| lc + &self.x.lc(*params.scale()), ); // Compute v = (x - 1) / (x + 1) let v = AllocatedNum::alloc(cs.namespace(|| "v"), || { let mut t0 = *self.x.get_value().get()?; let mut t1 = t0; t0.sub_assign(&E::Fr::one()); t1.add_assign(&E::Fr::one()); match t1.inverse() { Some(t1) => { t0.mul_assign(&t1); Ok(t0) } None => Err(SynthesisError::DivisionByZero), } })?; let one = CS::one(); cs.enforce( || "v computation", |lc| lc + &self.x.lc(E::Fr::one()) + one, |lc| lc + v.get_variable(), |lc| lc + &self.x.lc(E::Fr::one()) - one, ); Ok(EdwardsPoint { x: u, y: v }) } /// Interprets an (x, y) pair as a point /// in Montgomery, does not check that it's /// on the curve. Useful for constants and /// window table lookups. pub fn interpret_unchecked(x: Num<E>, y: Num<E>) -> Self { MontgomeryPoint { x, y } } /// Performs an affine point addition, not defined for /// coincident points. pub fn add<CS>( &self, mut cs: CS, other: &Self, params: &E::Params, ) -> Result<Self, SynthesisError> where CS: ConstraintSystem<E>, { // Compute lambda = (y' - y) / (x' - x) let lambda = AllocatedNum::alloc(cs.namespace(|| "lambda"), || { let mut n = *other.y.get_value().get()?; n.sub_assign(self.y.get_value().get()?); let mut d = *other.x.get_value().get()?; d.sub_assign(self.x.get_value().get()?); match d.inverse() { Some(d) => { n.mul_assign(&d); Ok(n) } None => Err(SynthesisError::DivisionByZero), } })?; cs.enforce( || "evaluate lambda", |lc| lc + &other.x.lc(E::Fr::one()) - &self.x.lc(E::Fr::one()), |lc| lc + lambda.get_variable(), |lc| lc + &other.y.lc(E::Fr::one()) - &self.y.lc(E::Fr::one()), ); // Compute x'' = lambda^2 - A - x - x' let xprime = AllocatedNum::alloc(cs.namespace(|| "xprime"), || { let mut t0 = *lambda.get_value().get()?; t0.square(); t0.sub_assign(params.montgomery_a()); t0.sub_assign(self.x.get_value().get()?); t0.sub_assign(other.x.get_value().get()?); Ok(t0) })?; // (lambda) * (lambda) = (A + x + x' + x'') let one = CS::one(); cs.enforce( || "evaluate xprime", |lc| lc + lambda.get_variable(), |lc| lc + lambda.get_variable(), |lc| { lc + (*params.montgomery_a(), one) + &self.x.lc(E::Fr::one()) + &other.x.lc(E::Fr::one()) + xprime.get_variable() }, ); // Compute y' = -(y + lambda(x' - x)) let yprime = AllocatedNum::alloc(cs.namespace(|| "yprime"), || { let mut t0 = *xprime.get_value().get()?; t0.sub_assign(self.x.get_value().get()?); t0.mul_assign(lambda.get_value().get()?); t0.add_assign(self.y.get_value().get()?); t0.negate(); Ok(t0) })?; // y' + y = lambda(x - x') cs.enforce( || "evaluate yprime", |lc| lc + &self.x.lc(E::Fr::one()) - xprime.get_variable(), |lc| lc + lambda.get_variable(), |lc| lc + yprime.get_variable() + &self.y.lc(E::Fr::one()), ); Ok(MontgomeryPoint { x: xprime.into(), y: yprime.into(), }) } } #[cfg(test)] mod test { use bellman::ConstraintSystem; use ff::{BitIterator, Field, PrimeField}; use pairing::bls12_381::{Bls12, Fr}; use rand_core::{RngCore, SeedableRng}; use rand_xorshift::XorShiftRng; use bellman::gadgets::test::*; use zcash_primitives::jubjub::fs::Fs; use zcash_primitives::jubjub::{ edwards, montgomery, FixedGenerators, JubjubBls12, JubjubParams, }; use super::{fixed_base_multiplication, AllocatedNum, EdwardsPoint, MontgomeryPoint}; use bellman::gadgets::boolean::{AllocatedBit, Boolean}; #[test] fn test_into_edwards() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x3d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let mut cs = TestConstraintSystem::<Bls12>::new(); let p = montgomery::Point::<Bls12, _>::rand(rng, params); let (u, v) = edwards::Point::from_montgomery(&p, params).to_xy(); let (x, y) = p.to_xy().unwrap(); let numx = AllocatedNum::alloc(cs.namespace(|| "mont x"), || Ok(x)).unwrap(); let numy = AllocatedNum::alloc(cs.namespace(|| "mont y"), || Ok(y)).unwrap(); let p = MontgomeryPoint::interpret_unchecked(numx.into(), numy.into()); let q = p.into_edwards(&mut cs, params).unwrap(); assert!(cs.is_satisfied()); assert!(q.x.get_value().unwrap() == u); assert!(q.y.get_value().unwrap() == v); cs.set("u/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied().unwrap(), "u computation"); cs.set("u/num", u); assert!(cs.is_satisfied()); cs.set("v/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied().unwrap(), "v computation"); cs.set("v/num", v); assert!(cs.is_satisfied()); } } #[test] fn test_interpret() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let p = edwards::Point::<Bls12, _>::rand(rng, &params); let mut cs = TestConstraintSystem::<Bls12>::new(); let q = EdwardsPoint::witness(&mut cs, Some(p.clone()), &params).unwrap(); let p = p.to_xy(); assert!(cs.is_satisfied()); assert_eq!(q.x.get_value().unwrap(), p.0); assert_eq!(q.y.get_value().unwrap(), p.1); } for _ in 0..100 { let p = edwards::Point::<Bls12, _>::rand(rng, &params); let (x, y) = p.to_xy(); let mut cs = TestConstraintSystem::<Bls12>::new(); let numx = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x)).unwrap(); let numy = AllocatedNum::alloc(cs.namespace(|| "y"), || Ok(y)).unwrap(); let p = EdwardsPoint::interpret(&mut cs, &numx, &numy, &params).unwrap(); assert!(cs.is_satisfied()); assert_eq!(p.x.get_value().unwrap(), x); assert_eq!(p.y.get_value().unwrap(), y); } // Random (x, y) are unlikely to be on the curve. for _ in 0..100 { let x = Fr::random(rng); let y = Fr::random(rng); let mut cs = TestConstraintSystem::<Bls12>::new(); let numx = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x)).unwrap(); let numy = AllocatedNum::alloc(cs.namespace(|| "y"), || Ok(y)).unwrap(); EdwardsPoint::interpret(&mut cs, &numx, &numy, &params).unwrap(); assert_eq!(cs.which_is_unsatisfied().unwrap(), "on curve check"); } } #[test] fn test_edwards_fixed_base_multiplication() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let mut cs = TestConstraintSystem::<Bls12>::new(); let p = params.generator(FixedGenerators::NoteCommitmentRandomness); let s = Fs::random(rng); let q = p.mul(s, params); let (x1, y1) = q.to_xy(); let mut s_bits = BitIterator::new(s.into_repr()).collect::<Vec<_>>(); s_bits.reverse(); s_bits.truncate(Fs::NUM_BITS as usize); let s_bits = s_bits .into_iter() .enumerate() .map(|(i, b)| { AllocatedBit::alloc(cs.namespace(|| format!("scalar bit {}", i)), Some(b)) .unwrap() }) .map(|v| Boolean::from(v)) .collect::<Vec<_>>(); let q = fixed_base_multiplication( cs.namespace(|| "multiplication"), FixedGenerators::NoteCommitmentRandomness, &s_bits, params, ) .unwrap(); assert_eq!(q.x.get_value().unwrap(), x1); assert_eq!(q.y.get_value().unwrap(), y1); } } #[test] fn test_edwards_multiplication() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let mut cs = TestConstraintSystem::<Bls12>::new(); let p = edwards::Point::<Bls12, _>::rand(rng, params); let s = Fs::random(rng); let q = p.mul(s, params); let (x0, y0) = p.to_xy(); let (x1, y1) = q.to_xy(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); let p = EdwardsPoint { x: num_x0, y: num_y0, }; let mut s_bits = BitIterator::new(s.into_repr()).collect::<Vec<_>>(); s_bits.reverse(); s_bits.truncate(Fs::NUM_BITS as usize); let s_bits = s_bits .into_iter() .enumerate() .map(|(i, b)| { AllocatedBit::alloc(cs.namespace(|| format!("scalar bit {}", i)), Some(b)) .unwrap() }) .map(|v| Boolean::from(v)) .collect::<Vec<_>>(); let q = p .mul(cs.namespace(|| "scalar mul"), &s_bits, params) .unwrap(); assert!(cs.is_satisfied()); assert_eq!(q.x.get_value().unwrap(), x1); assert_eq!(q.y.get_value().unwrap(), y1); } } #[test] fn test_conditionally_select() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..1000 { let mut cs = TestConstraintSystem::<Bls12>::new(); let p = edwards::Point::<Bls12, _>::rand(rng, params); let (x0, y0) = p.to_xy(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); let p = EdwardsPoint { x: num_x0, y: num_y0, }; let mut should_we_select = rng.next_u32() % 2 != 0; // Conditionally allocate let mut b = if rng.next_u32() % 2 != 0 { Boolean::from( AllocatedBit::alloc(cs.namespace(|| "condition"), Some(should_we_select)) .unwrap(), ) } else { Boolean::constant(should_we_select) }; // Conditionally negate if rng.next_u32() % 2 != 0 { b = b.not(); should_we_select = !should_we_select; } let q = p .conditionally_select(cs.namespace(|| "select"), &b) .unwrap(); assert!(cs.is_satisfied()); if should_we_select { assert_eq!(q.x.get_value().unwrap(), x0); assert_eq!(q.y.get_value().unwrap(), y0); cs.set("select/y'/num", Fr::one()); assert_eq!(cs.which_is_unsatisfied().unwrap(), "select/y' computation"); cs.set("select/x'/num", Fr::zero()); assert_eq!(cs.which_is_unsatisfied().unwrap(), "select/x' computation"); } else { assert_eq!(q.x.get_value().unwrap(), Fr::zero()); assert_eq!(q.y.get_value().unwrap(), Fr::one()); cs.set("select/y'/num", x0); assert_eq!(cs.which_is_unsatisfied().unwrap(), "select/y' computation"); cs.set("select/x'/num", y0); assert_eq!(cs.which_is_unsatisfied().unwrap(), "select/x' computation"); } } } #[test] fn test_edwards_addition() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let p1 = edwards::Point::<Bls12, _>::rand(rng, params); let p2 = edwards::Point::<Bls12, _>::rand(rng, params); let p3 = p1.add(&p2, params); let (x0, y0) = p1.to_xy(); let (x1, y1) = p2.to_xy(); let (x2, y2) = p3.to_xy(); let mut cs = TestConstraintSystem::<Bls12>::new(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); let num_x1 = AllocatedNum::alloc(cs.namespace(|| "x1"), || Ok(x1)).unwrap(); let num_y1 = AllocatedNum::alloc(cs.namespace(|| "y1"), || Ok(y1)).unwrap(); let p1 = EdwardsPoint { x: num_x0, y: num_y0, }; let p2 = EdwardsPoint { x: num_x1, y: num_y1, }; let p3 = p1.add(cs.namespace(|| "addition"), &p2, params).unwrap(); assert!(cs.is_satisfied()); assert!(p3.x.get_value().unwrap() == x2); assert!(p3.y.get_value().unwrap() == y2); let u = cs.get("addition/U/num"); cs.set("addition/U/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/U computation")); cs.set("addition/U/num", u); assert!(cs.is_satisfied()); let x3 = cs.get("addition/x3/num"); cs.set("addition/x3/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/x3 computation")); cs.set("addition/x3/num", x3); assert!(cs.is_satisfied()); let y3 = cs.get("addition/y3/num"); cs.set("addition/y3/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/y3 computation")); cs.set("addition/y3/num", y3); assert!(cs.is_satisfied()); } } #[test] fn test_edwards_doubling() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let p1 = edwards::Point::<Bls12, _>::rand(rng, params); let p2 = p1.double(params); let (x0, y0) = p1.to_xy(); let (x1, y1) = p2.to_xy(); let mut cs = TestConstraintSystem::<Bls12>::new(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); let p1 = EdwardsPoint { x: num_x0, y: num_y0, }; let p2 = p1.double(cs.namespace(|| "doubling"), params).unwrap(); assert!(cs.is_satisfied()); assert!(p2.x.get_value().unwrap() == x1); assert!(p2.y.get_value().unwrap() == y1); } } #[test] fn test_montgomery_addition() { let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc, 0xe5, ]); for _ in 0..100 { let p1 = loop { let x = Fr::random(rng); let s: bool = rng.next_u32() % 2 != 0; if let Some(p) = montgomery::Point::<Bls12, _>::get_for_x(x, s, params) { break p; } }; let p2 = loop { let x = Fr::random(rng); let s: bool = rng.next_u32() % 2 != 0; if let Some(p) = montgomery::Point::<Bls12, _>::get_for_x(x, s, params) { break p; } }; let p3 = p1.add(&p2, params); let (x0, y0) = p1.to_xy().unwrap(); let (x1, y1) = p2.to_xy().unwrap(); let (x2, y2) = p3.to_xy().unwrap(); let mut cs = TestConstraintSystem::<Bls12>::new(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); let num_x1 = AllocatedNum::alloc(cs.namespace(|| "x1"), || Ok(x1)).unwrap(); let num_y1 = AllocatedNum::alloc(cs.namespace(|| "y1"), || Ok(y1)).unwrap(); let p1 = MontgomeryPoint { x: num_x0.into(), y: num_y0.into(), }; let p2 = MontgomeryPoint { x: num_x1.into(), y: num_y1.into(), }; let p3 = p1.add(cs.namespace(|| "addition"), &p2, params).unwrap(); assert!(cs.is_satisfied()); assert!(p3.x.get_value().unwrap() == x2); assert!(p3.y.get_value().unwrap() == y2); cs.set("addition/yprime/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/evaluate yprime")); cs.set("addition/yprime/num", y2); assert!(cs.is_satisfied()); cs.set("addition/xprime/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/evaluate xprime")); cs.set("addition/xprime/num", x2); assert!(cs.is_satisfied()); cs.set("addition/lambda/num", Fr::random(rng)); assert_eq!(cs.which_is_unsatisfied(), Some("addition/evaluate lambda")); } } }
31.700544
95
0.477558
64aa4346d16cadd6dde1bbedb2392cecaef9c66a
4,117
//! Rust bindings to the [sodium library](https://github.com/jedisct1/libsodium). //! //! Sodium is a portable implementation of Dan Bernsteins [`NaCl`: Networking and //! Cryptography library](http://nacl.cr.yp.to) //! //! For most users, if you want public-key (asymmetric) cryptography you should use //! the functions in [`crypto::box_`](crypto/box_/index.html) for encryption/decryption. //! //! If you want secret-key (symmetric) cryptography you should be using the //! functions in [`crypto::secretbox`](crypto/secretbox/index.html) for encryption/decryption. //! //! For public-key signatures you should use the functions in //! [`crypto::sign`](crypto/sign/index.html) for signature creation and verification. //! //! Unless you know what you're doing you most certainly don't want to use the //! functions in [`crypto::scalarmult`](crypto/scalarmult/index.html), //! [`crypto::stream`](crypto/stream/index.html), [`crypto::auth`](crypto/auth/index.html) and //! [`crypto::onetimeauth`](crypto/onetimeauth/index.html). //! //! ## Thread Safety //! All functions in this library are thread-safe provided that the [`init()`](fn.init.html) //! function has been called during program execution. //! //! If [`init()`](fn.init.html) hasn't been called then all functions except the random-number //! generation functions and the key-generation functions are thread-safe. //! //! # Public-key cryptography //! [`crypto::box_`](crypto/box_/index.html) //! //! [`crypto::sign`](crypto/sign/index.html) //! //! # Sealed boxes //! [`crypto::sealedbox`](crypto/sealedbox/index.html) //! //! # Secret-key cryptography //! [`crypto::secretbox`](crypto/secretbox/index.html) //! //! [`crypto::secretstream`](crypto/secretstream/index.html) //! //! [`crypto::stream`](crypto/stream/index.html) //! //! [`crypto::auth`](crypto/auth/index.html) //! //! [`crypto::onetimeauth`](crypto/onetimeauth/index.html) //! //! # Low-level functions //! [`crypto::hash`](crypto/hash/index.html) //! //! [`crypto::kdf`](crypto/kdf/index.html) //! //! [`crypto::verify`](crypto/verify/index.html) //! //! [`crypto::shorthash`](crypto/shorthash/index.html) #![crate_name = "sodiumoxide"] #![crate_type = "lib"] #![warn(missing_docs)] #![warn(non_upper_case_globals)] #![warn(non_camel_case_types)] #![warn(unused_qualifications)] #![cfg_attr(not(feature = "std"), no_std)] #![deny(clippy::all)] // Remove this after https://github.com/sodiumoxide/sodiumoxide/issues/221 is done #![allow(clippy::result_unit_err)] extern crate libsodium_sys as ffi; extern crate ed25519; extern crate libc; #[cfg(any(test, feature = "serde"))] extern crate serde; extern crate sha2; #[cfg(not(feature = "std"))] #[macro_use] extern crate alloc; #[cfg(all(test, not(feature = "std")))] extern crate std; #[cfg(all(not(test), not(feature = "std")))] mod std { pub use core::{cmp, fmt, hash, iter, mem, ops, ptr, slice, str}; } #[cfg(not(feature = "std"))] mod prelude { pub use alloc::string::String; pub use alloc::string::ToString; pub use alloc::vec::Vec; } /// `init()` initializes the sodium library and chooses faster versions of /// the primitives if possible. `init()` also makes the random number generation /// functions (`gen_key`, `gen_keypair`, `gen_nonce`, `randombytes`, `randombytes_into`) /// thread-safe /// /// `init()` returns `Ok` if initialization succeeded and `Err` if it failed. pub fn init() -> Result<(), ()> { if unsafe { ffi::sodium_init() } >= 0 { Ok(()) } else { Err(()) } } #[macro_use] mod newtype_macros; pub mod base64; pub mod hex; pub mod padding; pub mod randombytes; pub mod utils; pub mod version; pub mod vrf; #[cfg(test)] mod test_utils; /// Cryptographic functions pub mod crypto { pub mod aead; pub mod auth; pub mod box_; pub mod generichash; pub mod hash; pub mod kdf; pub mod kx; mod nonce; pub mod onetimeauth; pub mod pwhash; pub mod scalarmult; pub mod sealedbox; pub mod secretbox; pub mod secretstream; pub mod shorthash; pub mod sign; pub mod stream; pub mod verify; }
29.618705
94
0.67452
161567c886154cf554cfdfc49b55b4497fbb358a
73
use rustc_serialize; pub mod action; pub mod progstate; pub mod record;
12.166667
20
0.780822
e525b3954f5edf8863f569b7f192f2acc17c0979
569
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn f(_: &[f32]) {} fn main() { ()[f(&[1.0])]; //~^ ERROR cannot index a value of type `()` }
33.470588
68
0.688928
9199a8d536ce4063626b3e927a6a72be3b2cfb91
4,229
extern crate serde; use self::serde::de::value::{MapDeserializer, SeqDeserializer}; use self::serde::de::{ Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor, }; use self::serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use std::fmt::{self, Formatter}; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; use IndexMap; /// Requires crate feature `"serde-1"` impl<K, V, S> Serialize for IndexMap<K, V, S> where K: Serialize + Hash + Eq, V: Serialize, S: BuildHasher, { fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error> where T: Serializer, { let mut map_serializer = serializer.serialize_map(Some(self.len()))?; for (key, value) in self { map_serializer.serialize_entry(key, value)?; } map_serializer.end() } } struct IndexMapVisitor<K, V, S>(PhantomData<(K, V, S)>); impl<'de, K, V, S> Visitor<'de> for IndexMapVisitor<K, V, S> where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, S: Default + BuildHasher, { type Value = IndexMap<K, V, S>; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { write!(formatter, "a map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut values = IndexMap::with_capacity_and_hasher(map.size_hint().unwrap_or(0), S::default()); while let Some((key, value)) = map.next_entry()? { values.insert(key, value); } Ok(values) } } /// Requires crate feature `"serde-1"` impl<'de, K, V, S> Deserialize<'de> for IndexMap<K, V, S> where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, S: Default + BuildHasher, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_map(IndexMapVisitor(PhantomData)) } } impl<'de, K, V, S, E> IntoDeserializer<'de, E> for IndexMap<K, V, S> where K: IntoDeserializer<'de, E> + Eq + Hash, V: IntoDeserializer<'de, E>, S: BuildHasher, E: Error, { type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>; fn into_deserializer(self) -> Self::Deserializer { MapDeserializer::new(self.into_iter()) } } use IndexSet; /// Requires crate feature `"serde-1"` impl<T, S> Serialize for IndexSet<T, S> where T: Serialize + Hash + Eq, S: BuildHasher, { fn serialize<Se>(&self, serializer: Se) -> Result<Se::Ok, Se::Error> where Se: Serializer, { let mut set_serializer = serializer.serialize_seq(Some(self.len()))?; for value in self { set_serializer.serialize_element(value)?; } set_serializer.end() } } struct IndexSetVisitor<T, S>(PhantomData<(T, S)>); impl<'de, T, S> Visitor<'de> for IndexSetVisitor<T, S> where T: Deserialize<'de> + Eq + Hash, S: Default + BuildHasher, { type Value = IndexSet<T, S>; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { write!(formatter, "a set") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let mut values = IndexSet::with_capacity_and_hasher(seq.size_hint().unwrap_or(0), S::default()); while let Some(value) = seq.next_element()? { values.insert(value); } Ok(values) } } /// Requires crate feature `"serde-1"` impl<'de, T, S> Deserialize<'de> for IndexSet<T, S> where T: Deserialize<'de> + Eq + Hash, S: Default + BuildHasher, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(IndexSetVisitor(PhantomData)) } } impl<'de, T, S, E> IntoDeserializer<'de, E> for IndexSet<T, S> where T: IntoDeserializer<'de, E> + Eq + Hash, S: BuildHasher, E: Error, { type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; fn into_deserializer(self) -> Self::Deserializer { SeqDeserializer::new(self.into_iter()) } }
25.475904
91
0.608182
e57a98803d5149e5238267de213499d6e05bcf1b
7,837
//extern crate serde; //extern crate toml; use serde::ser::Serialize; use std::prelude::v1::*; const NO_PRETTY: &'static str = "\ [example] array = [\"item 1\", \"item 2\"] empty = [] oneline = \"this has no newlines.\" text = \"\\nthis is the first line\\nthis is the second line\\n\" "; //#[test] pub fn no_pretty() { let toml = NO_PRETTY; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); value .serialize(&mut toml::Serializer::new(&mut result)) .unwrap(); println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } //#[test] pub fn disable_pretty() { let toml = NO_PRETTY; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::pretty(&mut result); serializer.pretty_string(false); serializer.pretty_array(false); value.serialize(&mut serializer).unwrap(); } println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } const PRETTY_STD: &'static str = "\ [example] array = [ 'item 1', 'item 2', ] empty = [] one = ['one'] oneline = 'this has no newlines.' text = ''' this is the first line this is the second line ''' "; //#[test] pub fn pretty_std() { let toml = PRETTY_STD; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); value .serialize(&mut toml::Serializer::pretty(&mut result)) .unwrap(); println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } const PRETTY_INDENT_2: &'static str = "\ [example] array = [ 'item 1', 'item 2', ] empty = [] one = ['one'] oneline = 'this has no newlines.' text = ''' this is the first line this is the second line ''' three = [ 'one', 'two', 'three', ] "; //#[test] pub fn pretty_indent_2() { let toml = PRETTY_INDENT_2; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::pretty(&mut result); serializer.pretty_array_indent(2); value.serialize(&mut serializer).unwrap(); } println!(">> Result:\n{}", result); assert_eq!(toml, &result); } const PRETTY_INDENT_2_OTHER: &'static str = "\ [example] array = [ \"item 1\", \"item 2\", ] empty = [] oneline = \"this has no newlines.\" text = \"\\nthis is the first line\\nthis is the second line\\n\" "; //#[test] /// Test pretty indent when gotten the other way pub fn pretty_indent_2_other() { let toml = PRETTY_INDENT_2_OTHER; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::new(&mut result); serializer.pretty_array_indent(2); value.serialize(&mut serializer).unwrap(); } assert_eq!(toml, &result); } const PRETTY_ARRAY_NO_COMMA: &'static str = "\ [example] array = [ \"item 1\", \"item 2\" ] empty = [] oneline = \"this has no newlines.\" text = \"\\nthis is the first line\\nthis is the second line\\n\" "; //#[test] /// Test pretty indent when gotten the other way pub fn pretty_indent_array_no_comma() { let toml = PRETTY_ARRAY_NO_COMMA; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::new(&mut result); serializer.pretty_array_trailing_comma(false); value.serialize(&mut serializer).unwrap(); } assert_eq!(toml, &result); } const PRETTY_NO_STRING: &'static str = "\ [example] array = [ \"item 1\", \"item 2\", ] empty = [] oneline = \"this has no newlines.\" text = \"\\nthis is the first line\\nthis is the second line\\n\" "; //#[test] /// Test pretty indent when gotten the other way pub fn pretty_no_string() { let toml = PRETTY_NO_STRING; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::pretty(&mut result); serializer.pretty_string(false); value.serialize(&mut serializer).unwrap(); } assert_eq!(toml, &result); } const PRETTY_TRICKY: &'static str = r##"[example] f = "\f" glass = ''' Nothing too unusual, except that I can eat glass in: - Greek: Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. - Polish: Mogę jeść szkło, i mi nie szkodzi. - Hindi: मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती. - Japanese: 私はガラスを食べられます。それは私を傷つけません。 ''' r = "\r" r_newline = """ \r """ single = '''this is a single line but has '' cuz it's tricky''' single_tricky = "single line with ''' in it" tabs = ''' this is pretty standard except for some tabs right here ''' text = """ this is the first line. This has a ''' in it and \"\"\" cuz it's tricky yo Also ' and \" because why not this is the fourth line """ "##; //#[test] pub fn pretty_tricky() { let toml = PRETTY_TRICKY; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); value .serialize(&mut toml::Serializer::pretty(&mut result)) .unwrap(); println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } const PRETTY_TABLE_ARRAY: &'static str = r##"[[array]] key = 'foo' [[array]] key = 'bar' [abc] doc = 'this is a table' [example] single = 'this is a single line string' "##; //#[test] pub fn pretty_table_array() { let toml = PRETTY_TABLE_ARRAY; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); value .serialize(&mut toml::Serializer::pretty(&mut result)) .unwrap(); println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } const TABLE_ARRAY: &'static str = r##"[[array]] key = "foo" [[array]] key = "bar" [abc] doc = "this is a table" [example] single = "this is a single line string" "##; //#[test] pub fn table_array() { let toml = TABLE_ARRAY; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); value .serialize(&mut toml::Serializer::new(&mut result)) .unwrap(); println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); } const PRETTY_TRICKY_NON_LITERAL: &'static str = r##"[example] f = "\f" glass = """ Nothing too unusual, except that I can eat glass in: - Greek: Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. - Polish: Mogę jeść szkło, i mi nie szkodzi. - Hindi: मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती. - Japanese: 私はガラスを食べられます。それは私を傷つけません。 """ plain = """ This has a couple of lines Because it likes to. """ r = "\r" r_newline = """ \r """ single = "this is a single line but has '' cuz it's tricky" single_tricky = "single line with ''' in it" tabs = """ this is pretty standard \texcept for some \ttabs right here """ text = """ this is the first line. This has a ''' in it and \"\"\" cuz it's tricky yo Also ' and \" because why not this is the fourth line """ "##; //#[test] pub fn pretty_tricky_non_literal() { let toml = PRETTY_TRICKY_NON_LITERAL; let value: toml::Value = toml::from_str(toml).unwrap(); let mut result = String::with_capacity(128); { let mut serializer = toml::Serializer::pretty(&mut result); serializer.pretty_string_literal(false); value.serialize(&mut serializer).unwrap(); } println!("EXPECTED:\n{}", toml); println!("\nRESULT:\n{}", result); assert_eq!(toml, &result); }
24.800633
67
0.622177
2ffd8b0699523a2414aeae89843c717f6f78d46b
206
spirv_interop::reflect!(mod reflect_test: "src/bin/reflect_test.vert.spv"); fn main() { dbg!(reflect_test::ENTRY_POINTS); dbg!(reflect_test::UNIFORM_VARS); dbg!(reflect_test::input_attrs()); }
25.75
75
0.708738