text:
pub(crate) mod multiple_keys;
use polars_arrow::utils::CustomIterTools;

use crate::frame::hash_join::multiple_keys::{
    inner_join_multiple_keys, left_join_multiple_keys, outer_join_multiple_keys,
};
use crate::frame::select::Selection;
use crate::prelude::*;
use crate::utils::{set_partition_size, split_ca};
use crate::vector_hasher::{
    create_hash_and_keys_threaded_vectorized, prepare_hashed_relation_threaded, this_partition,
    AsU64, StrHash,
};
use crate::{datatypes::PlHashMap, POOL};
use ahash::RandomState;
use hashbrown::hash_map::{Entry, RawEntryMut};
use hashbrown::HashMap;
use itertools::Itertools;
use rayon::prelude::*;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::{BuildHasher, Hash, Hasher};
use std::ops::Deref;
use unsafe_unwrap::UnsafeUnwrap;

#[cfg(feature = "private")]
pub use self::multiple_keys::private_left_join_multiple_keys;
use crate::frame::groupby::hashing::HASHMAP_INIT_SIZE;
use crate::utils::series::to_physical;

/// If Categorical types are created without a global string cache or under
/// a different global string cache the mapping will be incorrect.
#[cfg(feature = "dtype-categorical")]
pub(crate) fn check_categorical_src(l: &Series, r: &Series) -> Result<()> {
    if let (Ok(l), Ok(r)) = (l.categorical(), r.categorical()) {
        let l = l.categorical_map.as_ref().unwrap();
        let r = r.categorical_map.as_ref().unwrap();
        if !l.same_src(&*r) {
            return Err(PolarsError::ValueError("joins on categorical dtypes can only happen if they are created under the same global string cache".into()));
        }
    }
    Ok(())
}

