text:
use std::{collections::HashMap, io::Write};

use crate::{
    codec::{Decoder, Encoder},
    error::{DecodeError, EncodeError},
    protocol::commands::COMMAND_OPEN,
    response::ResponseCode,
    FromResponse,
};

use super::Command;

#[cfg(test)]
use fake::Fake;

#[cfg_attr(test, derive(fake::Dummy))]
#[derive(PartialEq, Debug)]
pub struct OpenCommand {
    correlation_id: u32,
    virtual_host: String,
}

impl OpenCommand {
    pub fn new(correlation_id: u32, virtual_host: String) -> Self {
        Self {
            correlation_id,
            virtual_host,
        }
    }
}

impl Encoder for OpenCommand {
    fn encode(&self, writer: &mut impl Write) -> Result<(), EncodeError> {
        self.correlation_id.encode(writer)?;
        self.virtual_host.as_str().encode(writer)?;
        Ok(())
    }

    fn encoded_size(&self) -> u32 {
        self.correlation_id.encoded_size() + self.virtual_host.as_str().encoded_size()
    }
}

impl Command for OpenCommand {
    fn key(&self) -> u16 {
        COMMAND_OPEN
    }
}

#[cfg_attr(test, derive(fake::Dummy))]
#[derive(Debug, PartialEq)]
pub struct OpenResponse {
    pub(crate) correlation_id: u32,
    pub(crate) code: ResponseCode,
    pub connection_properties: HashMap<String, String>,
}

impl OpenResponse {
    /// Get a reference to the open response's connection properties.
    pub fn connection_properties(&self) -> &HashMap<String, String> {
        &self.connection_properties
    }
}

impl FromResponse for OpenResponse {
    fn from_response(response: crate::Response) -> Option<Self> {
        match response.kind {
            crate::ResponseKind::Open(open) => Some(open),
            _ => None,
        }
    }
}

impl Decoder for OpenResponse {
    fn decode(input: &[u8]) -> Result<(&[u8], Self), DecodeError> {
        let (input, correlation_id) = u32::decode(input)?;
        let (input, response_code) = ResponseCode::decode(input)?;
        let (input, connection_properties) = HashMap::decode(input)?;

        Ok((
            input,
            OpenResponse {
                correlation_id,
                code: response_code,
                connection_properties,
            },
        ))
    }
}

impl Decoder for OpenCommand {
    fn decode(input: &[u8]) -> Result<(&[u8], Self), DecodeError> {
        let (input, correlation_id) = u32::decode(input)?;
        let (input, virtual_host) = Option::decode(input)?;

        Ok((
            input,
            OpenCommand {
                correlation_id,
                virtual_host: virtual_host.unwrap(),
            },
        ))
    }
}

#[cfg(test)]
mod tests {

    use super::OpenCommand;
    use crate::{
        codec::Encoder,
        commands::{open::OpenResponse, tests::command_encode_decode_test},
    };

    #[test]
    fn open_command_test() {
        command_encode_decode_test::<OpenCommand>()
    }

    impl Encoder for OpenResponse {
        fn encode(
            &self,
            writer: &mut impl std::io::Write,
        ) -> Result<(), crate::error::EncodeError> {
            self.correlation_id.encode(writer)?;
            self.code.encode(writer)?;
            self.connection_properties.encode(writer)?;
            Ok(())
        }

        fn encoded_size(&self) -> u32 {
            0
        }
    }

    #[test]
    fn open_response_test() {
        command_encode_decode_test::<OpenResponse>();
    }
}


text:
//! Shader compilation.

#![warn(
    missing_debug_implementations,
    missing_copy_implementations,
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications
)]

#[cfg(feature = "shader-compiler")]
mod shaderc;

#[cfg(feature = "spirv-reflection")]
#[allow(dead_code)]
mod reflect;

#[cfg(feature = "shader-compiler")]
pub use self::shaderc::*;

#[cfg(feature = "spirv-reflection")]
pub use self::reflect::{ReflectError, ReflectTypeError, RetrievalKind, SpirvReflection};

use rendy_core::hal::{pso::ShaderStageFlags, Backend};
use std::collections::HashMap;

/// Error type returned by this module.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ShaderError {}

impl std::error::Error for ShaderError {}
impl std::fmt::Display for ShaderError {
    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {}
    }
}

/// Interface to create shader modules from shaders.
/// Implemented for static shaders via [`compile_to_spirv!`] macro.
///
pub trait Shader {
    /// The error type returned by the spirv function of this shader.
    type Error: std::fmt::Debug;

    /// Get spirv bytecode.
    fn spirv(&self) -> Result<std::borrow::Cow<'_, [u32]>, <Self as Shader>::Error>;

    /// Get the entry point of the shader.
    fn entry(&self) -> &str;

    /// Get the rendy_core::hal representation of this shaders kind/stage.
    fn stage(&self) -> ShaderStageFlags;

    /// Create shader module.
    ///
    /// Spir-V bytecode must adhere valid usage on this Vulkan spec page:
    /// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkShaderModuleCreateInfo.html
    unsafe fn module<B>(
        &self,
        factory: &rendy_factory::Factory<B>,
    ) -> Result<B::ShaderModule, rendy_core::hal::device::ShaderError>
    where
        B: Backend,
    {
        rendy_core::hal::device::Device::create_shader_module(
            factory.device().raw(),
            &self.spirv().map_err(|e| {
                rendy_core::hal::device::ShaderError::CompilationFailed(format!("{:?}", e))
            })?,
        )
    }
}

/// Spir-V shader.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SpirvShader {
    #[cfg_attr(feature = "serde", serde(with = "serde_spirv"))]
    spirv: Vec<u32>,
    stage: ShaderStageFlags,
    entry: String,
}

#[cfg(feature = "serde")]
mod serde_spirv {
    pub fn serialize<S>(data: &Vec<u32>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_bytes(rendy_core::cast_slice(&data))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u32>, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Via the serde::Deserialize impl for &[u8].
        let bytes: &[u8] = serde::Deserialize::deserialize(deserializer)?;
        rendy_core::hal::pso::read_spirv(std::io::Cursor::new(bytes))
            .map_err(serde::de::Error::custom)
    }
}

impl SpirvShader {
    /// Create Spir-V shader from bytes.
    pub fn new(spirv: Vec<u32>, stage: ShaderStageFlags, entrypoint: &str) -> Self {
        assert!(!spirv.is_empty());
        Self {
            spirv,
            stage,
            entry: entrypoint.to_string(),
        }
    }

    /// Create Spir-V shader from bytecode stored as bytes.
    /// Errors when passed byte array length is not a multiple of 4.
    pub fn from_bytes(
        spirv: &[u8],
        stage: ShaderStageFlags,
        entrypoint: &str,
    ) -> std::io::Result<Self> {
        Ok(Self::new(
            rendy_core::hal::pso::read_spirv(std::io::Cursor::new(spirv))?,
            stage,
            entrypoint,
        ))
    }
}

impl Shader for SpirvShader {
    type Error = ShaderError;

    fn spirv(&self) -> Result<std::borrow::Cow<'_, [u32]>, ShaderError> {
        Ok(std::borrow::Cow::Borrowed(&self.spirv))
    }

    fn entry(&self) -> &str {
        &self.entry
    }

    fn stage(&self) -> ShaderStageFlags {
        self.stage
    }
}

/// A `ShaderSet` object represents a merged collection of `ShaderStorage` structures, which reflects merged information for all shaders in the set.
#[derive(Debug)]
pub struct ShaderSet<B: Backend> {
    shaders: HashMap<ShaderStageFlags, ShaderStorage<B>>,
}

impl<B> Default for ShaderSet<B>
where
    B: Backend,
{
    fn default() -> Self {
        ShaderSet {
            shaders: HashMap::default(),
        }
    }
}

impl<B: Backend> ShaderSet<B> {
    /// This function compiles and loads all shaders into B::ShaderModule objects which must be dropped later with `dispose`
    pub fn load(
        &mut self,
        factory: &rendy_factory::Factory<B>,
    ) -> Result<&mut Self, rendy_core::hal::device::ShaderError> {
        for (_, v) in self.shaders.iter_mut() {
            unsafe { v.compile(factory)? }
        }

        Ok(self)
    }

    /// Returns the `GraphicsShaderSet` structure to provide all the runtime information needed to use the shaders in this set in rendy_core::hal.
    pub fn raw<'a>(
        &'a self,
    ) -> Result<rendy_core::hal::pso::GraphicsShaderSet<'a, B>, ShaderError> {
        Ok(rendy_core::hal::pso::GraphicsShaderSet {
            vertex: self
                .shaders
                .get(&ShaderStageFlags::VERTEX)
                .expect("ShaderSet doesn't contain vertex shader")
                .get_entry_point()?
                .unwrap(),
            fragment: match self.shaders.get(&ShaderStageFlags::FRAGMENT) {
                Some(fragment) => fragment.get_entry_point()?,
                None => None,
            },
            domain: match self.shaders.get(&ShaderStageFlags::DOMAIN) {
                Some(domain) => domain.get_entry_point()?,
                None => None,
            },
            hull: match self.shaders.get(&ShaderStageFlags::HULL) {
                Some(hull) => hull.get_entry_point()?,
                None => None,
            },
            geometry: match self.shaders.get(&ShaderStageFlags::GEOMETRY) {
                Some(geometry) => geometry.get_entry_point()?,
                None => None,
            },
        })
    }

    /// Must be called to perform a drop of the Backend ShaderModule object otherwise the shader will never be destroyed in memory.
    pub fn dispose(&mut self, factory: &rendy_factory::Factory<B>) {
        for (_, shader) in self.shaders.iter_mut() {
            shader.dispose(factory);
        }
    }
}

/// A set of Specialization constants for a certain shader set.
#[derive(Debug, Default, Clone)]
#[allow(missing_copy_implementations)]
pub struct SpecConstantSet {
    /// Vertex specialization
    pub vertex: Option<rendy_core::hal::pso::Specialization<'static>>,
    /// Fragment specialization
    pub fragment: Option<rendy_core::hal::pso::Specialization<'static>>,
    /// Geometry specialization
    pub geometry: Option<rendy_core::hal::pso::Specialization<'static>>,
    /// Hull specialization
    pub hull: Option<rendy_core::hal::pso::Specialization<'static>>,
    /// Domain specialization
    pub domain: Option<rendy_core::hal::pso::Specialization<'static>>,
    /// Compute specialization
    pub compute: Option<rendy_core::hal::pso::Specialization<'static>>,
}

