text:
use super::{
    inputs::{Claim, Witness},
    pedersen_points::{PEDERSEN_POINTS, SHIFT_POINT},
};
use std::prelude::v1::*;
use zkp_elliptic_curve::Affine;
use zkp_primefield::FieldElement;
use zkp_stark::TraceTable;
use zkp_u256::U256;

// TODO: Naming
#[allow(clippy::module_name_repetitions)]
pub fn get_trace_table(claim: &Claim, witness: &Witness) -> TraceTable {
    let num_columns = 8;
    let mut trace = TraceTable::new(claim.path_length * 256, num_columns);

    let mut row: Row = Row::default();
    row.right.point = Affine::Point {
        x: claim.leaf.clone(),
        y: FieldElement::ZERO,
    };

    for path_index in 0..claim.path_length {
        for bit_index in 0..256 {
            if bit_index % 256 == 0 {
                let other_hash = U256::from(&witness.path[path_index]);
                let (x, _) = get_coordinates(&row.right.point);
                if witness.directions[path_index] {
                    row = initialize_hash(other_hash, U256::from(x));
                } else {
                    row = initialize_hash(U256::from(x), other_hash);
                }
            } else {
                row = hash_next_bit(&row, bit_index);
            }
            let row_index = path_index * 256 + bit_index;

            let (left_x, left_y) = get_coordinates(&row.left.point);
            trace[(row_index, 0)] = FieldElement::from(row.left.source.clone());
            trace[(row_index, 1)] = row.left.slope.clone();
            trace[(row_index, 2)] = left_x.clone();
            trace[(row_index, 3)] = left_y.clone();

            let (right_x, right_y) = get_coordinates(&row.right.point);
            trace[(row_index, 4)] = FieldElement::from(row.right.source.clone());
            trace[(row_index, 5)] = row.right.slope.clone();
            trace[(row_index, 6)] = right_x.clone();
            trace[(row_index, 7)] = right_y.clone();
        }
    }
    trace
}

fn initialize_hash(left_source: U256, right_source: U256) -> Row {
    let mut row: Row = Row::default();
    row.left.source = left_source;
    row.right.source = right_source;
    row.right.point = SHIFT_POINT;
    row
}

fn hash_next_bit(row: &Row, bit_index: usize) -> Row {
    let mut next_row = Row {
        left:  Subrow {
            source: row.left.source.clone() >> 1,
            point: row.right.point.clone(),
            ..Subrow::default()
        },
        right: Subrow {
            source: row.right.source.clone() >> 1,
            ..Subrow::default()
        },
    };
    if row.left.source.bit(0) {
        let p = &PEDERSEN_POINTS[bit_index];
        next_row.left.slope = get_slope(&next_row.left.point, &p);
        next_row.left.point += p;
    }

    next_row.right.point = next_row.left.point.clone();
    if row.right.source.bit(0) {
        let p = &PEDERSEN_POINTS[bit_index + 252];
        next_row.right.slope = get_slope(&next_row.right.point, &p);
        next_row.right.point += p;
    }
    next_row
}

#[derive(Default)]
struct Row {
    left:  Subrow,
    right: Subrow,
}

struct Subrow {
    source: U256,
    slope:  FieldElement,
    point:  Affine,
}

impl Default for Subrow {
    fn default() -> Self {
        Self {
            source: U256::ZERO,
            slope:  FieldElement::ZERO,
            point:  Affine::Point {
                x: FieldElement::ZERO,
                y: FieldElement::ZERO,
            },
        }
    }
}

fn get_slope(p_1: &Affine, p_2: &Affine) -> FieldElement {
    let (x_1, y_1) = get_coordinates(p_1);
    let (x_2, y_2) = get_coordinates(p_2);
    (y_1 - y_2) / (x_1 - x_2)
}

fn get_coordinates(p: &Affine) -> (&FieldElement, &FieldElement) {
    match p {
        Affine::Zero => panic!(),
        Affine::Point { x, y } => (x, y),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        super::inputs::{short_witness, SHORT_CLAIM},
        *,
    };

    #[test]
    fn short_inputs_consistent() {
        let trace = get_trace_table(&SHORT_CLAIM, &short_witness());
        assert_eq!(trace[(trace.num_rows() - 1, 6)], SHORT_CLAIM.root);
    }
}

domain: rust


text:
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT

use crate::Accessible;
use crate::AccessibleRole;
use crate::Align;
use crate::Buildable;
use crate::ConstraintTarget;
use crate::LayoutManager;
use crate::Overflow;
use crate::Widget;
use glib::object::Cast;
use glib::object::IsA;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;

glib::wrapper! {
    pub struct PopoverMenuBar(Object<ffi::GtkPopoverMenuBar>) @extends Widget, @implements Accessible, Buildable, ConstraintTarget;

    match fn {
        get_type => || ffi::gtk_popover_menu_bar_get_type(),
    }
}

