text:
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::string::ToString;

use indy_api_types::{CommandHandle, PoolHandle, WalletHandle};
use indy_api_types::errors::prelude::*;
use indy_utils::next_command_handle;
use rust_base58::ToBase58;
use serde_json;
use serde_json::Value;

use indy_wallet::{RecordOptions, WalletService};

use crate::api::ledger::{CustomFree, CustomTransactionParser};
use crate::commands::{BoxedCallbackStringStringSend, Command, CommandExecutor};
use crate::domain::anoncreds::credential_definition::{CredentialDefinition, CredentialDefinitionId, CredentialDefinitionV1};
use crate::domain::anoncreds::revocation_registry_definition::{RevocationRegistryDefinition, RevocationRegistryDefinitionV1, RevocationRegistryId};
use crate::domain::anoncreds::revocation_registry_delta::{RevocationRegistryDelta, RevocationRegistryDeltaV1};
use crate::domain::anoncreds::schema::{Schema, SchemaId, SchemaV1};
use crate::domain::crypto::did::{Did, DidValue};
use crate::domain::crypto::key::Key;
use crate::domain::ledger::auth_rule::{AuthRules, Constraint};
use crate::domain::ledger::author_agreement::{AcceptanceMechanisms, GetTxnAuthorAgreementData};
use crate::domain::ledger::node::NodeOperationData;
use crate::domain::ledger::pool::Schedule;
use crate::domain::ledger::request::Request;
use crate::services::crypto::CryptoService;
use crate::services::ledger::LedgerService;
use crate::services::pool::{
    parse_response_metadata,
    PoolService
};
use crate::utils::crypto::signature_serializer::serialize_signature;