macro_rules! det_hash_prone_order {
    ($self:expr, $other:expr) => {{
        // The shortest relation will be used to create a hash table.
        let left_first = $self.len() > $other.len();
        let a;
        let b;
        if left_first {
            a = $self;
            b = $other;
        } else {
            b = $self;
            a = $other;
        }

        (a, b, !left_first)
    }};
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JoinType {
    Left,
    Inner,
    Outer,
    #[cfg(feature = "asof_join")]
    AsOf,
    #[cfg(feature = "cross_join")]
    Cross,
}

pub(crate) unsafe fn get_hash_tbl_threaded_join_partitioned<T, H>(
    h: u64,
    hash_tables: &[HashMap<T, Vec<u32>, H>],
    len: u64,
) -> &HashMap<T, Vec<u32>, H> {
    let mut idx = 0;
    for i in 0..len {
        // can only be done for powers of two.
        // n % 2^i = n & (2^i - 1)
        if (h + i) & (len - 1) == 0 {
            idx = i as usize;
        }
    }
    hash_tables.get_unchecked(idx)
}

#[allow(clippy::type_complexity)]
unsafe fn get_hash_tbl_threaded_join_mut_partitioned<T, H>(
    h: u64,
    hash_tables: &mut [HashMap<T, (bool, Vec<u32>), H>],
    len: u64,
) -> &mut HashMap<T, (bool, Vec<u32>), H> {
    let mut idx = 0;
    for i in 0..len {
        // can only be done for powers of two.
        // n % 2^i = n & (2^i - 1)
        if (h + i) & (len - 1) == 0 {
            idx = i as usize;
        }
    }
    hash_tables.get_unchecked_mut(idx)
}

/// Probe the build table and add tuples to the results (inner join)
fn probe_inner<T, F>(
    probe: &[T],
    hash_tbls: &[PlHashMap<T, Vec<u32>>],
    results: &mut Vec<(u32, u32)>,
    local_offset: usize,
    n_tables: u64,
    swap_fn: F,
) where
    T: Send + Hash + Eq + Sync + Copy + AsU64,
    F: Fn(u32, u32) -> (u32, u32),
{
    assert!(hash_tbls.len().is_power_of_two());
    probe.iter().enumerate().for_each(|(idx_a, k)| {
        let idx_a = (idx_a + local_offset) as u32;
        // probe table that contains the hashed value
        let current_probe_table =
            unsafe { get_hash_tbl_threaded_join_partitioned(k.as_u64(), hash_tbls, n_tables) };

        let value = current_probe_table.get(k);

        if let Some(indexes_b) = value {
            let tuples = indexes_b.iter().map(|&idx_b| swap_fn(idx_a, idx_b));
            results.extend(tuples);
        }
    });
}

pub(crate) fn create_probe_table<T, IntoSlice>(keys: Vec<IntoSlice>) -> Vec<PlHashMap<T, Vec<u32>>>
where
    T: Send + Hash + Eq + Sync + Copy + AsU64,
    IntoSlice: AsRef<[T]> + Send + Sync,
{
    let n_partitions = set_partition_size();

    // We will create a hashtable in every thread.
    // We use the hash to partition the keys to the matching hashtable.
    // Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition.
    POOL.install(|| {
        (0..n_partitions).into_par_iter().map(|partition_no| {
            let partition_no = partition_no as u64;

            let mut hash_tbl: PlHashMap<T, Vec<u32>> = PlHashMap::with_capacity(HASHMAP_INIT_SIZE);

            let n_partitions = n_partitions as u64;
            let mut offset = 0;
            for keys in &keys {
                let keys = keys.as_ref();
                let len = keys.len() as u32;

                let mut cnt = 0;
                keys.iter().for_each(|k| {
                    let idx = cnt + offset;
                    cnt += 1;

                    if this_partition(k.as_u64(), partition_no, n_partitions) {
                        let entry = hash_tbl.entry(*k);

                        match entry {
                            Entry::Vacant(entry) => {
                                entry.insert(vec![idx]);
                            }
                            Entry::Occupied(mut entry) => {
                                let v = entry.get_mut();
                                v.push(idx);
                            }
                        }
                    }
                });
                offset += len;
            }
            hash_tbl
        })
    })
    .collect()
}

fn hash_join_tuples_inner<T, IntoSlice>(
    probe: Vec<IntoSlice>,
    build: Vec<IntoSlice>,
    // Because b should be the shorter relation we could need to swap to keep left left and right right.
    swap: bool,
) -> Vec<(u32, u32)>
where
    IntoSlice: AsRef<[T]> + Send + Sync,
    T: Send + Hash + Eq + Sync + Copy + AsU64,
{
    // NOTE: see the left join for more elaborate comments

    // first we hash one relation
    let hash_tbls = create_probe_table(build);

    let n_tables = hash_tbls.len() as u64;
    debug_assert!(n_tables.is_power_of_two());
    let offsets = probe
        .iter()
        .map(|ph| ph.as_ref().len())
        .scan(0, |state, val| {
            let out = *state;
            *state += val;
            Some(out)
        })
        .collect::<Vec<_>>();
    // next we probe the other relation
    // code duplication is because we want to only do the swap check once
    POOL.install(|| {
        probe
            .into_par_iter()
            .zip(offsets)
            .map(|(probe, offset)| {
                let probe = probe.as_ref();
                // local reference
                let hash_tbls = &hash_tbls;
                let mut results = Vec::with_capacity(probe.len());
                let local_offset = offset;

                // branch is to hoist swap out of the inner loop.
                if swap {
                    probe_inner(
                        probe,
                        hash_tbls,
                        &mut results,
                        local_offset,
                        n_tables,
                        |idx_a, idx_b| (idx_b, idx_a),
                    )
                } else {
                    probe_inner(
                        probe,
                        hash_tbls,
                        &mut results,
                        local_offset,
                        n_tables,
                        |idx_a, idx_b| (idx_a, idx_b),
                    )
                }

                results
            })
            .flatten()
            .collect()
    })
}

fn hash_join_tuples_left<T, IntoSlice>(
    probe: Vec<IntoSlice>,
    build: Vec<IntoSlice>,
) -> Vec<(u32, Option<u32>)>
where
    IntoSlice: AsRef<[T]> + Send + Sync,
    T: Send + Hash + Eq + Sync + Copy + AsU64,
{
    // first we hash one relation
    let hash_tbls = create_probe_table(build);

    // we determine the offset so that we later know which index to store in the join tuples
    let offsets = probe
        .iter()
        .map(|ph| ph.as_ref().len())
        .scan(0, |state, val| {
            let out = *state;
            *state += val;
            Some(out)
        })
        .collect::<Vec<_>>();

    let n_tables = hash_tbls.len() as u64;
    debug_assert!(n_tables.is_power_of_two());

    // next we probe the other relation
    POOL.install(|| {
        probe
            .into_par_iter()
            .zip(offsets)
            // probes_hashes: Vec<u64> processed by this thread
            // offset: offset index
            .map(|(probe, offset)| {
                // local reference
                let hash_tbls = &hash_tbls;
                let probe = probe.as_ref();

                // assume the result tuples equal lenght of the no. of hashes processed by this thread.
                let mut results = Vec::with_capacity(probe.len());

                probe.iter().enumerate().for_each(|(idx_a, k)| {
                    let idx_a = (idx_a + offset) as u32;
                    // probe table that contains the hashed value
                    let current_probe_table = unsafe {
                        get_hash_tbl_threaded_join_partitioned(k.as_u64(), hash_tbls, n_tables)
                    };

                    // we already hashed, so we don't have to hash again.
                    let value = current_probe_table.get(k);

                    match value {
                        // left and right matches
                        Some(indexes_b) => {
                            results.extend(indexes_b.iter().map(|&idx_b| (idx_a, Some(idx_b))))
                        }
                        // only left values, right = null
                        None => results.push((idx_a, None)),
                    }
                });
                results
            })
            .flatten()
            .collect()
    })
}

/// Probe the build table and add tuples to the results (inner join)
fn probe_outer<T, F, G, H>(
    probe_hashes: &[Vec<(u64, T)>],
    hash_tbls: &mut [PlHashMap<T, (bool, Vec<u32>)>],
    results: &mut Vec<(Option<u32>, Option<u32>)>,
    n_tables: u64,
    // Function that get index_a, index_b when there is a match and pushes to result
    swap_fn_match: F,
    // Function that get index_a when there is no match and pushes to result
    swap_fn_no_match: G,
    // Function that get index_b from the build table that did not match any in A and pushes to result
    swap_fn_drain: H,
) where
    T: Send + Hash + Eq + Sync + Copy,
    // idx_a, idx_b -> ...
    F: Fn(u32, u32) -> (Option<u32>, Option<u32>),
    // idx_a -> ...
    G: Fn(u32) -> (Option<u32>, Option<u32>),
    // idx_b -> ...
    H: Fn(u32) -> (Option<u32>, Option<u32>),
{
    // needed for the partition shift instead of modulo to make sense
    assert!(n_tables.is_power_of_two());
    let mut idx_a = 0;
    for probe_hashes in probe_hashes {
        for (h, key) in probe_hashes {
            let h = *h;
            // probe table that contains the hashed value
            let current_probe_table =
                unsafe { get_hash_tbl_threaded_join_mut_partitioned(h, hash_tbls, n_tables) };

            let entry = current_probe_table
                .raw_entry_mut()
                .from_key_hashed_nocheck(h, key);

            match entry {
                // match and remove
                RawEntryMut::Occupied(mut occupied) => {
                    let (tracker, indexes_b) = occupied.get_mut();
                    *tracker = true;
                    results.extend(indexes_b.iter().map(|&idx_b| swap_fn_match(idx_a, idx_b)))
                }
                // no match
                RawEntryMut::Vacant(_) => results.push(swap_fn_no_match(idx_a)),
            }
            idx_a += 1;
        }
    }

    for hash_tbl in hash_tbls {
        hash_tbl.iter().for_each(|(_k, (tracker, indexes_b))| {
            // remaining joined values from the right table
            if !*tracker {
                results.extend(indexes_b.iter().map(|&idx_b| swap_fn_drain(idx_b)))
            }
        });
    }
}

/// Hash join outer. Both left and right can have no match so Options
fn hash_join_tuples_outer<T, I, J>(
    a: Vec<I>,
    b: Vec<J>,
    swap: bool,
) -> Vec<(Option<u32>, Option<u32>)>
where
    I: Iterator<Item = T> + Send + TrustedLen,
    J: Iterator<Item = T> + Send + TrustedLen,
    T: Hash + Eq + Copy + Sync + Send,
{
    // This function is partially multi-threaded.
    // Parts that are done in parallel:
    //  - creation of the probe tables
    //  - creation of the hashes

    // during the probe phase values are removed from the tables, that's done single threaded to
    // keep it lock free.

    let size = a.iter().map(|a| a.size_hint().0).sum::<usize>()
        + b.iter().map(|b| b.size_hint().0).sum::<usize>();
    let mut results = Vec::with_capacity(size);

    // prepare hash table
    let mut hash_tbls = prepare_hashed_relation_threaded(b);
    let random_state = hash_tbls[0].hasher().clone();

    // we pre hash the probing values
    let (probe_hashes, _) = create_hash_and_keys_threaded_vectorized(a, Some(random_state));

    let n_tables = hash_tbls.len() as u64;

    // probe the hash table.
    // Note: indexes from b that are not matched will be None, Some(idx_b)
    // Therefore we remove the matches and the remaining will be joined from the right

    // branch is because we want to only do the swap check once
    if swap {
        probe_outer(
            &probe_hashes,
            &mut hash_tbls,
            &mut results,
            n_tables,
            |idx_a, idx_b| (Some(idx_b), Some(idx_a)),
            |idx_a| (None, Some(idx_a)),
            |idx_b| (Some(idx_b), None),
        )
    } else {
        probe_outer(
            &probe_hashes,
            &mut hash_tbls,
            &mut results,
            n_tables,
            |idx_a, idx_b| (Some(idx_a), Some(idx_b)),
            |idx_a| (Some(idx_a), None),
            |idx_b| (None, Some(idx_b)),
        )
    }
    results
}

pub(crate) trait HashJoin<T> {
    fn hash_join_inner(&self, _other: &ChunkedArray<T>) -> Vec<(u32, u32)> {
        unimplemented!()
    }
    fn hash_join_left(&self, _other: &ChunkedArray<T>) -> Vec<(u32, Option<u32>)> {
        unimplemented!()
    }
    fn hash_join_outer(&self, _other: &ChunkedArray<T>) -> Vec<(Option<u32>, Option<u32>)> {
        unimplemented!()
    }
}

impl HashJoin<Float32Type> for Float32Chunked {
    fn hash_join_inner(&self, other: &Float32Chunked) -> Vec<(u32, u32)> {
        let ca = self.bit_repr_small();
        let other = other.bit_repr_small();
        ca.hash_join_inner(&other)
    }
    fn hash_join_left(&self, other: &Float32Chunked) -> Vec<(u32, Option<u32>)> {
        let ca = self.bit_repr_small();
        let other = other.bit_repr_small();
        ca.hash_join_left(&other)
    }
    fn hash_join_outer(&self, other: &Float32Chunked) -> Vec<(Option<u32>, Option<u32>)> {
        let ca = self.bit_repr_small();
        let other = other.bit_repr_small();
        ca.hash_join_outer(&other)
    }
}

impl HashJoin<Float64Type> for Float64Chunked {
    fn hash_join_inner(&self, other: &Float64Chunked) -> Vec<(u32, u32)> {
        let ca = self.bit_repr_large();
        let other = other.bit_repr_large();
        ca.hash_join_inner(&other)
    }
    fn hash_join_left(&self, other: &Float64Chunked) -> Vec<(u32, Option<u32>)> {
        let ca = self.bit_repr_large();
        let other = other.bit_repr_large();
        ca.hash_join_left(&other)
    }
    fn hash_join_outer(&self, other: &Float64Chunked) -> Vec<(Option<u32>, Option<u32>)> {
        let ca = self.bit_repr_large();
        let other = other.bit_repr_large();
        ca.hash_join_outer(&other)
    }
}

impl HashJoin<CategoricalType> for CategoricalChunked {
    fn hash_join_inner(&self, other: &CategoricalChunked) -> Vec<(u32, u32)> {
        self.deref().hash_join_inner(other.deref())
    }
    fn hash_join_left(&self, other: &CategoricalChunked) -> Vec<(u32, Option<u32>)> {
        self.deref().hash_join_left(other.deref())
    }
    fn hash_join_outer(&self, other: &CategoricalChunked) -> Vec<(Option<u32>, Option<u32>)> {
        self.deref().hash_join_outer(other.deref())
    }
}

fn num_group_join_inner<T>(left: &ChunkedArray<T>, right: &ChunkedArray<T>) -> Vec<(u32, u32)>
where
    T: PolarsIntegerType,
    T::Native: Hash + Eq + Send + AsU64 + Copy,
    Option<T::Native>: AsU64,
{
    let n_threads = POOL.current_num_threads();
    let (a, b, swap) = det_hash_prone_order!(left, right);
    let splitted_a = split_ca(a, n_threads).unwrap();
    let splitted_b = split_ca(b, n_threads).unwrap();
    match (
        left.has_validity(),
        right.has_validity(),
        left.chunks.len(),
        right.chunks.len(),
    ) {
        (false, false, 1, 1) => {
            let keys_a = splitted_a
                .iter()
                .map(|ca| ca.cont_slice().unwrap())
                .collect::<Vec<_>>();
            let keys_b = splitted_b
                .iter()
                .map(|ca| ca.cont_slice().unwrap())
                .collect::<Vec<_>>();
            hash_join_tuples_inner(keys_a, keys_b, swap)
        }
        (false, false, _, _) => {
            let keys_a = splitted_a
                .iter()
                .map(|ca| ca.into_no_null_iter().collect::<Vec<_>>())
                .collect::<Vec<_>>();
            let keys_b = splitted_b
                .iter()
                .map(|ca| ca.into_no_null_iter().collect::<Vec<_>>())
                .collect::<Vec<_>>();
            hash_join_tuples_inner(keys_a, keys_b, swap)
        }
        (_, _, 1, 1) => {
            let keys_a = splitted_a
                .iter()
                .map(|ca| {
                    ca.downcast_iter()
                        .map(|v| v.into_iter().map(|v| v.copied().as_u64()))
                        .flatten()
                        .collect::<Vec<_>>()
                })
                .collect::<Vec<_>>();

            let keys_b = splitted_b
                .iter()
                .map(|ca| {
                    ca.downcast_iter()
                        .map(|v| v.into_iter().map(|v| v.copied().as_u64()))
                        .flatten()
                        .collect::<Vec<_>>()
                })
                .collect::<Vec<_>>();
            hash_join_tuples_inner(keys_a, keys_b, swap)
        }
        _ => {
            let keys_a = splitted_a
                .iter()
                .map(|ca| ca.into_iter().map(|v| v.as_u64()).collect::<Vec<_>>())
                .collect::<Vec<_>>();
            let keys_b = splitted_b
                .iter()
                .map(|ca| ca.into_iter().map(|v| v.as_u64()).collect::<Vec<_>>())
                .collect::<Vec<_>>();
            hash_join_tuples_inner(keys_a, keys_b, swap)
        }
    }
}

fn num_group_join_left<T>(
    left: &ChunkedArray<T>,
    right: &ChunkedArray<T>,
) -> Vec<(u32, Option<u32>)>
where
    T: PolarsIntegerType,
    T::Native: Hash + Eq + Send + AsU64,
    Option<T::Native>: AsU64,
{
    let n_threads = POOL.current_num_threads();
    let splitted_a = split_ca(left, n_threads).unwrap();
    let splitted_b = split_ca(right, n_threads).unwrap();
    match (
        left.has_validity(),
        right.has_validity(),
        left.chunks.len(),
        right.chunks.len(),
    ) {
        (false, false, 1, 1) => {
            let keys_a = splitted_a
                .iter()
                .map(|ca| ca.cont_slice().unwrap())
                .collect::<Vec<_>>();
            let keys_b = splitted_b
                .iter()
                .map(|ca| ca.cont_slice().unwrap())
                .collect::<Vec<_>>();
            hash_join_tuples_left(keys_a, keys_b)


text:
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Response<T> {
    pub message: String,
    pub status: Option<String>,
    pub data: Option<T>,
    pub error: Option<String>,
    pub status_code: u32,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RateGetResponse {
    pub message: String,
    pub status: Option<String>,
    pub rate: f64,
    pub error: Option<String>,
    pub status_code: u32,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentSendData {
    pub reference: String,
    pub business_name: String,
    pub business_email: String,
    pub business_logo: String,
    pub customer_name: String,
    pub customer_email: String,
    pub address: String,
    pub crypto_amount: f64,
    pub fiat_amount: f64,
    pub fee_in_crypto: f64,
    pub currency: String,
    pub coin: String,
    pub accept_partial_payment: bool,
    pub network: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentConfirmData {
    pub id: String,
    pub reference: String,
    pub sender_address: Option<String>,
    pub recipient_address: String,
    pub actual_amount: f64,
    pub amount_paid: Option<String>,
    pub amount_paid_fiat: Option<String>,
    pub fiat_amount: f64,
    pub amount_recieved: Option<String>,
    pub amount_recieved_fiat: Option<String>,
    pub coin: String,
    pub currency: String,
    pub hash: Option<String>,
    pub block_number: Option<String>,
    #[serde(rename = "type")]
    pub kind: Option<String>,
    pub accept_partial_payment: bool,
    pub status: String,
    pub network: String,
    pub blockchain: String,
    pub fee_in_crypto: f64,
    pub customer: PaymentConfirmCustomerData,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentConfirmCustomerData {
    pub customer_name: String,
    pub customer_email: String,
    pub customer_phone: Option<String>,
    pub id: String,
    pub network: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferSendData {
    pub id: String,
    pub transaction_hash: String,
    pub wallet_address: String,
    pub amount: f64,
    pub coin: String,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcceptedCoinData {
    pub id: String,
    pub name: String,
    pub symbol: String,
    pub logo: String,
    pub address: String,
    pub network: String,
    pub blockchain: String,
    pub status: String,
    pub created_at: String,
    pub updated_at: String,
}

domain: rust


text:
use crate::{
    util::{range::NumRange, unit::Meter3},
    world::{
        generate::{Generate, TileBuilder, WorldBuilder},
        hex::{HexAxialDirection, HexAxis, TilePoint, TilePointMap},
        World,
    },
    WorldConfig,
};
use std::iter;

/// Generate rainfall on each tile using a simulation of
/// evaporation & precipitation based on wind direction and elevation. This has
/// to run **after elevation and ocean generation**.
#[derive(Debug)]
pub struct RainfallGenerator;

impl Generate for RainfallGenerator {
    fn generate(&self, world: &mut WorldBuilder) {
        // This generator works as a one-pass rainfall simulator. Imagine a line
        // (our clouds) that runs perpendicular to the wind, and is as wide as
        // the world at its fattest point (i.e. it always covers the
        // whole world, but in most places will hang over the edge a
        // bit).
        //
        // We'll start at the upwind side of the world, and move along the world
        // one row at a time. For each row that the clouds are over, we'll pick
        // up moisture (where the amount is based on whether or not it's water),
        // and drop rain (where the amount is based on elevation).

        // This step can be disabled to improve performance
        if world.config.rainfall.enabled {
            let mut cloud_line =
                CloudLine::new(&world.config, world.wind_direction());

            let radius = world.config.radius as i16;
            for _ in -radius..=radius {
                cloud_line.precipitate_and_evaporate(&mut world.tiles);
                cloud_line.advance();
            }
        } else {
            for tile in world.tiles.values_mut() {
                tile.set_rainfall(Meter3(0.0));
            }
        }
    }
}

struct CloudLine<'a> {
    config: &'a WorldConfig,
    wind_direction: HexAxialDirection,
    coax_offset: i16,
    cloud_volumes: Vec<Meter3>,
    rainfall_factor_range: NumRange<f64>,
    spread_coefficients: Vec<f64>,
}

impl<'a> CloudLine<'a> {
    fn new(config: &'a WorldConfig, wind_direction: HexAxialDirection) -> Self {
        let world_width = (config.radius as usize) * 2 + 1;
        let cloud_volumes: Vec<Meter3> =
            iter::repeat(Meter3(0.0)).take(world_width).collect();

        let l = (2 * config.rainfall.evaporation_spread_distance + 1) as usize;
        let center_idx = config.rainfall.evaporation_spread_distance as usize;
        let mut spread_coefficients: Vec<f64> =
            iter::repeat(0.0).take(l).collect();
        let spread_range = NumRange::new(
            0.0,
            config.rainfall.evaporation_spread_distance as f64,
        );
        for d in 0..=config.rainfall.evaporation_spread_distance {
            let v = spread_range
                .normalize(d as f64)
                .powf(config.rainfall.evaporation_spread_exponent);
            spread_coefficients[center_idx - d as usize] = v;
            spread_coefficients[center_idx + d as usize] = v;
        }
        let sum: f64 = spread_coefficients.iter().sum();
        for v in spread_coefficients.iter_mut() {
            *v /= sum;
        }

        Self {
            config,
            wind_direction,
            coax_offset: -(config.radius as i16) * wind_direction.signum(),
            cloud_volumes,
            rainfall_factor_range: NumRange::new(
                0.0,
                config.rainfall.rainfall_fraction_limit,
            ),
            spread_coefficients,
        }
    }

    fn index_to_pos(&self, index: usize) -> TilePoint {
        let perp_offset = (index as i16) - (self.config.radius as i16);
        match self.wind_direction.axis {
            HexAxis::X => TilePoint::new_xy(self.coax_offset, perp_offset),
            HexAxis::Y => TilePoint::new_yz(self.coax_offset, perp_offset),
            HexAxis::Z => TilePoint::new_xz(perp_offset, self.coax_offset),
        }
    }

    /// Calculate a scaling factor for how much rain a tile should get. Higher
    /// tiles get more rain. This simulates the clouds getting stuck up against
    /// mountains.
    fn calc_rainfall_factor(&self, tile: &TileBuilder) -> f64 {
        World::ELEVATION_RANGE
            .value(tile.elevation())
            .convert::<f64>()
            .map_to(self.rainfall_factor_range)
            .clamp()
            .inner()
    }

    /// Calculate how much water vapor this tile produces when the clouds pass
    /// over it.
    fn calc_evaporation(&self, tile: &TileBuilder) -> Meter3 {
        if tile.is_water_biome() {
            self.config.rainfall.evaporation_default
        } else {
            self.config.rainfall.evaporation_default
                * self.config.rainfall.evaporation_land_scale
        }
    }

    /// Simulation precipitation on the current line, then simulation
    /// evaporation. It's easiest to do this all together so we only have to
    /// each tile lookup once.
    fn precipitate_and_evaporate(
        &mut self,
        tiles: &mut TilePointMap<TileBuilder>,
    ) {
        let mut evaporation: Vec<Meter3> = iter::repeat(Meter3(0.0))
            .take(self.cloud_volumes.len())
            .collect();

        // drop the load
        #[allow(clippy::needless_range_loop)]
        for i in 0..self.cloud_volumes.len() {
            let pos = self.index_to_pos(i);
            if let Some(tile) = tiles.get_mut(&pos) {
                evaporation[i] = self.calc_evaporation(tile);
                // Each tile receives some fraction of the current water
                // available in the cloud
                let rainfall =
                    self.cloud_volumes[i] * self.calc_rainfall_factor(tile);
                self.cloud_volumes[i] -= rainfall;
                tile.set_rainfall(rainfall);
            }
        }

        // big succ
        // For each slot in the clouds, it draws water from n tiles to its
        // left and right. The exact distance, and the diminishing factor, are
        // determined by the config.
        let spread_dist =
            self.config.rainfall.evaporation_spread_distance as usize;
        for (i, v) in self.cloud_volumes.iter_mut().enumerate() {
            let evap: Meter3 = self
                .spread_coefficients
                .iter()
                .enumerate()
                .filter_map(|(j, coef)| {
                    let idx = (i + j).checked_sub(spread_dist)?;
                    let e = *evaporation.get(idx)?;
                    Some(e * coef)
                })
                .sum();
            *v += evap;
        }
    }

    fn advance(&mut self) {
        self.coax_offset += self.wind_direction.signum();
    }
}


text:
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
pub mod private_endpoint_connection {
    use crate::models::*;
    pub async fn get(
        operation_config: &crate::OperationConfig,
        vault_name: &str,
        resource_group_name: &str,
        subscription_id: &str,
        private_endpoint_connection_name: &str,
    ) -> std::result::Result<PrivateEndpointConnectionResource, get::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateEndpointConnections/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            vault_name,
            private_endpoint_connection_name
        );
        let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::GET);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(get::Error::GetTokenError)?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
        let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: PrivateEndpointConnectionResource =
                    serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                let rsp_value: ErrorResponse =
                    serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
                Err(get::Error::DefaultResponse {
                    status_code,
                    value: rsp_value,
                })
            }
        }
    }
    pub mod get {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("HTTP status code {}", status_code)]
            DefaultResponse {
                status_code: http::StatusCode,
                value: models::ErrorResponse,
            },
            #[error("Failed to parse request URL: {0}")]
            ParseUrlError(url::ParseError),
            #[error("Failed to build request: {0}")]
            BuildRequestError(http::Error),
            #[error("Failed to execute request: {0}")]
            ExecuteRequestError(azure_core::HttpError),
            #[error("Failed to serialize request body: {0}")]
            SerializeError(serde_json::Error),
            #[error("Failed to deserialize response: {0}, body: {1:?}")]
            DeserializeError(serde_json::Error, bytes::Bytes),
            #[error("Failed to get access token: {0}")]
            GetTokenError(azure_core::Error),
        }
    }
    pub async fn put(
        operation_config: &crate::OperationConfig,
        vault_name: &str,
        resource_group_name: &str,
        subscription_id: &str,
        private_endpoint_connection_name: &str,
        parameters: &PrivateEndpointConnectionResource,
    ) -> std::result::Result<put::Response, put::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateEndpointConnections/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            vault_name,
            private_endpoint_connection_name
        );
        let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::PUT);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(put::Error::GetTokenError)?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        req_builder = req_builder.header("content-type", "application/json");
        let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
        let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: PrivateEndpointConnectionResource =
                    serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
                Ok(put::Response::Ok200(rsp_value))
            }
            http::StatusCode::CREATED => {
                let rsp_body = rsp.body();
                let rsp_value: PrivateEndpointConnectionResource =
                    serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
                Ok(put::Response::Created201(rsp_value))
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(put::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod put {
        use crate::{models, models::*};
        #[derive(Debug)]
        pub enum Response {
            Ok200(PrivateEndpointConnectionResource),
            Created201(PrivateEndpointConnectionResource),
        }
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {0}")]
            ParseUrlError(url::ParseError),
            #[error("Failed to build request: {0}")]
            BuildRequestError(http::Error),
            #[error("Failed to execute request: {0}")]
            ExecuteRequestError(azure_core::HttpError),
            #[error("Failed to serialize request body: {0}")]
            SerializeError(serde_json::Error),
            #[error("Failed to deserialize response: {0}, body: {1:?}")]
            DeserializeError(serde_json::Error, bytes::Bytes),
            #[error("Failed to get access token: {0}")]
            GetTokenError(azure_core::Error),
        }
    }
    pub async fn delete(
        operation_config: &crate::OperationConfig,
        vault_name: &str,
        resource_group_name: &str,
        subscription_id: &str,
        private_endpoint_connection_name: &str,
    ) -> std::result::Result<delete::Response, delete::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateEndpointConnections/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            vault_name,
            private_endpoint_connection_name
        );
        let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::DELETE);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(delete::Error::GetTokenError)?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?;
        let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?;
        match rsp.status() {
            http::StatusCode::OK => Ok(delete::Response::Ok200),
            http::StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
            http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
            status_code => {
                let rsp_body = rsp.body();
                let rsp_value: ErrorResponse =
                    serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?;
                Err(delete::Error::DefaultResponse {
                    status_code,
                    value: rsp_value,
                })
            }
        }
    }
    pub mod delete {
        use crate::{models, models::*};
        #[derive(Debug)]
        pub enum Response {
            Ok200,
            Accepted202,
            NoContent204,
        }
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("HTTP status code {}", status_code)]
            DefaultResponse {
                status_code: http::StatusCode,
                value: models::ErrorResponse,
            },
            #[error("Failed to parse request URL: {0}")]
            ParseUrlError(url::ParseError),
            #[error("Failed to build request: {0}")]
            BuildRequestError(http::Error),
            #[error("Failed to execute request: {0}")]
            ExecuteRequestError(azure_core::HttpError),
            #[error("Failed to serialize request body: {0}")]
            SerializeError(serde_json::Error),
            #[error("Failed to deserialize response: {0}, body: {1:?}")]
            DeserializeError(serde_json::Error, bytes::Bytes),
            #[error("Failed to get access token: {0}")]
            GetTokenError(azure_core::Error),
        }
    }
}
pub async fn get_operation_status(
    operation_config: &crate::OperationConfig,
    vault_name: &str,
    resource_group_name: &str,
    subscription_id: &str,
    private_endpoint_connection_name: &str,
    operation_id: &str,
) -> std::result::Result<OperationStatus, get_operation_status::Error> {
    let http_client = operation_config.http_client();
    let url_str = & format ! ("{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/privateEndpointConnections/{}/operationsStatus/{}" , operation_config . base_path () , subscription_id , resource_group_name , vault_name , private_endpoint_connection_name , operation_id) ;
    let mut url = url::Url::parse(url_str).map_err(get_operation_status::Error::ParseUrlError)?;
    let mut req_builder = http::request::Builder::new();
    req_builder = req_builder.method(http::Method::GET);
    if let Some(token_credential) = operation_config.token_credential() {
        let token_response = token_credential
            .get_token(operation_config.token_credential_resource())
            .await
            .map_err(get_operation_status::Error::GetTokenError)?;
        req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
    }
    url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
    let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
    req_builder = req_builder.uri(url.as_str());
    let req = req_builder.body(req_body).map_err(get_operation_status::Error::BuildRequestError)?;
    let rsp = http_client
        .execute_request(req)
        .await
        .map_err(get_operation_status::Error::ExecuteRequestError)?;
    match rsp.status() {
        http::StatusCode::OK => {
            let rsp_body = rsp.body();
            let rsp_value: OperationStatus = serde_json::from_slice(rsp_body)
                .map_err(|source| get_operation_status::Error::DeserializeError(source, rsp_body.clone()))?;
            Ok(rsp_value)
        }
        status_code => {
            let rsp_body = rsp.body();
            let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body)
                .map_err(|source| get_operation_status::Error::DeserializeError(source, rsp_body.clone()))?;
            Err(get_operation_status::Error::DefaultResponse {
                status_code,
                value: rsp_value,
            })
        }
    }
}
pub mod get_operation_status {
    use crate::{models, models::*};
    #[derive(Debug, thiserror :: Error)]
    pub enum Error {
        #[error("HTTP status code {}", status_code)]
        DefaultResponse {
            status_code: http::StatusCode,
            value: models::ErrorResponse,
        },
        #[error("Failed to parse request URL: {0}")]
        ParseUrlError(url::ParseError),
        #[error("Failed to build request: {0}")]
        BuildRequestError(http::Error),
        #[error("Failed to execute request: {0}")]
        ExecuteRequestError(azure_core::HttpError),
        #[error("Failed to serialize request body: {0}")]
        SerializeError(serde_json::Error),
        #[error("Failed to deserialize response: {0}, body: {1:?}")]
        DeserializeError(serde_json::Error, bytes::Bytes),
        #[error("Failed to get access token: {0}")]
        GetTokenError(azure_core::Error),
    }
}
pub mod backup_resource_vault_configs {
    use crate::models::*;
    pub async fn get(
        operation_config: &crate::OperationConfig,
        vault_name: &str,
        resource_group_name: &str,
        subscription_id: &str,
    ) -> std::result::Result<BackupResourceVaultConfigResource, get::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/backupconfig/vaultconfig",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            vault_name
        );
        let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::GET);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(get::Error::GetTokenError)?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
        let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: BackupResourceVaultConfigResource =
                    serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(get::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod get {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {0}")]
            ParseUrlError(url::ParseError),
            #[error("Failed to build request: {0}")]
            BuildRequestError(http::Error),
            #[error("Failed to execute request: {0}")]
            ExecuteRequestError(azure_core::HttpError),
            #[error("Failed to serialize request body: {0}")]
            SerializeError(serde_json::Error),
            #[error("Failed to deserialize response: {0}, body: {1:?}")]
            DeserializeError(serde_json::Error, bytes::Bytes),
            #[error("Failed to get access token: {0}")]
            GetTokenError(azure_core::Error),
        }
    }
    pub async fn put(
        operation_config: &crate::OperationConfig,
        vault_name: &str,
        resource_group_name: &str,
        subscription_id: &str,
        parameters: &BackupResourceVaultConfigResource,
    ) -> std::result::Result<BackupResourceVaultConfigResource, put::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/Subscriptions/{}/resourceGroups/{}/providers/Microsoft.RecoveryServices/vaults/{}/backupconfig/vaultconfig",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            vault_name
        );
        let mut url = url::Url::parse(url_str).map_err(put::Error::ParseUrlError)?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::PUT);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(put::Error::GetTokenError)?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        req_builder = req_builder.header("content-type", "application/json");
        let req_body = azure_core::to_json(parameters).map_err(put::Error::SerializeError)?;
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder.body(req_body).map_err(put::Error::BuildRequestError)?;
        let rsp = http_client.execute_request(req).await.map_err(put::Error::ExecuteRequestError)?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: BackupResourceVaultConfigResource =
                    serde_json::from_slice(rsp_body).map_err(|source| put::Error::DeserializeError(source, rsp_body.clone()))?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                let rsp_value: ErrorResponse =