impl PopoverMenuBar {
    #[doc(alias = "gtk_popover_menu_bar_new_from_model")]
    pub fn from_model<P: IsA<gio::MenuModel>>(model: Option<&P>) -> PopoverMenuBar {
        assert_initialized_main_thread!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_popover_menu_bar_new_from_model(
                model.map(|p| p.as_ref()).to_glib_none().0,
            ))
            .unsafe_cast()
        }
    }

    #[doc(alias = "gtk_popover_menu_bar_add_child")]
    pub fn add_child<P: IsA<Widget>>(&self, child: &P, id: &str) -> bool {
        unsafe {
            from_glib(ffi::gtk_popover_menu_bar_add_child(
                self.to_glib_none().0,
                child.as_ref().to_glib_none().0,
                id.to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "gtk_popover_menu_bar_get_menu_model")]
    pub fn menu_model(&self) -> Option<gio::MenuModel> {
        unsafe {
            from_glib_none(ffi::gtk_popover_menu_bar_get_menu_model(
                self.to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "gtk_popover_menu_bar_remove_child")]
    pub fn remove_child<P: IsA<Widget>>(&self, child: &P) -> bool {
        unsafe {
            from_glib(ffi::gtk_popover_menu_bar_remove_child(
                self.to_glib_none().0,
                child.as_ref().to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "gtk_popover_menu_bar_set_menu_model")]
    pub fn set_menu_model<P: IsA<gio::MenuModel>>(&self, model: Option<&P>) {
        unsafe {
            ffi::gtk_popover_menu_bar_set_menu_model(
                self.to_glib_none().0,
                model.map(|p| p.as_ref()).to_glib_none().0,
            );
        }
    }

    pub fn connect_property_menu_model_notify<F: Fn(&PopoverMenuBar) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_menu_model_trampoline<F: Fn(&PopoverMenuBar) + 'static>(
            this: *mut ffi::GtkPopoverMenuBar,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::menu-model\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_menu_model_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

#[derive(Clone, Default)]
pub struct PopoverMenuBarBuilder {
    menu_model: Option<gio::MenuModel>,
    can_focus: Option<bool>,
    can_target: Option<bool>,
    css_classes: Option<Vec<String>>,
    css_name: Option<String>,
    cursor: Option<gdk::Cursor>,
    focus_on_click: Option<bool>,
    focusable: Option<bool>,
    halign: Option<Align>,
    has_tooltip: Option<bool>,
    height_request: Option<i32>,
    hexpand: Option<bool>,
    hexpand_set: Option<bool>,
    layout_manager: Option<LayoutManager>,
    margin_bottom: Option<i32>,
    margin_end: Option<i32>,
    margin_start: Option<i32>,
    margin_top: Option<i32>,
    name: Option<String>,
    opacity: Option<f64>,
    overflow: Option<Overflow>,
    receives_default: Option<bool>,
    sensitive: Option<bool>,
    tooltip_markup: Option<String>,
    tooltip_text: Option<String>,
    valign: Option<Align>,
    vexpand: Option<bool>,
    vexpand_set: Option<bool>,
    visible: Option<bool>,
    width_request: Option<i32>,
    accessible_role: Option<AccessibleRole>,
}

impl PopoverMenuBarBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn build(self) -> PopoverMenuBar {
        let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
        if let Some(ref menu_model) = self.menu_model {
            properties.push(("menu-model", menu_model));
        }
        if let Some(ref can_focus) = self.can_focus {
            properties.push(("can-focus", can_focus));
        }
        if let Some(ref can_target) = self.can_target {
            properties.push(("can-target", can_target));
        }
        if let Some(ref css_classes) = self.css_classes {
            properties.push(("css-classes", css_classes));
        }
        if let Some(ref css_name) = self.css_name {
            properties.push(("css-name", css_name));
        }
        if let Some(ref cursor) = self.cursor {
            properties.push(("cursor", cursor));
        }
        if let Some(ref focus_on_click) = self.focus_on_click {
            properties.push(("focus-on-click", focus_on_click));
        }
        if let Some(ref focusable) = self.focusable {
            properties.push(("focusable", focusable));
        }
        if let Some(ref halign) = self.halign {
            properties.push(("halign", halign));
        }
        if let Some(ref has_tooltip) = self.has_tooltip {
            properties.push(("has-tooltip", has_tooltip));
        }
        if let Some(ref height_request) = self.height_request {
            properties.push(("height-request", height_request));
        }
        if let Some(ref hexpand) = self.hexpand {
            properties.push(("hexpand", hexpand));
        }
        if let Some(ref hexpand_set) = self.hexpand_set {
            properties.push(("hexpand-set", hexpand_set));
        }
        if let Some(ref layout_manager) = self.layout_manager {
            properties.push(("layout-manager", layout_manager));
        }
        if let Some(ref margin_bottom) = self.margin_bottom {
            properties.push(("margin-bottom", margin_bottom));
        }
        if let Some(ref margin_end) = self.margin_end {
            properties.push(("margin-end", margin_end));
        }
        if let Some(ref margin_start) = self.margin_start {
            properties.push(("margin-start", margin_start));
        }
        if let Some(ref margin_top) = self.margin_top {
            properties.push(("margin-top", margin_top));
        }
        if let Some(ref name) = self.name {
            properties.push(("name", name));
        }
        if let Some(ref opacity) = self.opacity {
            properties.push(("opacity", opacity));
        }
        if let Some(ref overflow) = self.overflow {
            properties.push(("overflow", overflow));
        }
        if let Some(ref receives_default) = self.receives_default {
            properties.push(("receives-default", receives_default));
        }
        if let Some(ref sensitive) = self.sensitive {
            properties.push(("sensitive", sensitive));
        }
        if let Some(ref tooltip_markup) = self.tooltip_markup {
            properties.push(("tooltip-markup", tooltip_markup));
        }
        if let Some(ref tooltip_text) = self.tooltip_text {
            properties.push(("tooltip-text", tooltip_text));
        }
        if let Some(ref valign) = self.valign {
            properties.push(("valign", valign));
        }
        if let Some(ref vexpand) = self.vexpand {
            properties.push(("vexpand", vexpand));
        }
        if let Some(ref vexpand_set) = self.vexpand_set {
            properties.push(("vexpand-set", vexpand_set));
        }
        if let Some(ref visible) = self.visible {
            properties.push(("visible", visible));
        }
        if let Some(ref width_request) = self.width_request {
            properties.push(("width-request", width_request));
        }
        if let Some(ref accessible_role) = self.accessible_role {
            properties.push(("accessible-role", accessible_role));
        }
        let ret = glib::Object::new::<PopoverMenuBar>(&properties).expect("object new");
        ret
    }

    pub fn menu_model<P: IsA<gio::MenuModel>>(mut self, menu_model: &P) -> Self {
        self.menu_model = Some(menu_model.clone().upcast());
        self
    }

    pub fn can_focus(mut self, can_focus: bool) -> Self {
        self.can_focus = Some(can_focus);
        self
    }

    pub fn can_target(mut self, can_target: bool) -> Self {
        self.can_target = Some(can_target);
        self
    }

    pub fn css_classes(mut self, css_classes: Vec<String>) -> Self {
        self.css_classes = Some(css_classes);
        self
    }

    pub fn css_name(mut self, css_name: &str) -> Self {
        self.css_name = Some(css_name.to_string());
        self
    }

    pub fn cursor(mut self, cursor: &gdk::Cursor) -> Self {
        self.cursor = Some(cursor.clone());
        self
    }

    pub fn focus_on_click(mut self, focus_on_click: bool) -> Self {
        self.focus_on_click = Some(focus_on_click);
        self
    }

    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = Some(focusable);
        self
    }

    pub fn halign(mut self, halign: Align) -> Self {
        self.halign = Some(halign);
        self
    }

    pub fn has_tooltip(mut self, has_tooltip: bool) -> Self {
        self.has_tooltip = Some(has_tooltip);
        self
    }

    pub fn height_request(mut self, height_request: i32) -> Self {
        self.height_request = Some(height_request);
        self
    }

    pub fn hexpand(mut self, hexpand: bool) -> Self {
        self.hexpand = Some(hexpand);
        self
    }

    pub fn hexpand_set(mut self, hexpand_set: bool) -> Self {
        self.hexpand_set = Some(hexpand_set);
        self
    }

    pub fn layout_manager<P: IsA<LayoutManager>>(mut self, layout_manager: &P) -> Self {
        self.layout_manager = Some(layout_manager.clone().upcast());
        self
    }

    pub fn margin_bottom(mut self, margin_bottom: i32) -> Self {
        self.margin_bottom = Some(margin_bottom);
        self
    }

    pub fn margin_end(mut self, margin_end: i32) -> Self {
        self.margin_end = Some(margin_end);
        self
    }

    pub fn margin_start(mut self, margin_start: i32) -> Self {
        self.margin_start = Some(margin_start);
        self
    }

    pub fn margin_top(mut self, margin_top: i32) -> Self {
        self.margin_top = Some(margin_top);
        self
    }

    pub fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    pub fn opacity(mut self, opacity: f64) -> Self {
        self.opacity = Some(opacity);
        self
    }

    pub fn overflow(mut self, overflow: Overflow) -> Self {
        self.overflow = Some(overflow);
        self
    }

    pub fn receives_default(mut self, receives_default: bool) -> Self {
        self.receives_default = Some(receives_default);
        self
    }

    pub fn sensitive(mut self, sensitive: bool) -> Self {
        self.sensitive = Some(sensitive);
        self
    }

    pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self {
        self.tooltip_markup = Some(tooltip_markup.to_string());
        self
    }

    pub fn tooltip_text(mut self, tooltip_text: &str) -> Self {
        self.tooltip_text = Some(tooltip_text.to_string());
        self
    }

    pub fn valign(mut self, valign: Align) -> Self {
        self.valign = Some(valign);
        self
    }

    pub fn vexpand(mut self, vexpand: bool) -> Self {
        self.vexpand = Some(vexpand);
        self
    }

    pub fn vexpand_set(mut self, vexpand_set: bool) -> Self {
        self.vexpand_set = Some(vexpand_set);
        self
    }

    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = Some(visible);
        self
    }

    pub fn width_request(mut self, width_request: i32) -> Self {
        self.width_request = Some(width_request);
        self
    }

    pub fn accessible_role(mut self, accessible_role: AccessibleRole) -> Self {
        self.accessible_role = Some(accessible_role);
        self
    }
}

impl fmt::Display for PopoverMenuBar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("PopoverMenuBar")
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::error::*;
use serde_derive::*;
use std::{cell::RefCell, sync::Arc};
use url::Url;
use viaduct::Request;

#[derive(Deserialize)]
struct ClientConfigurationResponse {
    auth_server_base_url: String,
    oauth_server_base_url: String,
    profile_server_base_url: String,
    sync_tokenserver_base_url: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct OpenIdConfigurationResponse {
    authorization_endpoint: String,
    issuer: String,
    jwks_uri: String,
    token_endpoint: String,
    userinfo_endpoint: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
    content_url: String,
    // RemoteConfig is lazily fetched from the server.
    remote_config: RefCell<Option<Arc<RemoteConfig>>>,
    pub client_id: String,
    pub redirect_uri: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// `RemoteConfig` struct stores configuration values from the FxA
/// `/.well-known/fxa-client-configuration` and the
/// `/.well-known/openid-configuration` endpoints.
pub struct RemoteConfig {
    auth_url: String,
    oauth_url: String,
    profile_url: String,
    token_server_endpoint_url: String,
    authorization_endpoint: String,
    issuer: String,
    jwks_uri: String,
    token_endpoint: String,
    userinfo_endpoint: String,
}

impl Config {
    pub fn release(client_id: &str, redirect_uri: &str) -> Self {
        Self::new("https://accounts.firefox.com", client_id, redirect_uri)
    }

    pub fn stable_dev(client_id: &str, redirect_uri: &str) -> Self {
        Self::new("https://stable.dev.lcip.org", client_id, redirect_uri)
    }

    pub fn stage_dev(client_id: &str, redirect_uri: &str) -> Self {
        Self::new("https://accounts.stage.mozaws.net", client_id, redirect_uri)
    }

    pub fn new(content_url: &str, client_id: &str, redirect_uri: &str) -> Self {
        Self {
            content_url: content_url.to_string(),
            client_id: client_id.to_string(),
            redirect_uri: redirect_uri.to_string(),
            remote_config: RefCell::new(None),
        }
    }

    // FIXME
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn init(
        content_url: String,
        auth_url: String,
        oauth_url: String,
        profile_url: String,
        token_server_endpoint_url: String,
        authorization_endpoint: String,
        issuer: String,
        jwks_uri: String,
        token_endpoint: String,
        userinfo_endpoint: String,
        client_id: String,
        redirect_uri: String,
    ) -> Self {
        let remote_config = RemoteConfig {
            auth_url,
            oauth_url,
            profile_url,
            token_server_endpoint_url,
            authorization_endpoint,
            issuer,
            jwks_uri,
            token_endpoint,
            userinfo_endpoint,
        };

        Config {
            content_url,
            remote_config: RefCell::new(Some(Arc::new(remote_config))),
            client_id,
            redirect_uri,
        }
    }

    fn remote_config(&self) -> Result<Arc<RemoteConfig>> {
        if let Some(remote_config) = self.remote_config.borrow().clone() {
            return Ok(remote_config);
        }

        let config_url =
            Url::parse(&self.content_url)?.join(".well-known/fxa-client-configuration")?;
        let resp: ClientConfigurationResponse =
            Request::get(config_url).send()?.require_success()?.json()?;

        let openid_config_url =
            Url::parse(&self.content_url)?.join(".well-known/openid-configuration")?;
        let openid_resp: OpenIdConfigurationResponse = Request::get(openid_config_url)
            .send()?
            .require_success()?
            .json()?;

        let remote_config = RemoteConfig {
            auth_url: format!("{}/", resp.auth_server_base_url),
            oauth_url: format!("{}/", resp.oauth_server_base_url),
            profile_url: format!("{}/", resp.profile_server_base_url),
            token_server_endpoint_url: format!("{}/", resp.sync_tokenserver_base_url),
            authorization_endpoint: openid_resp.authorization_endpoint,
            issuer: openid_resp.issuer,
            jwks_uri: openid_resp.jwks_uri,
            // TODO: bring back openid token endpoint once https://github.com/mozilla/fxa/issues/453 has been resolved
            // and the openid response has been switched to the new endpoint.
            // token_endpoint: openid_resp.token_endpoint,
            token_endpoint: format!("{}/v1/oauth/token", resp.auth_server_base_url),
            userinfo_endpoint: openid_resp.userinfo_endpoint,
        };
        let rc = Arc::new(remote_config);
        let result = rc.clone();
        self.remote_config.replace(Some(rc));
        Ok(result)
    }

    pub fn content_url(&self) -> Result<Url> {
        Url::parse(&self.content_url).map_err(Into::into)
    }

    pub fn content_url_path(&self, path: &str) -> Result<Url> {
        self.content_url()?.join(path).map_err(Into::into)
    }

    pub fn auth_url(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.auth_url).map_err(Into::into)
    }

    pub fn auth_url_path(&self, path: &str) -> Result<Url> {
        self.auth_url()?.join(path).map_err(Into::into)
    }

    pub fn profile_url(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.profile_url).map_err(Into::into)
    }

    pub fn profile_url_path(&self, path: &str) -> Result<Url> {
        self.profile_url()?.join(path).map_err(Into::into)
    }

    pub fn oauth_url(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.oauth_url).map_err(Into::into)
    }

    pub fn oauth_url_path(&self, path: &str) -> Result<Url> {
        self.oauth_url()?.join(path).map_err(Into::into)
    }

    pub fn token_server_endpoint_url(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.token_server_endpoint_url).map_err(Into::into)
    }

    pub fn authorization_endpoint(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.authorization_endpoint).map_err(Into::into)
    }

    pub fn issuer(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.issuer).map_err(Into::into)
    }

    pub fn jwks_uri(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.jwks_uri).map_err(Into::into)
    }

    pub fn token_endpoint(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.token_endpoint).map_err(Into::into)
    }

    pub fn userinfo_endpoint(&self) -> Result<Url> {
        Url::parse(&self.remote_config()?.userinfo_endpoint).map_err(Into::into)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_paths() {
        let remote_config = RemoteConfig {
            auth_url: "https://stable.dev.lcip.org/auth/".to_string(),
            oauth_url: "https://oauth-stable.dev.lcip.org/".to_string(),
            profile_url: "https://stable.dev.lcip.org/profile/".to_string(),
            token_server_endpoint_url: "https://stable.dev.lcip.org/syncserver/token/1.0/sync/1.5"
                .to_string(),
            authorization_endpoint: "https://oauth-stable.dev.lcip.org/v1/authorization"
                .to_string(),
            issuer: "https://dev.lcip.org/".to_string(),
            jwks_uri: "https://oauth-stable.dev.lcip.org/v1/jwks".to_string(),
            token_endpoint: "https://stable.dev.lcip.org/auth/v1/oauth/token".to_string(),
            userinfo_endpoint: "https://stable.dev.lcip.org/profile/v1/profile".to_string(),
        };

        let config = Config {
            content_url: "https://stable.dev.lcip.org/".to_string(),
            remote_config: RefCell::new(Some(Arc::new(remote_config))),
            client_id: "263ceaa5546dce83".to_string(),
            redirect_uri: "https://127.0.0.1:8080".to_string(),
        };
        assert_eq!(
            config.auth_url_path("v1/account/keys").unwrap().to_string(),
            "https://stable.dev.lcip.org/auth/v1/account/keys"
        );
        assert_eq!(
            config.oauth_url_path("v1/token").unwrap().to_string(),
            "https://oauth-stable.dev.lcip.org/v1/token"
        );
        assert_eq!(
            config.profile_url_path("v1/profile").unwrap().to_string(),
            "https://stable.dev.lcip.org/profile/v1/profile"
        );
        assert_eq!(
            config.content_url_path("oauth/signin").unwrap().to_string(),
            "https://stable.dev.lcip.org/oauth/signin"
        );
        assert_eq!(
            config.token_server_endpoint_url().unwrap().to_string(),
            "https://stable.dev.lcip.org/syncserver/token/1.0/sync/1.5"
        );

        assert_eq!(
            config.token_endpoint().unwrap().to_string(),
            "https://stable.dev.lcip.org/auth/v1/oauth/token"
        );
    }
}