/// Builder class which is used to begin the reflection and shader set construction process for a shader set. Provides all the functionality needed to
/// build a shader set with provided shaders and then reflect appropriate gfx-hal and generic shader information.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShaderSetBuilder {
    vertex: Option<(Vec<u32>, String)>,
    fragment: Option<(Vec<u32>, String)>,
    geometry: Option<(Vec<u32>, String)>,
    hull: Option<(Vec<u32>, String)>,
    domain: Option<(Vec<u32>, String)>,
    compute: Option<(Vec<u32>, String)>,
}

impl ShaderSetBuilder {
    /// Builds the Backend-specific shader modules using the provided SPIRV code provided to the builder.
    /// This function is called during the creation of a render pass.
    ///
    /// # Parameters
    ///
    /// `factory`   - factory to create shader modules.
    ///
    pub fn build<B: Backend>(
        &self,
        factory: &rendy_factory::Factory<B>,
        spec_constants: SpecConstantSet,
    ) -> Result<ShaderSet<B>, rendy_core::hal::device::ShaderError> {
        let mut set = ShaderSet::<B>::default();

        if self.vertex.is_none() && self.compute.is_none() {
            let msg = "A vertex or compute shader must be provided".to_string();
            return Err(rendy_core::hal::device::ShaderError::InterfaceMismatch(msg));
        }
        type ShaderTy = (
            Vec<u32>,
            String,
            Option<rendy_core::hal::pso::Specialization<'static>>,
        );

        let create_storage =
            move |stage,
                  shader: ShaderTy,
                  factory|
                  -> Result<ShaderStorage<B>, rendy_core::hal::device::ShaderError> {
                let mut storage = ShaderStorage {
                    stage,
                    spirv: shader.0,
                    module: None,
                    entrypoint: shader.1.clone(),
                    specialization: shader.2,
                };
                unsafe {
                    storage.compile(factory)?;
                }
                Ok(storage)
            };

        if let Some(shader) = self.vertex.clone() {
            set.shaders.insert(
                ShaderStageFlags::VERTEX,
                create_storage(
                    ShaderStageFlags::VERTEX,
                    (shader.0, shader.1, spec_constants.vertex),
                    factory,
                )?,
            );
        }

        if let Some(shader) = self.fragment.clone() {
            set.shaders.insert(
                ShaderStageFlags::FRAGMENT,
                create_storage(
                    ShaderStageFlags::FRAGMENT,
                    (shader.0, shader.1, spec_constants.fragment),
                    factory,
                )?,
            );
        }

        if let Some(shader) = self.compute.clone() {
            set.shaders.insert(
                ShaderStageFlags::COMPUTE,
                create_storage(
                    ShaderStageFlags::COMPUTE,
                    (shader.0, shader.1, spec_constants.compute),
                    factory,
                )?,
            );
        }

        if let Some(shader) = self.domain.clone() {
            set.shaders.insert(
                ShaderStageFlags::DOMAIN,
                create_storage(
                    ShaderStageFlags::DOMAIN,
                    (shader.0, shader.1, spec_constants.domain),
                    factory,
                )?,
            );
        }

        if let Some(shader) = self.hull.clone() {
            set.shaders.insert(
                ShaderStageFlags::HULL,
                create_storage(
                    ShaderStageFlags::HULL,
                    (shader.0, shader.1, spec_constants.hull),
                    factory,
                )?,
            );
        }

        if let Some(shader) = self.geometry.clone() {
            set.shaders.insert(
                ShaderStageFlags::GEOMETRY,
                create_storage(
                    ShaderStageFlags::GEOMETRY,
                    (shader.0, shader.1, spec_constants.geometry),
                    factory,
                )?,
            );
        }

        Ok(set)
    }

    /// Add a vertex shader to this shader set
    #[inline(always)]
    pub fn with_vertex<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.vertex = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    /// Add a fragment shader to this shader set
    #[inline(always)]
    pub fn with_fragment<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.fragment = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    /// Add a geometry shader to this shader set
    #[inline(always)]
    pub fn with_geometry<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.geometry = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    /// Add a hull shader to this shader set
    #[inline(always)]
    pub fn with_hull<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.hull = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    /// Add a domain shader to this shader set
    #[inline(always)]
    pub fn with_domain<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.domain = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    /// Add a compute shader to this shader set.
    /// Note a compute or vertex shader must always exist in a shader set.
    #[inline(always)]
    pub fn with_compute<S: Shader>(mut self, shader: &S) -> Result<Self, S::Error> {
        let data = shader.spirv()?;
        self.compute = Some((data.to_vec(), shader.entry().to_string()));
        Ok(self)
    }

    #[cfg(feature = "spirv-reflection")]
    /// This function processes all shaders provided to the builder and computes and stores full reflection information on the shader.
    /// This includes names, attributes, descriptor sets and push constants used by the shaders, as well as compiling local caches for performance.
    pub fn reflect(&self) -> Result<SpirvReflection, ReflectError> {
        if self.vertex.is_none() && self.compute.is_none() {
            return Err(ReflectError::NoVertComputeProvided);
        }

        // We need to combine and merge all the reflections into a single SpirvReflection instance
        let mut reflections = Vec::new();
        if let Some(vertex) = self.vertex.as_ref() {
            reflections.push(SpirvReflection::reflect(&vertex.0, None)?);
        }
        if let Some(fragment) = self.fragment.as_ref() {
            reflections.push(SpirvReflection::reflect(&fragment.0, None)?);
        }
        if let Some(hull) = self.hull.as_ref() {
            reflections.push(SpirvReflection::reflect(&hull.0, None)?);
        }
        if let Some(domain) = self.domain.as_ref() {
            reflections.push(SpirvReflection::reflect(&domain.0, None)?);
        }
        if let Some(compute) = self.compute.as_ref() {
            reflections.push(SpirvReflection::reflect(&compute.0, None)?);
        }
        if let Some(geometry) = self.geometry.as_ref() {
            reflections.push(SpirvReflection::reflect(&geometry.0, None)?);
        }

        reflect::merge(&reflections)?.compile_cache()
    }
}

/// Contains reflection and runtime nformation for a given compiled Shader Module.
#[derive(Debug)]
pub struct ShaderStorage<B: Backend> {
    stage: ShaderStageFlags,
    spirv: Vec<u32>,
    module: Option<B::ShaderModule>,
    entrypoint: String,
    specialization: Option<rendy_core::hal::pso::Specialization<'static>>,
}
impl<B: Backend> ShaderStorage<B> {
    /// Builds the `EntryPoint` structure used by rendy_core::hal to determine how to utilize this shader
    pub fn get_entry_point<'a>(
        &'a self,
    ) -> Result<Option<rendy_core::hal::pso::EntryPoint<'a, B>>, ShaderError> {
        Ok(Some(rendy_core::hal::pso::EntryPoint {
            entry: &self.entrypoint,
            module: self.module.as_ref().unwrap(),
            specialization: self.specialization.clone().unwrap_or_default(),
        }))
    }

    /// Compile the SPIRV code with the backend and store the reference to the module inside this structure.
    pub unsafe fn compile(
        &mut self,
        factory: &rendy_factory::Factory<B>,
    ) -> Result<(), rendy_core::hal::device::ShaderError> {
        self.module = Some(rendy_core::hal::device::Device::create_shader_module(
            factory.device().raw(),
            &self.spirv,
        )?);

        Ok(())
    }

    fn dispose(&mut self, factory: &rendy_factory::Factory<B>) {
        use rendy_core::hal::device::Device;

        if let Some(module) = self.module.take() {
            unsafe { factory.destroy_shader_module(module) };
        }
        self.module = None;
    }
}

impl<B: Backend> Drop for ShaderStorage<B> {
    fn drop(&mut self) {
        if self.module.is_some() {
            panic!("This shader storage class needs to be manually dropped with dispose() first");
        }
    }
}

domain: rust


text:
use crate::mechanics::car::{Car, CarState};
use crate::{CarID, FOLLOWING_DISTANCE};
use geom::{Distance, Time};
use map_model::{Map, Traversable};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, VecDeque};

#[derive(Serialize, Deserialize, PartialEq, Clone)]
pub struct Queue {
    pub id: Traversable,
    pub cars: VecDeque<CarID>,
    // This car's back is still partly in this queue.
    pub laggy_head: Option<CarID>,

    pub geom_len: Distance,
    // When a car's turn is accepted, reserve the vehicle length + FOLLOWING_DISTANCE for the
    // target lane. When the car completely leaves (stops being the laggy_head), free up that
    // space. To prevent blocking the box for possibly scary amounts of time, allocate some of this
    // length first. This is unused for turns themselves. This value can exceed geom_len (for the
    // edge case of ONE long car on a short queue).
    pub reserved_length: Distance,
}

impl Queue {
    pub fn new(id: Traversable, map: &Map) -> Queue {
        Queue {
            id,
            cars: VecDeque::new(),
            laggy_head: None,
            geom_len: id.length(map),
            reserved_length: Distance::ZERO,
        }
    }

    // Farthest along (greatest distance) is first.
    pub fn get_car_positions(
        &self,
        now: Time,
        cars: &BTreeMap<CarID, Car>,
        queues: &BTreeMap<Traversable, Queue>,
    ) -> Vec<(CarID, Distance)> {
        self.inner_get_car_positions(now, cars, queues, &mut BTreeSet::new())
    }