text:
use graphannis_core::annostorage::MatchGroup;

use super::{ExecutionNode, ExecutionNodeDesc};
use crate::annis::db::aql::conjunction::BinaryOperatorEntry;
use crate::annis::operator::{BinaryOperator, BinaryOperatorBase};
use std::iter::Peekable;

pub struct NestedLoop<'a> {
    outer: Peekable<Box<dyn ExecutionNode<Item = MatchGroup> + 'a>>,
    inner: Box<dyn ExecutionNode<Item = MatchGroup> + 'a>,
    op: BinaryOperator<'a>,
    inner_idx: usize,
    outer_idx: usize,
    inner_cache: Vec<MatchGroup>,
    pos_inner_cache: Option<usize>,

    left_is_outer: bool,
    desc: ExecutionNodeDesc,

    global_reflexivity: bool,
}

impl<'a> NestedLoop<'a> {
    pub fn new(
        op_entry: BinaryOperatorEntry<'a>,
        lhs: Box<dyn ExecutionNode<Item = MatchGroup> + 'a>,
        rhs: Box<dyn ExecutionNode<Item = MatchGroup> + 'a>,
        lhs_idx: usize,
        rhs_idx: usize,
    ) -> NestedLoop<'a> {
        let mut left_is_outer = true;
        if let (Some(desc_lhs), Some(desc_rhs)) = (lhs.get_desc(), rhs.get_desc()) {
            if let (&Some(ref cost_lhs), &Some(ref cost_rhs)) = (&desc_lhs.cost, &desc_rhs.cost) {
                if cost_lhs.output > cost_rhs.output {
                    left_is_outer = false;
                }
            }
        }