text:
#[doc = "Register `USBOEPCNF_5` reader"]
pub struct R(crate::R<USBOEPCNF_5_SPEC>);
impl core::ops::Deref for R {
    type Target = crate::R<USBOEPCNF_5_SPEC>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl core::convert::From<crate::R<USBOEPCNF_5_SPEC>> for R {
    fn from(reader: crate::R<USBOEPCNF_5_SPEC>) -> Self {
        R(reader)
    }
}
#[doc = "Register `USBOEPCNF_5` writer"]
pub struct W(crate::W<USBOEPCNF_5_SPEC>);
impl core::ops::Deref for W {
    type Target = crate::W<USBOEPCNF_5_SPEC>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl core::ops::DerefMut for W {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}
impl core::convert::From<crate::W<USBOEPCNF_5_SPEC>> for W {
    fn from(writer: crate::W<USBOEPCNF_5_SPEC>) -> Self {
        W(writer)
    }
}
#[doc = "Field `USBIIE` reader - USB - Transaction Interrupt indication enable"]
pub struct USBIIE_R(crate::FieldReader<bool, bool>);
impl USBIIE_R {
    pub(crate) fn new(bits: bool) -> Self {
        USBIIE_R(crate::FieldReader::new(bits))
    }
}
impl core::ops::Deref for USBIIE_R {
    type Target = crate::FieldReader<bool, bool>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[doc = "Field `USBIIE` writer - USB - Transaction Interrupt indication enable"]
pub struct USBIIE_W<'a> {
    w: &'a mut W,
}
impl<'a> USBIIE_W<'a> {
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u8 & 0x01) << 2);
        self.w
    }
}
#[doc = "Field `STALL` reader - USB - Stall Condition"]
pub struct STALL_R(crate::FieldReader<bool, bool>);
impl STALL_R {
    pub(crate) fn new(bits: bool) -> Self {
        STALL_R(crate::FieldReader::new(bits))
    }
}
impl core::ops::Deref for STALL_R {
    type Target = crate::FieldReader<bool, bool>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[doc = "Field `STALL` writer - USB - Stall Condition"]
pub struct STALL_W<'a> {
    w: &'a mut W,
}
impl<'a> STALL_W<'a> {
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u8 & 0x01) << 3);
        self.w
    }
}
#[doc = "Field `DBUF` reader - USB - Double Buffer Enable"]
pub struct DBUF_R(crate::FieldReader<bool, bool>);
impl DBUF_R {
    pub(crate) fn new(bits: bool) -> Self {
        DBUF_R(crate::FieldReader::new(bits))
    }
}
impl core::ops::Deref for DBUF_R {
    type Target = crate::FieldReader<bool, bool>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[doc = "Field `DBUF` writer - USB - Double Buffer Enable"]
pub struct DBUF_W<'a> {
    w: &'a mut W,
}
impl<'a> DBUF_W<'a> {
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u8 & 0x01) << 4);
        self.w
    }
}
#[doc = "Field `TOGGLE` reader - USB - Toggle Bit"]
pub struct TOGGLE_R(crate::FieldReader<bool, bool>);
impl TOGGLE_R {
    pub(crate) fn new(bits: bool) -> Self {
        TOGGLE_R(crate::FieldReader::new(bits))
    }
}
impl core::ops::Deref for TOGGLE_R {
    type Target = crate::FieldReader<bool, bool>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[doc = "Field `TOGGLE` writer - USB - Toggle Bit"]
pub struct TOGGLE_W<'a> {
    w: &'a mut W,
}
impl<'a> TOGGLE_W<'a> {
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u8 & 0x01) << 5);
        self.w
    }
}
#[doc = "Field `UBME` reader - USB - UBM In-Endpoint Enable"]
pub struct UBME_R(crate::FieldReader<bool, bool>);
impl UBME_R {
    pub(crate) fn new(bits: bool) -> Self {
        UBME_R(crate::FieldReader::new(bits))
    }
}
impl core::ops::Deref for UBME_R {
    type Target = crate::FieldReader<bool, bool>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[doc = "Field `UBME` writer - USB - UBM In-Endpoint Enable"]
pub struct UBME_W<'a> {
    w: &'a mut W,
}
impl<'a> UBME_W<'a> {
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u8 & 0x01) << 7);
        self.w
    }
}
impl R {
    #[doc = "Bit 2 - USB - Transaction Interrupt indication enable"]
    #[inline(always)]
    pub fn usbiie(&self) -> USBIIE_R {
        USBIIE_R::new(((self.bits >> 2) & 0x01) != 0)
    }
    #[doc = "Bit 3 - USB - Stall Condition"]
    #[inline(always)]
    pub fn stall(&self) -> STALL_R {
        STALL_R::new(((self.bits >> 3) & 0x01) != 0)
    }
    #[doc = "Bit 4 - USB - Double Buffer Enable"]
    #[inline(always)]
    pub fn dbuf(&self) -> DBUF_R {
        DBUF_R::new(((self.bits >> 4) & 0x01) != 0)
    }
    #[doc = "Bit 5 - USB - Toggle Bit"]
    #[inline(always)]
    pub fn toggle(&self) -> TOGGLE_R {
        TOGGLE_R::new(((self.bits >> 5) & 0x01) != 0)
    }
    #[doc = "Bit 7 - USB - UBM In-Endpoint Enable"]
    #[inline(always)]
    pub fn ubme(&self) -> UBME_R {
        UBME_R::new(((self.bits >> 7) & 0x01) != 0)
    }
}
impl W {
    #[doc = "Bit 2 - USB - Transaction Interrupt indication enable"]
    #[inline(always)]
    pub fn usbiie(&mut self) -> USBIIE_W {
        USBIIE_W { w: self }
    }
    #[doc = "Bit 3 - USB - Stall Condition"]
    #[inline(always)]
    pub fn stall(&mut self) -> STALL_W {
        STALL_W { w: self }
    }
    #[doc = "Bit 4 - USB - Double Buffer Enable"]
    #[inline(always)]
    pub fn dbuf(&mut self) -> DBUF_W {
        DBUF_W { w: self }
    }
    #[doc = "Bit 5 - USB - Toggle Bit"]
    #[inline(always)]
    pub fn toggle(&mut self) -> TOGGLE_W {
        TOGGLE_W { w: self }
    }
    #[doc = "Bit 7 - USB - UBM In-Endpoint Enable"]
    #[inline(always)]
    pub fn ubme(&mut self) -> UBME_W {
        UBME_W { w: self }
    }
    #[doc = "Writes raw bits to the register."]
    pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
        self.0.bits(bits);
        self
    }
}
#[doc = "Output Endpoint_5: Configuration\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usboepcnf_5](index.html) module"]
pub struct USBOEPCNF_5_SPEC;
impl crate::RegisterSpec for USBOEPCNF_5_SPEC {
    type Ux = u8;
}
#[doc = "`read()` method returns [usboepcnf_5::R](R) reader structure"]
impl crate::Readable for USBOEPCNF_5_SPEC {
    type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [usboepcnf_5::W](W) writer structure"]
impl crate::Writable for USBOEPCNF_5_SPEC {
    type Writer = W;
}
#[doc = "`reset()` method sets USBOEPCNF_5 to value 0"]
impl crate::Resettable for USBOEPCNF_5_SPEC {
    #[inline(always)]
    fn reset_value() -> Self::Ux {
        0
    }
}


text:
// test of Kd-Tree

use kdtree::KdTree;
//use kdtree::ErrorKind;
use kdtree::distance::squared_euclidean;

use ppmpa::ray::algebra::*;
use ppmpa::ray::geometry::*;
use ppmpa::ray::optics::*;
use ppmpa::ray::physics::*;

fn main() {
  let dimensions = 3;
  let mut kdtree = KdTree::new(dimensions);

  let p1 = Photon::new(&Wavelength::Red, &Ray::new(&Vector3::new(0.0, 0.0, 0.0), &Vector3::EY));
  let p2 = Photon::new(&Wavelength::Green, &Ray::new(&Vector3::new(1.0, 1.0, 0.0), &Vector3::EX));
  let p3 = Photon::new(&Wavelength::Blue, &Ray::new(&Vector3::new(1.0, 1.0, 1.0), &Vector3::EZ));
  let p4 = Photon::new(&Wavelength::Red, &Ray::new(&Vector3::new(-1.0, -1.0, -1.0), &Vector3::EY));
  let p5 = Photon::new(&Wavelength::Green, &Ray::new(&Vector3::new(2.0, 2.0, 2.0), &Vector3::EX));
  let p6 = Photon::new(&Wavelength::Blue, &Ray::new(&Vector3::new(2.0, 2.0, 2.0), &Vector3::EZ));

  kdtree.add(p1.ray.pos.v, p1).unwrap();
  kdtree.add(p2.ray.pos.v, p2).unwrap();
  kdtree.add(p3.ray.pos.v, p3).unwrap();
  kdtree.add(p4.ray.pos.v, p4).unwrap();
  kdtree.add(p5.ray.pos.v, p5).unwrap();
  kdtree.add(p6.ray.pos.v, p6).unwrap();

  println!("SIZE:{}", kdtree.size());
  println!("\nNEAREST 2 Photons");
  for p in kdtree.nearest(&Vector3::new(0.0, 0.0, 0.0).v, 2, &squared_euclidean).unwrap().iter() {
    println!("P: {:?}", p);
  }

  println!("\nNEAREST 3 Photons");
  for p in kdtree.nearest(&Vector3::new(0.0, 0.0, 0.0).v, 3, &squared_euclidean).unwrap().iter() {
    println!("P: {:?}", p);
  }

  println!("\nWITHIN 2.5");
  for p in kdtree.within(&Vector3::new(0.0, 0.0, 0.0).v, 2.5, &squared_euclidean).unwrap().iter() {
    println!("P: {:?}", p);
  }

  println!("\nWITHIN 12.0");
  for p in kdtree.within(&Vector3::new(0.0, 0.0, 0.0).v, 3.5*3.5, &squared_euclidean).unwrap().iter() {
    println!("P: {:?}", p);
  }

}


text:
use crate::{
    heartbeat::Heartbeat,
    socket_state::{SocketEvent, SocketStateHandle},
    tcp::TcpStream,
    thread::ThreadHandle,
    Result,
};
use log::trace;
use mio::{Events, Interest, Poll, Token, Waker};
use std::{
    collections::HashMap,
    fmt,
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc,
    },
    thread::Builder as ThreadBuilder,
};