    fn inner_get_car_positions(
        &self,
        now: Time,
        cars: &BTreeMap<CarID, Car>,
        queues: &BTreeMap<Traversable, Queue>,
        recursed_queues: &mut BTreeSet<Traversable>,
    ) -> Vec<(CarID, Distance)> {
        if self.cars.is_empty() {
            return Vec::new();
        }

        let mut result: Vec<(CarID, Distance)> = Vec::new();

        for id in &self.cars {
            let bound = match result.last() {
                Some((leader, last_dist)) => {
                    *last_dist - cars[leader].vehicle.length - FOLLOWING_DISTANCE
                }
                None => match self.laggy_head {
                    Some(id) => {
                        // The simple but broken version:
                        //self.geom_len - cars[&id].vehicle.length - FOLLOWING_DISTANCE

                        // The expensive case. We need to figure out exactly where the laggy head
                        // is on their queue.
                        let leader = &cars[&id];

                        // But don't create a cycle!
                        let recurse_to = leader.router.head();
                        if recursed_queues.contains(&recurse_to) {
                            // See the picture in
                            // https://github.com/dabreegster/abstreet/issues/30. We have two
                            // extremes to break the cycle.
                            //
                            // 1) Hope that the last person in this queue isn't bounded by the
                            //    agent in front of them yet. geom_len
                            // 2) Assume the leader has advanced minimally into the next lane.
                            //    geom_len - laggy head's length - FOLLOWING_DISTANCE.
                            //
                            // For now, optimistically assume 1. If we're wrong, consequences could
                            // be queue spillover (we're too optimistic about the number of
                            // vehicles that can fit on a lane) or cars jumping positions slightly
                            // while the cycle occurs.
                            self.geom_len
                        } else {
                            recursed_queues.insert(recurse_to);

                            let (head, head_dist) = *queues[&leader.router.head()]
                                .inner_get_car_positions(now, cars, queues, recursed_queues)
                                .last()
                                .unwrap();
                            assert_eq!(head, id);

                            let mut dist_away_from_this_queue = head_dist;
                            for on in &leader.last_steps {
                                if *on == self.id {
                                    break;
                                }
                                dist_away_from_this_queue += queues[on].geom_len;
                            }
                            // They might actually be out of the way, but laggy_head hasn't been
                            // updated yet.
                            if dist_away_from_this_queue
                                < leader.vehicle.length + FOLLOWING_DISTANCE
                            {
                                self.geom_len
                                    - (cars[&id].vehicle.length - dist_away_from_this_queue)
                                    - FOLLOWING_DISTANCE
                            } else {
                                self.geom_len
                            }
                        }
                    }
                    None => self.geom_len,
                },
            };

            // There's spillover and a car shouldn't have been able to enter yet.
            if bound < Distance::ZERO {
                dump_cars(&result, cars, self.id, now);
                panic!(
                    "Queue has spillover on {} at {} -- can't draw {}, bound is {}. Laggy head is \
                     {:?}. This is usually a geometry bug; check for duplicate roads going \
                     between the same intersections.",
                    self.id, now, id, bound, self.laggy_head
                );
            }

            let car = &cars[id];
            let front = match car.state {
                CarState::Queued { .. } => {
                    if car.router.last_step() {
                        car.router.get_end_dist().min(bound)
                    } else {
                        bound
                    }
                }
                CarState::WaitingToAdvance { .. } => {
                    assert_eq!(bound, self.geom_len);
                    self.geom_len
                }
                CarState::Crossing(ref time_int, ref dist_int) => {
                    // TODO Why percent_clamp_end? We process car updates in any order, so we might
                    // calculate this before moving this car from Crossing to another state.
                    dist_int.lerp(time_int.percent_clamp_end(now)).min(bound)
                }
                CarState::Unparking(front, _, _) => front,
                CarState::Parking(front, _, _) => front,
                CarState::Idling(front, _) => front,
            };

            result.push((*id, front));
        }
        validate_positions(result, cars, now, self.id)
    }

    pub fn get_idx_to_insert_car(
        &self,
        start_dist: Distance,
        vehicle_len: Distance,
        now: Time,
        cars: &BTreeMap<CarID, Car>,
        queues: &BTreeMap<Traversable, Queue>,
    ) -> Option<usize> {
        if self.laggy_head.is_none() && self.cars.is_empty() {
            return Some(0);
        }

        let dists = self.get_car_positions(now, cars, queues);
        // TODO Binary search
        let idx = match dists.iter().position(|(_, dist)| start_dist >= *dist) {
            Some(i) => i,
            None => dists.len(),
        };

        // Nope, there's not actually room at the front right now.
        if self.laggy_head.is_some() && idx == 0 {
            return None;
        }

        // Are we too close to the leader?
        if idx != 0
            && dists[idx - 1].1 - cars[&dists[idx - 1].0].vehicle.length - FOLLOWING_DISTANCE
                < start_dist
        {
            return None;
        }
        // Or the follower?
        if idx != dists.len() && start_dist - vehicle_len - FOLLOWING_DISTANCE < dists[idx].1 {
            return None;
        }

        Some(idx)
    }

    // If true, there's room and the car must actually start the turn (because the space is
    // reserved).
    pub fn try_to_reserve_entry(&mut self, car: &Car, force_entry: bool) -> bool {
        // Sometimes a car + FOLLOWING_DISTANCE might be longer than the geom_len entirely. In that
        // case, it just means the car won't totally fit on the queue at once, which is fine.
        // Reserve the normal amount of space; the next car trying to enter will get rejected.
        // Also allow this don't-block-the-box prevention to be disabled.
        let dist = car.vehicle.length + FOLLOWING_DISTANCE;
        if self.reserved_length + dist < self.geom_len
            || self.reserved_length == Distance::ZERO
            || force_entry
        {
            self.reserved_length += dist;
            return true;
        }
        false
    }

    // TODO Refactor
    pub fn room_for_car(&self, car: &Car) -> bool {
        self.reserved_length == Distance::ZERO
            || self.reserved_length + car.vehicle.length + FOLLOWING_DISTANCE < self.geom_len
    }

    pub fn free_reserved_space(&mut self, car: &Car) {
        self.reserved_length -= car.vehicle.length + FOLLOWING_DISTANCE;
        assert!(self.reserved_length >= Distance::ZERO);
    }
}

fn validate_positions(
    dists: Vec<(CarID, Distance)>,
    cars: &BTreeMap<CarID, Car>,
    now: Time,
    id: Traversable,
) -> Vec<(CarID, Distance)> {
    for pair in dists.windows(2) {
        if pair[0].1 - cars[&pair[0].0].vehicle.length - FOLLOWING_DISTANCE < pair[1].1 {
            dump_cars(&dists, cars, id, now);
            panic!(
                "get_car_positions wound up with bad positioning: {} then {}\n{:?}",
                pair[0].1, pair[1].1, dists
            );
        }
    }
    dists
}

fn dump_cars(
    dists: &Vec<(CarID, Distance)>,
    cars: &BTreeMap<CarID, Car>,
    id: Traversable,
    now: Time,
) {
    println!("\nOn {} at {}...", id, now);
    for (id, dist) in dists {
        let car = &cars[id];
        println!("- {} @ {} (length {})", id, dist, car.vehicle.length);
        match car.state {
            CarState::Crossing(ref time_int, ref dist_int) => {
                println!(
                    "  Going {} .. {} during {} .. {}",
                    dist_int.start, dist_int.end, time_int.start, time_int.end
                );
            }
            CarState::Queued { .. } => {
                println!("  Queued currently");
            }
            CarState::WaitingToAdvance { .. } => {
                println!("  WaitingToAdvance currently");
            }
            CarState::Unparking(_, _, ref time_int) => {
                println!("  Unparking during {} .. {}", time_int.start, time_int.end);
            }
            CarState::Parking(_, _, ref time_int) => {
                println!("  Parking during {} .. {}", time_int.start, time_int.end);
            }
            CarState::Idling(_, ref time_int) => {
                println!("  Idling during {} .. {}", time_int.start, time_int.end);
            }
        }
    }
    println!();
}


text:
fn main() {

    use std::io::{self, Read};
    use std::cmp::Ordering;
    use std::collections::{HashMap,HashSet};
    use std::mem;

    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let input_strs = buffer.split_whitespace().map( |x| x.parse::<i64>().unwrap() ).collect::< Vec<i64> >();

    let n = *input_strs.iter().nth(0).unwrap();

    let x = input_strs.iter().skip(1).take(n as usize).cloned().collect::<Vec<i64>>();
    let y = input_strs.iter().skip(1+n as usize).cloned().collect::<Vec<i64>>();

    let mut hs = HashSet::new();
    let mut v = vec![];
    let mut x_lim = (10000000000i64,-10000000000i64);
    let mut y_lim = (10000000000i64,-10000000000i64);
    for i in x.iter().zip(y.iter()) {
        v.push(i);
        hs.insert((*i.0,*i.1));
        if *i.0 < x_lim.0 {
            x_lim.0 = *i.0;
        }
        if *i.0 > x_lim.1 {
            x_lim.1 = *i.0;
        }

        if *i.1 < y_lim.0 {
            y_lim.0 = *i.1;
        }
        if *i.1 > y_lim.1 {
            y_lim.1 = *i.1;
        }
    }

    println!("{:?}", x_lim );

    println!("{:?}", y_lim );
}


text:
// run-pass

// aux-build:cross_crates_defaults.rs

#![feature(specialization)]

extern crate cross_crates_defaults;

use cross_crates_defaults::*;

struct LocalDefault;
struct LocalOverride;

impl Foo for LocalDefault {}

impl Foo for LocalOverride {
    fn foo(&self) -> bool { true }
}

fn test_foo() {
    assert!(!0i8.foo());
    assert!(!0i32.foo());
    assert!(0i64.foo());

    assert!(!LocalDefault.foo());
    assert!(LocalOverride.foo());
}

fn test_bar() {
    assert!(0u8.bar() == 0);
    assert!(0i32.bar() == 1);
    assert!("hello".bar() == 0);
    assert!(vec![()].bar() == 2);
    assert!(vec![0i32].bar() == 2);
    assert!(vec![0i64].bar() == 3);
}

fn main() {
    test_foo();
    test_bar();
}