        let processed_func = |_, out_lhs: usize, out_rhs: usize| {
            if out_lhs <= out_rhs {
                // we use LHS as outer
                out_lhs + (out_lhs * out_rhs)
            } else {
                // we use RHS as outer
                out_rhs + (out_rhs * out_lhs)
            }
        };

        if left_is_outer {
            NestedLoop {
                desc: ExecutionNodeDesc::join(
                    &op_entry.op,
                    lhs.get_desc(),
                    rhs.get_desc(),
                    "nestedloop L-R",
                    &format!(
                        "#{} {} #{}",
                        op_entry.args.left, op_entry.op, op_entry.args.right
                    ),
                    &processed_func,
                ),

                outer: lhs.peekable(),
                inner: rhs,
                op: op_entry.op,
                outer_idx: lhs_idx,
                inner_idx: rhs_idx,
                inner_cache: Vec::new(),
                pos_inner_cache: None,
                left_is_outer,
                global_reflexivity: op_entry.args.global_reflexivity,
            }
        } else {
            NestedLoop {
                desc: ExecutionNodeDesc::join(
                    &op_entry.op,
                    rhs.get_desc(),
                    lhs.get_desc(),
                    "nestedloop R-L",
                    &format!(
                        "#{} {} #{}",
                        op_entry.args.left, op_entry.op, op_entry.args.right
                    ),
                    &processed_func,
                ),

                outer: rhs.peekable(),
                inner: lhs,
                op: op_entry.op,
                outer_idx: rhs_idx,
                inner_idx: lhs_idx,
                inner_cache: Vec::new(),
                pos_inner_cache: None,
                left_is_outer,
                global_reflexivity: op_entry.args.global_reflexivity,
            }
        }
    }
}