pub type Slot = usize;

pub trait ReactorBuilder: fmt::Debug + Send + Sync {
    fn build(&self, heartbeat: Heartbeat) -> Result<Box<dyn Reactor + Send>>;
}

pub trait Reactor: fmt::Debug + Send {
    fn register(&mut self, socket: &mut TcpStream, socket_state: SocketStateHandle)
        -> Result<Slot>;
    fn handle(&self) -> Box<dyn ReactorHandle + Send> {
        Box::new(DummyHandle)
    }
    #[allow(clippy::boxed_local)]
    fn start(self: Box<Self>) -> Result<ThreadHandle> {
        Ok(ThreadHandle::default())
    }
}

pub trait ReactorHandle {
    fn shutdown(&self) -> Result<()> {
        Ok(())
    }
    fn start_heartbeat(&self) {}
    fn poll_read(&self, _slot: Slot) {}
    fn poll_write(&self, _slot: Slot) {}
}

pub(crate) struct DefaultReactorBuilder;

impl ReactorBuilder for DefaultReactorBuilder {
    fn build(&self, heartbeat: Heartbeat) -> Result<Box<dyn Reactor + Send>> {
        Ok(Box::new(DefaultReactor::new(heartbeat)?))
    }
}

pub(crate) struct DefaultReactor {
    slot: AtomicUsize,
    poll: Poll,
    heartbeat: Heartbeat,
    slots: HashMap<Token, SocketStateHandle>,
    handle: DefaultReactorHandle,
}

#[derive(Clone)]
pub(crate) struct DefaultReactorHandle {
    run: Arc<AtomicBool>,
    waker: Arc<Waker>,
}

impl Reactor for DefaultReactor {
    fn handle(&self) -> Box<dyn ReactorHandle + Send> {
        Box::new(self.handle.clone())
    }

    fn register(
        &mut self,
        socket: &mut TcpStream,
        socket_state: SocketStateHandle,
    ) -> Result<usize> {
        let token = Token(self.slot.fetch_add(1, Ordering::SeqCst));
        self.poll
            .registry()
            .register(socket, token, Interest::READABLE | Interest::WRITABLE)?;
        self.slots.insert(token, socket_state);
        Ok(token.0)
    }

    fn start(mut self: Box<Self>) -> Result<ThreadHandle> {
        Ok(ThreadHandle::new(
            ThreadBuilder::new()
                .name("lapin-reactor".into())
                .spawn(move || {
                    let mut events = Events::with_capacity(16);
                    while self.should_run() {
                        self.run(&mut events)?;
                    }
                    Ok(())
                })?,
        ))
    }
}

impl DefaultReactor {
    fn new(heartbeat: Heartbeat) -> Result<Self> {
        let poll = Poll::new()?;
        let handle = DefaultReactorHandle {
            run: Arc::new(AtomicBool::new(true)),
            waker: Arc::new(Waker::new(poll.registry(), Token(0))?),
        };
        Ok(Self {
            slot: AtomicUsize::new(1),
            poll,
            heartbeat,
            slots: HashMap::default(),
            handle,
        })
    }

    fn should_run(&self) -> bool {
        self.handle.run.load(Ordering::SeqCst)
    }

    fn run(&mut self, events: &mut Events) -> Result<()> {
        trace!("reactor poll");
        self.poll.poll(events, self.heartbeat.poll_timeout()?)?;
        trace!("reactor poll done");
        for event in events.iter() {
            if let Some(socket) = self.slots.get(&event.token()) {
                if event.is_error() {
                    socket.send(SocketEvent::Error);
                }
                if event.is_read_closed() || event.is_write_closed() {
                    socket.send(SocketEvent::Closed);
                }
                if event.is_readable() {
                    socket.send(SocketEvent::Readable);
                }
                if event.is_writable() {
                    socket.send(SocketEvent::Writable);
                }
            }
        }
        Ok(())
    }
}

impl ReactorHandle for DefaultReactorHandle {
    fn shutdown(&self) -> Result<()> {
        self.run.store(false, Ordering::SeqCst);
        self.waker.wake()?;
        Ok(())
    }
}

impl fmt::Debug for DefaultReactorBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DefaultReactorBuilder").finish()
    }
}

impl fmt::Debug for DefaultReactor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DefaultReactor").finish()
    }
}

#[derive(Clone)]
struct DummyHandle;

impl ReactorHandle for DummyHandle {}


text:
use crate::{
    net::{http::HttpNamingRemote, NamingRemote},
    data::model::Instance,
    error::Result
};

fn init_logger() {
    let _ = env_logger::builder()
        // Include all events in tests
        .filter_level(log::LevelFilter::max())
        // Ensure events are captured by `cargo test`
        .is_test(true)
        // Ignore errors initializing the logger if tests race to configure it
        .try_init();
}

#[tokio::test]
async fn test_http_remote_register() -> Result<()> {
    init_logger();
    let http_remote = HttpNamingRemote::new("http://192.168.1.248:8848/nacos", 8765);
    http_remote.register_instance("public", Instance::new_with_defaults("test", "192.168.1.221", 8888)).await?;
    let info = http_remote.query_instances(
        "public", "DEFAULT_GROUP@@test".to_string(), &["DEFAULT"], false
    ).await?;
    assert!(info.hosts.len() == 1, "after register; hosts len: {}", info.hosts.len());

    http_remote.deregister_instance("public", Instance::new_with_defaults("test", "192.168.1.221", 8888)).await?;
    let info = http_remote.query_instances(
        "public", "DEFAULT_GROUP@@test".to_string(), &["DEFAULT"], false
    ).await?;

    assert!(info.hosts.len() == 0, "after deregister; hosts len: {}", info.hosts.len());
    Ok(())
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to make layout debugging easier.

use crate::flow::{BoxTree, FragmentTree};
use serde_json::{to_string, to_value, Value};
use std::cell::RefCell;
use std::fs;
#[cfg(debug_assertions)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None));

#[cfg(debug_assertions)]
static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);

pub struct Scope;

#[macro_export]
macro_rules! layout_debug_scope(
    ($($arg:tt)*) => (
        if cfg!(debug_assertions) {
            layout_debug::Scope::new(format!($($arg)*))
        } else {
            layout_debug::Scope
        }
    )
);

#[derive(Serialize)]
struct TreeValues {
    pub box_tree: Value,
    pub fragment_tree: Value,
}

#[derive(Serialize)]
struct ScopeData {
    name: String,
    pre: TreeValues,
    post: TreeValues,
    children: Vec<Box<ScopeData>>,
}

impl ScopeData {
    fn new(name: String, box_tree: Value, fragment_tree: Value) -> ScopeData {
        ScopeData {
            name,
            pre: TreeValues {
                box_tree,
                fragment_tree,
            },
            post: TreeValues {
                box_tree: Value::Null,
                fragment_tree: Value::Null,
            },
            children: vec![],
        }
    }
}

struct State {
    fragment_tree: Arc<FragmentTree>,
    box_tree: Arc<BoxTree>,
    scope_stack: Vec<Box<ScopeData>>,
}

/// A layout debugging scope. The entire state of the box and fragment trees
/// will be output at the beginning and end of this scope.
impl Scope {
    pub fn new(name: String) -> Scope {
        STATE_KEY.with(|ref r| {
            if let Some(ref mut state) = *r.borrow_mut() {
                let box_tree = to_value(&state.box_tree).unwrap();
                let fragment_tree = to_value(&state.fragment_tree).unwrap();
                let data = Box::new(ScopeData::new(name.clone(), box_tree, fragment_tree));
                state.scope_stack.push(data);
            }
        });
        Scope
    }
}

#[cfg(debug_assertions)]
impl Drop for Scope {
    fn drop(&mut self) {
        STATE_KEY.with(|ref r| {
            if let Some(ref mut state) = *r.borrow_mut() {
                let mut current_scope = state.scope_stack.pop().unwrap();
                current_scope.post = TreeValues {
                    box_tree: to_value(&state.box_tree).unwrap(),
                    fragment_tree: to_value(&state.fragment_tree).unwrap(),
                };
                let previous_scope = state.scope_stack.last_mut().unwrap();
                previous_scope.children.push(current_scope);
            }
        });
    }
}