pub enum LedgerCommand {
    SignAndSubmitRequest(
        PoolHandle, // pool handle
        WalletHandle,
        DidValue, // submitter did
        String, // request json
        Box<dyn Fn(IndyResult<String>) + Send>),
    SubmitRequest(
        PoolHandle, // pool handle
        String, // request json
        Box<dyn Fn(IndyResult<String>) + Send>),
    SubmitAck(
        CommandHandle,
        IndyResult<String>, // result json or error
    ),
    SubmitAction(
        PoolHandle, // pool handle
        String, // request json
        Option<String>, // nodes
        Option<i32>, // timeout
        Box<dyn Fn(IndyResult<String>) + Send>),
    SignRequest(
        WalletHandle,
        DidValue, // submitter did
        String, // request json
        Box<dyn Fn(IndyResult<String>) + Send>),
    MultiSignRequest(
        WalletHandle,
        DidValue, // submitter did
        String, // request json
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetDdoRequest(
        Option<DidValue>, // submitter did
        DidValue, // target did
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildNymRequest(
        DidValue, // submitter did
        DidValue, // target did
        Option<String>, // verkey
        Option<String>, // alias
        Option<String>, // role
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildAttribRequest(
        DidValue, // submitter did
        DidValue, // target did
        Option<String>, // hash
        Option<serde_json::Value>, // raw
        Option<String>, // enc
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetAttribRequest(
        Option<DidValue>, // submitter did
        DidValue, // target did
        Option<String>, // raw
        Option<String>, // hash
        Option<String>, // enc
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetNymRequest(
        Option<DidValue>, // submitter did
        DidValue, // target did
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetNymResponse(
        String, // get nym response json
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildSchemaRequest(
        DidValue, // submitter did
        Schema, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetSchemaRequest(
        Option<DidValue>, // submitter did
        SchemaId, // id
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetSchemaResponse(
        String, // get schema response json
        BoxedCallbackStringStringSend),
    BuildCredDefRequest(
        DidValue, // submitter did
        CredentialDefinition, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetCredDefRequest(
        Option<DidValue>, // submitter did
        CredentialDefinitionId, // id
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetCredDefResponse(
        String, // get cred definition response
        BoxedCallbackStringStringSend),
    BuildNodeRequest(
        DidValue, // submitter did
        DidValue, // target_did
        NodeOperationData, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetValidatorInfoRequest(
        DidValue, // submitter did
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetTxnRequest(
        Option<DidValue>, // submitter did
        Option<String>, // ledger type
        i32, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildPoolConfigRequest(
        DidValue, // submitter did
        bool, // writes
        bool, // force
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildPoolRestartRequest(
        DidValue, //submitter did
        String, //action
        Option<String>, //datetime
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildPoolUpgradeRequest(
        DidValue, // submitter did
        String, // name
        String, // version
        String, // action
        String, // sha256
        Option<u32>, // timeout
        Option<Schedule>, // schedule
        Option<String>, // justification
        bool, // reinstall
        bool, // force
        Option<String>, // package
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildRevocRegDefRequest(
        DidValue, // submitter did
        RevocationRegistryDefinition, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetRevocRegDefRequest(
        Option<DidValue>, // submitter did
        RevocationRegistryId, // revocation registry definition id
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetRevocRegDefResponse(
        String, // get revocation registry definition response
        BoxedCallbackStringStringSend),
    BuildRevocRegEntryRequest(
        DidValue, // submitter did
        RevocationRegistryId, // revocation registry definition id
        String, // revocation registry definition type
        RevocationRegistryDelta, // value
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetRevocRegRequest(
        Option<DidValue>, // submitter did
        RevocationRegistryId, // revocation registry definition id
        i64, // timestamp
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetRevocRegResponse(
        String, // get revocation registry response
        Box<dyn Fn(IndyResult<(String, String, u64)>) + Send>),
    BuildGetRevocRegDeltaRequest(
        Option<DidValue>, // submitter did
        RevocationRegistryId, // revocation registry definition id
        Option<i64>, // from
        i64, // to
        Box<dyn Fn(IndyResult<String>) + Send>),
    ParseGetRevocRegDeltaResponse(
        String, // get revocation registry delta response
        Box<dyn Fn(IndyResult<(String, String, u64)>) + Send>),
    RegisterSPParser(
        String, // txn type
        CustomTransactionParser,
        CustomFree,
        Box<dyn Fn(IndyResult<()>) + Send>),
    GetResponseMetadata(
        String, // response
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildAuthRuleRequest(
        DidValue, // submitter did
        String, // auth type
        String, // auth action
        String, // field
        Option<String>, // old value
        Option<String>, // new value
        Constraint, // constraint
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildAuthRulesRequest(
        DidValue, // submitter did
        AuthRules, // auth rules
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetAuthRuleRequest(
        Option<DidValue>, // submitter did
        Option<String>, // auth type
        Option<String>, // auth action
        Option<String>, // field
        Option<String>, // old value
        Option<String>, // new value
        Box<dyn Fn(IndyResult<String>) + Send>),
    GetSchema(
        PoolHandle,
        Option<DidValue>,
        SchemaId,
        BoxedCallbackStringStringSend,
    ),
    GetSchemaContinue(
        SchemaId,
        IndyResult<String>,
        CommandHandle,
    ),
    GetCredDef(
        PoolHandle,
        Option<DidValue>,
        CredentialDefinitionId,
        BoxedCallbackStringStringSend,
    ),
    GetCredDefContinue(
        CredentialDefinitionId,
        IndyResult<String>,
        CommandHandle,
    ),
    BuildTxnAuthorAgreementRequest(
        DidValue, // submitter did
        Option<String>, // text
        String, // version
        Option<u64>,   // ratification date
        Option<u64>,   // retirement date
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildDisableAllTxnAuthorAgreementsRequest(
        DidValue, // submitter did
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetTxnAuthorAgreementRequest(
        Option<DidValue>, // submitter did
        Option<GetTxnAuthorAgreementData>, // data
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildAcceptanceMechanismRequests(
        DidValue, // submitter did
        AcceptanceMechanisms, // aml
        String, // version
        Option<String>, // aml context
        Box<dyn Fn(IndyResult<String>) + Send>),
    BuildGetAcceptanceMechanismsRequest(
        Option<DidValue>, // submitter did
        Option<u64>, // timestamp
        Option<String>, // version
        Box<dyn Fn(IndyResult<String>) + Send>),
    AppendTxnAuthorAgreementAcceptanceToRequest(
        String, // request json
        Option<String>, // text
        Option<String>, // version
        Option<String>, // hash
        String, // acceptance mechanism type
        u64, // time of acceptance
        Box<dyn Fn(IndyResult<String>) + Send>),
    AppendRequestEndorser(
        String, // request json
        DidValue, // endorser did
        Box<dyn Fn(IndyResult<String>) + Send>),
}

pub struct LedgerCommandExecutor {
    pool_service: Rc<PoolService>,
    crypto_service: Rc<CryptoService>,
    wallet_service: Rc<WalletService>,
    ledger_service: Rc<LedgerService>,

    send_callbacks: RefCell<HashMap<CommandHandle, Box<dyn Fn(IndyResult<String>)>>>,
    pending_callbacks: RefCell<HashMap<CommandHandle, Box<dyn Fn(IndyResult<(String, String)>)>>>,
}

impl LedgerCommandExecutor {
    pub fn new(pool_service: Rc<PoolService>,
               crypto_service: Rc<CryptoService>,
               wallet_service: Rc<WalletService>,
               ledger_service: Rc<LedgerService>) -> LedgerCommandExecutor {
        LedgerCommandExecutor {
            pool_service,
            crypto_service,
            wallet_service,
            ledger_service,
            send_callbacks: RefCell::new(HashMap::new()),
            pending_callbacks: RefCell::new(HashMap::new()),
        }
    }

    pub fn execute(&self, command: LedgerCommand) {
        match command {
            LedgerCommand::SignAndSubmitRequest(pool_handle, wallet_handle, submitter_did, request_json, cb) => {
                debug!(target: "ledger_command_executor", "SignAndSubmitRequest command received");
                self.sign_and_submit_request(pool_handle, wallet_handle, &submitter_did, &request_json, cb);
            }
            LedgerCommand::SubmitRequest(handle, request_json, cb) => {
                debug!(target: "ledger_command_executor", "SubmitRequest command received");
                self.submit_request(handle, &request_json, cb);
            }
            LedgerCommand::SubmitAck(handle, result) => {
                debug!(target: "ledger_command_executor", "SubmitAck command received");
                match self.send_callbacks.borrow_mut().remove(&handle) {
                    Some(cb) => cb(result.map_err(IndyError::from)),
                    None => {
                        error!("Can't process LedgerCommand::SubmitAck for handle {:?} with result {:?} - appropriate callback not found!",
                               handle, result);
                    }
                }
            }
            LedgerCommand::SubmitAction(handle, request_json, nodes, timeout, cb) => {
                debug!(target: "ledger_command_executor", "SubmitRequest command received");
                self.submit_action(handle, &request_json, nodes.as_ref().map(String::as_str), timeout, cb);
            }
            LedgerCommand::RegisterSPParser(txn_type, parser, free, cb) => {
                debug!(target: "ledger_command_executor", "RegisterSPParser command received");
                cb(self.register_sp_parser(&txn_type, parser, free));
            }
            LedgerCommand::SignRequest(wallet_handle, submitter_did, request_json, cb) => {
                debug!(target: "ledger_command_executor", "SignRequest command received");
                cb(self.sign_request(wallet_handle, &submitter_did, &request_json));
            }
            LedgerCommand::MultiSignRequest(wallet_handle, submitter_did, request_json, cb) => {
                debug!(target: "ledger_command_executor", "MultiSignRequest command received");
                cb(self.multi_sign_request(wallet_handle, &submitter_did, &request_json));
            }
            LedgerCommand::BuildGetDdoRequest(submitter_did, target_did, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetDdoRequest command received");
                cb(self.build_get_ddo_request(submitter_did.as_ref(), &target_did));
            }
            LedgerCommand::BuildNymRequest(submitter_did, target_did, verkey, alias, role, cb) => {
                debug!(target: "ledger_command_executor", "BuildNymRequest command received");
                cb(self.build_nym_request(&submitter_did, &target_did,
                                          verkey.as_ref().map(String::as_str),
                                          alias.as_ref().map(String::as_str),
                                          role.as_ref().map(String::as_str)));
            }
            LedgerCommand::BuildAttribRequest(submitter_did, target_did, hash, raw, enc, cb) => {
                debug!(target: "ledger_command_executor", "BuildAttribRequest command received");
                cb(self.build_attrib_request(&submitter_did, &target_did,
                                             hash.as_ref().map(String::as_str),
                                             raw.as_ref(),
                                             enc.as_ref().map(String::as_str)));
            }
            LedgerCommand::BuildGetAttribRequest(submitter_did, target_did, raw, hash, enc, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetAttribRequest command received");
                cb(self.build_get_attrib_request(submitter_did.as_ref(), &target_did,
                                                 raw.as_ref().map(String::as_str),
                                                 hash.as_ref().map(String::as_str),
                                                 enc.as_ref().map(String::as_str)));
            }
            LedgerCommand::BuildGetNymRequest(submitter_did, target_did, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetNymRequest command received");
                cb(self.build_get_nym_request(submitter_did.as_ref(), &target_did));
            }
            LedgerCommand::ParseGetNymResponse(get_nym_response, cb) => {
                info!(target: "ledger_command_executor", "ParseGetNymResponse command received");
                cb(self.parse_get_nym_response(&get_nym_response));
            }
            LedgerCommand::BuildSchemaRequest(submitter_did, data, cb) => {
                debug!(target: "ledger_command_executor", "BuildSchemaRequest command received");
                cb(self.build_schema_request(&submitter_did, SchemaV1::from(data)));
            }
            LedgerCommand::BuildGetSchemaRequest(submitter_did, id, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetSchemaRequest command received");
                cb(self.build_get_schema_request(submitter_did.as_ref(), &id));
            }
            LedgerCommand::ParseGetSchemaResponse(get_schema_response, cb) => {
                debug!(target: "ledger_command_executor", "ParseGetSchemaResponse command received");
                cb(self.parse_get_schema_response(&get_schema_response));
            }
            LedgerCommand::BuildCredDefRequest(submitter_did, data, cb) => {
                debug!(target: "ledger_command_executor", "BuildCredDefRequest command received");
                cb(self.build_cred_def_request(&submitter_did, CredentialDefinitionV1::from(data)));
            }
            LedgerCommand::BuildGetCredDefRequest(submitter_did, id, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetCredDefRequest command received");
                cb(self.build_get_cred_def_request(submitter_did.as_ref(), &id));
            }
            LedgerCommand::ParseGetCredDefResponse(get_cred_def_response, cb) => {
                debug!(target: "ledger_command_executor", "ParseGetCredDefResponse command received");
                cb(self.parse_get_cred_def_response(&get_cred_def_response));
            }
            LedgerCommand::BuildNodeRequest(submitter_did, target_did, data, cb) => {
                debug!(target: "ledger_command_executor", "BuildNodeRequest command received");
                cb(self.build_node_request(&submitter_did, &target_did, data));
            }
            LedgerCommand::BuildGetValidatorInfoRequest(submitter_did, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetValidatorInfoRequest command received");
                cb(self.build_get_validator_info_request(&submitter_did));
            }
            LedgerCommand::BuildGetTxnRequest(submitter_did, ledger_type, seq_no, cb) => {
                debug!(target: "ledger_command_executor", "BuildGetTxnRequest command received");
                cb(self.build_get_txn_request(submitter_did.as_ref(), ledger_type.as_ref().map(String::as_str), seq_no));
            }
            LedgerCommand::BuildPoolConfigRequest(submitter_did, writes, force, cb) => {
                debug!(target: "ledger_command_executor", "BuildPoolConfigRequest command received");
                cb(self.build_pool_config_request(&submitter_did, writes, force));
            }
            LedgerCommand::BuildPoolRestartRequest(submitter_did, action, datetime, cb) => {
                debug!(target: "ledger_command_executor", "BuildPoolRestartRequest command received");
                cb(self.build_pool_restart_request(&submitter_did, &action, datetime.as_ref().map(String::as_str)));
            }
            LedgerCommand::BuildPoolUpgradeRequest(submitter_did, name, version, action, sha256, timeout, schedule, justification, reinstall, force, package, cb) => {
                debug!(target: "ledger_command_executor", "BuildPoolUpgradeRequest command received");
                cb(self.build_pool_upgrade_request(&submitter_did, &name, &version, &action, &sha256, timeout,
                                                   schedule,
                                                   justification.as_ref().map(String::as_str),
                                                   reinstall, force, package.as_ref().map(String::as_str)));
            }
            LedgerCommand::BuildRevocRegDefRequest(submitter_did, data, cb) => {
                debug!(target: "ledger_command_executor", "BuildRevocRegDefRequest command received");
                cb(self.build_revoc_reg_def_request(&submitter_did, RevocationRegistryDefinitionV1::from(data)));
            }
            LedgerCommand::BuildGetRevocRegDefRequest(submitter_did, id, cb) => {


text:
use azure_core::prelude::*;
use azure_storage::blob::prelude::*;
use azure_storage::core::prelude::*;
use futures::stream::StreamExt;
use std::cell::RefCell;
use std::rc::Rc;

// This example shows how to stream data from a blob. We will create a simple blob first, the we
// ask it back using streaming features of the future crate. In this simple example we just
// concatenate the data received in order to make sure the retrieved blob is equals to the one
// created in the first place.
// We do not use leases here but you definitely want to do so otherwise the returned stream
// is not guaranteed to be consistent.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let file_name = "azure_sdk_for_rust_stream_test.txt";

    // First we retrieve the account name and master key from environment variables.
    let account =
        std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
    let master_key =
        std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");

    let container_name = std::env::args()
        .nth(1)
        .expect("please specify container name as first command line parameter");

    let http_client = new_http_client();

    let storage_account_client =
        StorageAccountClient::new_access_key(http_client.clone(), &account, &master_key);
    let storage_client = storage_account_client.as_storage_client();
    let blob = storage_client
        .as_container_client(&container_name)
        .as_blob_client(file_name);

    let string = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";

    let _response = blob
        .put_block_blob(string)
        .content_type("text/plain")
        .execute()
        .await?;

    println!("{}/{} blob created!", container_name, file_name);

    // this is how you stream data from azure blob. Notice that you have
    // to specify the range requested. Also make sure to specify how big
    // a chunk is going to be. Bigger chunks are of course more efficient as the
    // http overhead will be less but it also means you will have to wait for more
    // time before receiving anything. In this example we use a very small chunk size
    // just to make sure to loop at least twice.
    let mut stream = Box::pin(blob.get().stream(128));

    let result = Rc::new(RefCell::new(Vec::new()));

    {
        let mut res_closure = result.borrow_mut();
        while let Some(value) = stream.next().await {
            let mut value = value?.data.to_vec();
            println!("received {:?} bytes", value.len());
            res_closure.append(&mut value);
        }
    }

    let returned_string = {
        let rlock = result.borrow();
        String::from_utf8(rlock.to_vec())?
    };

    // You can of course conctenate all the
    // pieces as shown below.
    // It generally does not make sense as you
    // will lose the ability to process the data as it
    // comes in.
    //
    //let fut = stream.concat2().map(|res| {
    //    println!("all blocks received");
    //    res
    //});
    //
    //let result = reactor.run(fut)?;
    //let returned_string = String::from_utf8(result)?;

    println!("{}", returned_string);

    assert!(
        string == returned_string,
        "string = {}, returned_string = {}",
        string,
        returned_string
    );

    blob.delete()
        .delete_snapshots_method(DeleteSnapshotsMethod::Include)
        .execute()
        .await?;

    Ok(())
}

domain: rust


text:
//! Ported to Rust from <https://www.shadertoy.com/view/MtX3Ws>
//!
//! Original comment:
//! ```glsl
//! // License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
//! // Created by S. Guillitte 2015
//! ```

use crate::SampleCube;
use shared::*;
use spirv_std::glam::{vec2, vec3, vec4, Mat2, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles};

// Note: This cfg is incorrect on its surface, it really should be "are we compiling with std", but
// we tie #[no_std] above to the same condition, so it's fine.
#[cfg(target_arch = "spirv")]
use spirv_std::num_traits::Float;

pub struct Inputs<C0> {
    pub resolution: Vec3,
    pub time: f32,
    pub mouse: Vec4,
    pub channel0: C0,
}

const ZOOM: f32 = 1.0;

fn _cmul(a: Vec2, b: Vec2) -> Vec2 {
    vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x)
}
fn csqr(a: Vec2) -> Vec2 {
    vec2(a.x * a.x - a.y * a.y, 2. * a.x * a.y)
}

fn rot(a: f32) -> Mat2 {
    Mat2::from_cols_array(&[a.cos(), a.sin(), -a.sin(), a.cos()])
}

//from iq
fn i_sphere(ro: Vec3, rd: Vec3, sph: Vec4) -> Vec2 {
    let oc: Vec3 = ro - sph.xyz();
    let b: f32 = oc.dot(rd);
    let c: f32 = oc.dot(oc) - sph.w * sph.w;
    let mut h: f32 = b * b - c;
    if h < 0.0 {
        return Vec2::splat(-1.0);
    }
    h = h.sqrt();
    vec2(-b - h, -b + h)
}

fn map(mut p: Vec3) -> f32 {
    let mut res: f32 = 0.0;
    let c: Vec3 = p;
    let mut i = 0;
    while i < 10 {
        p = 0.7 * p.abs() / p.dot(p) - Vec3::splat(0.7);
        p = csqr(p.yz()).extend(p.x).zxy();
        p = p.zxy();
        res += (-19.0 * p.dot(c).abs()).exp();
        i += 1;
    }
    res / 2.0
}

impl<C0: SampleCube> Inputs<C0> {
    fn raymarch(&self, ro: Vec3, rd: Vec3, tminmax: Vec2) -> Vec3 {
        let mut t: f32 = tminmax.x;
        let dt: f32 = 0.02;
        //let dt: f32 = 0.2 - 0.195 * (self.time * 0.05).cos(); //animated
        let mut col: Vec3 = Vec3::zero();
        let mut c: f32 = 0.0;
        let mut i = 0;
        while i < 64 {
            t += dt * (-2.0 * c).exp();
            if t > tminmax.y {
                break;
            }
            let _pos: Vec3 = ro + t * rd;

            c = map(ro + t * rd);

            col = 0.99 * col + 0.08 * vec3(c * c, c, c * c * c); //green

            // col = 0.99 * col + 0.08 * vec3(c * c * c, c * c, c); //blue
            i += 1;
        }
        col
    }
    pub fn main_image(&mut self, frag_color: &mut Vec4, frag_coord: Vec2) {
        let time: f32 = self.time;
        let q: Vec2 = frag_coord / self.resolution.xy();
        let mut p: Vec2 = Vec2::splat(-1.0) + 2.0 * q;
        p.x *= self.resolution.x / self.resolution.y;
        let mut m: Vec2 = Vec2::zero();
        if self.mouse.z > 0.0 {
            m = self.mouse.xy() / self.resolution.xy() * 3.14;
        }
        m = m - Vec2::splat(0.5);

        // camera

        let mut ro: Vec3 = ZOOM * Vec3::splat(4.0);
        ro = (rot(m.y).transpose() * ro.yz()).extend(ro.x).zxy();
        ro = (rot(m.x + 0.1 * time).transpose() * ro.xz())
            .extend(ro.y)
            .xzy();
        let ta: Vec3 = Vec3::zero();
        let ww: Vec3 = (ta - ro).normalize();
        let uu: Vec3 = (ww.cross(vec3(0.0, 1.0, 0.0))).normalize();
        let vv: Vec3 = (uu.cross(ww)).normalize();
        let rd: Vec3 = (p.x * uu + p.y * vv + 4.0 * ww).normalize();

        let tmm: Vec2 = i_sphere(ro, rd, vec4(0.0, 0.0, 0.0, 2.0));
        // raymarch
        let mut col: Vec3 = self.raymarch(ro, rd, tmm);
        if tmm.x < 0.0 {
            col = self.channel0.sample_cube(rd).xyz();
        } else {
            let mut nor: Vec3 = (ro + tmm.x * rd) / 2.;
            nor = rd.reflect(nor);
            let fre: f32 = (0.5 + nor.dot(rd).clamp(0.0, 1.0)).powf(3.0) * 1.3;
            col += self.channel0.sample_cube(nor).xyz() * fre;
        }

        //shade

        col = 0.5 * (Vec3::one() + col).ln();
        col = col.clamp(Vec3::zero(), Vec3::one());

        *frag_color = col.extend(1.0);
    }
}


text:
use cstr::cstr;
use dispose::defer;
#[cfg(target_arch = "x86_64")]
#[cfg(feature = "into_x86_from_x64")]
use goblin::Object;
use rust_win32error::Win32Error;
use std::{
    convert::TryInto,
    fs,
    lazy::OnceCell,
    mem::{self, MaybeUninit},
    path::{Path, PathBuf},
    ptr,
    time::Duration,
};
use u16cstr::u16cstr;
use widestring::{U16CString, U16Str};
use winapi::{
    shared::{
        minwindef::{BOOL, HMODULE, MAX_PATH},
        ntdef::LPCWSTR,
    },
    um::{
        handleapi::CloseHandle,
        minwinbase::STILL_ACTIVE,
        processthreadsapi::{CreateRemoteThread, GetExitCodeThread},
        synchapi::WaitForSingleObject,
        winbase::{INFINITE, WAIT_FAILED},
        wow64apiset::GetSystemWow64DirectoryW,
    },
};

use crate::{
    error::InjectError,
    utils::{retry_with_filter, ForeignProcessWideString},
    InjectedModule, ModuleHandle, Process, ProcessModule,
};

type LoadLibraryWFn = unsafe extern "system" fn(LPCWSTR) -> HMODULE;
type FreeLibraryFn = unsafe extern "system" fn(HMODULE) -> BOOL;

#[derive(Debug, Clone)]
struct InjectHelpData {
    kernel32_module: ModuleHandle,
    load_library_offset: usize,
    free_library_offset: usize,
}

impl InjectHelpData {
    pub fn get_load_library_fn_ptr(&self) -> LoadLibraryWFn {
        unsafe { mem::transmute(self.kernel32_module as usize + self.load_library_offset) }
    }
    pub fn get_free_library_fn_ptr(&self) -> FreeLibraryFn {
        unsafe { mem::transmute(self.kernel32_module as usize + self.free_library_offset) }
    }
}

/// An injector that can inject modules (.dll's) into processes.
/// This struct keeps internal state to allow for faster injcetions if reused.
///
/// # Example
/// ```no_run
/// use dll_syringe::{Syringe, Process};
///
/// // find target process by name
/// let target_process = Process::find_first_by_name("target_process").unwrap();
///
/// // create new syringe (reuse for better performance)
/// let syringe = Syringe::new();
///
/// // inject the payload into the target process
/// let injected_payload = syringe.inject(&target_process, "injection_payload.dll").unwrap();
///
/// // do something else
///
/// // eject the payload from the target (this is optional)
/// injected_payload.eject().unwrap();
/// ```
#[derive(Default, Debug, Clone)]
pub struct Syringe {
    x86_data: OnceCell<InjectHelpData>,
    #[cfg(target_arch = "x86_64")]
    x64_data: OnceCell<InjectHelpData>,
}

impl Syringe {
    /// Creates a new syringe.
    /// This operation is cheap as internal state is initialized lazily.
    pub fn new() -> Self {
        Self::default()
    }

    fn get_inject_help_data_for_process(
        &self,
        process: &Process,
    ) -> Result<&InjectHelpData, InjectError> {
        let is_target_x64 = !process.is_wow64()?;

        #[cfg(target_arch = "x86_64")]
        {
            if is_target_x64 {
                self.x64_data
                    .get_or_try_init(Self::load_inject_help_data_for_current_target)
            } else if cfg!(feature = "into_x86_from_x64") {
                self.x86_data
                    .get_or_try_init(|| Self::load_inject_help_data_for_process(process))
            } else {
                Err(InjectError::UnsupportedTarget)
            }
        }

        #[cfg(target_arch = "x86")]
        {
            if is_target_x64 {
                Err(InjectError::UnsupportedTarget)
            } else {
                self.x86_data
                    .get_or_try_init(Self::load_inject_help_data_for_current_target)
            }
        }
    }

    /// Inject the module at the given path into the given process.
    ///
    /// # Limitations
    /// - The target process and the given module need to be of the same bitness.
    /// - If the current process is `x64` the target process can be either `x64` (always available) or `x86` (with the `into_x86_from_x64` feature enabled).
    /// - If the current process is `x86` the target process can only be `x86`.
    pub fn inject<'a>(
        &'a self,
        process: &'a Process,
        payload_path: impl AsRef<Path>,
    ) -> Result<InjectedModule<'a>, InjectError> {
        let inject_data = self.get_inject_help_data_for_process(process)?;

        let module_path = payload_path.as_ref();
        let mut foreign_string = ForeignProcessWideString::allocate_in_process(
            process,
            U16CString::from_os_str(module_path.as_os_str())?,
        )?;

        // creating a thread that will call LoadLibraryW with a pointer to payload_path as argument
        let thread_handle = unsafe {
            CreateRemoteThread(
                process.handle(),
                ptr::null_mut(),
                0,
                Some(mem::transmute(inject_data.get_load_library_fn_ptr())),
                foreign_string.as_mut_ptr(),
                0,
                ptr::null_mut(),
            )
        };
        if thread_handle.is_null() {
            return Err(Win32Error::new().into());
        }

        // ensure handle is closed once we exit this function
        let _h = defer(|| unsafe {
            CloseHandle(thread_handle);
        });

        let reason = unsafe { WaitForSingleObject(thread_handle, INFINITE) };
        if reason == WAIT_FAILED {
            return Err(Win32Error::new().into());
        }

        let mut exit_code = MaybeUninit::uninit();
        let result = unsafe { GetExitCodeThread(thread_handle, exit_code.as_mut_ptr()) };
        if result == 0 {
            return Err(Win32Error::new().into());
        }
        assert_ne!(result, STILL_ACTIVE.try_into().unwrap());

        let exit_code = unsafe { exit_code.assume_init() };

        // reinterpret the possibly truncated exit code as a truncated handle to the loaded module
        let truncated_injected_module_handle =
            unsafe { mem::transmute::<usize, ModuleHandle>(exit_code as usize) };
        if truncated_injected_module_handle.is_null() {
            return Err(InjectError::RemoteOperationFailed);
        }

        let injected_module = process.find_module_by_path(module_path)?.unwrap();
        assert_eq!(
            injected_module.handle() as u32,
            truncated_injected_module_handle as u32
        );

        Ok(InjectedModule {
            syringe: self,
            module: injected_module,
        })
    }

    /// Ejects a previously injected module from its target process.
    pub fn eject(&self, module: InjectedModule<'_>) -> Result<(), InjectError> {
        let process = module.target_process();
        let inject_data = self.get_inject_help_data_for_process(module.target_process())?;

        let thread_handle = unsafe {
            CreateRemoteThread(
                process.handle(),
                ptr::null_mut(),
                0,
                Some(mem::transmute(inject_data.get_free_library_fn_ptr())),
                module.payload().handle().cast(),
                0,
                ptr::null_mut(),
            )
        };
        if thread_handle.is_null() {
            return Err(Win32Error::new().into());
        }

        // ensure handle is closed once we exit this function
        let _h = defer(|| unsafe {
            CloseHandle(thread_handle);
        });

        let reason = unsafe { WaitForSingleObject(thread_handle, INFINITE) };
        if reason == WAIT_FAILED {
            return Err(Win32Error::new().into());
        }

        let mut exit_code = MaybeUninit::uninit();
        let result = unsafe { GetExitCodeThread(thread_handle, exit_code.as_mut_ptr()) };
        if result == 0 {
            return Err(Win32Error::new().into());
        }
        assert_ne!(result, STILL_ACTIVE.try_into().unwrap());

        let exit_code = unsafe { exit_code.assume_init() };

        let free_library_result = unsafe { mem::transmute::<u32, BOOL>(exit_code) };
        if free_library_result == 0 {
            return Err(InjectError::RemoteOperationFailed);
        }

        assert!(!process
            .get_module_handles()?
            .as_ref()
            .contains(&module.payload().handle()));

        Ok(())
    }

    fn load_inject_help_data_for_current_target() -> Result<InjectHelpData, InjectError> {
        let kernel32_module =
            ProcessModule::__get_local_from_name_or_abs_path(u16cstr!("kernel32.dll"))?.unwrap();
        let load_library_fn_ptr = kernel32_module
            .__get_procedure(cstr!("LoadLibraryW"))
            .unwrap();
        let free_library_fn_ptr = kernel32_module
            .__get_procedure(cstr!("FreeLibrary"))
            .unwrap();

        Ok(InjectHelpData {
            kernel32_module: kernel32_module.handle(),
            load_library_offset: load_library_fn_ptr as usize - kernel32_module.handle() as usize,
            free_library_offset: free_library_fn_ptr as usize - kernel32_module.handle() as usize,
        })
    }

    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into_x86_from_x64")]
    fn load_inject_help_data_for_process(process: &Process) -> Result<InjectHelpData, InjectError> {
        // get kernel32 handle of target process
        let kernel32_module = retry_with_filter(
            || process.find_module_by_name("kernel32.dll"),
            Option::is_some,
            Duration::from_secs(1),
        )?
        .unwrap();

        // get path of kernel32 used in target process
        let kernel32_path = if process.is_wow64()? {
            // we need to manually construct the path to the kernel32.dll used in WOW64 processes
            let mut wow64_path = Self::get_wow64_dir()?;
            wow64_path.push("kernel32.dll");
            wow64_path
        } else {
            kernel32_module.get_path()?
        };

        // load the dll as a pe and extract the fn offsets
        let module_file_buffer = fs::read(kernel32_path)?;
        if let Object::PE(pe) = Object::parse(&module_file_buffer)? {
            let load_library_export = pe
                .exports
                .iter()
                .find(|export| matches!(export.name, Some("LoadLibraryW")))
                .unwrap();

            let free_library_export = pe
                .exports
                .iter()
                .find(|export| matches!(export.name, Some("FreeLibrary")))
                .unwrap();

            Ok(InjectHelpData {
                kernel32_module: kernel32_module.handle(),
                load_library_offset: load_library_export.rva,
                free_library_offset: free_library_export.rva,
            })
        } else {
            unreachable!()
        }
    }

    #[cfg(all(target_arch = "x86_64", feature = "into_x86_from_x64"))]
    fn get_wow64_dir() -> Result<PathBuf, Win32Error> {
        let mut path_buf = MaybeUninit::uninit_array::<MAX_PATH>();
        let path_buf_len: u32 = path_buf.len().try_into().unwrap();
        let result = unsafe { GetSystemWow64DirectoryW(path_buf[0].as_mut_ptr(), path_buf_len) };
        if result == 0 {
            return Err(Win32Error::new());
        }

        let path_len = result as usize;
        let path = unsafe { MaybeUninit::slice_assume_init_ref(&path_buf[..path_len]) };
        Ok(PathBuf::from(U16Str::from_slice(path).to_os_string()))
    }
}


text:
use crate::{
    class::Class,
    function::Function,
    ident::{Ident, PrivateName},
    jsx::{JSXElement, JSXEmptyExpr, JSXFragment, JSXMemberExpr, JSXNamespacedName},
    lit::{Bool, Lit, Number, Str},
    operators::{AssignOp, BinaryOp, UnaryOp, UpdateOp},
    pat::Pat,
    prop::Prop,
    stmt::BlockStmt,
    typescript::{
        TsAsExpr, TsNonNullExpr, TsTypeAnn, TsTypeAssertion, TsTypeCastExpr, TsTypeParamDecl,
        TsTypeParamInstantiation,
    },
};
#[cfg(feature = "fold")]
use swc_common::Fold;
use swc_common::{ast_node, Span, Spanned, DUMMY_SP};

#[ast_node]
pub enum Expr {
    This(ThisExpr),

    Array(ArrayLit),

    Object(ObjectLit),

    Fn(FnExpr),

    Unary(UnaryExpr),

    /// `++v`, `--v`, `v++`, `v--`
    Update(UpdateExpr),

    Bin(BinExpr),

    Assign(AssignExpr),

    //
    // Logical {
    //
    //     op: LogicalOp,
    //     left: Box<Expr>,
    //     right: Box<Expr>,
    // },
    /// A member expression. If computed is true, the node corresponds to a
    /// computed (a[b]) member expression and property is an Expression. If
    /// computed is false, the node corresponds to a static (a.b) member
    /// expression and property is an Identifier.
    Member(MemberExpr),

    /// true ? 'a' : 'b'
    Cond(CondExpr),

    Call(CallExpr),

    /// `new Cat()`
    New(NewExpr),

    Seq(SeqExpr),

    Ident(Ident),

    Lit(Lit),

    Tpl(Tpl),

    TaggedTpl(TaggedTpl),

    Arrow(ArrowExpr),

    Class(ClassExpr),

    Yield(YieldExpr),

    MetaProp(MetaPropExpr),

    Await(AwaitExpr),

    Paren(ParenExpr),

    JSXMebmer(JSXMemberExpr),
    JSXNamespacedName(JSXNamespacedName),
    JSXEmpty(JSXEmptyExpr),
    JSXElement(JSXElement),
    JSXFragment(JSXFragment),

    TsTypeAssertion(TsTypeAssertion),
    TsNonNull(TsNonNullExpr),
    TsTypeCast(TsTypeCastExpr),
    TsAs(TsAsExpr),

    PrivateName(PrivateName),
}

#[ast_node]
#[derive(Copy)]
pub struct ThisExpr {
    pub span: Span,
}

/// Array literal.
#[ast_node]
pub struct ArrayLit {
    pub span: Span,
    pub elems: Vec<(Option<ExprOrSpread>)>,
}

/// Object literal.
#[ast_node]
pub struct ObjectLit {
    pub span: Span,
    pub props: Vec<PropOrSpread>,
}

#[ast_node]
pub enum PropOrSpread {
    Prop(Box<Prop>),
    /// Spread properties, e.g., `{a: 1, ...obj, b: 2}`.
    Spread(SpreadElement),
}

#[ast_node]
pub struct SpreadElement {
    #[span(lo)]
    pub dot3_token: Span,
    #[span(hi)]
    pub expr: Box<Expr>,
}

#[ast_node]
pub struct UnaryExpr {
    pub span: Span,
    pub op: UnaryOp,

    pub arg: Box<Expr>,
}

#[ast_node]
pub struct UpdateExpr {
    pub span: Span,
    pub op: UpdateOp,
    pub prefix: bool,

    pub arg: Box<Expr>,
}

#[ast_node]
pub struct BinExpr {
    pub span: Span,
    pub op: BinaryOp,

    pub left: Box<Expr>,

    pub right: Box<Expr>,
}

/// Function expression.
#[ast_node]
pub struct FnExpr {
    pub ident: Option<Ident>,
    #[span]
    pub function: Function,
}

/// Class expression.
#[ast_node]
pub struct ClassExpr {
    pub ident: Option<Ident>,
    #[span]
    pub class: Class,
}

#[ast_node]
pub struct AssignExpr {
    pub span: Span,
    pub op: AssignOp,
    pub left: PatOrExpr,
    pub right: Box<Expr>,
}

#[ast_node]
pub struct MemberExpr {
    pub span: Span,
    pub obj: ExprOrSuper,
    pub prop: Box<Expr>,
    pub computed: bool,
}

#[ast_node]
pub struct CondExpr {
    pub span: Span,
    pub test: Box<Expr>,
    pub cons: Box<Expr>,
    pub alt: Box<Expr>,
}

#[ast_node]
pub struct CallExpr {
    pub span: Span,
    pub callee: ExprOrSuper,
    pub args: Vec<ExprOrSpread>,
    pub type_args: Option<TsTypeParamInstantiation>,
    // pub type_params: Option<TsTypeParamInstantiation>,
}

#[ast_node]
pub struct NewExpr {
    pub span: Span,
    pub callee: Box<Expr>,
    pub args: Option<(Vec<ExprOrSpread>)>,
    pub type_args: Option<TsTypeParamInstantiation>,
    // pub type_params: Option<TsTypeParamInstantiation>,
}

#[ast_node]
pub struct SeqExpr {
    /// TODO: Calculate
    pub span: Span,
    pub exprs: Vec<(Box<Expr>)>,
}

#[ast_node]
pub struct ArrowExpr {
    pub span: Span,
    pub params: Vec<Pat>,
    pub body: BlockStmtOrExpr,
    pub is_async: bool,
    pub is_generator: bool,
    pub type_params: Option<TsTypeParamDecl>,
    pub return_type: Option<TsTypeAnn>,
}

#[ast_node]
pub struct YieldExpr {
    pub span: Span,
    pub arg: Option<(Box<Expr>)>,
    pub delegate: bool,
}
#[ast_node]
pub struct MetaPropExpr {
    #[span(lo)]
    pub meta: Ident,
    #[span(hi)]
    pub prop: Ident,
}
#[ast_node]
pub struct AwaitExpr {
    pub span: Span,
    pub arg: Box<Expr>,
}

#[ast_node]
pub struct Tpl {
    pub span: Span,
    pub exprs: Vec<(Box<Expr>)>,
    pub quasis: Vec<TplElement>,
}

#[ast_node]
pub struct TaggedTpl {
    pub span: Span,
    pub tag: Box<Expr>,
    pub exprs: Vec<(Box<Expr>)>,
    pub quasis: Vec<TplElement>,
    pub type_params: Option<TsTypeParamInstantiation>,
}

#[ast_node]
pub struct TplElement {
    pub span: Span,
    pub tail: bool,
    pub cooked: Option<Str>,
    pub raw: Str,
}

#[ast_node]
pub struct ParenExpr {
    pub span: Span,
    pub expr: Box<Expr>,
}

#[ast_node]
#[allow(variant_size_differences)]
pub enum ExprOrSuper {
    Super(Span),
    Expr(Box<Expr>),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "fold", derive(Fold))]
pub struct ExprOrSpread {
    pub spread: Option<Span>,
    pub expr: Box<Expr>,
}
impl Spanned for ExprOrSpread {
    fn span(&self) -> Span {
        let expr = self.expr.span();
        match self.spread {
            Some(spread) => expr.with_lo(spread.lo()),
            None => expr,
        }
    }
}

#[ast_node]
#[allow(variant_size_differences)]
pub enum BlockStmtOrExpr {
    BlockStmt(BlockStmt),
    Expr(Box<Expr>),
}

#[ast_node]
pub enum PatOrExpr {
    Pat(Box<Pat>),
    Expr(Box<Expr>),
}

impl From<bool> for Expr {
    fn from(value: bool) -> Self {
        Expr::Lit(Lit::Bool(Bool {
            span: DUMMY_SP,
            value,
        }))
    }
}

impl From<f64> for Expr {
    fn from(value: f64) -> Self {
        Expr::Lit(Lit::Num(Number {
            span: DUMMY_SP,
            value,
        }))
    }
}

impl From<Bool> for Expr {
    fn from(v: Bool) -> Self {
        Expr::Lit(Lit::Bool(v))
    }
}

impl From<Number> for Expr {
    fn from(v: Number) -> Self {
        Expr::Lit(Lit::Num(v))
    }
}

impl From<Str> for Expr {
    fn from(v: Str) -> Self {
        Expr::Lit(Lit::Str(v))
    }
}


text:
// Generated from definition io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup

/// APIGroup contains the name, the supported versions, and the preferred version of a group.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct APIGroup {
    /// name is the name of the group.
    pub name: String,

    /// preferredVersion is the version preferred by the API server, which probably is the storage version.
    pub preferred_version: Option<crate::v1_8::apimachinery::pkg::apis::meta::v1::GroupVersionForDiscovery>,

    /// a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.
    pub server_address_by_client_cidrs: Option<Vec<crate::v1_8::apimachinery::pkg::apis::meta::v1::ServerAddressByClientCIDR>>,

    /// versions are the versions supported in this group.
    pub versions: Vec<crate::v1_8::apimachinery::pkg::apis::meta::v1::GroupVersionForDiscovery>,
}

impl crate::Resource for APIGroup {
    fn api_version() -> &'static str {
        "v1"
    }

    fn group() -> &'static str {
        ""
    }

    fn kind() -> &'static str {
        "APIGroup"
    }

    fn version() -> &'static str {
        "v1"
    }
}

impl<'de> serde::Deserialize<'de> for APIGroup {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
        #[allow(non_camel_case_types)]
        enum Field {
            Key_api_version,
            Key_kind,
            Key_name,
            Key_preferred_version,
            Key_server_address_by_client_cidrs,
            Key_versions,
            Other,
        }

        impl<'de> serde::Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
                struct Visitor;

                impl<'de> serde::de::Visitor<'de> for Visitor {
                    type Value = Field;

                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        write!(f, "field identifier")
                    }

                    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
                        Ok(match v {
                            "apiVersion" => Field::Key_api_version,
                            "kind" => Field::Key_kind,
                            "name" => Field::Key_name,
                            "preferredVersion" => Field::Key_preferred_version,
                            "serverAddressByClientCIDRs" => Field::Key_server_address_by_client_cidrs,
                            "versions" => Field::Key_versions,
                            _ => Field::Other,
                        })
                    }
                }

                deserializer.deserialize_identifier(Visitor)
            }
        }

        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = APIGroup;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "struct APIGroup")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
                let mut value_name: Option<String> = None;
                let mut value_preferred_version: Option<crate::v1_8::apimachinery::pkg::apis::meta::v1::GroupVersionForDiscovery> = None;
                let mut value_server_address_by_client_cidrs: Option<Vec<crate::v1_8::apimachinery::pkg::apis::meta::v1::ServerAddressByClientCIDR>> = None;
                let mut value_versions: Option<Vec<crate::v1_8::apimachinery::pkg::apis::meta::v1::GroupVersionForDiscovery>> = None;

                while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
                    match key {
                        Field::Key_api_version => {
                            let value_api_version: String = serde::de::MapAccess::next_value(&mut map)?;
                            if value_api_version != <Self::Value as crate::Resource>::api_version() {
                                return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::api_version()));
                            }
                        },
                        Field::Key_kind => {
                            let value_kind: String = serde::de::MapAccess::next_value(&mut map)?;
                            if value_kind != <Self::Value as crate::Resource>::kind() {
                                return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::kind()));
                            }
                        },
                        Field::Key_name => value_name = Some(serde::de::MapAccess::next_value(&mut map)?),
                        Field::Key_preferred_version => value_preferred_version = serde::de::MapAccess::next_value(&mut map)?,
                        Field::Key_server_address_by_client_cidrs => value_server_address_by_client_cidrs = serde::de::MapAccess::next_value(&mut map)?,
                        Field::Key_versions => value_versions = Some(serde::de::MapAccess::next_value(&mut map)?),
                        Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
                    }
                }

                Ok(APIGroup {
                    name: value_name.ok_or_else(|| serde::de::Error::missing_field("name"))?,
                    preferred_version: value_preferred_version,
                    server_address_by_client_cidrs: value_server_address_by_client_cidrs,
                    versions: value_versions.ok_or_else(|| serde::de::Error::missing_field("versions"))?,
                })
            }
        }

        deserializer.deserialize_struct(
            "APIGroup",
            &[
                "apiVersion",
                "kind",
                "name",
                "preferredVersion",
                "serverAddressByClientCIDRs",
                "versions",
            ],
            Visitor,
        )
    }
}

impl serde::Serialize for APIGroup {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
        let mut state = serializer.serialize_struct(
            "APIGroup",
            4 +
            self.preferred_version.as_ref().map_or(0, |_| 1) +
            self.server_address_by_client_cidrs.as_ref().map_or(0, |_| 1),
        )?;
        serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::api_version())?;
        serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::kind())?;
        serde::ser::SerializeStruct::serialize_field(&mut state, "name", &self.name)?;
        if let Some(value) = &self.preferred_version {
            serde::ser::SerializeStruct::serialize_field(&mut state, "preferredVersion", value)?;
        }
        if let Some(value) = &self.server_address_by_client_cidrs {
            serde::ser::SerializeStruct::serialize_field(&mut state, "serverAddressByClientCIDRs", value)?;
        }
        serde::ser::SerializeStruct::serialize_field(&mut state, "versions", &self.versions)?;
        serde::ser::SerializeStruct::end(state)
    }
}


text:
use std::io;
use std::path::PathBuf;

mod file;
mod opts;
pub fn extract_ibd() ->Result<(),io::Error>{
    let opts = opts::Opt::new();
    let save_loc = match opts.output{
        Some(path) => path,
        None => PathBuf::from("./ibd_urls")
    };

    let paths = match opts.dir_path{
        Some(path) => file::FileHandler::get_ibd_files(path),
        None => opts.paths
    };

    multiple_ibd_files(paths,save_loc)?;

    Ok(())
}
/// Starts extracting multiple ibd files
fn multiple_ibd_files(paths:Vec<PathBuf>,save_loc:PathBuf)->io::Result<()>{
    for opt in paths{
        let file_handler = file::FileHandler::new(opt,&save_loc);
        file_handler.start()?;
    }
    Ok(())
}


text:
use crate::bindgen::{FPDF_BITMAP, FPDF_DOCUMENT, FPDF_DWORD, FPDF_PAGE};
use crate::bindings::PdfiumLibraryBindings;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    // Bind to Javascript functions in the FPDF object namespace that themselves
    // wrap exported WASM functions from a separate WASM module containing the compiled
    // PDFium library.

    // The Javascript function signatures are broadly similar to the native C
    // function signatures, with one important exception: we cannot pass pointers to
    // shared memory across WASM modules. We must pass our byte buffers directly;
    // these are exposed to Javascript as ArrayBuffer objects. This affects the
    // LoadMemDocument() function.

    #[wasm_bindgen(js_namespace = FPDF)]
    fn InitLibrary();

    #[wasm_bindgen(js_namespace = FPDF)]
    fn DestroyLibrary();

    #[wasm_bindgen(js_namespace = FPDF)]
    fn GetLastError() -> ::std::os::raw::c_ulong;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn LoadDocument(file_path: &str, password: &str) -> FPDF_DOCUMENT;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn LoadMemDocument(bytes: &[u8], password: &str) -> FPDF_DOCUMENT;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn CloseDocument(document: FPDF_DOCUMENT);

    #[wasm_bindgen(js_namespace = FPDF)]
    fn GetPageCount(document: FPDF_DOCUMENT) -> ::std::os::raw::c_int;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn LoadPage(document: FPDF_DOCUMENT, page_index: ::std::os::raw::c_int) -> FPDF_PAGE;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn ClosePage(page: FPDF_PAGE);

    #[wasm_bindgen(js_namespace = FPDF)]
    fn GetPageWidthF(page: FPDF_PAGE) -> f32;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn GetPageHeightF(page: FPDF_PAGE) -> f32;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_CreateEx(
        width: ::std::os::raw::c_int,
        height: ::std::os::raw::c_int,
        format: ::std::os::raw::c_int,
        first_scan: *mut ::std::os::raw::c_void,
        stride: ::std::os::raw::c_int,
    ) -> FPDF_BITMAP;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_Destroy(bitmap: FPDF_BITMAP);

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_FillRect(
        bitmap: FPDF_BITMAP,
        left: ::std::os::raw::c_int,
        top: ::std::os::raw::c_int,
        width: ::std::os::raw::c_int,
        height: ::std::os::raw::c_int,
        color: FPDF_DWORD,
    );

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_GetBuffer(bitmap: FPDF_BITMAP) -> Vec<u8>;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_GetWidth(bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_GetHeight(bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn Bitmap_GetStride(bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int;

    #[wasm_bindgen(js_namespace = FPDF)]
    fn RenderPageBitmap(
        bitmap: FPDF_BITMAP,
        page: FPDF_PAGE,
        start_x: ::std::os::raw::c_int,
        start_y: ::std::os::raw::c_int,
        size_x: ::std::os::raw::c_int,
        size_y: ::std::os::raw::c_int,
        rotate: ::std::os::raw::c_int,
        flags: ::std::os::raw::c_int,
    );
}

pub(crate) struct WasmPdfiumBindings {}

impl WasmPdfiumBindings {
    #[inline]
    pub(crate) fn new() -> Self {
        WasmPdfiumBindings {}
    }
}

impl PdfiumLibraryBindings for WasmPdfiumBindings {
    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_InitLibrary(&self) {
        InitLibrary();
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_DestroyLibrary(&self) {
        DestroyLibrary();
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_GetLastError(&self) -> ::std::os::raw::c_ulong {
        GetLastError()
    }

    #[inline]
    #[cfg(not(target_arch = "wasm32"))]
    #[allow(non_snake_case)]
    fn FPDF_LoadDocument(&self, _file_path: &str, _password: Option<&str>) -> FPDF_DOCUMENT {
        // FPDF_LoadDocument is not available on WASM. When compiling to WASM,
        // this function definition in the PdfiumLibraryBindings trait will be
        // entirely omitted, so calling code that attempts to call FPDF_LoadDocument
        // will fail at compile-time, not run-time.

        unimplemented!()
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_LoadMemDocument(&self, bytes: &[u8], password: Option<&str>) -> FPDF_DOCUMENT {
        LoadMemDocument(bytes, password.unwrap_or(""))
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_CloseDocument(&self, document: FPDF_DOCUMENT) {
        CloseDocument(document);
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_GetPageCount(&self, document: FPDF_DOCUMENT) -> ::std::os::raw::c_int {
        GetPageCount(document)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_LoadPage(
        &self,
        document: FPDF_DOCUMENT,
        page_index: ::std::os::raw::c_int,
    ) -> FPDF_PAGE {
        LoadPage(document, page_index)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_ClosePage(&self, page: FPDF_PAGE) {
        ClosePage(page);
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_GetPageWidthF(&self, page: FPDF_PAGE) -> f32 {
        GetPageWidthF(page)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_GetPageHeightF(&self, page: FPDF_PAGE) -> f32 {
        GetPageHeightF(page)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_CreateEx(
        &self,
        width: ::std::os::raw::c_int,
        height: ::std::os::raw::c_int,
        format: ::std::os::raw::c_int,
        first_scan: *mut std::os::raw::c_void,
        stride: ::std::os::raw::c_int,
    ) -> FPDF_BITMAP {
        Bitmap_CreateEx(width, height, format, first_scan, stride)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_Destroy(&self, bitmap: FPDF_BITMAP) {
        Bitmap_Destroy(bitmap);
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_FillRect(
        &self,
        bitmap: FPDF_BITMAP,
        left: ::std::os::raw::c_int,
        top: ::std::os::raw::c_int,
        width: ::std::os::raw::c_int,
        height: ::std::os::raw::c_int,
        color: FPDF_DWORD,
    ) {
        Bitmap_FillRect(bitmap, left, top, width, height, color);
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_GetBuffer(&self, bitmap: FPDF_BITMAP) -> *mut ::std::os::raw::c_void {
        Bitmap_GetBuffer(bitmap).as_ptr() as *mut ::std::os::raw::c_void
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_GetWidth(&self, bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int {
        Bitmap_GetWidth(bitmap)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_GetHeight(&self, bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int {
        Bitmap_GetHeight(bitmap)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDFBitmap_GetStride(&self, bitmap: FPDF_BITMAP) -> ::std::os::raw::c_int {
        Bitmap_GetStride(bitmap)
    }

    #[inline]
    #[allow(non_snake_case)]
    fn FPDF_RenderPageBitmap(
        &self,
        bitmap: FPDF_BITMAP,
        page: FPDF_PAGE,
        start_x: ::std::os::raw::c_int,
        start_y: ::std::os::raw::c_int,
        size_x: ::std::os::raw::c_int,
        size_y: ::std::os::raw::c_int,
        rotate: ::std::os::raw::c_int,
        flags: ::std::os::raw::c_int,
    ) {
        RenderPageBitmap(
            bitmap, page, start_x, start_y, size_x, size_y, rotate, flags,
        );
    }
}

impl Default for WasmPdfiumBindings {
    #[inline]
    fn default() -> Self {
        WasmPdfiumBindings::new()
    }
}


text:
// Copyright 2014 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.

// exec-env:RUST_POISON_ON_FREE=1

// Test argument patterns where we create refs to the inside of
// boxes. Make sure that we don't free the box as we match the
// pattern.

#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]

fn getaddr(box ref x: Box<uint>) -> *const uint {
    let addr: *const uint = &*x;
    addr
}

fn checkval(box ref x: Box<uint>) -> uint {
    *x
}

pub fn main() {
    let obj: Box<_> = box 1;
    let objptr: *const uint = &*obj;
    let xptr = getaddr(obj);
    assert_eq!(objptr, xptr);

    let obj = box 22;
    assert_eq!(checkval(obj), 22);
}


text:
use core::marker::PhantomData;
use embassy::util::Unborrow;
use embassy_hal_common::unborrow;

use crate::gpio::sealed::AFType::OutputPushPull;
use crate::gpio::Speed;
use crate::pac::gpio::vals::Pupdr;

mod pins;
pub use pins::*;

pub struct Fmc<'d, T: Instance> {
    peri: PhantomData<&'d mut T>,
}

unsafe impl<'d, T> Send for Fmc<'d, T> where T: Instance {}

unsafe impl<'d, T> stm32_fmc::FmcPeripheral for Fmc<'d, T>
where
    T: Instance,
{
    const REGISTERS: *const () = crate::pac::FMC.0 as *const _;

    fn enable(&mut self) {
        <T as crate::rcc::sealed::RccPeripheral>::enable();
        <T as crate::rcc::sealed::RccPeripheral>::reset();
    }

    fn memory_controller_enable(&mut self) {
        // The FMCEN bit of the FMC_BCR2..4 registers is don’t
        // care. It is only enabled through the FMC_BCR1 register.
        unsafe { T::regs().bcr1().modify(|r| r.set_fmcen(true)) };
    }

    fn source_clock_hz(&self) -> u32 {
        <T as crate::rcc::sealed::RccPeripheral>::frequency().0
    }
}

macro_rules! config_pins {
    ($($pin:ident),*) => {
        unborrow!($($pin),*);
        $(
            $pin.set_as_af($pin.af_num(), OutputPushPull);
            $pin.set_speed(Speed::VeryHigh);
            $pin.block().pupdr().modify(|w| w.set_pupdr($pin.pin() as usize, Pupdr::PULLUP));
        )*
    };
}

macro_rules! fmc_sdram_constructor {
    ($name:ident: (
        bank: $bank:expr,
        addr: [$(($addr_pin_name:ident: $addr_signal:ident)),*],
        ba: [$(($ba_pin_name:ident: $ba_signal:ident)),*],
        d: [$(($d_pin_name:ident: $d_signal:ident)),*],
        nbl: [$(($nbl_pin_name:ident: $nbl_signal:ident)),*],
        ctrl: [$(($ctrl_pin_name:ident: $ctrl_signal:ident)),*]
    )) => {
        pub fn $name<CHIP: stm32_fmc::SdramChip>(
            _instance: impl Unborrow<Target = T> + 'd,
            $($addr_pin_name: impl Unborrow<Target = impl $addr_signal<T>> + 'd),*,
            $($ba_pin_name: impl Unborrow<Target = impl $ba_signal<T>> + 'd),*,
            $($d_pin_name: impl Unborrow<Target = impl $d_signal<T>> + 'd),*,
            $($nbl_pin_name: impl Unborrow<Target = impl $nbl_signal<T>> + 'd),*,
            $($ctrl_pin_name: impl Unborrow<Target = impl $ctrl_signal<T>> + 'd),*,
            chip: CHIP
        ) -> stm32_fmc::Sdram<Fmc<'d, T>, CHIP> {

        critical_section::with(|_| unsafe {
            config_pins!(
                $($addr_pin_name),*,
                $($ba_pin_name),*,
                $($d_pin_name),*,
                $($nbl_pin_name),*,
                $($ctrl_pin_name),*
            );
        });

            let fmc = Self { peri: PhantomData };
            stm32_fmc::Sdram::new_unchecked(
                fmc,
                $bank,
                chip,
            )
        }
    };
}

impl<'d, T: Instance> Fmc<'d, T> {
    fmc_sdram_constructor!(sdram_a12bits_d32bits_4banks_bank1: (
        bank: stm32_fmc::SdramTargetBank::Bank1,
        addr: [
            (a0: A0Pin), (a1: A1Pin), (a2: A2Pin), (a3: A3Pin), (a4: A4Pin), (a5: A5Pin), (a6: A6Pin), (a7: A7Pin), (a8: A8Pin), (a9: A9Pin), (a10: A10Pin), (a11: A11Pin)
        ],
        ba: [(ba0: BA0Pin), (ba1: BA1Pin)],
        d: [
            (d0: D0Pin), (d1: D1Pin), (d2: D2Pin), (d3: D3Pin), (d4: D4Pin), (d5: D5Pin), (d6: D6Pin), (d7: D7Pin),
            (d8: D8Pin), (d9: D9Pin), (d10: D10Pin), (d11: D11Pin), (d12: D12Pin), (d13: D13Pin), (d14: D14Pin), (d15: D15Pin),
            (d16: D16Pin), (d17: D17Pin), (d18: D18Pin), (d19: D19Pin), (d20: D20Pin), (d21: D21Pin), (d22: D22Pin), (d23: D23Pin),
            (d24: D24Pin), (d25: D25Pin), (d26: D26Pin), (d27: D27Pin), (d28: D28Pin), (d29: D29Pin), (d30: D30Pin), (d31: D31Pin)
        ],
        nbl: [
            (nbl0: NBL0Pin), (nbl1: NBL1Pin), (nbl2: NBL2Pin), (nbl3: NBL3Pin)
        ],
        ctrl: [
            (sdcke: SDCKE0Pin), (sdclk: SDCLKPin), (sdncas: SDNCASPin), (sdne: SDNE0Pin), (sdnras: SDNRASPin), (sdnwe: SDNWEPin)
        ]
    ));

    fmc_sdram_constructor!(sdram_a12bits_d32bits_4banks_bank2: (
        bank: stm32_fmc::SdramTargetBank::Bank2,
        addr: [
            (a0: A0Pin), (a1: A1Pin), (a2: A2Pin), (a3: A3Pin), (a4: A4Pin), (a5: A5Pin), (a6: A6Pin), (a7: A7Pin), (a8: A8Pin), (a9: A9Pin), (a10: A10Pin), (a11: A11Pin)
        ],
        ba: [(ba0: BA0Pin), (ba1: BA1Pin)],
        d: [
            (d0: D0Pin), (d1: D1Pin), (d2: D2Pin), (d3: D3Pin), (d4: D4Pin), (d5: D5Pin), (d6: D6Pin), (d7: D7Pin),
            (d8: D8Pin), (d9: D9Pin), (d10: D10Pin), (d11: D11Pin), (d12: D12Pin), (d13: D13Pin), (d14: D14Pin), (d15: D15Pin),
            (d16: D16Pin), (d17: D17Pin), (d18: D18Pin), (d19: D19Pin), (d20: D20Pin), (d21: D21Pin), (d22: D22Pin), (d23: D23Pin),
            (d24: D24Pin), (d25: D25Pin), (d26: D26Pin), (d27: D27Pin), (d28: D28Pin), (d29: D29Pin), (d30: D30Pin), (d31: D31Pin)
        ],
        nbl: [
            (nbl0: NBL0Pin), (nbl1: NBL1Pin), (nbl2: NBL2Pin), (nbl3: NBL3Pin)
        ],
        ctrl: [
            (sdcke: SDCKE1Pin), (sdclk: SDCLKPin), (sdncas: SDNCASPin), (sdne: SDNE1Pin), (sdnras: SDNRASPin), (sdnwe: SDNWEPin)
        ]
    ));
}

crate::pac::peripherals!(
    (fmc, $inst:ident) => {
        impl crate::fmc::sealed::Instance for crate::peripherals::$inst {
            fn regs() -> stm32_metapac::fmc::Fmc {
                crate::pac::$inst
            }
        }
        impl crate::fmc::Instance for crate::peripherals::$inst {}
    };
);


text:
#![feature(alloc)]
#![no_std]
#![no_main]

#[macro_use]
extern crate rcore_user;

extern crate alloc;

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use isomorphic_drivers::net::ethernet::intel::ixgbe;
use isomorphic_drivers::provider;
use rcore_user::syscall::*;

use smoltcp::iface::*;
use smoltcp::phy;
use smoltcp::phy::*;
use smoltcp::socket::*;
use smoltcp::time::*;
use smoltcp::wire::*;
use smoltcp::Result;

#[derive(Copy, Clone)]
pub struct Provider;

impl Provider {
    pub fn new() -> Box<Provider> {
        Box::new(Provider {})
    }
}

impl provider::Provider for Provider {
    /// Get page size
    fn get_page_size(&self) -> usize {
        4096
    }

    // Translate virtual address to physical address
    fn translate_va(&self, va: usize) -> usize {
        let mut pa = [0u64; 1];
        sys_get_paddr(&[va as u64], &mut pa[..]);
        pa[0] as usize
    }

    // Bulk translate virtual addresses to physical addresses for performance
    fn translate_vas(&self, vas: &[usize]) -> Vec<usize> {
        let mut pas = vec![0u64; vas.len()];
        let mut vec_vas = vec![0u64; vas.len()];
        for va in vas.iter() {
            vec_vas.push(*va as u64);
        }
        sys_get_paddr(&vec_vas[..], &mut pas[..]);
        let mut res = vec![0usize; vas.len()];
        for pa in pas {
            res.push(pa as usize);
        }
        res
    }
}

#[derive(Clone)]
struct IXGBEDriver {
    inner: ixgbe::IXGBEDriver,
}

pub struct IXGBERxToken(Vec<u8>);
pub struct IXGBETxToken(IXGBEDriver);

impl<'a> phy::Device<'a> for IXGBEDriver {
    type RxToken = IXGBERxToken;
    type TxToken = IXGBETxToken;

    fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
        if self.inner.can_send() {
            if let Some(data) = self.inner.recv() {
                Some((IXGBERxToken(data), IXGBETxToken(self.clone())))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn transmit(&'a mut self) -> Option<Self::TxToken> {
        if self.inner.can_send() {
            Some(IXGBETxToken(self.clone()))
        } else {
            None
        }
    }

    fn capabilities(&self) -> DeviceCapabilities {
        let mut caps = DeviceCapabilities::default();
        caps.max_transmission_unit = ixgbe::IXGBEDriver::get_mtu(); // max MTU
                                                                    //caps.max_transmission_unit = 1500; // max MTU
        caps.max_burst_size = Some(256);
        // IP Rx checksum is offloaded with RXCSUM
        caps.checksum.ipv4 = Checksum::Tx;
        caps
    }
}

impl phy::RxToken for IXGBERxToken {
    fn consume<R, F>(self, _timestamp: Instant, f: F) -> Result<R>
    where
        F: FnOnce(&[u8]) -> Result<R>,
    {
        f(&self.0)
    }
}

impl phy::TxToken for IXGBETxToken {
    fn consume<R, F>(self, _timestamp: Instant, len: usize, f: F) -> Result<R>
    where
        F: FnOnce(&mut [u8]) -> Result<R>,
    {
        let mut buffer = [0u8; ixgbe::IXGBEDriver::get_mtu()];
        let result = f(&mut buffer[..len]);
        if result.is_ok() {
            (self.0).inner.send(&buffer[..len]);
        }
        result
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
enum State {
    BEGIN,
    CONTROL_SOCKET_CONNECT,
    CONTROL_COOKIE_SENT,
    JSON_CONFIG_SENT,
    CREATE_STREAMS,
    DATA_SOCKET_CONNECT,
    DATA_COOKIE_SENT,
    TEST_START,
    TEST_RUNNING,
}

// IMPORTANT: Must define main() like this
#[no_mangle]
pub fn main() {
    enlarge_heap();
    println!("I am going to map IXGBE driver to user space");
    println!("Kernel network stack should not use it anymore");
    let addr = sys_map_pci_device(0x8086, 0x10fb);
    println!("IXGBE addr at {:#X}", addr);
    let ixgbe = ixgbe::IXGBEDriver::init(Provider::new(), addr as usize, 0x20000);
    println!("IXGBE driver up");
    println!("IXGBE driver waiting for link up");
    while !ixgbe.is_link_up() {}
    println!("IXGBE driver link is up");

    let ethernet_addr = ixgbe.get_mac();
    let ip_addrs = [IpCidr::new(IpAddress::v4(10, 0, 0, 2), 24)];
    let neighbor_cache = NeighborCache::new(BTreeMap::new());
    let mut iface = EthernetInterfaceBuilder::new(IXGBEDriver { inner: ixgbe })
        .ethernet_addr(EthernetAddress::from_bytes(&ethernet_addr.as_bytes()))
        .ip_addrs(ip_addrs)
        .neighbor_cache(neighbor_cache)
        .finalize();

    // 37 byte ascii cookie
    let cookie = String::from("cafebabed00dbeefELFGIF89aPKGET/HTTP/\0").into_bytes();
    assert_eq!(cookie.len(), 37);
    // Json config
    let json = String::from(r##"{"tcp":true,"omit":0,"time":10,"parallel":1,"len":2147483647,"pacing_timer":1000,"client_version":"3.6"}"##).into_bytes();
    println!("Waiting for 3s");
    sys_sleep(3);
    println!("Simulating iperf3 client to 10.0.0.1");

    // tcp for control, tcp2 for data
    let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
    let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
    let tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);

    let tcp2_rx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
    let tcp2_tx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
    let tcp2_socket = TcpSocket::new(tcp2_rx_buffer, tcp2_tx_buffer);

    let mut sockets = SocketSet::new(vec![]);
    let tcp_handle = sockets.add(tcp_socket);
    let tcp2_handle = sockets.add(tcp2_socket);

    let mut tick = 0;
    let mut state = State::BEGIN;
    let mut last_state = State::BEGIN;
    let data = [0u8; 204800];
    loop {
        tick += 1;
        iface.poll(&mut sockets, Instant::from_millis(tick * 1000_000));
        {
            let mut socket = sockets.get::<TcpSocket>(tcp_handle);
            if let State::BEGIN = state {
                socket
                    .connect(
                        IpEndpoint::new(IpAddress::v4(10, 0, 0, 1), 5201),
                        IpEndpoint::new(IpAddress::v4(10, 0, 0, 2), 5201),
                    )
                    .unwrap();
                state = State::CONTROL_SOCKET_CONNECT;
            } else if let State::CONTROL_SOCKET_CONNECT = state {
                if socket.may_send() {
                    socket.send_slice(&cookie).unwrap();
                    state = State::CONTROL_COOKIE_SENT;
                }
            } else if let State::CONTROL_COOKIE_SENT = state {
                let mut recv = [0u8; 1];
                if socket.may_recv() {
                    socket.recv_slice(&mut recv).unwrap();
                    if recv[0] == 9 {
                        // param exchange
                        // dword len
                        let len = json.len();
                        let mut len_data = [0u8; 4];
                        len_data[3] = len as u8;
                        socket.send_slice(&len_data).unwrap();
                        socket.send_slice(&json).unwrap();
                        state = State::JSON_CONFIG_SENT;
                    }
                }
            } else if let State::JSON_CONFIG_SENT = state {
                let mut recv = [0u8; 1];
                if socket.may_recv() {
                    socket.recv_slice(&mut recv).unwrap();
                    if recv[0] == 10 {
                        // create streams
                        state = State::CREATE_STREAMS;
                    }
                }
            } else if let State::DATA_COOKIE_SENT = state {
                let mut recv = [0u8; 1];
                if socket.may_recv() {
                    socket.recv_slice(&mut recv).unwrap();
                    if recv[0] == 1 {
                        // test start
                        state = State::TEST_START;
                    }
                }
            } else if let State::TEST_START = state {
                let mut recv = [0u8; 1];
                if socket.may_recv() {
                    socket.recv_slice(&mut recv).unwrap();
                    if recv[0] == 2 {
                        // test running
                        state = State::TEST_RUNNING;
                    }
                }
            }
        }

        {
            let mut socket = sockets.get::<TcpSocket>(tcp2_handle);
            if let State::CREATE_STREAMS = state {
                socket
                    .connect(
                        IpEndpoint::new(IpAddress::v4(10, 0, 0, 1), 5201),
                        IpEndpoint::new(IpAddress::v4(10, 0, 0, 2), 5202),
                    )
                    .unwrap();
                state = State::DATA_SOCKET_CONNECT;
            } else if let State::DATA_SOCKET_CONNECT = state {
                if socket.may_send() {
                    socket.send_slice(&cookie).unwrap();
                    state = State::DATA_COOKIE_SENT;
                }
            } else if let State::TEST_RUNNING = state {
                if socket.can_send() {
                    socket.send_slice(&data).unwrap();
                }
            }
        }
        if state != last_state {
            println!("{:?} -> {:?}", last_state, state);
        }
        last_state = state;
    }
}


text:
use crate::to_rows;
use async_trait::async_trait;
use cubestore::cluster::Cluster;
use cubestore::config::{env_parse, Config, CubeServices};
use cubestore::table::TableValue;
use cubestore::util::strings::path_to_string;
use cubestore::CubeError;
use flate2::read::GzDecoder;
use std::any::Any;
use std::io::Cursor;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tar::Archive;
use tokio::time::timeout;

pub type BenchState = dyn Any + Send + Sync;

#[async_trait]
pub trait Bench: Send + Sync {
    fn config(self: &Self, prefix: &str) -> (String, Config);
    async fn setup(self: &Self, services: &CubeServices) -> Result<Arc<BenchState>, CubeError>;
    async fn bench(
        self: &Self,
        services: &CubeServices,
        state: Arc<BenchState>,
    ) -> Result<(), CubeError>;
}

fn config_name(prefix: &str, name: &str) -> String {
    format!("{}::{}", prefix, name)
}

pub fn cubestore_benches() -> Vec<Arc<dyn Bench>> {
    return vec![
        Arc::new(SimpleBench {}),
        Arc::new(ParquetMetadataCacheBench {}),
    ];
}

pub struct SimpleBenchState {
    query: String,
}
pub struct SimpleBench;
#[async_trait]
impl Bench for SimpleBench {
    fn config(self: &Self, prefix: &str) -> (String, Config) {
        let name = config_name(prefix, "simple");
        let config = Config::test(name.as_str());
        (name, config)
    }

    async fn setup(self: &Self, _services: &CubeServices) -> Result<Arc<BenchState>, CubeError> {
        Ok(Arc::new(SimpleBenchState {
            query: "SELECT 23".to_string(),
        }))
    }

    async fn bench(
        self: &Self,
        services: &CubeServices,
        state: Arc<BenchState>,
    ) -> Result<(), CubeError> {
        let state = state
            .downcast_ref::<SimpleBenchState>()
            .ok_or(CubeError::internal("bad state".to_string()))?;
        let r = services
            .sql_service
            .exec_query(state.query.as_str())
            .await?;
        let rows = to_rows(&r);
        assert_eq!(rows, vec![vec![TableValue::Int(23)]]);
        Ok(())
    }
}

// To compare, bench without / with bench enabled.
// CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=0 cargo bench parquet_metadata_cache
// CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=1000000 cargo bench parquet_metadata_cache
pub struct ParquetMetadataCacheBench;
#[async_trait]
impl Bench for ParquetMetadataCacheBench {
    fn config(self: &Self, prefix: &str) -> (String, Config) {
        let name = config_name(prefix, "parquet_metadata_cache");
        let config = Config::test(name.as_str()).update_config(|mut c| {
            c.partition_split_threshold = 10_000_000;
            c.max_partition_split_threshold = 10_000_000;
            c.max_cached_queries = 0;
            c.metadata_cache_max_capacity_bytes =
                env_parse("CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES", 0);
            c.metadata_cache_time_to_idle_secs = 1000;
            c
        });
        (name, config)
    }

    async fn setup(self: &Self, services: &CubeServices) -> Result<Arc<BenchState>, CubeError> {
        let dataset_path = download_and_unzip(
            "https://github.com/cube-js/testing-fixtures/raw/master/github-commits.tar.gz",
            "github-commits",
        )
        .await?;
        let path = dataset_path.join("github-commits-000.csv");

        let _ = services
            .sql_service
            .exec_query("CREATE SCHEMA IF NOT EXISTS test")
            .await?;

        let _ = services.sql_service
            .exec_query(format!("CREATE TABLE test.table (`repo` text, `email` text, `commit_count` int) WITH (input_format = 'csv') LOCATION '{}'", path_to_string(path)?).as_str())
            .await?;

        // Wait for all pending (compaction) jobs to finish.
        wait_for_all_jobs(&services).await?;

        let state = Arc::new(());

        // Warmup metadata cache.
        self.bench(services, state.clone()).await?;

        Ok(state)
    }

    async fn bench(
        self: &Self,
        services: &CubeServices,
        _state: Arc<BenchState>,
    ) -> Result<(), CubeError> {
        let repo = "2degrees/twod.wsgi";
        let r = services
            .sql_service
            .exec_query(
                format!(
                    "SELECT COUNT(*) FROM test.table WHERE repo = '{}' GROUP BY repo",
                    repo
                )
                .as_str(),
            )
            .await?;
        let rows = to_rows(&r);
        assert_eq!(rows, vec![vec![TableValue::Int(6)]]);
        Ok(())
    }
}

async fn download_and_unzip(url: &str, dataset: &str) -> Result<Box<Path>, CubeError> {
    let root = std::env::current_dir()?.join("data");
    let dataset_path = root.join(dataset);
    if !dataset_path.exists() {
        println!("Downloading {}", dataset);
        let response = reqwest::get(url).await?;
        let content = Cursor::new(response.bytes().await?);
        let tarfile = GzDecoder::new(content);
        let mut archive = Archive::new(tarfile);
        archive.unpack(root)?;
    }
    assert!(dataset_path.exists());
    Ok(dataset_path.into_boxed_path())
}

async fn wait_for_all_jobs(services: &CubeServices) -> Result<(), CubeError> {
    let wait_for = services
        .meta_store
        .all_jobs()
        .await?
        .iter()
        .map(|j| {
            (
                j.get_row().row_reference().clone(),
                j.get_row().job_type().clone(),
            )
        })
        .collect();
    let listener = services.cluster.job_result_listener();
    timeout(
        Duration::from_secs(10),
        listener.wait_for_job_results(wait_for),
    )
    .await??;
    Ok(())
}


text:
use std::path::PathBuf;

use clap::{ArgEnum, Args, Parser, Subcommand};

/// Encrypt, decrypt and solve classical ciphers.
#[derive(Parser, Debug)]
#[clap(name = "cipher", author = "Tom Thorogood <tomthorogood@outlook.com>")]
pub enum Opt {
    /// Generate completion scripts
    Completions {
        /// Output file to write completion to, if unspecified then writes to
        /// stdout
        #[clap(short, long, parse(from_os_str))]
        output: Option<PathBuf>,
        /// Shell to generate completions for
        #[clap(arg_enum)]
        shell: Shell,
    },
    /// Manage language configuration
    Lang {
        #[clap(subcommand)]
        sub: LangCmd,
    },
    /// Perform statistical analysis on a ciphertext
    Stats {
        /// If present, overrides the selected lang and uses the value given
        #[clap(global = true, short, long)]
        lang: Option<String>,
        /// Text to analyse. If not present then read from stdin
        #[clap(global = true, short, long)]
        text: Option<String>,
        #[clap(subcommand)]
        cmd: StatsCmd,
    },
    /// Encrypt a plaintext with a cipher. Ciphers are specified with
    /// the submodules
    Encrypt(CryptCmd),
    /// Decrypt a ciphertext with a cipher. Ciphers are specified with
    /// the submodules
    Decrypt(CryptCmd),
    /// Solve a ciphertext. Use submodules to solve a specific cipher.
    /// If no cipher is specified, the input will be solved by analysing
    /// the text and trying likely ciphers
    Solve {
        /// The cipher to solve as. If not specified, the message will be
        /// automatically solved
        #[clap(subcommand)]
        cipher: Option<CipherSolveCmd>,
        /// A crib to aid in solving. This may not always be used
        #[clap(global = true, short, long)]
        crib: Option<String>,
        /// The position of the crib within the ciphertext
        #[clap(global = true, long, short = 'p', requires("crib"))]
        crib_pos: Option<usize>,
        /// Display the key once solved
        #[clap(global = true, short = 'k', long)]
        show_key: bool,
        /// Hide the plaintext once solved
        #[clap(global = true, short = 'T', long)]
        no_plain: bool,
        /// Control the scoring statistics used to break the cipher
        #[clap(global = true, arg_enum, short = 's', long = "size")]
        stats_size: Option<StatsSizeOpt>,
        /// If present, overrides the selected lang and uses the value given
        #[clap(global = true, short, long)]
        lang: Option<String>,
        /// The text to solve, if not specified then read from stdin
        #[clap(global = true, short, long)]
        text: Option<String>,
    },
}

#[derive(ArgEnum, Clone, Copy, Debug)]
pub enum StatsSizeOpt {
    Unigrams,
    Bigrams,
    Trigrams,
    Quadgrams,
}

#[derive(ArgEnum, Clone, Copy, Debug)]
pub enum Shell {
    Bash,
    PowerShell,
}

#[derive(Subcommand, Debug)]
pub enum LangCmd {
    /// List all languages
    List,
    /// Select a language
    Set {
        /// Name of the language
        #[clap(short, long)]
        lang: String,
    },
    /// Select an alphabet. You can view the current selection with `lang list`
    SetAlph {
        /// Language to select alphabet for
        #[clap(short, long)]
        lang: Option<String>,
        /// Length of alphabet to select
        #[clap(short, long)]
        length: usize,
    },
    /// Remove a language
    #[clap(name = "rm")]
    Remove {
        /// Name of the language to remove
        #[clap(short, long)]
        name: String,
        /// Remove without asking for confirmation
        #[clap(short, long)]
        force: bool,
    },
    /// Add a new language
    New {
        /// Name of the language to add
        #[clap(short, long)]
        name: String,
        /// Uppercase alphabet
        #[clap(short, long)]
        upper: String,
        /// Lowercase alphabet
        #[clap(short, long)]
        lower: String,
        /// Text corpus, if not present then read from stdin
        #[clap(short, long)]
        corpus: Option<String>,
    },
    /// Change an existing language, adding or overwriting a cipher
    /// alphabet
    Alphabet {
        /// Name of the language to add the alphabet to
        #[clap(short, long)]
        name: String,
        /// Uppercase alphabet
        #[clap(short, long)]
        upper: String,
        /// Lowercase alphabet
        #[clap(short, long)]
        lower: String,
        /// Uppercase letters which should be removed from the alphabet
        /// when scoring
        #[clap(long)]
        discard_upper: String,
        /// Lowercase letters which should be removed from the alphabet
        /// when scoring
        #[clap(long)]
        discard_lower: String,
        /// Text corpus, if not present then read from stdin
        #[clap(short, long)]
        corpus: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum StatsCmd {
    /// Display a graph showing periodic index of coincedence
    Periodic {
        /// If present, sets the width of the graph
        #[clap(short, long, default_value = "60")]
        width: usize,
        /// If present, consider the the characters given rather than the
        /// language's alphabet
        #[clap(short, long)]
        alphabet: Option<String>,
    },
    /// Display a chart showing letter frequency
    Freq {
        /// If present, also show frequencies for whitespace characters
        #[clap(short, long)]
        whitespace: bool,
        /// If present, also show frequencies for all other (non-whitespace)
        /// characters
        #[clap(short, long)]
        punct: bool,
        /// If present, consider the the characters given rather than the
        /// language's alphabet
        #[clap(short, long)]
        alphabet: Option<String>,
    },
    /// Display the index of coincedence of the text
    Ioc {
        /// If present, consider the the characters given rather than the
        /// language's alphabet
        #[clap(short, long)]
        alphabet: Option<String>,
    },
    /// Display the text length and its factors
    Length {
        /// If present, consider the the characters given rather than the
        /// language's alphabet
        #[clap(short, long)]
        alphabet: Option<String>,
    },
    /// Display the chi squared value for the text
    ChiSquared,
    /// Display the Unigram score for the text
    Unigram,
    /// Display the Bigram score for the text
    Bigram,
    /// Display the Trigram score for the text
    Trigram,
    /// Display the Quadgram score for the text
    Quadgram,
}

#[derive(Args, Debug)]
pub struct CryptCmd {
    /// The algorithm to use
    #[clap(subcommand)]
    pub cipher: CipherCmd,
    /// If present, overrides the selected lang and uses the value given
    #[clap(global = true, short, long)]
    pub lang: Option<String>,
    /// The text to encrypt/decrypt, if not specified then read from stdin
    #[clap(global = true, short, long)]
    pub text: Option<String>,
}

#[derive(Subcommand, Debug)]
pub enum CipherCmd {
    /// The Affine cipher
    Affine {
        /// Affine coefficient, a
        #[clap(short, long)]
        a: i32,
        /// Affine constant, b
        #[clap(short, long)]
        b: i32,
    },
    /// The Atbash cipher
    Atbash,
    /// The Caesar cipher
    Caesar {
        /// Caesar shift
        #[clap(short, long)]
        shift: i32,
    },
    ClassicVigenere {
        /// Keyword
        #[clap(short, long)]
        keyword: String,
    },
    /// The Railfence cipher
    Railfence {
        /// Number of rails
        #[clap(short, long)]
        rails: i32,
    },
    /// The Rot13 cipher
    Rot13,
    /// The Scytale cipher
    Scytale {
        /// Number of faces
        #[clap(short, long)]
        faces: i32,
    },
    /// The Substitution cipher
    Substitution {
        /// Keyword or alphabet
        #[clap(short, long)]
        keyword: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum CipherSolveCmd {
    /// The Affine cipher
    Affine,
    /// The Atbash cipher
    Atbash,
    /// The Caesar cipher
    Caesar,
    ClassicVigenere {
        /// Maximum key length to try
        #[clap(long, default_value = "30")]
        max_key_length: usize,
    },
    /// The Railfence cipher
    Railfence,
    /// The Rot13 cipher
    Rot13,
    /// The Scytale cipher
    Scytale,
    /// The Substitution cipher
    Substitution {
        /// Limit to the number of iterations that the algorithm should run for
        #[clap(long, default_value = "2000")]
        max_iterations: usize,
        /// Number of times that a solution must be reached to determine that it
        /// is the optimal solution
        #[clap(long, default_value = "5")]
        min_repetitions: usize,
    },
}


text:
// Copyright 2020 Lukas Pustina
//
// 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::Result;
use bcc::{
    perf_event::{init_perf_map, PerfMap},
    BPF,
};
use log::info;
use log::trace;
use std::{
    ptr,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

#[repr(C)]
#[allow(non_camel_case_types, dead_code)]
#[derive(Debug, PartialEq, Eq)]
pub enum EventType {
    EVENT_ARG,
    EVENT_RET,
}

#[repr(C)]
pub struct Event {
    pub pid: libc::c_uint,
    pub ppid: libc::c_uint,
    pub ancestor: libc::c_uint,
    pub comm: [u8; 16], // TASK_COMM_LEN, cf. exec_logger.c
    pub r#type: EventType,
    pub argv: [u8; 128], // ARGSIZE, cf. exec_logger.c
    pub tty: [u8; 64],   // TTYSIZE, cf. exec_logger.c
    pub uid: libc::c_uint,
    pub gid: libc::c_uint,
    pub ret_val: libc::c_int,
}

impl From<&[u8]> for Event {
    fn from(bytes: &[u8]) -> Self {
        parse_struct(bytes)
    }
}

#[allow(clippy::unused_unit)]
pub struct KProbe<F: FnOnce(Event) -> () + Clone + std::marker::Send + 'static> {
    runnable: Arc<AtomicBool>,
    handler: F,
    opts: KProbeOpts,
}

#[allow(clippy::unused_unit)]
impl<F: FnOnce(Event) -> () + Clone + std::marker::Send + 'static> KProbe<F> {
    pub fn new(runnable: Arc<AtomicBool>, handler: F, opts: KProbeOpts) -> Self {
        KProbe {
            runnable,
            handler,
            opts,
        }
    }

    pub fn run(self) -> Result<()> {
        info!("Running Kprobe handler: {:?}", &self.opts);
        let handler = create_handler(self.handler);
        // It is important, to keep bpf in scope while running the event_loop. Otherwise it gets
        // dropped and we loose the connection to our kprobe
        let bpf = load_bpf(&self.opts)?;

        // create events table
        let table = bpf.table("events");
        let perf_map = init_perf_map(table, handler)?;

        event_loop(self.runnable, perf_map, self.opts.interval_ms)
    }
}

#[derive(Debug)]
pub struct KProbeOpts {
    pub max_args: u32,
    pub ancestor_name: String,
    pub max_ancestors: u32,
    pub interval_ms: u32,
}

impl Default for KProbeOpts {
    fn default() -> Self {
        KProbeOpts {
            max_args: 20,
            ancestor_name: "sshd".to_string(),
            max_ancestors: 20,
            interval_ms: 200,
        }
    }
}

impl KProbeOpts {
    fn max_args_key(&self) -> &'static str {
        "MAX_ARGS"
    }

    fn max_args_value(&self) -> String {
        self.max_args.to_string()
    }

    fn max_ancestors_key(&self) -> &'static str {
        "MAX_ANCESTORS"
    }

    fn max_ancestors_value(&self) -> String {
        self.max_ancestors.to_string()
    }

    fn ancestor_name_key(&self) -> &'static str {
        "ANCESTOR_NAME"
    }

    fn ancestor_name_value(&self) -> &str {
        self.ancestor_name.as_str()
    }
}

fn load_bpf(opts: &KProbeOpts) -> Result<BPF> {
    // load and parameterize BPF
    let code = include_str!("exec_logger.c");
    let code = code.replace(opts.max_args_key(), &opts.max_args_value());
    let code = code.replace(opts.ancestor_name_key(), opts.ancestor_name_value());
    let code = code.replace(opts.max_ancestors_key(), &opts.max_ancestors_value());
    // compile the above BPF code!
    let mut module = BPF::new(&code)?;
    // load + attach kprobes!
    bcc::Kprobe::new()
        .handler("hld_syscall_execve_entry")
        .function("sys_execve")
        .attach(&mut module)?;
    bcc::Kretprobe::new()
        .handler("hld_syscall_execve_return")
        .function("sys_execve")
        .attach(&mut module)?;

    Ok(module)
}

fn event_loop(runnable: Arc<AtomicBool>, mut perf_map: PerfMap, interval_ms: u32) -> Result<()> {
    while runnable.load(Ordering::SeqCst) {
        trace!("Event loop: polling perf map.");
        perf_map.poll(interval_ms as i32);
    }

    Ok(())
}

type HandlerGenerator = Box<dyn Fn() -> Box<dyn FnMut(&[u8]) + Send>>;

#[allow(clippy::unused_unit)]
fn create_handler<F>(handler: F) -> HandlerGenerator
where
    F: FnOnce(Event) -> () + Clone + std::marker::Send + 'static,
{
    Box::new(move || {
        let handler = handler.clone();
        Box::new(move |x| {
            let h = handler.clone();
            let event = x.into();
            h(event)
        })
    })
}

pub fn parse_struct<T>(buf: &[u8]) -> T {
    unsafe { ptr::read(buf.as_ptr() as *const T) }
}

pub fn parse_string(buf: &[u8]) -> String {
    // Search has to start from the front, so we find the _first_ 0 in order to prevent
    // reading invalid memory
    match buf.iter().position(|&x| x == 0) {
        Some(zero_pos) => String::from_utf8_lossy(&buf[0..zero_pos]).to_string(),
        None => String::from_utf8_lossy(buf).to_string(),
    }
}


text:
extern crate aoc2017;
extern crate failure;
use aoc2017::puzzles::day24;
use aoc2017::puzzles;

use std::io::BufRead;
use std::error::Error;

#[test]
fn part_one() {
  use aoc2017::puzzles::day24::Bridge;

  let connectors = get_connectors().expect("Error loading connectors");
  assert_eq!(
    day24::bridges(&connectors).map(|b| b.strength()).max(),
    Some(1906)
  );
}

#[test]
fn part_two() {
  use aoc2017::puzzles::day24::Bridge;

  let connectors = get_connectors().expect("Error loading connectors");
  let (_bl, bs) = day24::bridges(&connectors)
    .map(|b| (b.len(), b.strength()))
    .max()
    .unwrap();
  assert_eq!(bs, 1824);
}

fn get_connectors() -> Result<Vec<day24::Connector>, Box<Error>> {
  Ok(puzzles::get_puzzle_reader(24)?
    .lines()
    .map(|l| Ok(l?.parse::<day24::Connector>()?))
    .collect::<Result<Vec<day24::Connector>, Box<Error>>>()?)
}


text:
use combine::easy::Errors;

use tokenizer::Token;
use position::Pos;

pub type InternalError<'a> = Errors<Token<'a>, Token<'a>, Pos>;

/// Error parsing schema
///
/// This structure is opaque for forward compatibility. We are exploring a
/// way to improve both error message and API.
#[derive(Fail, Debug)]
#[fail(display="schema parse error: {}", _0)]
pub struct ParseError(String);

impl<'a> From<InternalError<'a>> for ParseError {
    fn from(e: InternalError<'a>) -> ParseError {
        ParseError(format!("{}", e))
    }
}