impl<'a> ExecutionNode for NestedLoop<'a> {
    fn as_iter(&mut self) -> &mut dyn Iterator<Item = MatchGroup> {
        self
    }

    fn get_desc(&self) -> Option<&ExecutionNodeDesc> {
        Some(&self.desc)
    }
}

impl<'a> Iterator for NestedLoop<'a> {
    type Item = MatchGroup;

    fn next(&mut self) -> Option<MatchGroup> {
        loop {
            if let Some(m_outer) = self.outer.peek() {
                if self.pos_inner_cache.is_some() {
                    let mut cache_pos = self.pos_inner_cache.unwrap();

                    while cache_pos < self.inner_cache.len() {
                        let m_inner = &self.inner_cache[cache_pos];
                        cache_pos += 1;
                        self.pos_inner_cache = Some(cache_pos);
                        let filter_true = if self.left_is_outer {
                            self.op
                                .filter_match(&m_outer[self.outer_idx], &m_inner[self.inner_idx])
                        } else {
                            self.op
                                .filter_match(&m_inner[self.inner_idx], &m_outer[self.outer_idx])
                        };
                        // filter by reflexivity if necessary
                        if filter_true
                            && (self.op.is_reflexive()
                                || (self.global_reflexivity
                                    && m_outer[self.outer_idx].different_to_all(m_inner)
                                    && m_inner[self.inner_idx].different_to_all(m_outer))
                                || (!self.global_reflexivity
                                    && m_outer[self.outer_idx]
                                        .different_to(&m_inner[self.inner_idx])))
                        {
                            let mut result = m_outer.clone();
                            result.append(&mut m_inner.clone());
                            return Some(result);
                        }
                    }
                } else {
                    for mut m_inner in &mut self.inner {
                        self.inner_cache.push(m_inner.clone());

                        let filter_true = if self.left_is_outer {
                            self.op
                                .filter_match(&m_outer[self.outer_idx], &m_inner[self.inner_idx])
                        } else {
                            self.op
                                .filter_match(&m_inner[self.inner_idx], &m_outer[self.outer_idx])
                        };
                        // filter by reflexivity if necessary
                        if filter_true
                            && (self.op.is_reflexive()
                                || m_outer[self.outer_idx].node != m_inner[self.inner_idx].node
                                || m_outer[self.outer_idx].anno_key
                                    != m_inner[self.inner_idx].anno_key)
                        {
                            let mut result = m_outer.clone();
                            result.append(&mut m_inner);
                            return Some(result);
                        }
                    }
                }
                // inner was completed once, use cache from now, or reset to first item once completed
                self.pos_inner_cache = Some(0)
            }

            // consume next outer
            self.outer.next()?;
        }
    }
}


text:
use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};

// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() {
    // This loads all the core architecture, platform, etc plugins
    // Standalone executables probably need to call this, but plugins do not
    println!("Loading plugins...");
    binaryninja::headless::init();

    // Your code here...
    println!("Loading binary...");
    let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`");

    println!("Filename:  `{}`", bv.metadata().filename());
    println!("File size: `{:#x}`", bv.len());
    println!("Function count: {}", bv.functions().len());

    for func in &bv.functions() {
        println!("  `{}`:", func.symbol().full_name());
        for basic_block in &func.basic_blocks() {
            // TODO : This is intended to be refactored to be more nice to work with soon(TM)
            for addr in basic_block.as_ref() {
                print!("    {}  ", addr);
                match func.arch().instruction_text(
                    bv.read_buffer(addr, func.arch().max_instr_len())
                        .unwrap()
                        .get_data(),
                    addr,
                ) {
                    Some((_, tokens)) => {
                        tokens
                            .iter()
                            .for_each(|token| print!("{}", token.text().to_str().unwrap()));
                        println!("")
                    }
                    _ => (),
                }
            }
        }
    }

    // Important!  Standalone executables need to call shutdown or they will hang forever
    binaryninja::headless::shutdown();
}