/// Generate a unique ID for Fragments.
#[cfg(debug_assertions)]
pub fn generate_unique_debug_id() -> u16 {
    DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16
}

/// Begin a layout debug trace. If this has not been called,
/// creating debug scopes has no effect.
pub fn begin_trace(box_tree: Arc<BoxTree>, fragment_tree: Arc<FragmentTree>) {
    assert!(STATE_KEY.with(|ref r| r.borrow().is_none()));

    STATE_KEY.with(|ref r| {
        let box_tree_value = to_value(&box_tree).unwrap();
        let fragment_tree_value = to_value(&fragment_tree).unwrap();
        let state = State {
            scope_stack: vec![Box::new(ScopeData::new(
                "root".to_owned(),
                box_tree_value,
                fragment_tree_value,
            ))],
            box_tree,
            fragment_tree,
        };
        *r.borrow_mut() = Some(state);
    });
}

/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace(generation: u32) {
    let mut thread_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unwrap());
    assert_eq!(thread_state.scope_stack.len(), 1);
    let mut root_scope = thread_state.scope_stack.pop().unwrap();
    root_scope.post = TreeValues {
        box_tree: to_value(&thread_state.box_tree).unwrap_or(Value::Null),
        fragment_tree: to_value(&thread_state.fragment_tree).unwrap_or(Value::Null),
    };
    let result = to_string(&root_scope).unwrap();
    fs::write(
        format!("layout_trace-{}.json", generation),
        result.as_bytes(),
    )
    .unwrap();
}


text:
use std::error::Error;
use std::fmt;
use std::str;
use std::iter::Peekable;

#[derive(Debug, PartialEq, Eq)]
pub enum Token<'a> {
    LeftParen,
    RightParen,
    Ident(&'a str),
    Comma,
    Equals,
    String(&'a str),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TokenType {
    LeftParen,
    RightParen,
    Ident,
    Comma,
    Equals,
    String,
}

impl fmt::Display for TokenType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TokenType::Ident => write!(f, "identifier"),
            TokenType::String => write!(f, "string"),
            TokenType::LeftParen => write!(f, "`(`"),
            TokenType::RightParen => write!(f, "`)`"),
            TokenType::Comma => write!(f, "`,`"),
            TokenType::Equals => write!(f, "`=`"),
        }
    }
}

impl<'a> fmt::Display for Token<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Token::Ident(ref s) => write!(f, "`{}`", s),
            &Token::String(ref s) => write!(f, r#"`"{}"`"#, s),
            t => t.get_type().fmt(f),
        }
    }
}

impl<'a> Token<'a> {
    pub fn is_type(&self, t: TokenType) -> bool {
        self.get_type() == t
    }

    fn get_type(&self) -> TokenType {
        match self {
            &Token::LeftParen => TokenType::LeftParen,
            &Token::RightParen => TokenType::RightParen,
            &Token::Ident(_) => TokenType::Ident,
            &Token::Comma => TokenType::Comma,
            &Token::Equals => TokenType::Equals,
            &Token::String(_) => TokenType::String,
        }

    }
}

pub struct Tokenizer<'a> {
    s: Peekable<str::CharIndices<'a>>,
    orig: &'a str,
}

#[derive(Debug, PartialEq, Eq)]
pub enum TokenError {
    UnterminatedString{
        pos: usize,
    },
    UnexpectedCharacter{
        pos: usize,
        ch: char,
    },
}

impl fmt::Display for TokenError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &TokenError::UnterminatedString{pos} => write!(f, "Unterminated string starting at {}", pos),
            &TokenError::UnexpectedCharacter{pos, ch} => write!(f, "Unexpected character {} at {}", ch, pos),
        }
    }
}

impl Error for TokenError {
    fn description(&self) -> &str {
        match self {
            &TokenError::UnterminatedString{..} => "unterminated string",
            &TokenError::UnexpectedCharacter{..} => "unexpected character",
        }
    }

    fn cause(&self) -> Option<&Error> {
        None
    }
}

impl<'a> From<&'a str> for Tokenizer<'a> {
    fn from(s: &'a str) -> Self {
        Tokenizer{
            s: s.char_indices().peekable(),
            orig: s,
        }
    }
}

impl<'a> Iterator for Tokenizer<'a> {
    type Item = Result<Token<'a>, TokenError>;

    fn next(&mut self) -> Option<Result<Token<'a>, TokenError>> {
        loop {
            match self.s.next() {
                Some((_, ' ')) => {}
                Some((_, '(')) => return Some(Ok(Token::LeftParen)),
                Some((_, ')')) => return Some(Ok(Token::RightParen)),
                Some((_, ',')) => return Some(Ok(Token::Comma)),
                Some((_, '=')) => return Some(Ok(Token::Equals)),
                Some((start, '"')) => {
                    while let Some((end, ch)) = self.s.next() {
                        if ch == '"' {
                            return Some(Ok(Token::String(&self.orig[start+1..end])))
                        }
                    }
                    return Some(Err(TokenError::UnterminatedString{pos: start}))
                }
                Some((start, ch)) if is_ident_start(ch) => {
                    while let Some(&(end, ch)) = self.s.peek() {
                        if !is_ident_rest(ch) {
                            return Some(Ok(Token::Ident(&self.orig[start..end])))
                        } else {
                            self.s.next();
                        }
                    }
                    return Some(Ok(Token::Ident(&self.orig[start..])))
                }
                Some((pos, ch)) => return Some(Err(TokenError::UnexpectedCharacter{pos, ch})),
                None => return None
            }
        }
    }
}

fn is_ident_start(ch: char) -> bool {
    ch == '_' || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')
}

fn is_ident_rest(ch: char) -> bool {
    is_ident_start(ch) || ('0' <= ch && ch <= '9')
}

#[cfg(test)]
mod tests {
    use super::{Tokenizer, Token, TokenError};