text:
#![doc = "generated by AutoRust"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccessPolicyEntry {
    #[serde(rename = "tenantId")]
    pub tenant_id: String,
    #[serde(rename = "objectId")]
    pub object_id: String,
    #[serde(rename = "applicationId", default, skip_serializing_if = "Option::is_none")]
    pub application_id: Option<String>,
    pub permissions: Permissions,
}
impl AccessPolicyEntry {
    pub fn new(tenant_id: String, object_id: String, permissions: Permissions) -> Self {
        Self {
            tenant_id,
            object_id,
            application_id: None,
            permissions,
        }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CheckNameAvailabilityResult {
    #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
    pub name_available: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<check_name_availability_result::Reason>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}
impl CheckNameAvailabilityResult {
    pub fn new() -> Self {
        Self::default()
    }
}
pub mod check_name_availability_result {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum Reason {
        AccountNameInvalid,
        AlreadyExists,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct DeletedVault {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<DeletedVaultProperties>,
}
impl DeletedVault {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct DeletedVaultListResult {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub value: Vec<DeletedVault>,
    #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
    pub next_link: Option<String>,
}
impl DeletedVaultListResult {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct DeletedVaultProperties {
    #[serde(rename = "vaultId", default, skip_serializing_if = "Option::is_none")]
    pub vault_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    #[serde(rename = "deletionDate", default, skip_serializing_if = "Option::is_none")]
    pub deletion_date: Option<String>,
    #[serde(rename = "scheduledPurgeDate", default, skip_serializing_if = "Option::is_none")]
    pub scheduled_purge_date: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<serde_json::Value>,
}
impl DeletedVaultProperties {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IpRule {
    pub value: String,
}
impl IpRule {
    pub fn new(value: String) -> Self {
        Self { value }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct LogSpecification {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")]
    pub blob_duration: Option<String>,
}
impl LogSpecification {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct NetworkRuleSet {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bypass: Option<network_rule_set::Bypass>,
    #[serde(rename = "defaultAction", default, skip_serializing_if = "Option::is_none")]
    pub default_action: Option<network_rule_set::DefaultAction>,
    #[serde(rename = "ipRules", default, skip_serializing_if = "Vec::is_empty")]
    pub ip_rules: Vec<IpRule>,
    #[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")]
    pub virtual_network_rules: Vec<VirtualNetworkRule>,
}
impl NetworkRuleSet {
    pub fn new() -> Self {
        Self::default()
    }
}
pub mod network_rule_set {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum Bypass {
        AzureServices,
        None,
    }
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum DefaultAction {
        Allow,
        Deny,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Operation {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display: Option<operation::Display>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<OperationProperties>,
}
impl Operation {
    pub fn new() -> Self {
        Self::default()
    }
}
pub mod operation {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
    pub struct Display {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub provider: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub resource: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub operation: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub description: Option<String>,
    }
    impl Display {
        pub fn new() -> Self {
            Self::default()
        }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationListResult {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub value: Vec<Operation>,
    #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
    pub next_link: Option<String>,
}
impl OperationListResult {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationProperties {
    #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")]
    pub service_specification: Option<ServiceSpecification>,
}
impl OperationProperties {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Permissions {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keys: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub certificates: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub storage: Vec<String>,
}
impl Permissions {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
    pub location: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<serde_json::Value>,
}
impl Resource {
    pub fn new(location: String) -> Self {
        Self {
            id: None,
            name: None,
            type_: None,
            location,
            tags: None,
        }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ResourceListResult {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub value: Vec<Resource>,
    #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
    pub next_link: Option<String>,
}
impl ResourceListResult {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ServiceSpecification {
    #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")]
    pub log_specifications: Vec<LogSpecification>,
}
impl ServiceSpecification {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
    pub family: sku::Family,
    pub name: sku::Name,
}
impl Sku {
    pub fn new(family: sku::Family, name: sku::Name) -> Self {
        Self { family, name }
    }
}
pub mod sku {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum Family {
        A,
    }
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum Name {
        #[serde(rename = "standard")]
        Standard,
        #[serde(rename = "premium")]
        Premium,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Vault {
    #[serde(flatten)]
    pub resource: Resource,
    pub properties: VaultProperties,
}
impl Vault {
    pub fn new(resource: Resource, properties: VaultProperties) -> Self {
        Self { resource, properties }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VaultAccessPolicyParameters {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    pub properties: VaultAccessPolicyProperties,
}
impl VaultAccessPolicyParameters {
    pub fn new(properties: VaultAccessPolicyProperties) -> Self {
        Self {
            id: None,
            name: None,
            type_: None,
            location: None,
            properties,
        }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VaultAccessPolicyProperties {
    #[serde(rename = "accessPolicies")]
    pub access_policies: Vec<AccessPolicyEntry>,
}
impl VaultAccessPolicyProperties {
    pub fn new(access_policies: Vec<AccessPolicyEntry>) -> Self {
        Self { access_policies }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VaultCheckNameAvailabilityParameters {
    pub name: String,
    #[serde(rename = "type")]
    pub type_: vault_check_name_availability_parameters::Type,
}
impl VaultCheckNameAvailabilityParameters {
    pub fn new(name: String, type_: vault_check_name_availability_parameters::Type) -> Self {
        Self { name, type_ }
    }
}
pub mod vault_check_name_availability_parameters {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum Type {
        #[serde(rename = "Microsoft.KeyVault/vaults")]
        MicrosoftKeyVaultVaults,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VaultCreateOrUpdateParameters {
    pub location: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<serde_json::Value>,
    pub properties: VaultProperties,
}
impl VaultCreateOrUpdateParameters {
    pub fn new(location: String, properties: VaultProperties) -> Self {
        Self {
            location,
            tags: None,
            properties,
        }
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct VaultListResult {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub value: Vec<Vault>,
    #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
    pub next_link: Option<String>,
}
impl VaultListResult {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct VaultPatchParameters {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<VaultPatchProperties>,
}
impl VaultPatchParameters {
    pub fn new() -> Self {
        Self::default()
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct VaultPatchProperties {
    #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sku: Option<Sku>,
    #[serde(rename = "accessPolicies", default, skip_serializing_if = "Vec::is_empty")]
    pub access_policies: Vec<AccessPolicyEntry>,
    #[serde(rename = "enabledForDeployment", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_deployment: Option<bool>,
    #[serde(rename = "enabledForDiskEncryption", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_disk_encryption: Option<bool>,
    #[serde(rename = "enabledForTemplateDeployment", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_template_deployment: Option<bool>,
    #[serde(rename = "enableSoftDelete", default, skip_serializing_if = "Option::is_none")]
    pub enable_soft_delete: Option<bool>,
    #[serde(rename = "createMode", default, skip_serializing_if = "Option::is_none")]
    pub create_mode: Option<vault_patch_properties::CreateMode>,
    #[serde(rename = "enablePurgeProtection", default, skip_serializing_if = "Option::is_none")]
    pub enable_purge_protection: Option<bool>,
    #[serde(rename = "networkAcls", default, skip_serializing_if = "Option::is_none")]
    pub network_acls: Option<NetworkRuleSet>,
}
impl VaultPatchProperties {
    pub fn new() -> Self {
        Self::default()
    }
}
pub mod vault_patch_properties {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum CreateMode {
        #[serde(rename = "recover")]
        Recover,
        #[serde(rename = "default")]
        Default,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VaultProperties {
    #[serde(rename = "tenantId")]
    pub tenant_id: String,
    pub sku: Sku,
    #[serde(rename = "accessPolicies", default, skip_serializing_if = "Vec::is_empty")]
    pub access_policies: Vec<AccessPolicyEntry>,
    #[serde(rename = "vaultUri", default, skip_serializing_if = "Option::is_none")]
    pub vault_uri: Option<String>,
    #[serde(rename = "enabledForDeployment", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_deployment: Option<bool>,
    #[serde(rename = "enabledForDiskEncryption", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_disk_encryption: Option<bool>,
    #[serde(rename = "enabledForTemplateDeployment", default, skip_serializing_if = "Option::is_none")]
    pub enabled_for_template_deployment: Option<bool>,
    #[serde(rename = "enableSoftDelete", default, skip_serializing_if = "Option::is_none")]
    pub enable_soft_delete: Option<bool>,
    #[serde(rename = "createMode", default, skip_serializing_if = "Option::is_none")]
    pub create_mode: Option<vault_properties::CreateMode>,
    #[serde(rename = "enablePurgeProtection", default, skip_serializing_if = "Option::is_none")]
    pub enable_purge_protection: Option<bool>,
    #[serde(rename = "networkAcls", default, skip_serializing_if = "Option::is_none")]
    pub network_acls: Option<NetworkRuleSet>,
}
impl VaultProperties {
    pub fn new(tenant_id: String, sku: Sku) -> Self {
        Self {
            tenant_id,
            sku,
            access_policies: Vec::new(),
            vault_uri: None,
            enabled_for_deployment: None,
            enabled_for_disk_encryption: None,
            enabled_for_template_deployment: None,
            enable_soft_delete: None,
            create_mode: None,
            enable_purge_protection: None,
            network_acls: None,
        }
    }
}
pub mod vault_properties {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub enum CreateMode {
        #[serde(rename = "recover")]
        Recover,
        #[serde(rename = "default")]
        Default,
    }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRule {
    pub id: String,
}
impl VirtualNetworkRule {
    pub fn new(id: String) -> Self {
        Self { id }
    }
}


text:
//! Keyboard shortcut manager implementation.

#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unsafe_code)]
#![warn(unused_import_braces)]
#![warn(unused_qualifications)]

#![feature(test)]
#![feature(trait_alias)]

extern crate test;

use enso_automata::*;
use enso_prelude::*;
use ensogl_system_web as web;

pub use enso_logger::*;
pub use enso_logger::AnyLogger;
pub use enso_logger::WarningLogger as Logger;
pub use enso_logger as logger;

// ==============
// === Traits ===
// ==============

/// Common traits.
pub mod traits {
    pub use super::Registry as TRAIT_Registry;
}

// ===============
// === Helpers ===
// ===============

fn hash<T:Hash>(t:&T) -> u64 {
    let mut s = DefaultHasher::new();
    t.hash(&mut s);
    s.finish()
}

/// Pretty prints the provided matrix.
pub fn print_matrix(matrix:&data::Matrix<dfa::State>) {
    println!("rows x cols = {} x {} ({})",matrix.rows, matrix.columns,matrix.matrix.len());
    for row in 0..matrix.rows {
        for column in 0..matrix.columns {
            let elem = matrix.safe_index(row,column).unwrap();
            let repr = if elem.is_invalid() { "-".into() } else { format!("{}",elem.id()) };
            print!("{} ",repr);
        }
        println!();
    }
}

fn reverse_key(key:&str) -> String {
    format!("-{}",key)
}

/// List of special keys. Special keys can be grouped together to distinguish action sequences like
/// `ctrl + a` and `a + ctrl`. Please note, that this is currently not happening.
const SIDE_KEYS : &[&str] = &["ctrl","alt","alt-graph","meta","cmd","shift"];

lazy_static! {
    static ref SIDE_KEYS_SET: HashSet<&'static str> = SIDE_KEYS.iter().copied().collect();
}

const DOUBLE_EVENT_TIME_MS : f32 = 300.0;

// ==================
// === ActionType ===
// ==================

/// The type of the action. Could be applied to keyboard, mouse, or any mix of input events.
/// As a clarification, the event `DoublePress` is emitted on second press of a button/key happening
/// in short time interval from the first one. `DoubleClick`, on the other hand, happens on release,
/// not on press.
#[derive(Clone,Copy,Debug,Eq,Hash,PartialEq)]
#[allow(missing_docs)]
pub enum ActionType {
    Press, PressAndRepeat, Release, DoublePress, DoubleClick
}
pub use ActionType::*;

// ================
// === Registry ===
// ================

/// Abstraction for shortcut registry implementation.
#[allow(missing_docs)]
pub trait Registry<T> : Default {
    /// Add a new action mapping. `The expr` needs to be a list of keys separated by space, like
    /// "ctrl shift a".
    fn add (&self, action_type:ActionType, expr:impl AsRef<str>, action:impl Into<T>);

    /// Get a list of items registered for the action that just happened. It might include items
    /// registered for `DoublePress` or `DoubleClick` if the actions were performed fast enough.
    fn on_press (&self, input:impl AsRef<str>) -> Vec<T>;

    /// Get a list of items registered for the action that just happened. It might include items
    /// registered for `DoublePress` or `DoubleClick` if the actions were performed fast enough.
    fn on_release (&self, input:impl AsRef<str>) -> Vec<T>;

    /// Some engines might implement a separate optimization stage. This is intended to force the
    /// optimization at a given point in time. Used mainly in benchmarks.
    fn optimize (&self) {}
}

// =============================
// === AutomataRegistryModel ===
// =============================

type FullExprString = String;

/// Internal model of `AutomataRegistry`.
#[derive(Debug)]
pub struct AutomataRegistryModel<T> {
    dirty         : bool,
    nfa           : Nfa,
    dfa           : Dfa,
    states        : HashMap<FullExprString,nfa::State>,
    /// This field is used to allow efficient check if a connection already exists.
    connections   : HashSet<(nfa::State,nfa::State)>,
    /// The always state is a special state which always triggers. No matter what event happens,
    /// this state will always be re-entered. It is useful for implementing such rules as `-a`,
    /// which fire always when key `a` is released, no matter if other keys are pressed or not.
    always_state  : nfa::State,
    current       : dfa::State,
    pressed       : HashSet<FullExprString>,
    action_map    : HashMap<ActionType,HashMap<nfa::State,T>>,
    press_times   : HashMap<dfa::State,f32>,
    release_times : HashMap<dfa::State,f32>,
}

// === Getters ===

#[allow(missing_docs)]
impl<T> AutomataRegistryModel<T> {
    pub fn nfa(&self) -> &Nfa { &self.nfa }
    pub fn dfa(&self) -> &Dfa { &self.dfa }
}

// === API ===

impl<T> AutomataRegistryModel<T> {
    /// Constructor.
    pub fn new() -> Self {
        let mut nfa       = Nfa::default();
        let dfa           = Dfa::from(&nfa);
        let states        = default();
        let connections   = default();
        let always_state  = nfa.new_pattern(nfa.start,Pattern::any().many());
        let current       = Dfa::START_STATE;
        let pressed       = default();
        let dirty         = true;
        let action_map    = default();
        let press_times   = default();
        let release_times = default();
        Self {dirty,nfa,dfa,states,connections,always_state,current,pressed,action_map,press_times
            ,release_times}
    }
}

impl<T:Clone> AutomataRegistryModel<T> {
    fn add(&mut self, action_type:ActionType, expr:impl AsRef<str>, action:impl Into<T>) {
        self.dirty = true;
        let expr   = expr.as_ref();
        let end_state = if let Some(key) = expr.strip_prefix('-') {
            let key = format!("-{}",key.trim().to_lowercase());
            let sym = Symbol::new_named(hash(&key),key);
            let pat = Pattern::symbol(&sym);
            self.nfa.new_pattern(self.always_state,pat)
        } else {
            let all = expr.split(' ').map(|t| t.trim()).collect_vec();
            self.add_key_permutations(self.nfa.start,all)
        };
        self.action_map.entry(action_type).or_default().insert(end_state,action.into());
    }

    /// Process the press input event. See `on_event` docs to learn more.
    fn on_press(&mut self, input:impl AsRef<str>) -> Vec<T> {
        self.on_event(input,true)
    }

    /// Process the release input event. See `on_event` docs to learn more.
    fn on_release(&mut self, input:impl AsRef<str>) -> Vec<T> {
        self.on_event(input,false)
    }

    /// Get the approximate memory consumption of this shortcut registry DFA network.
    fn approx_dfa_memory_consumption_mb(&mut self) -> f32 {
        self.optimize();
        let elems = self.dfa.links.matrix.len() as f32;
        let bytes = elems * 8.0;
        bytes / 1_000_000.0
    }
}

impl<T:Clone> AutomataRegistryModel<T> {
    /// The `keys` para contains list of (key name, is side-aware key) items.
    fn add_key_permutations(&mut self, source:nfa::State, keys:Vec<&str>) -> nfa::State {
        let mut state = source;
        let keys = keys.into_iter().map(|key|(key,SIDE_KEYS_SET.contains(&key))).collect_vec();
        for perm in keys.iter().permutations(keys.len()) {
            state = source;
            let mut path : Vec<&str> = vec![];

            for alt_keys in perm {
                let (name,is_side_aware) = alt_keys;
                if *is_side_aware {
                    let alt_path = path.iter().chain(&[&**name]).cloned().sorted().collect_vec();
                    let alt_repr = alt_path.join(" ");
                    let out      = self.states.get(&alt_repr).cloned()
                                 .unwrap_or_else(||self.nfa.new_state_exported());

                    let alts = vec![format!("{}-left",name),format!("{}-right",name)];
                    for key in alts {
                        let mut local_path = path.clone();
                        local_path.push(&key);
                        local_path.sort_unstable();
                        let repr = local_path.join(" ");
                        match self.states.get(&repr) {
                            Some(&target) => {
                                self.bidirectional_connect_via(state,target,key.to_string());
                                self.bidirectional_connect(target,out);
                                self.bidirectional_connect_via(state,out,(*name).to_string());
                            },
                            None => {
                                let target = self.bidirectional_pattern(state,key.to_string());
                                self.states.insert(repr.clone(),target);
                                self.bidirectional_connect(target,out);
                                self.bidirectional_connect_via(state,out,(*name).to_string());
                            }
                        };
                    }
                    state = out;
                    path  = alt_path;
                    self.states.insert(alt_repr.clone(),out);
                } else {
                    let key = name;
                    path.push(key);
                    path.sort_unstable();
                    let repr = path.join(" ");
                    state = match self.states.get(&repr) {
                        Some(&target) => {
                            self.bidirectional_connect_via(state,target,(*key).to_string());
                            target
                        },
                        None => {
                            let target = self.bidirectional_pattern(state,(*key).to_string());
                            self.states.insert(repr.clone(),target);
                            target
                        }
                    };
                }
            }
        }
        state
    }

    fn bidirectional_connect_via(&mut self, source:nfa::State, target:nfa::State, key:String) {
        if !self.connections.contains(&(source,target)) {
            self.connections.insert((source,target));
            self.connections.insert((target,source));
            let key_r = reverse_key(&key);
            let sym   = Symbol::new_named(hash(&key),key);
            let sym_r = Symbol::new_named(hash(&key_r),key_r);
            self.nfa.connect_via(source,target,&(sym.clone()..=sym));
            self.nfa.connect_via(target,source,&(sym_r.clone()..=sym_r));
        }
    }

    fn bidirectional_connect(&mut self, source:nfa::State, target:nfa::State) {
        if !self.connections.contains(&(source,target)) {
            self.connections.insert((source,target));
            self.connections.insert((target,source));
            self.nfa.connect(source,target);
            self.nfa.connect(target,source);
        }
    }

    fn bidirectional_pattern(&mut self, source:nfa::State, key:String) -> nfa::State {
        let key_r  = reverse_key(&key);
        let sym    = Symbol::new_named(hash(&key),key);
        let sym_r  = Symbol::new_named(hash(&key_r),key_r);
        let pat    = Pattern::symbol(&sym);
        let target = self.nfa.new_pattern(source,pat);
        self.nfa.connect_via(target,source,&(sym_r.clone()..=sym_r));
        self.connections.insert((source,target));
        target
    }

    /// Process the `input` event. Events are strings uniquely identifying the source of the event,
    /// like "key_a", or "mouse_button_1". The `press` parameter is set to true if it was a press
    /// event, and is set to false in case of a release event.
    fn on_event(&mut self, input:impl AsRef<str>, press:bool) -> Vec<T> {
        self.optimize();
        let action      = if press { Press }       else { Release };
        let action2     = if press { DoublePress } else { DoubleClick };
        let input       = input.as_ref().to_lowercase();
        let sym_input   = if press { input.clone() } else { format!("-{}",input) };
        let symbol      = Symbol::from(hash(&sym_input));
        let state       = self.current;
        let next_state  = self.dfa.next_state(state,&symbol);
        let focus_state = if press { next_state } else { state };
        let nfa_states  = &self.dfa.sources[focus_state.id()];
        let time        = web::time_from_start() as f32;
        let time_map    = if press { &self.press_times } else { &self.release_times };
        let last_time   = time_map.get(&focus_state);
        let time_diff   = last_time.map(|t| time-t);
        let is_double   = time_diff.map(|t| t < DOUBLE_EVENT_TIME_MS) == Some(true);
        let new_time    = if is_double { 0.0 } else { time };
        self.current    = next_state;
        let mut actions = nfa_states.iter().filter_map(|t|self.get_action(action,*t)).collect_vec();
        if is_double {
            actions.extend(nfa_states.iter().filter_map(|t|self.get_action(action2,*t)));
        }
        if press {
            self.pressed.insert(input);
            self.press_times.insert(focus_state,new_time);
        } else {
            self.pressed.remove(&input);
            self.release_times.insert(focus_state,new_time);
            if self.pressed.is_empty() {
                self.current = Dfa::START_STATE;
            }
            self.reset_to_known_state();
        }
        actions
    }

    fn reset_to_known_state(&mut self) {
        if self.current.is_invalid() {
            let path = self.pressed.iter().sorted().cloned().collect_vec();
            self.current = Dfa::START_STATE;
            for p in path {
                self.current = self.dfa.next_state(self.current, &Symbol::from(hash(&p)));
            }
        }
    }

    fn get_action(&self, action_type:ActionType, state:nfa::State) -> Option<T> {
        self.action_map.get(&action_type).and_then(|m|m.get(&state).cloned())
    }

    fn optimize(&mut self) {
        if self.dirty {
            self.dirty         = false;
            self.dfa           = (&self.nfa).into();
            self.current       =  Dfa::START_STATE;
            self.pressed       = default();
            self.press_times   = default();
            self.release_times = default();
        }
    }
}

impl<T> Default for AutomataRegistryModel<T> {
    fn default() -> Self {
        Self::new()
    }
}

// ========================
// === AutomataRegistry ===
// ========================

// FIXME[WD] Replace T with Vec<T> to prevent shortcut override.

/// Shortcut registry implementation based on a finite state automata. When defining shortcuts,
/// a nondeterministic finite automata (NFA) is created. On the first usage, is it being optimized
/// to a deterministic finite automata (DFA), which provides a constant time to get results on every
/// key stroke. This allows us to define very complex shortcuts (regexp-like) and keep high
/// performance of their resolution. However, the first stage of this approach is costly, namely
/// building the NFA and optimizing it to DFA. Please refer to the benchmarks in this library to
/// compare between available implementations.
///
/// Please note, that this registry type allows for broader expression input syntax than what is
/// described in the `Registry` documentation. In particular, it allows for expressions like `-a`,
/// which means, that they will be triggered every time the key `a` is released, no matter if other
/// keys were pressed or not.
#[derive(CloneRef,Debug,Derivative)]
#[derivative(Clone(bound=""))]
#[derivative(Default(bound=""))]
pub struct AutomataRegistry<T> {
    rc : Rc<RefCell<AutomataRegistryModel<T>>>
}

impl<T> AutomataRegistry<T> {
    /// Constructor.
    pub fn new() -> Self {
        default()
    }
}

impl<T:Clone> AutomataRegistry<T> {
    /// Repesent the NFA graph as a GraphViz DOT code.
    pub fn nfa_as_graphviz_code(&self) -> String {
        self.rc.borrow().nfa.as_graphviz_code()
    }

    /// Repesent the DFA graph as a GraphViz DOT code.
    pub fn dfa_as_graphviz_code(&self) -> String {
        self.rc.borrow().dfa.as_graphviz_code()
    }

    /// Get the approximate memory consumption of this shortcut registry DFA network.
    pub fn approx_dfa_memory_consumption_mb(&mut self) -> f32 {
        self.rc.borrow_mut().approx_dfa_memory_consumption_mb()
    }
}

impl<T:Clone> Registry<T> for AutomataRegistry<T> {
    fn add(&self, action_type:ActionType, expr:impl AsRef<str>, action:impl Into<T>) {
        self.rc.borrow_mut().add(action_type,expr,action)
    }

    /// Process the press input event. See `on_event` docs to learn more.
    fn on_press(&self, input:impl AsRef<str>) -> Vec<T> {
        self.rc.borrow_mut().on_press(input)
    }

    /// Process the release input event. See `on_event` docs to learn more.
    fn on_release(&self, input:impl AsRef<str>) -> Vec<T> {
        self.rc.borrow_mut().on_release(input)
    }

    fn optimize(&self) {
        self.rc.borrow_mut().optimize();
    }
}

// ============================
// === HashSetRegistryModel ===
// ============================

pub trait HashSetRegistryItem = Clone+Debug+Eq+Hash;

/// Internal model for `HashSetRegistry`.
#[derive(Debug)]
pub struct HashSetRegistryModel<T> {
    current_expr  : String,
    actions       : HashMap<ActionType,HashMap<String,Vec<T>>>,
    pressed       : HashSet<String>,
    press_times   : HashMap<String,f32>,
    release_times : HashMap<String,f32>,
    side_keys     : HashMap<String,Vec<String>>,
    key_aliases   : HashMap<String,String>,
}

impl<T> HashSetRegistryModel<T> {
    /// Constructor.
    pub fn new() -> Self {
        let current_expr  = default();
        let actions       = default();
        let pressed       = default();
        let press_times   = default();
        let release_times = default();
        let side_keys     = default();
        let key_aliases   = key_aliases();
        Self {current_expr,actions,pressed,press_times,release_times,side_keys,key_aliases} . init()
    }

    fn init(mut self) -> Self {
        for key in SIDE_KEYS {
            let alts = vec![format!("{}-left",key),format!("{}-right",key),(*key).to_string()];
            self.side_keys.insert((*key).to_string(),alts);
        }
        self
    }

    fn current_expr(&self) -> String {
        self.pressed.iter().sorted().join(" ")
    }
}

impl<T:HashSetRegistryItem> HashSetRegistryModel<T> {
    /// Add a new shortcut definition.
    pub fn add(&mut self, action_type:ActionType, input:impl AsRef<str>, action:impl Into<T>) {
        let input  = input.as_ref();
        let action = action.into();
        let exprs  = self.possible_exprs(input);
        let map    = self.actions.entry(action_type).or_default();
        for expr in exprs {
            map.entry(expr).or_default().push(action.clone());
        }
    }

    #[allow(clippy::collapsible_else_if)]
    fn on_event(&mut self, input:impl AsRef<str>, press:bool) -> Vec<T> {
        let input  = input.as_ref().to_lowercase();
        let exists = self.pressed.contains(&input);
        let repeat = if press { exists } else { !exists };
        if !repeat {
            let out = self.process_event(Release);
            if press { self.pressed.insert(input); }
            else     { self.pressed.remove(&input); }
            self.current_expr = self.current_expr();
            out.extended(self.process_event(Press))
               .extended(self.process_event(PressAndRepeat))
        } else {
            if press {
                self.process_event(PressAndRepeat)
            } else {
                default()
            }
        }
    }

    fn process_event(&mut self, action:ActionType) -> Vec<T> {
        let expr    = &self.current_expr;
        let mut out = self.actions.get(&action).and_then(|t|t.get(expr)).into_iter().flatten()
                    .cloned().collect_vec();
        if action != PressAndRepeat {
            let is_press  = action == Press;
            let action2   = if is_press { DoublePress }           else { DoubleClick };
            let time_map  = if is_press { &mut self.press_times } else { &mut self.release_times };


text:
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py'

#![feature(struct_variant)]
extern crate rand;

struct Error;

#[deriving(Rand)]
enum Enum {
   A {
     x: Error //~ ERROR
   }
}

fn main() {}


text:
//! Module containing default implementation.
//! For instance default trait implementation to import in order to have a full tunnel
//! implementation even if the tunnel only implement send only or do not manage error
use rand::os::OsRng;
use rand::Rng;
use super::super::{
  BincErr,
  Info,
  ErrorProvider,
  Peer,
};
/// wrong use need redesign TODO redesign it on specific trait (not TW as param)
use bincode::Infinite;
use bincode::{
  serialize_into as bin_encode,
  deserialize_from as bin_decode,
};
use std::io::{
  Write,
  Read,
  Result,
};
use serde::{
  Serialize,
  Deserialize,
  Serializer,
  Deserializer,
};
use serde::de::DeserializeOwned;

#[derive(Serialize,Deserialize,Debug,Clone,PartialEq,Eq)]
pub enum MultipleErrorMode {
  /// do not propagate errors
  NoHandling,
  // TODO bitunnel route
  // if route is cached (info in local cache), report error with same route  CachedRoute,
  CachedRoute,
}

/// Only QueryCached error here
/// With multiple reply route, it could also be use in other case (ReplyCached to switch to other
/// route for instance)
#[derive(Serialize,Deserialize,Debug,Clone)]
pub enum MultipleErrorInfo {
  NoHandling,
//  Route(usize), // usize is error code (even if we reply with full route we still consider error code only
  /// only usable with QueryCached state : with single route config it is the only senseful usage.
  /// Please note that it could be use to clear cache
  CachedRoute(usize), // usize is error code
}
impl Info for MultipleErrorInfo {

  #[inline]
  fn do_cache (&self) -> bool {
    if let &MultipleErrorInfo::CachedRoute(..) = self {
      true
    } else {
      false
    }
  }

  fn write_in_header<W : Write>(&mut self, inw : &mut W) -> Result<()> {
    bin_encode(inw, self, Infinite).map_err(|e|BincErr(e))?;
    Ok(())
  }

  #[inline]
  fn write_read_info<W : Write>(&mut self, _ : &mut W) -> Result<()> {
    Ok(())
  }

  fn read_from_header<R : Read>(r : &mut R) -> Result<Self> {
    Ok(bin_decode(r, Infinite).map_err(|e|BincErr(e))?)
  }

  #[inline]
  fn read_read_info<R : Read>(&mut self, _ : &mut R) -> Result<()> {
    Ok(())
  }

}

/// TODO E as explicit limiter named trait for readability
pub struct MulErrorProvider {
  mode : MultipleErrorMode,
  gen : OsRng,
}

//type P : Peer;
  //type TW : TunnelWriter;
  //type TR : TunnelReader;

impl MulErrorProvider {
  pub fn new (mode : MultipleErrorMode) -> Result<MulErrorProvider> {
    Ok(MulErrorProvider {
      mode : mode,
      gen : OsRng::new()?,
    })
  }
}
impl<P : Peer> ErrorProvider<P, MultipleErrorInfo> for MulErrorProvider {
  /// Error infos bases for peers
  fn new_error_route (&mut self, route : &[&P]) -> Vec<MultipleErrorInfo> {

    let l = route.len();
     match self.mode {
       MultipleErrorMode::NoHandling =>
         vec![MultipleErrorInfo::NoHandling;l-1],
       MultipleErrorMode::CachedRoute => {
         let mut res : Vec<MultipleErrorInfo> = Vec::with_capacity(l-1);
         for _ in 1..l {
           let mut errorid = self.gen.gen();
           while errorid == 0 {
              errorid = self.gen.gen();
           }
           res.push(MultipleErrorInfo::CachedRoute(errorid))
         }
         res
       },
     }

  }
}

/// specific provider for no error
pub struct NoErrorProvider;

impl<P : Peer> ErrorProvider<P, MultipleErrorInfo> for NoErrorProvider {
  fn new_error_route (&mut self, p : &[&P]) -> Vec<MultipleErrorInfo> {
    vec![MultipleErrorInfo::NoHandling;p.len()-1]
/*    let mut r = Vec::with_capacity(p.len());
    for _ in 0..p.len() {
      r.push(
         MultipleErrorInfo::NoHandling
      );
    }
    r*/
  }
}


text:
use gtk::prelude::*;
use projectpadsql::models::Project;
use relm::Widget;
use relm_derive::{widget, Msg};
use std::cell::{Cell, RefCell};
use std::f64::consts::PI;
use std::io::Cursor;
use std::rc::Rc;

pub const OUTER_SIZE: i32 = 60;
const PADDING: i32 = 5;

#[derive(Msg, Debug)]
pub enum Msg {
    Click,
    Activate(Project),
    ActiveProjectChanged(i32),
    MouseEnter,
    MouseLeave,
    MouseEnterProject(i32),
    MouseLeaveProject(i32),
    DarkThemeToggled,
    ScaleFactorChange,
}

pub struct Model {
    relm: relm::Relm<ProjectBadge>,
    project: Project,
    font_size_for_width: Rc<RefCell<Option<(i32, f64)>>>, // cache the computed font size
    backing_buffer: Rc<RefCell<Option<cairo::ImageSurface>>>,
    is_active: Rc<Cell<bool>>,
}

#[widget]
impl Widget for ProjectBadge {
    fn init_view(&mut self) {
        self.widgets
            .drawing_area
            .set_size_request(OUTER_SIZE, OUTER_SIZE);
        self.widgets.drawing_area.add_events(
            gdk::EventMask::BUTTON_PRESS_MASK
                | gdk::EventMask::ENTER_NOTIFY_MASK
                | gdk::EventMask::LEAVE_NOTIFY_MASK,
        );
        let buf = self.model.backing_buffer.clone();
        let fsw = self.model.font_size_for_width.clone();
        let is_a = self.model.is_active.clone();
        let icon = self.model.project.icon.clone();
        let name = self.model.project.name.clone();
        self.widgets.drawing_area.connect_draw(move |da, context| {
            let allocation = da.get_allocation();
            let b0 = buf.borrow();
            let is_buffer_good = Some((allocation.width, allocation.height))
                == b0.as_ref().map(|b| (b.get_width(), b.get_height()));
            let surface_ref = if is_buffer_good {
                b0
            } else {
                drop(b0);
                // need to set up the backing buffer
                buf.replace(Some(Self::prepare_backing_buffer(
                    da,
                    &fsw,
                    is_a.get(),
                    &icon,
                    &name,
                    allocation.width,
                    allocation.height,
                )));
                buf.borrow()
            };
            // paint the backing buffer -
            let s = surface_ref.as_ref().unwrap();
            let output_scale = da.get_scale_factor();
            s.set_device_scale(output_scale as f64, output_scale as f64);
            context.set_source_surface(s, 0.0, 0.0);
            context.paint();
            Inhibit(false)
        });
    }

    fn model(relm: &relm::Relm<Self>, project: Project) -> Model {
        Model {
            relm: relm.clone(),
            project,
            font_size_for_width: Rc::new(RefCell::new(None)),
            backing_buffer: Rc::new(RefCell::new(None)),
            is_active: Rc::new(Cell::new(false)),
        }
    }

    fn prepare_backing_buffer(
        drawing_area: &gtk::DrawingArea,
        font_size_for_width: &RefCell<Option<(i32, f64)>>,
        is_active: bool,
        icon: &Option<Vec<u8>>,
        name: &str,
        allocation_width_: i32,
        allocation_height_: i32,
    ) -> cairo::ImageSurface {
        let output_scale = drawing_area.get_scale_factor();
        let allocation_width = allocation_width_ * output_scale;
        let allocation_height = allocation_height_ * output_scale;
        let buf =
            cairo::ImageSurface::create(cairo::Format::ARgb32, allocation_width, allocation_height)
                .expect("cairo backing buffer");
        let context = cairo::Context::new(&buf);

        // code to make the badge text bold, but i feel it doesn't work out
        // if let Some(family) = context.get_font_face().toy_get_family() {
        //     context.select_font_face(&family, cairo::FontSlant::Normal, cairo::FontWeight::Bold);
        // }

        // println!("drawing badge, allocation: {:?}", allocation);
        let new_fsw = match *font_size_for_width.borrow() {
            Some((w, font_size)) if w == allocation_width => {
                context.set_font_size(font_size);
                None
            }
            _ => Some((
                allocation_width,
                Self::compute_font_size(&context, (allocation_width - PADDING * 2) as f64 * 0.75),
            )),
        };
        if let Some(fsw) = new_fsw {
            font_size_for_width.replace(Some(fsw));
        }
        context.set_antialias(cairo::Antialias::Best);

        let style_context = drawing_area.get_style_context();

        gtk::render_background(
            &style_context,
            &context,
            0.0,
            0.0,
            allocation_width.into(),
            allocation_height.into(),
        );
        gtk::render_frame(
            &style_context,
            &context,
            0.0,
            0.0,
            allocation_width.into(),
            allocation_height.into(),
        );

        let fg_color = style_context.lookup_color("theme_fg_color").unwrap();
        context.set_source_rgb(fg_color.red, fg_color.green, fg_color.blue);
        if is_active {
            context.set_line_width(6.0 * output_scale as f64);
            context.set_line_cap(cairo::LineCap::Round);
            context.move_to(10.0, allocation_height as f64 - 5.0 * output_scale as f64);
            context.line_to(
                allocation_width as f64 - 10.0 * output_scale as f64,
                allocation_height as f64 - 5.0 * output_scale as f64,
            );
            context.stroke();
        } else {
            context.set_line_width(2.0 * output_scale as f64);
        }
        context.arc(
            (allocation_width / 2).into(),
            (allocation_width / 2).into(),
            (allocation_width / 2 - PADDING).into(),
            0.0,
            2.0 * PI,
        );
        context.stroke_preserve();
        let bg_color = style_context.lookup_color("theme_bg_color").unwrap();
        // so the goal here is to push the contrast. if the background color
        // is darker (<0.5) we go for pure black; if it's brighter, we go
        // for pure white.
        let bg_base = if bg_color.red < 0.5 { 0.0 } else { 1.0 };
        context.set_source_rgb(bg_base, bg_base, bg_base);
        context.fill();
        context.set_source_rgb(fg_color.red, fg_color.green, fg_color.blue);

        match icon {
            // the 'if' works around an issue reading from SQL. should be None if it's empty!!
            Some(icon) if !icon.is_empty() => Self::draw_icon(&context, allocation_width, icon),
            _ => Self::draw_label(&context, allocation_width, &name[..2]),
        }
        buf
    }

    fn compute_font_size(context: &cairo::Context, width: f64) -> f64 {
        let mut size = 5.0;
        context.set_font_size(size);
        while context.text_extents("HU").width < width * 0.8 {
            context.set_font_size(size);
            size += 1.0;
        }
        size
    }

    pub fn draw_icon(context: &cairo::Context, allocation_width: i32, icon: &[u8]) {
        context.save();
        match cairo::ImageSurface::create_from_png(&mut Cursor::new(icon)).ok() {
            Some(surface) => {
                let p = PADDING as f64;
                let aw = (allocation_width - PADDING * 2) as f64;
                let w = surface.get_width() as f64;
                let h = surface.get_height() as f64;
                let scale_ratio = f64::min(aw / w, aw / h);
                context.scale(scale_ratio, scale_ratio);
                let (offsetx, offsety) = if w > h {
                    (p, p + (aw - aw * h / w) / 2.0)
                } else {
                    (p + (aw - aw * w / h) / 2.0, p)
                };
                context.set_source_surface(&surface, offsetx / scale_ratio, offsety / scale_ratio);
                context.paint();
            }
            _ => {
                eprintln!("failed reading png {}", icon.len());
            }
        }
        context.restore();
    }

    fn draw_label(context: &cairo::Context, allocation_width: i32, contents: &str) {
        // context.set_source_rgb(1.0, 1.0, 1.0);
        let text_extents = context.text_extents(contents);
        context.move_to(
            (allocation_width / 2) as f64 - text_extents.width / 2.0 - text_extents.x_bearing,
            (allocation_width / 2) as f64 - text_extents.y_bearing - text_extents.height / 2.0,
        );
        context.text_path(contents);
        context.fill();
    }

    fn update(&mut self, event: Msg) {
        match event {
            Msg::Click => {
                self.model
                    .relm
                    .stream()
                    .emit(Msg::Activate(self.model.project.clone()));
            }
            Msg::Activate(_) => {
                // meant for my parent, not me
            }
            Msg::ActiveProjectChanged(pid) => {
                let new_active = pid == self.model.project.id;
                if new_active != self.model.is_active.get() {
                    self.model.is_active.set(new_active);
                    // force a recompute of the display
                    self.model.backing_buffer.replace(None);
                    self.widgets.drawing_area.queue_draw();
                }
            }
            Msg::MouseEnter => {
                self.model
                    .relm
                    .stream()
                    .emit(Msg::MouseEnterProject(self.model.project.id));
            }
            Msg::MouseLeave => {
                self.model
                    .relm
                    .stream()
                    .emit(Msg::MouseLeaveProject(self.model.project.id));
            }
            Msg::DarkThemeToggled | Msg::ScaleFactorChange => {
                // force a recompute of the display
                self.model.backing_buffer.replace(None);
                self.widgets.drawing_area.queue_draw();
            }
            Msg::MouseEnterProject(_) => {}
            Msg::MouseLeaveProject(_) => {}
        }
    }

    view! {
        #[name="drawing_area"]
        gtk::DrawingArea {
            button_press_event(_, _) => (Msg::Click, Inhibit(false)),
            enter_notify_event(_, _) => (Msg::MouseEnter, Inhibit(false)),
            leave_notify_event(_, _) => (Msg::MouseLeave, Inhibit(false)),
            property_scale_factor_notify => Msg::ScaleFactorChange,
        }
    }
}


text:
/*
 * Copyright (c) 2012-2020 MIRACL UK Ltd.
 *
 * This file is part of MIRACL Core
 * (see https://github.com/miracl/core).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::arch::Chunk;
use crate::fp256bn::big::NLEN;

// Base Bits= 28
pub const MODULUS: [Chunk; NLEN] = [
    0xED33013, 0x292DDBA, 0x80A82D3, 0x65FB129, 0x49F0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
    0xFFFFFFF, 0xF,
];
pub const ROI: [Chunk; NLEN] = [
    0xED33012, 0x292DDBA, 0x80A82D3, 0x65FB129, 0x49F0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
    0xFFFFFFF, 0xF,
];
pub const R2MODP: [Chunk; NLEN] = [
    0x3B9F8B, 0xEDE3363, 0xFEC54E8, 0x92FFEE9, 0x3C55F79, 0x13C1C06, 0xC0123FA, 0xA12F2EA,
    0xE559B2A, 0x8,
];
pub const MCONST: Chunk = 0x537E5E5;
pub const SQRTM3:[Chunk;NLEN]=[0x78FC004,0xF119926,0x1B0451C,0xB6BF2F7,0x3D3D540,0xDDCA517,0xAD3D42F,0xFFFCF0C,0xFFFFFFF,0xF];
pub const CURVE_COF_I: isize = 1;
pub const CURVE_B_I: isize = 3;
pub const CURVE_B: [Chunk; NLEN] = [0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
pub const CURVE_ORDER: [Chunk; NLEN] = [
    0x10B500D, 0x2D536CD, 0x9921AF6, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
    0xFFFFFFF, 0xF,
];
pub const CURVE_GX: [Chunk; NLEN] = [0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
pub const CURVE_GY: [Chunk; NLEN] = [0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
pub const CURVE_HTPC:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0];
pub const FRA: [Chunk; NLEN] = [
    0xF943106, 0x760328A, 0xAB28F74, 0x71511E3, 0x7CF39A1, 0x8DDB086, 0x52D1A6E, 0xCA786F3,
    0xD617662, 0x3,
];
pub const FRB: [Chunk; NLEN] = [
    0xF3EFF0D, 0xB32AB2F, 0xD57F35E, 0xF4A9F45, 0xCCFD33A, 0xD113693, 0x819CB83, 0x3584819,
    0x29E899D, 0xC,
];
pub const CURVE_BNX: [Chunk; NLEN] = [0xB0A801, 0x82F5C03, 0x68, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
pub const CURVE_COF: [Chunk; NLEN] = [0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
pub const CRU: [Chunk; NLEN] = [
    0x3A1B807, 0x1C0A24A, 0x32D1EDB, 0xD79DF19, 0x8659BCD, 0x4092101, 0x13988E1, 0x0, 0x0, 0x0,
];
pub const CURVE_PXA: [Chunk; NLEN] = [
    0x9C09EFB, 0x2616B68, 0xF843CD2, 0x539A12B, 0x13ACE1C, 0x577C289, 0x28560F, 0xB4C96C2,
    0xE0C3350, 0xF,
];
pub const CURVE_PXB: [Chunk; NLEN] = [
    0x37E6A2B, 0x69ED34A, 0x3589D2, 0x78E287D, 0x3B924DD, 0xC637D81, 0x4DB5AE1, 0x738AC05,
    0xEA66057, 0x4,
];
pub const CURVE_PYA: [Chunk; NLEN] = [
    0xEDC27FF, 0x9B481B, 0x15848E9, 0x24758D6, 0xE51EFCB, 0x75124E3, 0x376770D, 0xC542A3B,
    0x2046E7, 0x7,
];
pub const CURVE_PYB: [Chunk; NLEN] = [
    0xAAD049B, 0x1281114, 0xA98B3E0, 0xBE80821, 0x29F8B4C, 0x49297EB, 0x42EEA6, 0xD388C29,
    0x554E3BC, 0x0,
];
pub const CURVE_W: [[Chunk; NLEN]; 2] = [
    [
        0xB054003, 0xF0036E1, 0xE78663A, 0xFFFFFFF, 0xFFFF, 0x0, 0x0, 0x0, 0x0, 0x0,
    ],
    [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
];
pub const CURVE_SB: [[[Chunk; NLEN]; 2]; 2] = [
    [
        [
            0xC669004, 0xF5EEEE7, 0xE78670B, 0xFFFFFFF, 0xFFFF, 0x0, 0x0, 0x0, 0x0, 0x0,
        ],
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
    ],
    [
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [
            0x606100A, 0x3D4FFEB, 0xB19B4BB, 0x65FB129, 0x49D0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
    ],
];
pub const CURVE_WB: [[Chunk; NLEN]; 4] = [
    [
        0xD30A800, 0x20678F0, 0x4D2CC10, 0x5555555, 0x5555, 0x0, 0x0, 0x0, 0x0, 0x0,
    ],
    [
        0xD7DC805, 0xD6764C0, 0xBC3AD1A, 0x8FBEA10, 0x4467DE, 0x8061601, 0xD105EB, 0x0, 0x0, 0x0,
    ],
    [
        0xF173803, 0xACB6061, 0x5E1D6C1, 0x47DF508, 0x82233EF, 0xC030B00, 0x6882F5, 0x0, 0x0, 0x0,
    ],
    [
        0xE91F801, 0x26530F6, 0x4D2CCE1, 0x5555555, 0x5555, 0x0, 0x0, 0x0, 0x0, 0x0,
    ],
];
pub const CURVE_BB: [[[Chunk; NLEN]; 4]; 4] = [
    [
        [
            0x5AA80D, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [
            0x5AA80C, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [
            0x5AA80C, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [0x1615002, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
    ],
    [
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [
            0x5AA80C, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [
            0x5AA80D, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [
            0x5AA80C, 0xAA5DACA, 0x9921A8D, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
    ],
    [
        [0x1615002, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [0x1615001, 0x5EB806, 0xD1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
    ],
    [
        [0xB0A802, 0x82F5C03, 0x68, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
        [
            0x2C2A002, 0xBD700C, 0x1A2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        ],
        [
            0xFAA000A, 0x2767EC6, 0x9921A25, 0x65FB129, 0x49E0CDC, 0x5EEE71A, 0xD46E5F2, 0xFFFCF0C,
            0xFFFFFFF, 0xF,
        ],
        [0xB0A802, 0x82F5C03, 0x68, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
    ],
];

pub const USE_GLV: bool = true;
pub const USE_GS_G2: bool = true;
pub const USE_GS_GT: bool = true;
pub const GT_STRONG: bool = false;


text:
//! Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
//! choosing a pivot from candidates only (IK_GP)
//! implemented by multiple threads

use crate::bron_kerbosch_pivot::{visit, PivotChoice};
use crate::graph::{UndirectedGraph, Vertex, VertexSetLike};
use crate::graph_degeneracy::degeneracy_ordering;
use crate::pile::Pile;
use crate::reporter::{Clique, Reporter};

struct SendingReporter {
    tx: crossbeam_channel::Sender<Clique>,
}

impl Reporter for SendingReporter {
    fn record(&mut self, clique: Clique) {
        self.tx.send(clique).unwrap();
    }
}

struct VisitJob<VertexSet> {
    start: Vertex,
    candidates: VertexSet,
    excluded: VertexSet,
}

pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
    VertexSet: VertexSetLike + Send,
    Graph: UndirectedGraph<VertexSet = VertexSet>,
    Rprtr: Reporter,
{
    const NUM_VISITING_THREADS: usize = 5;

    crossbeam::thread::scope(|scope| {
        let (start_tx, start_rx) = crossbeam_channel::bounded(64);
        let (visit_tx, visit_rx) = crossbeam_channel::bounded(64);
        let (reporter_tx, reporter_rx) = crossbeam_channel::bounded(64);

        scope.spawn(move |_| {
            for vertex in degeneracy_ordering(graph, -1) {
                start_tx.send(vertex).unwrap();
            }
        });

        scope.spawn(move |_| {
            // In this initial iteration, we don't need to represent the set of candidates
            // because all neighbours are candidates until excluded.
            let mut excluded = VertexSet::new();
            while let Ok(v) = start_rx.recv() {
                let neighbours = graph.neighbours(v);
                debug_assert!(!neighbours.is_empty());
                let neighbouring_excluded: VertexSet = neighbours.intersection_collect(&excluded);
                if neighbouring_excluded.len() < neighbours.len() {
                    let neighbouring_candidates: VertexSet =
                        neighbours.difference_collect(&neighbouring_excluded);
                    visit_tx
                        .send(VisitJob {
                            start: v,
                            candidates: neighbouring_candidates,
                            excluded: neighbouring_excluded,
                        })
                        .unwrap();
                }
                excluded.insert(v);
            }
        });

        for _ in 0..NUM_VISITING_THREADS {
            let thread_visit_rx = visit_rx.clone();
            let thread_reporter_tx = reporter_tx.clone();
            scope.spawn(move |_| {
                let mut thread_reporter = SendingReporter {
                    tx: thread_reporter_tx,
                };
                while let Ok(job) = thread_visit_rx.recv() {
                    visit(
                        graph,
                        &mut thread_reporter,
                        PivotChoice::MaxDegreeLocal,
                        job.candidates,
                        job.excluded,
                        Some(&Pile::from(job.start)),
                    );
                }
            });
        }
        drop(visit_rx);
        drop(reporter_tx);

        while let Ok(clique) = reporter_rx.recv() {
            reporter.record(clique);
        }
    })
    .unwrap();
}


text:
use std::error;
use std::fmt;
use archive;

pub type ArchiveResult<T> = Result<T, ArchiveError>;

#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub struct ErrCode(pub i32);

impl fmt::Display for ErrCode {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.0)
    }
}

#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum ArchiveError {
    HeaderPosition,
    Sys(ErrCode, Option<String>),
}

impl error::Error for ArchiveError {
    fn description(&self) -> &str {
        match self {
            &ArchiveError::HeaderPosition => "Header position expected to be 0",
            &ArchiveError::Sys(_, _) => "libarchive system error",
        }
    }
}

impl fmt::Display for ArchiveError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &ArchiveError::HeaderPosition => write!(fmt, "Header position expected to be 0"),
            &ArchiveError::Sys(ref code, ref msg) => {
                if let &Some(ref msg) = msg {
                    write!(fmt, "{} (libarchive err_code={})", msg, code)
                } else {
                    write!(fmt, "(no message) (libarchive err_code={})", code)
                }
            }
        }
    }
}

impl<'a> From<&'a archive::Handle> for ArchiveError {
    fn from(handle: &'a archive::Handle) -> ArchiveError {
        ArchiveError::Sys(handle.err_code(), handle.err_msg())
    }
}

impl<'a> From<&'a archive::Handle> for ArchiveResult<()> {
    fn from(handle: &'a archive::Handle) -> ArchiveResult<()> {
        match handle.err_code() {
            ErrCode(0) => Ok(()),
            _ => Err(ArchiveError::from(handle)),
        }
    }
}