text:
// Take a look at the license at the top of the repository in the LICENSE file.

//! This module contains basic instance and class structs to be used for
//! `GObject` subclasses that don't require any additional data in these
//! structs and don't provide any new virtual methods.

use super::prelude::*;
use crate::object::ObjectType;

use std::fmt;
use std::ops;

/// A basic instance struct that does not store any additional data.
#[repr(C)]
pub struct InstanceStruct<T: ObjectSubclass> {
    parent: <T::ParentType as ObjectType>::GlibType,
}

impl<T: ObjectSubclass> fmt::Debug for InstanceStruct<T>
where
    <T::ParentType as ObjectType>::GlibType: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("InstanceStruct")
            .field("parent", &self.parent)
            .finish()
    }
}

unsafe impl<T: ObjectSubclass> super::types::InstanceStruct for InstanceStruct<T> {
    type Type = T;
}

/// A basic class struct that does not store any additional data
/// or virtual methods.
#[repr(C)]
pub struct ClassStruct<T: ObjectSubclass> {
    parent_class: <T::ParentType as ObjectType>::GlibClassType,
}

impl<T: ObjectSubclass> fmt::Debug for ClassStruct<T>
where
    <T::ParentType as ObjectType>::GlibClassType: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("InstanceStruct")
            .field("parent_class", &self.parent_class)
            .finish()
    }
}

unsafe impl<T: ObjectSubclass> super::types::ClassStruct for ClassStruct<T> {
    type Type = T;
}

impl<T: ObjectSubclass> ops::Deref for ClassStruct<T> {
    type Target = crate::Class<<T as ObjectSubclass>::Type>;

    fn deref(&self) -> &Self::Target {
        unsafe { &*(self as *const _ as *const Self::Target) }
    }
}

impl<T: ObjectSubclass> ops::DerefMut for ClassStruct<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *(self as *mut _ as *mut Self::Target) }
    }
}


text:
// Copyright 2019-2022 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use super::ProofVerifier;
use crate::{PoStProof, Randomness, RegisteredPoStProof, SealVerifyInfo, SectorInfo};
use std::error::Error as StdError;

/// Mock verifier. This does no-op verification of any proofs.
pub enum MockVerifier {}

impl ProofVerifier for MockVerifier {
    fn verify_seal(_: &SealVerifyInfo) -> Result<(), Box<dyn StdError>> {
        Ok(())
    }
    fn verify_winning_post(
        _: Randomness,
        _: &[PoStProof],
        _: &[SectorInfo],
        _: u64,
    ) -> Result<(), Box<dyn StdError>> {
        Ok(())
    }
    fn verify_window_post(
        _: Randomness,
        _: &[PoStProof],
        _: &[SectorInfo],
        _: u64,
    ) -> Result<bool, Box<dyn StdError>> {
        Ok(true)
    }
    fn generate_winning_post_sector_challenge(
        _: RegisteredPoStProof,
        _: u64,
        _: Randomness,
        _: u64,
    ) -> Result<Vec<u64>, Box<dyn StdError>> {
        Ok(vec![0])
    }
}


text:
use std::sync::Arc;

mod invalidated;
mod leased;
mod my;
mod our;
mod shared;
mod tenant;

use crate::interpreter::Interpreter;

#[derive(Debug)]
pub(crate) struct Permission {
    data: Arc<PermissionData>,
}

impl Permission {
    fn new(data: Arc<PermissionData>) -> Self {
        Self { data }
    }

    fn allocate(data: impl Into<PermissionData>) -> Self {
        Self::new(Arc::new(data.into()))
    }

    pub(crate) fn my(interpreter: &Interpreter<'_>) -> Self {
        Self::allocate(my::My::new(interpreter))
    }

    fn leased(interpreter: &Interpreter<'_>) -> Self {
        Self::allocate(leased::Leased::new(interpreter))
    }

    fn shared(interpreter: &Interpreter<'_>) -> Self {
        Self::allocate(shared::Shared::new(interpreter))
    }

    pub(crate) fn our(interpreter: &Interpreter<'_>) -> Self {
        Self::allocate(our::Our::new(interpreter))
    }

    /// Duplicates thie permision. Must be a non-affine permission.
    fn duplicate(&self) -> Self {
        assert!(matches!(
            &*self.data,
            PermissionData::Our(_) | PermissionData::Shared(_)
        ));

        Permission {
            data: self.data.clone(),
        }
    }

    /// True if data with this permission can be used in any way. This test does not indicate that any action
    /// has been taken by the user and hence does not alter any permissions. Actually using data
    /// requires invoking a method like [`perform_read`] which may have side-effects on other permissions;
    /// this function however indicates whether those method will succeed or return an error.
    pub(crate) fn is_valid(&self) -> bool {
        self.data.is_valid()
    }

    /// Checks that this permission permits reading of a field.
    pub(crate) fn perform_read(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        self.data.perform_read(interpreter)
    }

    /// Checks that this permission permits writing to a field.
    pub(crate) fn perform_write(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        self.data.perform_write(interpreter)
    }

    /// Checks that this permission permits awaiting the object.
    pub(crate) fn perform_await(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        self.data.perform_await(interpreter)
    }

    /// Given `var q = p.give`, what permission does `q` get?
    ///
    /// May also affect the permissions of `p`!
    pub(crate) fn give(&self, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        self.data.give(self, interpreter)
    }

    /// Given `var q = p.lease`, what permission does `q` get?
    ///
    /// May also affect the permissions of `p`!
    pub(crate) fn lease(&self, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        self.data.lease(self, interpreter)
    }

    /// Given `var q = p.give.share`, what permission does `q` get?
    ///
    /// May also affect the permissions of `p`!
    pub(crate) fn into_share(self, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        self.data.into_share(interpreter)
    }

    /// Given `var q = p.share`, what permission does `q` get?
    ///
    /// May also affect the permissions of `p`!
    pub(crate) fn share(&self, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        self.data.share(self, interpreter)
    }
}

#[derive(Debug)]
enum PermissionData {
    My(my::My),
    Leased(leased::Leased),
    Our(our::Our),
    Shared(shared::Shared),
}

impl PermissionData {
    /// True if this is an *exclusive* permision, meaning that while it is valid, no access cannot occur through an alias.
    ///
    /// The opposite of an exclusive permission is a *shared* permision, which permit reads throug aliases.
    fn exclusive(&self) -> bool {
        match self {
            PermissionData::My(_) | PermissionData::Leased(_) => true,
            PermissionData::Our(_) | PermissionData::Shared(_) => false,
        }
    }

    /// See [`Permission::is_valid`]
    fn is_valid(&self) -> bool {
        match self {
            PermissionData::My(p) => p.is_valid(),
            PermissionData::Leased(p) => p.is_valid(),
            PermissionData::Our(p) => p.is_valid(),
            PermissionData::Shared(p) => p.is_valid(),
        }
    }

    /// See [`Permission::give`]
    fn give(&self, this: &Permission, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        match self {
            PermissionData::My(p) => p.give(interpreter),

            // For things that are not `my` -- i.e., either not exclusive or not owned -- then
            // giving is the same as subleasing.
            _ => self.lease(this, interpreter),
        }
    }

    /// See [`Permission::lease`]
    fn lease(&self, this: &Permission, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        match self {
            PermissionData::My(p) => p.lease(interpreter),
            PermissionData::Leased(p) => p.lease(interpreter),

            // For non-exclusive permisions, leasing is the same as sharing:
            PermissionData::Shared(_) | PermissionData::Our(_) => self.share(this, interpreter),
        }
    }

    /// See [`Permission::share`]
    fn into_share(self: Arc<Self>, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        match &*self {
            PermissionData::My(_) => Ok(Permission::our(interpreter)),
            PermissionData::Leased(p) => p.share(interpreter),
            PermissionData::Shared(_) | PermissionData::Our(_) => Ok(Permission::new(self)),
        }
    }

    /// See [`Permission::share`]
    fn share(&self, this: &Permission, interpreter: &Interpreter<'_>) -> eyre::Result<Permission> {
        match self {
            PermissionData::My(p) => p.share(interpreter),
            PermissionData::Leased(p) => p.share(interpreter),
            PermissionData::Shared(p) => p.share(this, interpreter),
            PermissionData::Our(p) => p.share(this, interpreter),
        }
    }

    /// See [`Permission::cancel`]
    fn cancel(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        match self {
            PermissionData::Leased(p) => p.cancel(interpreter),
            PermissionData::Shared(p) => p.cancel(interpreter),
            PermissionData::My(_) | PermissionData::Our(_) => {
                unreachable!("cannot cancel an owned permission")
            }
        }
    }

    /// See [`Permission::check_read`]
    fn perform_read(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        match self {
            PermissionData::My(p) => p.check_read(interpreter),
            PermissionData::Leased(p) => p.check_read(interpreter),
            PermissionData::Shared(p) => p.check_read(interpreter),
            PermissionData::Our(p) => p.check_read(interpreter),
        }
    }