    #[test]
    fn single_token() {
        let mut t = Tokenizer::from("(");
        assert_eq!(t.next(), Some(Ok(Token::LeftParen)));
        assert_eq!(t.next(), None);

        t = Tokenizer::from(")");
        assert_eq!(t.next(), Some(Ok(Token::RightParen)));
        assert_eq!(t.next(), None);

        t = Tokenizer::from(",");
        assert_eq!(t.next(), Some(Ok(Token::Comma)));
        assert_eq!(t.next(), None);

        t = Tokenizer::from("=");
        assert_eq!(t.next(), Some(Ok(Token::Equals)));
        assert_eq!(t.next(), None);

        t = Tokenizer::from(r#""foo""#);
        assert_eq!(t.next(), Some(Ok(Token::String("foo"))));
        assert_eq!(t.next(), None);

        t = Tokenizer::from("foo");
        assert_eq!(t.next(), Some(Ok(Token::Ident("foo"))));
        assert_eq!(t.next(), None);

        t = Tokenizer::from("_bar");
        assert_eq!(t.next(), Some(Ok(Token::Ident("_bar"))));
        assert_eq!(t.next(), None);
    }

    #[test]
    fn single_bad() {
        let mut t = Tokenizer::from("");
        assert_eq!(t.next(), None);

        t = Tokenizer::from(" ");
        assert_eq!(t.next(), None);

        t = Tokenizer::from("\t");
        assert_eq!(t.next(), Some(Err(TokenError::UnexpectedCharacter{pos:0, ch: '\t'})));
        assert_eq!(t.next(), None);

        t = Tokenizer::from(r#"" "#);
        assert_eq!(t.next(), Some(Err(TokenError::UnterminatedString{pos:0})));
        assert_eq!(t.next(), None);

        t = Tokenizer::from("7");
        assert_eq!(t.next(), Some(Err(TokenError::UnexpectedCharacter{pos:0, ch: '7'})));
        assert_eq!(t.next(), None);
    }
}


text:
//! Abstraction over unix domain sockets / windows named pipes

use crate::internal::util::*;
use crate::internal::wire::*;
use crate::*;

use futures::{future::FutureExt, sink::SinkExt, stream::StreamExt};
use std::collections::HashMap;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[cfg(not(windows))]
mod unix_ipc;
#[cfg(not(windows))]
use unix_ipc::*;

#[cfg(windows)]
mod win_ipc;
#[cfg(windows)]
use win_ipc::*;

mod low_level;
pub(crate) use low_level::*;

/// IpcSender
pub type IpcSender = ghost_actor::GhostSender<IpcWireApi>;

/// IpcReceiver
pub type IpcReceiver = futures::channel::mpsc::Receiver<IpcWireApi>;

/// IncomingIpcReceiver
pub type IncomingIpcSender = futures::channel::mpsc::Sender<(
    KillSwitch,
    ghost_actor::GhostSender<IpcWireApi>,
    IpcReceiver,
)>;

/// IncomingIpcReceiver
pub type IncomingIpcReceiver = futures::channel::mpsc::Receiver<(
    KillSwitch,
    ghost_actor::GhostSender<IpcWireApi>,
    IpcReceiver,
)>;

ghost_actor::ghost_chan! {
    /// Ipc wire api for both incoming api requests and outgoing event requests.
    pub chan IpcWireApi<LairError> {
        /// Make an Ipc request.
        fn request(msg: LairWire) -> LairWire;
    }
}

/// Spawn/bind a new ipc listener connection awaiting incoming clients.
pub async fn spawn_bind_ipc(
    config: Arc<Config>,
) -> LairResult<(KillSwitch, IncomingIpcReceiver)> {
    let kill_switch = KillSwitch::new();
    let (in_send, in_recv) = futures::channel::mpsc::channel(10);

    let srv = IpcServer::bind(config)?;

    err_spawn(
        "srv-bind",
        srv_main_bind_task(kill_switch.clone(), srv, in_send),
    );

    Ok((kill_switch, in_recv))
}

async fn srv_main_bind_task(
    kill_switch: KillSwitch,
    mut srv: IpcServer,
    mut in_send: IncomingIpcSender,
) -> LairResult<()> {
    while let Ok((read_half, write_half)) = kill_switch.mix(srv.accept()).await
    {
        let (con_kill_switch, send, recv) = kill_switch
            .mix(async { spawn_connection_pair(read_half, write_half).await })
            .await?;

        kill_switch
            .mix(async {
                trace!("notify new connection");
                in_send
                    .send((con_kill_switch, send, recv))
                    .await
                    .map_err(LairError::other)
            })
            .await?;
    }
    Ok(())
}

/// Establish an outgoing client ipc connection to a lair server.
pub async fn spawn_ipc_connection(
    config: Arc<Config>,
) -> LairResult<(
    KillSwitch,
    ghost_actor::GhostSender<IpcWireApi>,
    IpcReceiver,
)> {
    let (read_half, write_half) = ipc_connect(config).await?;

    spawn_connection_pair(read_half, write_half).await
}

async fn spawn_connection_pair(
    read_half: IpcRead,
    write_half: IpcWrite,
) -> LairResult<(
    KillSwitch,
    ghost_actor::GhostSender<IpcWireApi>,
    IpcReceiver,
)> {
    let kill_switch = KillSwitch::new();

    let (evt_send, evt_recv) = futures::channel::mpsc::channel(10);

    let builder = ghost_actor::actor_builder::GhostActorBuilder::new();

    let sender = builder
        .channel_factory()
        .create_channel::<IpcWireApi>()
        .await?;

    let kill_sender = sender.clone();
    kill_switch
        .register_kill_callback(Box::new(move || {
            Box::pin(async move {
                use ghost_actor::GhostControlSender;
                if let Err(err) = kill_sender.ghost_actor_shutdown().await {
                    error!(?err);
                }
            })
        }))
        .await;

    let reader = spawn_low_level_read_half(kill_switch.clone(), read_half)?;
    builder.channel_factory().attach_receiver(reader).await?;

    let writer = spawn_low_level_write_half(kill_switch.clone(), write_half)?;

    tokio::task::spawn(builder.spawn(Internal {
        kill_switch: kill_switch.clone(),
        pending: HashMap::new(),
        writer,
        evt_send,
    }));

    Ok((kill_switch, sender, evt_recv))
}

struct Internal {
    kill_switch: KillSwitch,
    pending: HashMap<u64, tokio::sync::oneshot::Sender<LairWire>>,
    writer: futures::channel::mpsc::Sender<LowLevelWireApi>,
    evt_send: futures::channel::mpsc::Sender<IpcWireApi>,
}

impl ghost_actor::GhostControlHandler for Internal {}

impl ghost_actor::GhostHandler<LowLevelWireApi> for Internal {}

impl LowLevelWireApiHandler for Internal {
    fn handle_low_level_send(
        &mut self,
        msg: LairWire,
    ) -> LowLevelWireApiHandlerResult<()> {
        trace!(?msg, "RECV MSG");
        if msg.is_req() {
            let fut = self.kill_switch.mix_static(self.evt_send.request(msg));
            let writer_clone = self.writer.clone();
            let weak_kill_switch = self.kill_switch.weak();
            Ok(async move {
                if let Ok(res) = fut.await {
                    let _ = weak_kill_switch
                        .mix(writer_clone.low_level_send(res))
                        .await;
                }
                // TODO - send errors back so we don't have dangling reqs!!
                Ok(())
            }
            .boxed()
            .into())
        } else {
            if let Some(send) = self.pending.remove(&msg.get_msg_id()) {
                trace!("outgoing response received");
                let _ = send.send(msg);
            }
            Ok(async move { Ok(()) }.boxed().into())
        }
    }
}

impl ghost_actor::GhostHandler<IpcWireApi> for Internal {}

impl IpcWireApiHandler for Internal {
    fn handle_request(
        &mut self,
        msg: LairWire,
    ) -> IpcWireApiHandlerResult<LairWire> {
        let (send, recv) = tokio::sync::oneshot::channel();
        self.pending.insert(msg.get_msg_id(), send);
        trace!("con write {:?}", msg);
        let fut = self.kill_switch.mix_static(self.writer.low_level_send(msg));
        let weak_kill_switch = self.kill_switch.weak();
        Ok(async move {
            fut.await?;
            weak_kill_switch
                .mix(async move {
                    trace!("await incoming request...");
                    let res = recv.await.map_err(LairError::other);
                    trace!(?res, "respond to incoming request");
                    res
                })
                .await
        }
        .boxed()
        .into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn init_tracing() {
        let _ = subscriber::set_global_default(
            tracing_subscriber::FmtSubscriber::builder()
                .with_env_filter(
                    tracing_subscriber::EnvFilter::from_default_env(),
                )
                .compact()
                .finish(),
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_ipc_raw_wire() -> LairResult<()> {
        init_tracing();

        let tmpdir = tempfile::tempdir().unwrap();

        let config = Config::builder().set_root_path(tmpdir.path()).build();

        let (srv_kill, mut srv_recv) = spawn_bind_ipc(config.clone()).await?;

        let srv_task_kill = srv_kill.clone();
        err_spawn("test-outer", async move {
            while let Some((con_kill, con_send, mut con_recv)) =
                srv_recv.next().await
            {
                err_spawn("test-inner", async move {
                    println!("GOT CONNECTION!!");
                    let r = con_send
                        .request(LairWire::ToCliRequestUnlockPassphrase {
                            msg_id: 0,
                        })
                        .await
                        .unwrap();
                    println!("passphrase req RESPONSE: {:?}", r);
                    match r {
                        LairWire::ToLairRequestUnlockPassphraseResponse {
                            passphrase,
                            ..
                        } => {
                            assert_eq!("test-passphrase", &passphrase);
                        }
                        _ => panic!("unexpected: {:?}", r),
                    }
                    println!("DONE WITH PASSPHRASE LOOP\n\n");
                    while let Some(msg) = con_recv.next().await {
                        println!("GOT MESSAGE!!: {:?}", msg);
                        match msg {
                            IpcWireApi::Request { respond, msg, .. } => {
                                println!("GOT MESSAGE!!: {:?}", msg);
                                if let LairWire::ToLairLairGetLastEntryIndex {
                                    msg_id,
                                } = msg
                                {
                                    respond.respond(Ok(async move {
                                        Ok(LairWire::ToCliLairGetLastEntryIndexResponse {
                                            msg_id,
                                            last_keystore_index: 42.into(),
                                        })
                                    }.boxed().into()));
                                }
                            }
                        }
                        if !con_kill.cont() {
                            break;
                        }
                    }
                    LairResult::<()>::Ok(())
                });
                if !srv_task_kill.cont() {
                    break;
                }
            }
            LairResult::<()>::Ok(())
        });

        let (cli_kill, cli_send, mut cli_recv) =
            spawn_ipc_connection(config).await?;

        match cli_recv.next().await.unwrap() {
            IpcWireApi::Request { respond, msg, .. } => {
                println!("GOT: {:?}", msg);
                match msg {
                    LairWire::ToCliRequestUnlockPassphrase { msg_id } => {
                        respond.respond(Ok(async move {
                            Ok(LairWire::ToLairRequestUnlockPassphraseResponse {
                                msg_id,
                                passphrase: "test-passphrase".to_string(),
                            })
                        }
                        .boxed()
                        .into()));
                    }
                    _ => panic!("unexpected: {:?}", msg),
                }
            }
        }

        let res = cli_send
            .request(LairWire::ToLairLairGetLastEntryIndex { msg_id: 0 })
            .await
            .unwrap();
        println!("GOT: {:?}", res);

        match res {
            LairWire::ToCliLairGetLastEntryIndexResponse {
                last_keystore_index,
                ..
            } => {
                assert_eq!(42, last_keystore_index.0);
            }
            _ => panic!("unexpected: {:?}", res),
        }

        println!("COMPLETE - DROPPING ITEMS");

        drop(cli_kill);
        drop(srv_kill);
        drop(tmpdir);

        println!("COMPLETE - ITEMS DROPPED - exiting test");

        Ok(())
    }
}


text:
use crate::{
    compilation::{compile_validators, context::CompilationContext, JSONSchema},
    error::{CompilationError, ValidationError},
    keywords::{format_vec_of_validators, CompilationResult, Validators},
    validator::Validate,
};
use serde_json::{Map, Value};

pub(crate) struct AnyOfValidator {
    schemas: Vec<Validators>,
}

impl AnyOfValidator {
    #[inline]
    pub(crate) fn compile(schema: &Value, context: &CompilationContext) -> CompilationResult {
        if let Value::Array(items) = schema {
            let mut schemas = Vec::with_capacity(items.len());
            for item in items {
                let validators = compile_validators(item, context)?;
                schemas.push(validators)
            }
            Ok(Box::new(AnyOfValidator { schemas }))
        } else {
            Err(CompilationError::SchemaError)
        }
    }
}

macro_rules! any_of_impl_is_valid {
    ($method_suffix:tt, $instance_type: ty) => {
        paste::item! {
            #[inline]
            fn [<is_valid_ $method_suffix>](
                &self,
                schema: &JSONSchema,
                instance: &Value,
                instance_value: $instance_type,
            ) -> bool {
                self.schemas.iter().any(move |validators| {
                    validators.iter().all(move |validator| {
                        validator.[<is_valid_ $method_suffix>](schema, instance, instance_value)
                    })
                })
            }
        }
    };
}

impl Validate for AnyOfValidator {
    #[inline]
    fn build_validation_error<'a>(&self, instance: &'a Value) -> ValidationError<'a> {
        ValidationError::any_of(instance)
    }

    any_of_impl_is_valid!(array, &[Value]);
    any_of_impl_is_valid!(boolean, bool);
    any_of_impl_is_valid!(null, ());
    any_of_impl_is_valid!(number, f64);
    any_of_impl_is_valid!(object, &Map<String, Value>);
    any_of_impl_is_valid!(signed_integer, i64);
    any_of_impl_is_valid!(string, &str);
    any_of_impl_is_valid!(unsigned_integer, u64);
}
impl ToString for AnyOfValidator {
    fn to_string(&self) -> String {
        format!("anyOf: [{}]", format_vec_of_validators(&self.schemas))
    }
}

#[inline]
pub(crate) fn compile(
    _: &Map<String, Value>,
    schema: &Value,
    context: &CompilationContext,
) -> Option<CompilationResult> {
    Some(AnyOfValidator::compile(schema, context))
}


text:
use num_traits::{AsPrimitive, FromPrimitive, NumAssign, PrimInt, Unsigned};
use std::fmt::{Debug, Display};

pub trait UnsignedInt:
    PrimInt
    + Unsigned
    + Display
    + Debug
    + AsPrimitive<usize>
    + AsPrimitive<f64>
    + FromPrimitive
    + NumAssign
{
}

impl UnsignedInt for u16 {}
impl UnsignedInt for u32 {}

///
/// Solution of the linear assignment problem
///
#[derive(Debug, Clone)]
pub struct AuctionSolution<I>
where
    I: UnsignedInt,
{
    /// index i gives the object, j, owned by person i
    ///
    /// Unassigned people are marked by MAX value of the integer type (u32::MAX for u32)
    pub person_to_object: Vec<I>,
    /// index j gives the person, i, who owns object j
    ///
    /// Unassigned objects are marked by MAX value of the integer type (u32::MAX for u32)
    pub object_to_person: Vec<I>,
    /// number of unnassigned people in case perfect matching doesn't exist
    pub num_unassigned: I,
    /// found solution is ε-optimal if perfect matching exists. For integer weights small enough ε
    /// gives optimum.
    pub eps: f64,
}

impl<I> AuctionSolution<I>
where
    I: UnsignedInt,
{
    pub fn new(row_capacity: usize, column_capacity: usize) -> AuctionSolution<I> {
        AuctionSolution::<I> {
            person_to_object: Vec::with_capacity(row_capacity),
            object_to_person: Vec::with_capacity(column_capacity),
            eps: f64::NAN,
            num_unassigned: I::max_value(),
        }
    }
}


text:
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]

// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

use pallet_grandpa::{
	fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
	create_runtime_str, generic, impl_opaque_keys,
	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, Verify},
	transaction_validity::{TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, MultiSignature,
};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;

// A few exports that help ease life for downstream crates.
pub use frame_support::{
	construct_runtime, parameter_types,
	traits::{ConstU128, ConstU32, ConstU8, KeyOwnerProofSystem, Randomness, StorageInfo},
	weights::{
		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
		IdentityFee, Weight,
	},
	StorageValue,
};
pub use pallet_balances::Call as BalancesCall;
pub use pallet_timestamp::Call as TimestampCall;
use pallet_transaction_payment::CurrencyAdapter;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use sp_runtime::{Perbill, Permill};

/// Import the template pallet.
pub use pallet_template;

pub use pallet_kitties;

/// An index to a block.
pub type BlockNumber = u32;

/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;

/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;

/// Balance of an account.
pub type Balance = u128;

/// Index of a transaction in the chain.
pub type Index = u32;

/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;

/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
	use super::*;

	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;

	/// Opaque block header type.
	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
	/// Opaque block type.
	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
	/// Opaque block identifier type.
	pub type BlockId = generic::BlockId<Block>;

	impl_opaque_keys! {
		pub struct SessionKeys {
			pub aura: Aura,
			pub grandpa: Grandpa,
		}
	}
}

// To learn more about runtime versioning and what each of the following value means:
//   https://docs.substrate.io/v3/runtime/upgrades#runtime-versioning
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("node-template"),
	impl_name: create_runtime_str!("node-template"),
	authoring_version: 1,
	// The version of the runtime specification. A full node will not attempt to use its native
	//   runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`,
	//   `spec_version`, and `authoring_version` are the same between Wasm and native.
	// This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use
	//   the compatible custom types.
	spec_version: 100,
	impl_version: 1,
	apis: RUNTIME_API_VERSIONS,
	transaction_version: 1,
	state_version: 1,
};

/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 6000;

// NOTE: Currently it is not possible to change the slot duration after the chain has started.
//       Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;

// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;

/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}

const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);

parameter_types! {
	pub const Version: RuntimeVersion = VERSION;
	pub const BlockHashCount: BlockNumber = 2400;
	/// We allow for 2 seconds of compute with a 6 second average block time.
	pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights
		::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO);
	pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
		::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
	pub const SS58Prefix: u8 = 42;
}

// Configure FRAME pallets to include in runtime.

impl frame_system::Config for Runtime {
	/// The basic call filter to use in dispatchable.
	type BaseCallFilter = frame_support::traits::Everything;
	/// Block & extrinsics weights: base values and limits.
	type BlockWeights = BlockWeights;
	/// The maximum length of a block (in bytes).
	type BlockLength = BlockLength;
	/// The identifier used to distinguish between accounts.
	type AccountId = AccountId;
	/// The aggregated dispatch type that is available for extrinsics.
	type Call = Call;
	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
	type Lookup = AccountIdLookup<AccountId, ()>;
	/// The index type for storing how many extrinsics an account has signed.
	type Index = Index;
	/// The index type for blocks.
	type BlockNumber = BlockNumber;
	/// The type for hashing blocks and tries.
	type Hash = Hash;
	/// The hashing algorithm used.
	type Hashing = BlakeTwo256;
	/// The header type.
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
	/// The ubiquitous event type.
	type Event = Event;
	/// The ubiquitous origin type.
	type Origin = Origin;
	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
	type BlockHashCount = BlockHashCount;
	/// The weight of database operations that the runtime can invoke.
	type DbWeight = RocksDbWeight;
	/// Version of the runtime.
	type Version = Version;
	/// Converts a module to the index of the module in `construct_runtime!`.
	///
	/// This type is being generated by `construct_runtime!`.
	type PalletInfo = PalletInfo;
	/// What to do if a new account is created.
	type OnNewAccount = ();
	/// What to do if an account is fully reaped from the system.
	type OnKilledAccount = ();
	/// The data to be stored in an account.
	type AccountData = pallet_balances::AccountData<Balance>;
	/// Weight information for the extrinsics of this pallet.
	type SystemWeightInfo = ();
	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
	type SS58Prefix = SS58Prefix;
	/// The set code logic, just the default since we're not a parachain.
	type OnSetCode = ();
	type MaxConsumers = frame_support::traits::ConstU32<16>;
}

impl pallet_randomness_collective_flip::Config for Runtime {}

impl pallet_aura::Config for Runtime {
	type AuthorityId = AuraId;
	type DisabledValidators = ();
	type MaxAuthorities = ConstU32<32>;
}

impl pallet_grandpa::Config for Runtime {
	type Event = Event;
	type Call = Call;

	type KeyOwnerProofSystem = ();

	type KeyOwnerProof =
		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
		GrandpaId,
	)>>::IdentificationTuple;

	type HandleEquivocation = ();

	type WeightInfo = ();
	type MaxAuthorities = ConstU32<32>;
}

parameter_types! {
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}

impl pallet_timestamp::Config for Runtime {
	/// A timestamp: milliseconds since the unix epoch.
	type Moment = u64;
	type OnTimestampSet = Aura;
	type MinimumPeriod = MinimumPeriod;
	type WeightInfo = ();
}

impl pallet_balances::Config for Runtime {
	type MaxLocks = ConstU32<50>;
	type MaxReserves = ();
	type ReserveIdentifier = [u8; 8];
	/// The type for recording an account's balance.
	type Balance = Balance;
	/// The ubiquitous event type.
	type Event = Event;
	type DustRemoval = ();
	type ExistentialDeposit = ConstU128<500>;
	type AccountStore = System;
	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
}

parameter_types! {
	pub const TransactionByteFee: Balance = 1;
}

impl pallet_transaction_payment::Config for Runtime {
	type OnChargeTransaction = CurrencyAdapter<Balances, ()>;
	type TransactionByteFee = TransactionByteFee;
	type OperationalFeeMultiplier = ConstU8<5>;
	type WeightToFee = IdentityFee<Balance>;
	type FeeMultiplierUpdate = ();
}

impl pallet_sudo::Config for Runtime {
	type Event = Event;
	type Call = Call;
}

/// Configure the pallet-template in pallets/template.
impl pallet_template::Config for Runtime {
	type Event = Event;
}

parameter_types! {
	pub const MaxKittyOwned: u32 = 308;
}

impl pallet_kitties::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
	type KittyRandomness = RandomnessCollectiveFlip;
	type MaxKittyOwned = MaxKittyOwned;
	type TimeProvider = Timestamp;
}

// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
	pub enum Runtime where
		Block = Block,
		NodeBlock = opaque::Block,
		UncheckedExtrinsic = UncheckedExtrinsic
	{
		System: frame_system,
		RandomnessCollectiveFlip: pallet_randomness_collective_flip,
		Timestamp: pallet_timestamp,
		Aura: pallet_aura,
		Grandpa: pallet_grandpa,
		Balances: pallet_balances,
		TransactionPayment: pallet_transaction_payment,
		Sudo: pallet_sudo,
		// Include the custom logic from the pallet-template in the runtime.
		TemplateModule: pallet_template,
		Kitties: pallet_kitties,
	}
);

/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
	frame_system::CheckNonZeroSender<Runtime>,
	frame_system::CheckSpecVersion<Runtime>,
	frame_system::CheckTxVersion<Runtime>,
	frame_system::CheckGenesis<Runtime>,
	frame_system::CheckEra<Runtime>,
	frame_system::CheckNonce<Runtime>,
	frame_system::CheckWeight<Runtime>,
	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
	Runtime,
	Block,
	frame_system::ChainContext<Runtime>,
	Runtime,
	AllPalletsWithSystem,
>;

#[cfg(feature = "runtime-benchmarks")]
#[macro_use]
extern crate frame_benchmarking;

#[cfg(feature = "runtime-benchmarks")]
mod benches {
	define_benchmarks!(
		[frame_benchmarking, BaselineBench::<Runtime>]
		[frame_system, SystemBench::<Runtime>]
		[pallet_balances, Balances]
		[pallet_timestamp, Timestamp]
		[pallet_template, TemplateModule]
	);
}