    /// See [`Permission::check_write`]
    fn perform_write(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        match self {
            PermissionData::My(p) => p.check_write(interpreter),
            PermissionData::Leased(p) => p.check_write(interpreter),
            PermissionData::Shared(p) => p.check_write(interpreter),
            PermissionData::Our(p) => p.check_write(interpreter),
        }
    }

    /// See [`Permission::check_write`]
    fn perform_await(&self, interpreter: &Interpreter<'_>) -> eyre::Result<()> {
        match self {
            PermissionData::My(p) => p.check_await(interpreter),
            PermissionData::Leased(p) => p.check_await(interpreter),
            PermissionData::Shared(p) => p.check_await(interpreter),
            PermissionData::Our(p) => p.check_await(interpreter),
        }
    }
}


text:
#![deny(unsafe_code)]
#![no_main]
#![no_std]
#![allow(dead_code)]
#![allow(unused_imports)]

extern crate cortex_m;
#[macro_use]
extern crate librobot;
#[macro_use(entry, exception)]
extern crate cortex_m_rt as rt;
#[macro_use(block)]
extern crate nb;
extern crate drs_0x01;
extern crate embedded_hal;
extern crate panic_semihosting;
#[macro_use]
extern crate stm32f446_hal;

use drs_0x01::prelude::*;

mod communicator;
mod robot;
mod servo;

use core::cell::RefCell;

use robot::{init_peripherals, Robot};

use cortex_m::asm;
use embedded_hal::serial::{Read, Write};
use rt::ExceptionFrame;
use stm32f446_hal::prelude::*;
use stm32f446_hal::stm32f446;

use librobot::arrayvec::ArrayVec;
use librobot::trame_reader::TrameReader;
use librobot::Trame;

use drs_0x01::addr::WritableRamAddr;
use servo::ServoManager;

entry!(main);

fn handle_trame(trame: Trame) -> Option<Trame> {
    match (
        trame.id,
        trame.cmd,
        &trame.data[0..trame.data_length as usize],
    ) {
        (0...5, 0x0, [0x55]) => Some(trame!(trame.id, 0x00, [0xAA])),
        (_, _, _) => None,
    }
}

/// Envoie 3 messages d'initialisation aux servomoteurs :
/// * Reboot
/// * Toujours renvoyer des ack (pour le debug)
/// * Activer le couple
fn init_servo(robot: &mut Robot) {
    let servos = ServoManager::new();

    let m2 = servos[0xFE].reboot();

    for b in m2 {
        block!(robot.servo_tx.write(b)).unwrap();
    }

    for _ in 0..5 {
        robot.delay.delay_ms(70 as u32);
    }

    let m2 = servos[0xFE].ram_write(WritableRamAddr::AckPolicy(2));

    for b in m2 {
        block!(robot.servo_tx.write(b)).unwrap();
    }

    let m1 = servos[0xFE].enable_torque();

    for b in m1 {
        block!(robot.servo_tx.write(b)).unwrap();
    }
}

fn main() -> ! {
    let mut robot = init_peripherals(
        stm32f446::Peripherals::take().unwrap(),
        cortex_m::Peripherals::take().unwrap(),
    );

    init_servo(&mut robot);

    let mut reader = TrameReader::new();

    loop {
        let b = block!(robot.pc_rx.read()).unwrap();
        reader.step(b);
        if let Some(trame) = reader.pop_trame() {
            asm::bkpt();
        }

        /*
        let mess = servos[0x05].stat();
        for b in mess {
            block!(robot.servo_tx.write(b)).unwrap();
        }

        robot.delay.delay_ms(70 as u16);
*/
        /*
        if let Ok(byte) = pc_rx.read() {
            reader.step(byte);
        }
        if let Some(trame) = reader.pop_trame() {
            if let Some(sent) = handle_trame(trame) {
                let (arr, size): ([u8; 15], usize) = sent.into();
                for b in arr[0..size].iter() {
                    block!(pc_tx.write(*b)).unwrap();
                }
            }
        }*/
    }
}

interrupt!(USART6, usart_pc);

fn usart_pc() {}

exception!(HardFault, hard_fault);

fn hard_fault(ef: &ExceptionFrame) -> ! {
    panic!("Hardfault... : {:#?}", ef);
}

exception!(*, default_handler);

fn default_handler(irqn: i16) {
    panic!("Unhandled exception (IRQn = {})", irqn);
}


text:
use crate::fields::FieldContent;
use serde::Serialize;

#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ActivitySubtype {
    All,
    Cyclocross,
    Downhill,
    Elliptical,
    Generic,
    HandCycling,
    IndoorCycling,
    IndoorRowing,
    LapSwimming,
    Mountain,
    OpenWater,
    Recumbent,
    Road,
    Spin,
    StairClimbing,
    Street,
    Track,
    TrackCycling,
    Trail,
    Treadmill,
    UnknownValue(u64),
}

impl From<FieldContent> for ActivitySubtype {
    fn from(field: FieldContent) -> Self {
        if let FieldContent::Enum(enum_value) = field {
            match enum_value {
                0 => ActivitySubtype::Generic,
                1 => ActivitySubtype::Treadmill,
                2 => ActivitySubtype::Street,
                3 => ActivitySubtype::Trail,
                4 => ActivitySubtype::Track,
                5 => ActivitySubtype::Spin,
                6 => ActivitySubtype::IndoorCycling,
                7 => ActivitySubtype::Road,
                8 => ActivitySubtype::Mountain,
                9 => ActivitySubtype::Downhill,
                10 => ActivitySubtype::Recumbent,
                11 => ActivitySubtype::Cyclocross,
                12 => ActivitySubtype::HandCycling,
                13 => ActivitySubtype::TrackCycling,
                14 => ActivitySubtype::IndoorRowing,
                15 => ActivitySubtype::Elliptical,
                16 => ActivitySubtype::StairClimbing,
                17 => ActivitySubtype::LapSwimming,
                18 => ActivitySubtype::OpenWater,
                254 => ActivitySubtype::All,
                n => ActivitySubtype::UnknownValue(n as u64),
            }
        } else {
          panic!("can't convert ActivitySubtype to {:?}", field);
        }
    }
}


text:
#![allow(unused_imports, non_camel_case_types)]

use crate::models::r5::AdverseEvent_ContributingFactor::AdverseEvent_ContributingFactor;
use crate::models::r5::AdverseEvent_MitigatingAction::AdverseEvent_MitigatingAction;
use crate::models::r5::AdverseEvent_Participant::AdverseEvent_Participant;
use crate::models::r5::AdverseEvent_PreventiveAction::AdverseEvent_PreventiveAction;
use crate::models::r5::AdverseEvent_SupportingInfo::AdverseEvent_SupportingInfo;
use crate::models::r5::AdverseEvent_SuspectEntity::AdverseEvent_SuspectEntity;
use crate::models::r5::CodeableConcept::CodeableConcept;
use crate::models::r5::Element::Element;
use crate::models::r5::Extension::Extension;
use crate::models::r5::Identifier::Identifier;
use crate::models::r5::Meta::Meta;
use crate::models::r5::Narrative::Narrative;
use crate::models::r5::Period::Period;
use crate::models::r5::Reference::Reference;
use crate::models::r5::ResourceList::ResourceList;
use crate::models::r5::Timing::Timing;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;

/// An event (i.e. any change to current patient status) that may be related to
/// unintended effects on a patient or research subject.  The unintended effects
/// may require additional monitoring, treatment or hospitalization or may result in
/// death.  The AdverseEvent resource also extends to potential or avoided events that
/// could have had such effects.

#[derive(Debug)]
pub struct AdverseEvent<'a> {
    pub(crate) value: Cow<'a, Value>,
}

impl AdverseEvent<'_> {
    pub fn new(value: &Value) -> AdverseEvent {
        AdverseEvent {
            value: Cow::Borrowed(value),
        }
    }

    pub fn to_json(&self) -> Value {
        (*self.value).clone()
    }

    /// Extensions for actuality
    pub fn _actuality(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_actuality") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for detected
    pub fn _detected(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_detected") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for implicitRules
    pub fn _implicit_rules(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_implicitRules") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for language
    pub fn _language(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_language") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for occurrenceDateTime
    pub fn _occurrence_date_time(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_occurrenceDateTime") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for recordedDate
    pub fn _recorded_date(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_recordedDate") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Extensions for status
    pub fn _status(&self) -> Option<Element> {
        if let Some(val) = self.value.get("_status") {
            return Some(Element {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Whether the event actually happened, or just had the potential to. Note that this
    /// is independent of whether anyone was affected or harmed or how severely.
    pub fn actuality(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("actuality") {
            return Some(string);
        }
        return None;
    }

    /// The overall type of event, intended for search and filtering purposes.
    pub fn category(&self) -> Option<Vec<CodeableConcept>> {
        if let Some(Value::Array(val)) = self.value.get("category") {
            return Some(
                val.into_iter()
                    .map(|e| CodeableConcept {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Specific event that occurred or that was averted, such as patient fall, wrong
    /// organ removed, or wrong blood transfused.
    pub fn code(&self) -> Option<CodeableConcept> {
        if let Some(val) = self.value.get("code") {
            return Some(CodeableConcept {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// These resources do not have an independent existence apart from the resource that
    /// contains them - they cannot be identified independently, nor can they have their
    /// own independent transaction scope.
    pub fn contained(&self) -> Option<Vec<ResourceList>> {
        if let Some(Value::Array(val)) = self.value.get("contained") {
            return Some(
                val.into_iter()
                    .map(|e| ResourceList {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// The contributing factors suspected to have increased the probability or severity
    /// of the adverse event.
    pub fn contributing_factor(&self) -> Option<Vec<AdverseEvent_ContributingFactor>> {
        if let Some(Value::Array(val)) = self.value.get("contributingFactor") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_ContributingFactor {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Estimated or actual date the AdverseEvent began, in the opinion of the reporter.
    pub fn detected(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("detected") {
            return Some(string);
        }
        return None;
    }

    /// The Encounter associated with the start of the AdverseEvent.
    pub fn encounter(&self) -> Option<Reference> {
        if let Some(val) = self.value.get("encounter") {
            return Some(Reference {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// May be used to represent additional information that is not part of the basic
    /// definition of the resource. To make the use of extensions safe and manageable,
    /// there is a strict set of governance  applied to the definition and use of
    /// extensions. Though any implementer can define an extension, there is a set of
    /// requirements that SHALL be met as part of the definition of the extension.
    pub fn extension(&self) -> Option<Vec<Extension>> {
        if let Some(Value::Array(val)) = self.value.get("extension") {
            return Some(
                val.into_iter()
                    .map(|e| Extension {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// The logical id of the resource, as used in the URL for the resource. Once
    /// assigned, this value never changes.
    pub fn id(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("id") {
            return Some(string);
        }
        return None;
    }

    /// Business identifiers assigned to this adverse event by the performer or other
    /// systems which remain constant as the resource is updated and propagates from
    /// server to server.
    pub fn identifier(&self) -> Option<Vec<Identifier>> {
        if let Some(Value::Array(val)) = self.value.get("identifier") {
            return Some(
                val.into_iter()
                    .map(|e| Identifier {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// A reference to a set of rules that were followed when the resource was
    /// constructed, and which must be understood when processing the content. Often, this
    /// is a reference to an implementation guide that defines the special rules along
    /// with other profiles etc.
    pub fn implicit_rules(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("implicitRules") {
            return Some(string);
        }
        return None;
    }

    /// The base language in which the resource is written.
    pub fn language(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("language") {
            return Some(string);
        }
        return None;
    }

    /// The information about where the adverse event occurred.
    pub fn location(&self) -> Option<Reference> {
        if let Some(val) = self.value.get("location") {
            return Some(Reference {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// The metadata about the resource. This is content that is maintained by the
    /// infrastructure. Changes to the content might not always be associated with version
    /// changes to the resource.
    pub fn meta(&self) -> Option<Meta> {
        if let Some(val) = self.value.get("meta") {
            return Some(Meta {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// The ameliorating action taken after the adverse event occured in order to reduce
    /// the extent of harm.
    pub fn mitigating_action(&self) -> Option<Vec<AdverseEvent_MitigatingAction>> {
        if let Some(Value::Array(val)) = self.value.get("mitigatingAction") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_MitigatingAction {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// May be used to represent additional information that is not part of the basic
    /// definition of the resource and that modifies the understanding of the element
    /// that contains it and/or the understanding of the containing element's descendants.
    /// Usually modifier elements provide negation or qualification. To make the use of
    /// extensions safe and manageable, there is a strict set of governance applied to
    /// the definition and use of extensions. Though any implementer is allowed to define
    /// an extension, there is a set of requirements that SHALL be met as part of the
    /// definition of the extension. Applications processing a resource are required to
    /// check for modifier extensions.    Modifier extensions SHALL NOT change the meaning
    /// of any elements on Resource or DomainResource (including cannot change the meaning
    /// of modifierExtension itself).
    pub fn modifier_extension(&self) -> Option<Vec<Extension>> {
        if let Some(Value::Array(val)) = self.value.get("modifierExtension") {
            return Some(
                val.into_iter()
                    .map(|e| Extension {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// The date (and perhaps time) when the adverse event occurred.
    pub fn occurrence_date_time(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("occurrenceDateTime") {
            return Some(string);
        }
        return None;
    }

    /// The date (and perhaps time) when the adverse event occurred.
    pub fn occurrence_period(&self) -> Option<Period> {
        if let Some(val) = self.value.get("occurrencePeriod") {
            return Some(Period {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// The date (and perhaps time) when the adverse event occurred.
    pub fn occurrence_timing(&self) -> Option<Timing> {
        if let Some(val) = self.value.get("occurrenceTiming") {
            return Some(Timing {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Describes the type of outcome from the adverse event, such as resolved,
    /// recovering, ongoing, resolved-with-sequelae, or fatal.
    pub fn outcome(&self) -> Option<Vec<CodeableConcept>> {
        if let Some(Value::Array(val)) = self.value.get("outcome") {
            return Some(
                val.into_iter()
                    .map(|e| CodeableConcept {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Indicates who or what participated in the adverse event and how they were
    /// involved.
    pub fn participant(&self) -> Option<Vec<AdverseEvent_Participant>> {
        if let Some(Value::Array(val)) = self.value.get("participant") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_Participant {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Preventive actions that contributed to avoiding the adverse event.
    pub fn preventive_action(&self) -> Option<Vec<AdverseEvent_PreventiveAction>> {
        if let Some(Value::Array(val)) = self.value.get("preventiveAction") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_PreventiveAction {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// The date on which the existence of the AdverseEvent was first recorded.
    pub fn recorded_date(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("recordedDate") {
            return Some(string);
        }
        return None;
    }

    /// Information on who recorded the adverse event.  May be the patient or a
    /// practitioner.
    pub fn recorder(&self) -> Option<Reference> {
        if let Some(val) = self.value.get("recorder") {
            return Some(Reference {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// Information about the condition that occurred as a result of the adverse event,
    /// such as hives due to the exposure to a substance (for example, a drug or a
    /// chemical) or a broken leg as a result of the fall.
    pub fn resulting_condition(&self) -> Option<Vec<Reference>> {
        if let Some(Value::Array(val)) = self.value.get("resultingCondition") {
            return Some(
                val.into_iter()
                    .map(|e| Reference {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Assessment whether this event, or averted event, was of clinical importance.
    pub fn seriousness(&self) -> Option<CodeableConcept> {
        if let Some(val) = self.value.get("seriousness") {
            return Some(CodeableConcept {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    /// The current state of the adverse event or potential adverse event.
    pub fn status(&self) -> Option<&str> {
        if let Some(Value::String(string)) = self.value.get("status") {
            return Some(string);
        }
        return None;
    }

    /// The research study that the subject is enrolled in.
    pub fn study(&self) -> Option<Vec<Reference>> {
        if let Some(Value::Array(val)) = self.value.get("study") {
            return Some(
                val.into_iter()
                    .map(|e| Reference {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// This subject or group impacted by the event.
    pub fn subject(&self) -> Reference {
        Reference {
            value: Cow::Borrowed(&self.value["subject"]),
        }
    }

    /// Supporting information relevant to the event.
    pub fn supporting_info(&self) -> Option<Vec<AdverseEvent_SupportingInfo>> {
        if let Some(Value::Array(val)) = self.value.get("supportingInfo") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_SupportingInfo {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// Describes the entity that is suspected to have caused the adverse event.
    pub fn suspect_entity(&self) -> Option<Vec<AdverseEvent_SuspectEntity>> {
        if let Some(Value::Array(val)) = self.value.get("suspectEntity") {
            return Some(
                val.into_iter()
                    .map(|e| AdverseEvent_SuspectEntity {
                        value: Cow::Borrowed(e),
                    })
                    .collect::<Vec<_>>(),
            );
        }
        return None;
    }

    /// A human-readable narrative that contains a summary of the resource and can be used
    /// to represent the content of the resource to a human. The narrative need not encode
    /// all the structured data, but is required to contain sufficient detail to make it
    /// "clinically safe" for a human to just read the narrative. Resource definitions
    /// may define what content should be represented in the narrative to ensure clinical
    /// safety.
    pub fn text(&self) -> Option<Narrative> {
        if let Some(val) = self.value.get("text") {
            return Some(Narrative {
                value: Cow::Borrowed(val),
            });
        }
        return None;
    }

    pub fn validate(&self) -> bool {
        if let Some(_val) = self._actuality() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._detected() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._implicit_rules() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._language() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._occurrence_date_time() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._recorded_date() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self._status() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self.actuality() {}
        if let Some(_val) = self.category() {
            if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
                return false;
            }
        }
        if let Some(_val) = self.code() {
            if !_val.validate() {
                return false;
            }
        }
        if let Some(_val) = self.contained() {
            if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
                return false;
            }