impl_runtime_apis! {
	impl sp_api::Core<Block> for Runtime {
		fn version() -> RuntimeVersion {
			VERSION
		}

		fn execute_block(block: Block) {
			Executive::execute_block(block);
		}

		fn initialize_block(header: &<Block as BlockT>::Header) {
			Executive::initialize_block(header)
		}
	}

	impl sp_api::Metadata<Block> for Runtime {
		fn metadata() -> OpaqueMetadata {
			OpaqueMetadata::new(Runtime::metadata().into())
		}
	}

	impl sp_block_builder::BlockBuilder<Block> for Runtime {
		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
			Executive::apply_extrinsic(extrinsic)
		}

		fn finalize_block() -> <Block as BlockT>::Header {
			Executive::finalize_block()
		}

		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
			data.create_extrinsics()
		}

		fn check_inherents(
			block: Block,
			data: sp_inherents::InherentData,
		) -> sp_inherents::CheckInherentsResult {
			data.check_extrinsics(&block)
		}
	}

	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
		fn validate_transaction(
			source: TransactionSource,
			tx: <Block as BlockT>::Extrinsic,
			block_hash: <Block as BlockT>::Hash,
		) -> TransactionValidity {
			Executive::validate_transaction(source, tx, block_hash)
		}
	}

	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
		fn offchain_worker(header: &<Block as BlockT>::Header) {
			Executive::offchain_worker(header)
		}
	}

	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
		fn slot_duration() -> sp_consensus_aura::SlotDuration {
			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
		}

		fn authorities() -> Vec<AuraId> {
			Aura::authorities().into_inner()
		}
	}

	impl sp_session::SessionKeys<Block> for Runtime {
		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
			opaque::SessionKeys::generate(seed)
		}

		fn decode_session_keys(
			encoded: Vec<u8>,
		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
		}
	}

	impl fg_primitives::GrandpaApi<Block> for Runtime {
		fn grandpa_authorities() -> GrandpaAuthorityList {
			Grandpa::grandpa_authorities()
		}

		fn current_set_id() -> fg_primitives::SetId {
			Grandpa::current_set_id()
		}

		fn submit_report_equivocation_unsigned_extrinsic(
			_equivocation_proof: fg_primitives::EquivocationProof<
				<Block as BlockT>::Hash,
				NumberFor<Block>,
			>,
			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
		) -> Option<()> {
			None
		}

		fn generate_key_ownership_proof(
			_set_id: fg_primitives::SetId,
			_authority_id: GrandpaId,
		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
			// NOTE: this is the only implementation possible since we've
			// defined our key owner proof type as a bottom type (i.e. a type
			// with no values).
			None
		}
	}

	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
		fn account_nonce(account: AccountId) -> Index {
			System::account_nonce(account)
		}
	}

	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
		fn query_info(
			uxt: <Block as BlockT>::Extrinsic,
			len: u32,
		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
			TransactionPayment::query_info(uxt, len)
		}
		fn query_fee_details(
			uxt: <Block as BlockT>::Extrinsic,
			len: u32,
		) -> pallet_transaction_payment::FeeDetails<Balance> {
			TransactionPayment::query_fee_details(uxt, len)
		}
	}

	#[cfg(feature = "runtime-benchmarks")]
	impl frame_benchmarking::Benchmark<Block> for Runtime {
		fn benchmark_metadata(extra: bool) -> (
			Vec<frame_benchmarking::BenchmarkList>,
			Vec<frame_support::traits::StorageInfo>,
		) {
			use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
			use frame_support::traits::StorageInfoTrait;
			use frame_system_benchmarking::Pallet as SystemBench;
			use baseline::Pallet as BaselineBench;

			let mut list = Vec::<BenchmarkList>::new();
			list_benchmarks!(list, extra);

			let storage_info = AllPalletsWithSystem::storage_info();

			return (list, storage_info)
		}

		fn dispatch_benchmark(
			config: frame_benchmarking::BenchmarkConfig
		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
			use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch, TrackedStorageKey};

			use frame_system_benchmarking::Pallet as SystemBench;
			use baseline::Pallet as BaselineBench;

			impl frame_system_benchmarking::Config for Runtime {}
			impl baseline::Config for Runtime {}

			let whitelist: Vec<TrackedStorageKey> = vec![
				// Block Number
				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
				// Total Issuance
				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
				// Execution Phase
				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
				// Event Count
				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
				// System Events
				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
			];

			let mut batches = Vec::<BenchmarkBatch>::new();
			let params = (&config, &whitelist);
			add_benchmarks!(params, batches);

			Ok(batches)
		}
	}
}


text:
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::{Path,PathBuf};
use bindgen;
use common;

fn main() {
    common::print_cargo_watches();

    let mut builder = bindgen::Builder::default();

    let msg_list = if let Some(cmake_includes) = env::var("CMAKE_INCLUDE_DIRS").ok() {
        let packages = cmake_includes.split(":").flat_map(|i| Path::new(i).parent()).collect::<Vec<_>>();
        for p in cmake_includes.split(":") {
            builder = builder.clang_arg(format!("-I{}", p));
        }
        let deps = env::var("CMAKE_IDL_PACKAGES").unwrap_or(String::default());
        let deps = deps.split(":").collect::<Vec<_>>();
        let msgs = common::get_ros_msgs(&packages);
        common::parse_msgs(&msgs).into_iter()
            .filter(|msg| deps.contains(&msg.module.as_str())).collect::<Vec<_>>()
    } else {
        let ament_prefix_var = env::var("AMENT_PREFIX_PATH").expect("Source your ROS!");
        for p in ament_prefix_var.split(":") {
            builder = builder.clang_arg(format!("-I{}/include", p));
        }

        let paths = ament_prefix_var.split(":").map(|i| Path::new(i)).collect::<Vec<_>>();
        let msgs = common::get_ros_msgs(&paths);
        common::parse_msgs(&msgs)
    };

    let msg_map = common::as_map(&msg_list);

    for module in msg_map.keys() {
        println!(
            "cargo:rustc-link-lib=dylib={}__rosidl_typesupport_c",
            module
        );
        println!(
            "cargo:rustc-link-lib=dylib={}__rosidl_typesupport_introspection_c",
            module
        );
        println!("cargo:rustc-link-lib=dylib={}__rosidl_generator_c", module);
    }

    let mut includes = String::new();
    let mut introspecion_map = String::from(
        "\
         lazy_static! { \n
           static ref INTROSPECTION_FNS: HashMap<&'static str, usize> = {\n
             let mut m = HashMap::new();\n",
    );

    for msg in msg_list {
        // filename is certainly CamelCase -> snake_case. convert
        use heck::SnakeCase;
        let include_filename = msg.name.to_snake_case();

        includes.push_str(&format!(
            "#include <{}/{}/{}.h>\n",
            &msg.module, &msg.prefix, &include_filename
        ));
        includes.push_str(&format!(
            "#include <{}/{}/detail/{}__rosidl_typesupport_introspection_c.h>\n",
            &msg.module, &msg.prefix, &include_filename
        ));

        if msg.prefix == "srv" {
            for s in &["Request", "Response"] {
                let key = &format!("{}__{}__{}_{}", &msg.module, &msg.prefix, &msg.name, s);
                let val = &format!("unsafe {{ rosidl_typesupport_introspection_c__get_message_type_support_handle__{}__{}__{}_{}() }} as *const i32 as usize", &msg.module, &msg.prefix, &msg.name, s);
                introspecion_map.push_str(&format!("m.insert(\"{}\", {});\n", key, val));
            }
        } else {
            let key = &format!("{}__{}__{}", &msg.module, &msg.prefix, &msg.name);
            let val = &format!("unsafe {{ rosidl_typesupport_introspection_c__get_message_type_support_handle__{}__{}__{}() }} as *const i32 as usize", &msg.module, &msg.prefix, &msg.name);
            introspecion_map.push_str(&format!("m.insert(\"{}\", {});\n", key, val));
        }
    }
    introspecion_map.push_str("m \n }; }\n\n");

    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let msg_includes_fn = out_path.join("msg_includes.h");
    let introspection_fn = out_path.join("introspection_functions.rs");

    let mut f = File::create(msg_includes_fn.clone()).unwrap();
    write!(f, "{}", includes).unwrap();

    let mut f = File::create(introspection_fn).unwrap();
    write!(f, "{}", introspecion_map).unwrap();

    builder = builder
        .header(msg_includes_fn.to_str().unwrap())
        .derive_copy(false)
         // blacklist types that are handled by rcl bindings
        .blacklist_type("rosidl_message_type_support_t")
        .blacklist_type("rosidl_service_type_support_t")
        .blacklist_type("rosidl_runtime_c__String")
        .blacklist_type("rosidl_runtime_c__String__Sequence")
        .blacklist_type("rosidl_runtime_c__U16String")
        .blacklist_type("rosidl_runtime_c__U16String__Sequence")
        .blacklist_type("rosidl_runtime_c__float32__Sequence")
        .blacklist_type("rosidl_runtime_c__float__Sequence")
        .blacklist_type("rosidl_runtime_c__float64__Sequence")
        .blacklist_type("rosidl_runtime_c__double__Sequence")
        .blacklist_type("rosidl_runtime_c__long_double__Sequence")
        .blacklist_type("rosidl_runtime_c__char__Sequence")
        .blacklist_type("rosidl_runtime_c__wchar__Sequence")
        .blacklist_type("rosidl_runtime_c__boolean__Sequence")
        .blacklist_type("rosidl_runtime_c__octet__Sequence")
        .blacklist_type("rosidl_runtime_c__uint8__Sequence")
        .blacklist_type("rosidl_runtime_c__int8__Sequence")
        .blacklist_type("rosidl_runtime_c__uint16__Sequence")
        .blacklist_type("rosidl_runtime_c__int16__Sequence")
        .blacklist_type("rosidl_runtime_c__uint32__Sequence")
        .blacklist_type("rosidl_runtime_c__int32__Sequence")
        .blacklist_type("rosidl_runtime_c__uint64__Sequence")
        .blacklist_type("rosidl_runtime_c__int64__Sequence")
        .size_t_is_usize(true)
        .no_debug("_OSUnaligned.*")
        .default_enum_style(bindgen::EnumVariation::Rust {
            non_exhaustive: false,
        });

    let bindings = builder.generate().expect("Unable to generate bindings");

    bindings
        .write_to_file(out_path.join("msg_bindings.rs"))
        .expect("Couldn't write bindings!");
}


text:
// This test documents that `type Out = Box<dyn Bar<Assoc: Copy>>;`
// is allowed and will correctly reject an opaque `type Out` which
// does not satisfy the bound `<TheType as Bar>::Assoc: Copy`.
//
// FIXME(rust-lang/lang): I think this behavior is logical if we want to allow
// `dyn Trait<Assoc: Bound>` but we should decide if we want that. // Centril
//
// Additionally, as reported in https://github.com/rust-lang/rust/issues/63594,
// we check that the spans for the error message are sane here.

#![feature(associated_type_bounds)]

fn main() {}

trait Bar {
    type Assoc;
}

trait Thing {
    type Out;
    fn func() -> Self::Out;
}

struct AssocNoCopy;
impl Bar for AssocNoCopy {
    type Assoc = String;
}

impl Thing for AssocNoCopy {
    type Out = Box<dyn Bar<Assoc: Copy>>;
    //~^ ERROR the trait bound `String: Copy` is not satisfied

    fn func() -> Self::Out {
        Box::new(AssocNoCopy)
    }
}