<commit_before>// Implements the `zakopane checksum` subcommand.

use crate::structs::ZakopaneError;

const MAX_TASKS: usize = 8;

struct ChecksumWithPath {
    checksum: String,
    path: std::path::PathBuf,
}

impl ChecksumWithPath {
    pub fn new(checksum: String, path: std::path::PathBuf) -> Self {
        Self { checksum, path }
    }
}

type ChecksumResult = Result<ChecksumWithPath, ZakopaneError>;
type ChecksumTaskJoinHandle = tokio::task::JoinHandle<Vec<ChecksumWithPath>>;

struct ChecksumTaskDispatcherData {
    // Rate-limiter for spawned checksum tasks.
    semaphore: std::sync::Arc<tokio::sync::Semaphore>,

    // Counts total number of spawned checksum tasks.
    spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,

    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
}

impl ChecksumTaskDispatcherData {
    pub fn new(
        spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        sender: tokio::sync::mpsc::Sender<ChecksumResult>,
    ) -> Self {
        Self {
            semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_TASKS)),
            spawn_counter,
            sender,
        }
    }
}

// Sends a checksum task result downstream to the collector task.
fn checksum_task_send_result(
    result: ChecksumResult,
    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
) {
    if let Err(e) = sender.blocking_send(result) {
        eprintln!("BUG: Sender::send() failed: {}", e);
    }
}

// Separated from `checksum_task()` to ensure the `add_permits()` call is
// always hit.
fn checksum_task_impl(path: std::path::PathBuf, sender: tokio::sync::mpsc::Sender<ChecksumResult>) {
    let contents = match crate::helpers::ingest_file(path.to_str().unwrap()) {
        Ok(contents) => contents,
        Err(e) => return checksum_task_send_result(Err(e), sender),
    };
    let checksum = crypto_hash::hex_digest(crypto_hash::Algorithm::SHA256, contents.as_ref());
    checksum_task_send_result(Ok(ChecksumWithPath::new(checksum, path)), sender);
}

fn checksum_task(
    path: std::path::PathBuf,
    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
    semaphore_clone: std::sync::Arc<tokio::sync::Semaphore>,
) {
    checksum_task_impl(path, sender);

    // See comment in `ChecksumTaskManager::spawn_task()`.
    semaphore_clone.add_permits(1);
}

async fn collector_task(
    mut receiver: tokio::sync::mpsc::Receiver<ChecksumResult>,
    spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> Vec<ChecksumWithPath> {
    let mut sums: Vec<ChecksumWithPath> = Vec::new();
    let mut errors: usize = 0;
    loop {
        while let Some(result) = receiver.recv().await {
            match result {
                Ok(digest_with_path) => sums.push(digest_with_path),
                Err(_) => errors += 1,
            }
        }
        if sums.len() + errors == spawn_counter.load(std::sync::atomic::Ordering::SeqCst) {
            return sums;
        }
    }
}

// Spawns the collector task that listens for checksum results
// provided by the checksum tasks.
async fn spawn_collector() -> (ChecksumTaskDispatcherData, ChecksumTaskJoinHandle) {
    let (sender, receiver) = tokio::sync::mpsc::channel(MAX_TASKS);
    let spawn_counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let spawn_counter_clone = spawn_counter.clone();
    let join_handle =
        tokio::task::spawn(async move { collector_task(receiver, spawn_counter_clone).await });
    (
        ChecksumTaskDispatcherData::new(spawn_counter, sender),
        join_handle,
    )
}

async fn spawn_checksum_tasks(context: ChecksumTaskDispatcherData) {
    // TODO(j39m): Fix the hardcoded path.
    let walk_iter = walkdir::WalkDir::new("/home/kalvin/Documents/unsorted/").into_iter();
    for entry in walk_iter.filter_entry(|e| {
        !e.file_name()
            .to_str()
            .map(|path| path.starts_with(".")) // XXX(j39m)
            .unwrap_or(false)
    }) {
        if let Ok(direntry) = entry {
            let path = direntry.into_path();
            if !path.is_file() {
                continue;
            }

            context
                .spawn_counter
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let permit = context.semaphore.acquire().await.unwrap();

            // Icky workaround for not being able to pass `SemaphorePermit`
            // directly into a spawned task. Note that new permits are added
            // later in the checksum task.
            //
            // See also: https://github.com/tokio-rs/tokio/issues/1998
            permit.forget();

            let sender = context.sender.clone();
            let semaphore_clone = context.semaphore.clone();
            tokio::task::spawn_blocking(move || checksum_task(path, sender, semaphore_clone))
                .await
                .unwrap();
        }
    }
}

fn pretty_format_checksums(checksums: Vec<ChecksumWithPath>) -> String {
    let mut buffer: Vec<String> = Vec::new();
    for digest_line in checksums {
        buffer.push(format!(
            "{}  ./{}",
            digest_line.checksum,
            digest_line.path.to_str().unwrap()
        ));
    }
    buffer.join("\n")
}

async fn checksum_impl() -> String {
    let (dispatcher_data, join_handle) = spawn_collector().await;
    spawn_checksum_tasks(dispatcher_data).await;
    let mut checksums: Vec<ChecksumWithPath> = join_handle.await.unwrap();
    checksums.sort_by(|a, b| a.path.cmp(&b.path));
    pretty_format_checksums(checksums)
}

pub fn checksum() -> String {
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(checksum_impl())
}
<commit_msg>checksum: Parameterize `checksum()`<commit_after>// Implements the `zakopane checksum` subcommand.

use crate::structs::ZakopaneError;

const MAX_TASKS: usize = 8;

struct ChecksumWithPath {
    checksum: String,
    path: std::path::PathBuf,
}

impl ChecksumWithPath {
    pub fn new(checksum: String, path: std::path::PathBuf) -> Self {
        Self { checksum, path }
    }
}

type ChecksumResult = Result<ChecksumWithPath, ZakopaneError>;
type ChecksumTaskJoinHandle = tokio::task::JoinHandle<Vec<ChecksumWithPath>>;

struct ChecksumTaskDispatcherData {
    path: std::path::PathBuf,

    // Rate-limiter for spawned checksum tasks.
    semaphore: std::sync::Arc<tokio::sync::Semaphore>,

    // Counts total number of spawned checksum tasks.
    spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,

    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
}

impl ChecksumTaskDispatcherData {
    pub fn new(
        path: std::path::PathBuf,
        spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        sender: tokio::sync::mpsc::Sender<ChecksumResult>,
    ) -> Self {
        Self {
            path,
            semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_TASKS)),
            spawn_counter,
            sender,
        }
    }
}

// Sends a checksum task result downstream to the collector task.
fn checksum_task_send_result(
    result: ChecksumResult,
    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
) {
    if let Err(e) = sender.blocking_send(result) {
        eprintln!("BUG: Sender::send() failed: {}", e);
    }
}

// Separated from `checksum_task()` to ensure the `add_permits()` call is
// always hit.
fn checksum_task_impl(path: std::path::PathBuf, sender: tokio::sync::mpsc::Sender<ChecksumResult>) {
    let contents = match crate::helpers::ingest_file(path.to_str().unwrap()) {
        Ok(contents) => contents,
        Err(e) => return checksum_task_send_result(Err(e), sender),
    };
    let checksum = crypto_hash::hex_digest(crypto_hash::Algorithm::SHA256, contents.as_ref());
    checksum_task_send_result(Ok(ChecksumWithPath::new(checksum, path)), sender);
}

fn checksum_task(
    path: std::path::PathBuf,
    sender: tokio::sync::mpsc::Sender<ChecksumResult>,
    semaphore_clone: std::sync::Arc<tokio::sync::Semaphore>,
) {
    checksum_task_impl(path, sender);

    // See comment in `ChecksumTaskManager::spawn_task()`.
    semaphore_clone.add_permits(1);
}

async fn collector_task(
    mut receiver: tokio::sync::mpsc::Receiver<ChecksumResult>,
    spawn_counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> Vec<ChecksumWithPath> {
    let mut sums: Vec<ChecksumWithPath> = Vec::new();
    let mut errors: usize = 0;
    loop {
        while let Some(result) = receiver.recv().await {
            match result {
                Ok(digest_with_path) => sums.push(digest_with_path),
                Err(_) => errors += 1,
            }
        }
        if sums.len() + errors == spawn_counter.load(std::sync::atomic::Ordering::SeqCst) {
            return sums;
        }
    }
}

// Spawns the collector task that listens for checksum results
// provided by the checksum tasks.
async fn spawn_collector(
    path: std::path::PathBuf,
) -> (ChecksumTaskDispatcherData, ChecksumTaskJoinHandle) {
    let (sender, receiver) = tokio::sync::mpsc::channel(MAX_TASKS);
    let spawn_counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let spawn_counter_clone = spawn_counter.clone();
    let join_handle =
        tokio::task::spawn(async move { collector_task(receiver, spawn_counter_clone).await });
    (
        ChecksumTaskDispatcherData::new(path, spawn_counter, sender),
        join_handle,
    )
}

async fn spawn_checksum_tasks(context: ChecksumTaskDispatcherData) {
    let walk_iter = walkdir::WalkDir::new(context.path).into_iter();
    for entry in walk_iter.filter_entry(|e| {
        !e.file_name()
            .to_str()
            .map(|path| path.starts_with(".")) // XXX(j39m)
            .unwrap_or(false)
    }) {
        if let Ok(direntry) = entry {
            let path = direntry.into_path();
            if !path.is_file() {
                continue;
            }

            context
                .spawn_counter
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let permit = context.semaphore.acquire().await.unwrap();

            // Icky workaround for not being able to pass `SemaphorePermit`
            // directly into a spawned task. Note that new permits are added
            // later in the checksum task.
            //
            // See also: https://github.com/tokio-rs/tokio/issues/1998
            permit.forget();

            let sender = context.sender.clone();
            let semaphore_clone = context.semaphore.clone();
            tokio::task::spawn_blocking(move || checksum_task(path, sender, semaphore_clone))
                .await
                .unwrap();
        }
    }
}

fn pretty_format_checksums(path: std::path::PathBuf, checksums: Vec<ChecksumWithPath>) -> String {
    let mut buffer: Vec<String> = Vec::new();
    for digest_line in checksums {
        buffer.push(format!(
            "{}  ./{}",
            digest_line.checksum,
            digest_line
                .path
                .strip_prefix(&path)
                .unwrap()
                .to_str()
                .unwrap()
        ));
    }
    buffer.join("\n")
}

async fn checksum_impl(path: std::path::PathBuf) -> String {
    let (dispatcher_data, join_handle) = spawn_collector(path.clone()).await;
    spawn_checksum_tasks(dispatcher_data).await;
    let mut checksums: Vec<ChecksumWithPath> = join_handle.await.unwrap();
    checksums.sort_by(|a, b| a.path.cmp(&b.path));
    pretty_format_checksums(path, checksums)
}

pub fn checksum(path: std::path::PathBuf) -> String {
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(checksum_impl(path))
}
<|endoftext|>


<commit_before>pub struct Post {
    state: Option<Box<State>>,
    content: String
}

impl Post {
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new()
        }
    }
}

trait State {}

struct Draft {}

impl State for Draft {}
<commit_msg>Implement method for adding text to Post<commit_after>pub struct Post {
    state: Option<Box<State>>,
    content: String
}

impl Post {
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new()
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }
}

trait State {}

struct Draft {}

impl State for Draft {}
<|endoftext|>


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

mod foo {
    mod bar {
        pub fn y() { ::foo::x(); }
    }

    pub fn x() { debug!("x"); }
}

fn main() { foo::bar::y(); }
<commit_msg>test: fix check-fast breakage.<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

mod foo {
    mod bar {
        pub fn y() { super::super::foo::x(); }
    }

    pub fn x() { debug!("x"); }
}

fn main() { self::foo::bar::y(); }
<|endoftext|>


<commit_before>use crate::syntax::Type;
use proc_macro2::Ident;

#[derive(Copy, Clone, PartialEq)]
pub enum Atom {
    Bool,
    U8,
    U16,
    U32,
    U64,
    Usize,
    I8,
    I16,
    I32,
    I64,
    Isize,
    F32,
    F64,
    CxxString,
    RustString,
}

impl Atom {
    pub fn from(ident: &Ident) -> Option<Self> {
        use self::Atom::*;
        match ident.to_string().as_str() {
            "bool" => Some(Bool),
            "u8" => Some(U8),
            "u16" => Some(U16),
            "u32" => Some(U32),
            "u64" => Some(U64),
            "usize" => Some(Usize),
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
            "f32" => Some(F32),
            "f64" => Some(F64),
            "isize" => Some(Isize),
            "CxxString" => Some(CxxString),
            "String" => Some(RustString),
            _ => None,
        }
    }
}

impl PartialEq<Atom> for Ident {
    fn eq(&self, atom: &Atom) -> bool {
        Atom::from(self) == Some(*atom)
    }
}

impl PartialEq<Atom> for Type {
    fn eq(&self, atom: &Atom) -> bool {
        match self {
            Type::Ident(ident) => ident == atom,
            _ => false,
        }
    }
}

impl PartialEq<Atom> for &Ident {
    fn eq(&self, atom: &Atom) -> bool {
        *self == atom
    }
}

impl PartialEq<Atom> for &Type {
    fn eq(&self, atom: &Atom) -> bool {
        *self == atom
    }
}
<commit_msg>Clean up Atom::from match arm order<commit_after>use crate::syntax::Type;
use proc_macro2::Ident;

#[derive(Copy, Clone, PartialEq)]
pub enum Atom {
    Bool,
    U8,
    U16,
    U32,
    U64,
    Usize,
    I8,
    I16,
    I32,
    I64,
    Isize,
    F32,
    F64,
    CxxString,
    RustString,
}

impl Atom {
    pub fn from(ident: &Ident) -> Option<Self> {
        use self::Atom::*;
        match ident.to_string().as_str() {
            "bool" => Some(Bool),
            "u8" => Some(U8),
            "u16" => Some(U16),
            "u32" => Some(U32),
            "u64" => Some(U64),
            "usize" => Some(Usize),
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
            "isize" => Some(Isize),
            "f32" => Some(F32),
            "f64" => Some(F64),
            "CxxString" => Some(CxxString),
            "String" => Some(RustString),
            _ => None,
        }
    }
}

impl PartialEq<Atom> for Ident {
    fn eq(&self, atom: &Atom) -> bool {
        Atom::from(self) == Some(*atom)
    }
}

impl PartialEq<Atom> for Type {
    fn eq(&self, atom: &Atom) -> bool {
        match self {
            Type::Ident(ident) => ident == atom,
            _ => false,
        }
    }
}

impl PartialEq<Atom> for &Ident {
    fn eq(&self, atom: &Atom) -> bool {
        *self == atom
    }
}

impl PartialEq<Atom> for &Type {
    fn eq(&self, atom: &Atom) -> bool {
        *self == atom
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
#![allow(unused_variables)]

use crate::error::IDLError;
use crate::generator::Generator;
use crate::module::Module;
use crate::pretty_writer::PrettyWriter;
use crate::target::Target;
use crate::types::AtomType;
use crate::types::{DataType, DataTypeRef, FuncDecl, Ident, Named};
use heck::{CamelCase, SnakeCase};
use std::collections::HashMap;
use std::io::Write;

#[derive(Clone, Debug)]
struct CTypeInfo<'t> {
    /// The native type name
    type_name: String,
    /// Alignment rules for that type
    type_align: usize,
    /// The native type size
    type_size: usize,
    /// The leaf type node
    leaf_data_type_ref: &'t DataTypeRef,
}

/// Generator for the C backend
pub struct RustGenerator {
    pub target: Target,
    pub defined: HashMap<Ident, String>,
    pub w: PrettyWriter,
}

impl RustGenerator {
    pub fn new(target: Target, w: Box<dyn Write>) -> Self {
        Self {
            target,
            defined: HashMap::new(),
            w: PrettyWriter::new(w),
        }
    }

    fn define_name(&mut self, data_type_entry: &Named<DataType>) -> String {
        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());
        typename
    }

    fn get_defined_typename(&self, data_type_ref: &DataTypeRef) -> &str {
        match data_type_ref {
            DataTypeRef::Defined(id) => self.defined.get(id).expect("definition exists"),
            DataTypeRef::Atom(a) => Self::atom_name(a),
        }
    }

    fn atom_name(atom_type: &AtomType) -> &'static str {
        use AtomType::*;
        match atom_type {
            Bool => "bool",
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            I8 => "i32",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
            F32 => "f32",
            F64 => "f64",
        }
    }
}

impl Generator for RustGenerator {
    fn gen_type_header(
        &mut self,
        _module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        self.w.eob()?.writeln(format!(
            "/// {}: {:?}",
            data_type_entry.name.name, data_type_entry
        ))?;
        Ok(())
    }

    fn gen_alias(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (pointee, _attrs) =
            if let DataType::Alias { to: pointee, attrs } = &data_type_entry.entity {
                (pointee, attrs)
            } else {
                unreachable!()
            };

        let typename = self.define_name(data_type_entry);
        let pointee_name = self.get_defined_typename(pointee);

        self.w
            .writeln(format!("pub type {} = {};", typename, pointee_name))?
            .eob()?;
        Ok(())
    }

    fn gen_struct(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (named_members, _attrs) = if let DataType::Struct {
            members: named_members,
            attrs,
        } = &data_type_entry.entity
        {
            (named_members, attrs)
        } else {
            unreachable!()
        };

        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());

        self.w
            .writeln("#[repr(C)]")?
            .writeln(format!("pub struct {} {{", typename))?;

        let mut w = self.w.new_block();
        for m in named_members {
            w.writeln(format!(
                "{}: {},",
                m.name.to_snake_case(),
                self.get_defined_typename(&m.type_)
            ))?;
        }

        self.w.writeln("}")?.eob()?;
        Ok(())
    }

    // Enums generate both a specific typedef, and a traditional C-style enum
    // The typedef is required to use a native type which is consistent across all architectures
    fn gen_enum(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (named_members, _attrs) = if let DataType::Enum {
            members: named_members,
            attrs,
        } = &data_type_entry.entity
        {
            (named_members, attrs)
        } else {
            unreachable!()
        };

        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());

        self.w
            .writeln("#[repr(C)]")?
            .writeln("#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]")?
            .writeln(format!("pub enum {} {{", typename))?;

        let mut w = self.w.new_block();
        for m in named_members {
            w.writeln(format!("{},", m.name.to_camel_case()))?;
        }

        self.w.writeln("}")?.eob()?;
        Ok(())
    }

    fn gen_function(
        &mut self,
        module: &Module,
        func_decl_entry: &Named<FuncDecl>,
    ) -> Result<(), IDLError> {
        self.w
            .write_line(format!("// {:?}", func_decl_entry).as_bytes())?;

        let name = func_decl_entry.name.name.to_snake_case();
        let mut args = String::new();
        for a in func_decl_entry.entity.args.iter() {
            args += &format!(
                "{}: {},",
                a.name.to_snake_case(),
                self.get_defined_typename(&a.type_)
            );
        }

        let func_rets = &func_decl_entry.entity.rets;
        let rets = if func_rets.len() == 0 {
            "()".to_owned()
        } else {
            assert_eq!(func_rets.len(), 1);
            self.get_defined_typename(&func_rets[0].type_).to_owned()
        };

        self.w
            .writeln("#[no_mangle]")?
            .writeln(format!("pub fn {}({}) -> {} {{", name, args, rets))?;

        let mut w = self.w.new_block();
        w.writeln("unimplemented!()")?;

        self.w.writeln("}")?.eob()?;

        Ok(())
    }
}
<commit_msg>lucet-idl: fix rust backend<commit_after>#![allow(dead_code)]
#![allow(unused_variables)]

use crate::error::IDLError;
use crate::generator::Generator;
use crate::module::Module;
use crate::pretty_writer::PrettyWriter;
use crate::target::Target;
use crate::types::AtomType;
use crate::types::{DataType, DataTypeRef, FuncDecl, Ident, Named};
use heck::{CamelCase, SnakeCase};
use std::collections::HashMap;
use std::io::Write;

#[derive(Clone, Debug)]
struct CTypeInfo<'t> {
    /// The native type name
    type_name: String,
    /// Alignment rules for that type
    type_align: usize,
    /// The native type size
    type_size: usize,
    /// The leaf type node
    leaf_data_type_ref: &'t DataTypeRef,
}

/// Generator for the C backend
pub struct RustGenerator {
    pub target: Target,
    pub defined: HashMap<Ident, String>,
    pub w: PrettyWriter,
}

impl RustGenerator {
    pub fn new(target: Target, w: Box<dyn Write>) -> Self {
        Self {
            target,
            defined: HashMap::new(),
            w: PrettyWriter::new(w),
        }
    }

    fn define_name(&mut self, data_type_entry: &Named<DataType>) -> String {
        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());
        typename
    }

    fn get_defined_typename(&self, data_type_ref: &DataTypeRef) -> &str {
        match data_type_ref {
            DataTypeRef::Defined(id) => self.defined.get(id).expect("definition exists"),
            DataTypeRef::Atom(a) => Self::atom_name(a),
        }
    }

    fn atom_name(atom_type: &AtomType) -> &'static str {
        use AtomType::*;
        match atom_type {
            Bool => "bool",
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
            F32 => "f32",
            F64 => "f64",
        }
    }
}

impl Generator for RustGenerator {
    fn gen_type_header(
        &mut self,
        _module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        self.w.eob()?.writeln(format!(
            "/// {}: {:?}",
            data_type_entry.name.name, data_type_entry
        ))?;
        Ok(())
    }

    fn gen_alias(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (pointee, _attrs) =
            if let DataType::Alias { to: pointee, attrs } = &data_type_entry.entity {
                (pointee, attrs)
            } else {
                unreachable!()
            };

        let typename = self.define_name(data_type_entry);
        let pointee_name = self.get_defined_typename(pointee);

        self.w
            .writeln(format!("pub type {} = {};", typename, pointee_name))?
            .eob()?;
        Ok(())
    }

    fn gen_struct(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (named_members, _attrs) = if let DataType::Struct {
            members: named_members,
            attrs,
        } = &data_type_entry.entity
        {
            (named_members, attrs)
        } else {
            unreachable!()
        };

        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());

        self.w
            .writeln("#[repr(C)]")?
            .writeln(format!("pub struct {} {{", typename))?;

        let mut w = self.w.new_block();
        for m in named_members {
            w.writeln(format!(
                "{}: {},",
                m.name.to_snake_case(),
                self.get_defined_typename(&m.type_)
            ))?;
        }

        self.w.writeln("}")?.eob()?;
        Ok(())
    }

    // Enums generate both a specific typedef, and a traditional C-style enum
    // The typedef is required to use a native type which is consistent across all architectures
    fn gen_enum(
        &mut self,
        module: &Module,
        data_type_entry: &Named<DataType>,
    ) -> Result<(), IDLError> {
        let (named_members, _attrs) = if let DataType::Enum {
            members: named_members,
            attrs,
        } = &data_type_entry.entity
        {
            (named_members, attrs)
        } else {
            unreachable!()
        };

        let typename = data_type_entry.name.name.to_camel_case();
        self.defined.insert(data_type_entry.id, typename.clone());

        self.w
            .writeln("#[repr(C)]")?
            .writeln("#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]")?
            .writeln(format!("pub enum {} {{", typename))?;

        let mut w = self.w.new_block();
        for m in named_members {
            w.writeln(format!("{},", m.name.to_camel_case()))?;
        }

        self.w.writeln("}")?.eob()?;
        Ok(())
    }

    fn gen_function(
        &mut self,
        module: &Module,
        func_decl_entry: &Named<FuncDecl>,
    ) -> Result<(), IDLError> {
        self.w
            .write_line(format!("// {:?}", func_decl_entry).as_bytes())?;

        let name = func_decl_entry.name.name.to_snake_case();
        let mut args = String::new();
        for a in func_decl_entry.entity.args.iter() {
            args += &format!(
                "{}: {},",
                a.name.to_snake_case(),
                self.get_defined_typename(&a.type_)
            );
        }

        let func_rets = &func_decl_entry.entity.rets;
        let rets = if func_rets.len() == 0 {
            "()".to_owned()
        } else {
            assert_eq!(func_rets.len(), 1);
            self.get_defined_typename(&func_rets[0].type_).to_owned()
        };

        self.w
            .writeln("#[no_mangle]")?
            .writeln(format!("pub fn {}({}) -> {} {{", name, args, rets))?;

        let mut w = self.w.new_block();
        w.writeln("unimplemented!()")?;

        self.w.writeln("}")?.eob()?;

        Ok(())
    }
}
<|endoftext|>


<commit_before>extern crate eom;
extern crate ndarray;
extern crate ndarray_linalg;

use ndarray::*;
use ndarray_linalg::*;
use eom::*;
use eom::traits::*;

fn main() {
    let n = 128;
    let l = 100.0;
    let dt = 1e-3;
    let interval = 100;
    let step = 10000;

    let eom = pde::KSE::new(n, l);
    let n_coef = eom.model_size();
    let teo = semi_implicit::DiagRK4::new(eom, dt);
    let mut teo = adaptor::nstep(teo, interval);

    let x: Array1<c64> = c64::new(0.01, 0.0) * random(n_coef);
    let x = adaptor::iterate(&mut teo, x, 100);

    let mut l: Array1<f64> = Array::zeros(n_coef);
    let series = lyapunov::Series::new(teo, x, 1e-7);
    for (t, (_x, _q, r)) in series.take(step).enumerate() {
        let d = r.diag().map(|x| x.abs().ln());
        azip!(mut l, d in { *l += d } );
        let nums: Vec<_> = l.iter()
            .map(|x| format!("{:.07}", x / (t + 1) as f64))
            .collect();
        println!("{}", nums.join(","));
    }
}
<commit_msg>Drop Lyapunvo analysis of KSE (split PR)<commit_after><|endoftext|>


<commit_before>// See LICENSE file for copyright and license details.

use cgmath::vector::Vector2;
use core::types::{MInt, MapPos};

pub enum Dir {
  NorthEast,
  East,
  SouthEast,
  SouthWest,
  West,
  NorthWest,
}

static DIR_TO_POS_DIFF: [[Vector2<MInt>, ..6], ..2] = [
    [
        Vector2{x: 1, y: -1},
        Vector2{x: 1, y: 0},
        Vector2{x: 1, y: 1},
        Vector2{x: 0, y: 1},
        Vector2{x: -1, y: 0},
        Vector2{x: 0, y: -1},
    ],
    [
        Vector2{x: 0, y: -1},
        Vector2{x: 1, y: 0},
        Vector2{x: 0, y: 1},
        Vector2{x: -1, y: 1},
        Vector2{x: -1, y: 0},
        Vector2{x: -1, y: -1},
    ]
];

impl Dir {
    pub fn from_int(n: MInt) -> Dir {
        assert!(n >= 0 && n < 6);
        let dirs = [
            NorthEast,
            East,
            SouthEast,
            SouthWest,
            West,
            NorthWest,
        ];
        dirs[n as uint]
    }

    pub fn to_int(&self) -> MInt {
        match *self {
            NorthEast => 0,
            East => 1,
            SouthEast => 2,
            SouthWest => 3,
            West => 4,
            NorthWest => 5,
        }
    }

    pub fn get_dir_from_to(from: MapPos, to: MapPos) -> Dir {
        // assert!(from.distance(to) == 1);
        let diff = to.v - from.v;
        for i in range(0u, 6) {
            if diff == DIR_TO_POS_DIFF[(from.v.y % 2) as uint][i] {
                return Dir::from_int(i as MInt);
            }
        }
        fail!("impossible positions: {}, {}", from, to);
    }

    pub fn get_neighbour_pos(pos: MapPos, dir: Dir) -> MapPos {
        let is_odd_row = pos.v.y % 2 == 1;
        let subtable_index = if is_odd_row { 1 } else { 0 };
        let direction_index = dir.to_int();
        assert!(direction_index >= 0 && direction_index < 6);
        let difference = DIR_TO_POS_DIFF[subtable_index as uint][direction_index as uint];
        MapPos{v: pos.v + difference}
    }
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<commit_msg>Updated for Rust 90ab2f8<commit_after>// See LICENSE file for copyright and license details.

use cgmath::vector::Vector2;
use core::types::{MInt, MapPos};

pub enum Dir {
  NorthEast,
  East,
  SouthEast,
  SouthWest,
  West,
  NorthWest,
}

static DIR_TO_POS_DIFF: [[Vector2<MInt>, ..6], ..2] = [
    [
        Vector2{x: 1, y: -1},
        Vector2{x: 1, y: 0},
        Vector2{x: 1, y: 1},
        Vector2{x: 0, y: 1},
        Vector2{x: -1, y: 0},
        Vector2{x: 0, y: -1},
    ],
    [
        Vector2{x: 0, y: -1},
        Vector2{x: 1, y: 0},
        Vector2{x: 0, y: 1},
        Vector2{x: -1, y: 1},
        Vector2{x: -1, y: 0},
        Vector2{x: -1, y: -1},
    ]
];

impl Dir {
    pub fn from_int(n: MInt) -> Dir {
        assert!(n >= 0 && n < 6);
        let dirs = [
            NorthEast,
            East,
            SouthEast,
            SouthWest,
            West,
            NorthWest,
        ];
        dirs[n as uint]
    }

    pub fn to_int(&self) -> MInt {
        match *self {
            NorthEast => 0,
            East => 1,
            SouthEast => 2,
            SouthWest => 3,
            West => 4,
            NorthWest => 5,
        }
    }

    pub fn get_dir_from_to(from: MapPos, to: MapPos) -> Dir {
        // assert!(from.distance(to) == 1);
        let diff = to.v - from.v;
        for i in range(0u, 6) {
            if diff == DIR_TO_POS_DIFF[(from.v.y % 2) as uint][i] {
                return Dir::from_int(i as MInt);
            }
        }
        fail!("impossible positions: {}, {}", from, to);
    }

    pub fn get_neighbour_pos(pos: MapPos, dir: Dir) -> MapPos {
        let is_odd_row = pos.v.y % 2 == 1;
        let subtable_index = if is_odd_row { 1 } else { 0 };
        let direction_index = dir.to_int();
        assert!(direction_index >= 0 && direction_index < 6);
        let difference = DIR_TO_POS_DIFF[subtable_index][direction_index as uint];
        MapPos{v: pos.v + difference}
    }
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<|endoftext|>


<commit_before>//! This is the core module. It exports the non-holdem
//! related code.

/// card.rs has value and suit.
mod card;
/// Re-export Card, Value, and Suit
pub use self::card::{Card, Value, Suit};

/// Code related to cards in hands.
mod hand;
/// Everything in there should be public.
pub use self::hand::*;

/// We want to be able to iterate over five card hands.
mod card_iter;
/// Make that functionality public.
pub use self::card_iter::*;

/// Deck is the normal 52 card deck.
mod deck;
/// Export `Deck`
pub use self::deck::Deck;

/// Flattened deck
mod flat_deck;
/// Export the trait and the result.
pub use self::flat_deck::{FlatDeck, Flattenable};

/// 5 Card hand ranking code.
mod rank;
/// Export the trait and the results.
pub use self::rank::{Rank, Rankable};<commit_msg>Formatting<commit_after>//! This is the core module. It exports the non-holdem
//! related code.

/// card.rs has value and suit.
mod card;
/// Re-export Card, Value, and Suit
pub use self::card::{Card, Value, Suit};

/// Code related to cards in hands.
mod hand;
/// Everything in there should be public.
pub use self::hand::*;

/// We want to be able to iterate over five card hands.
mod card_iter;
/// Make that functionality public.
pub use self::card_iter::*;

/// Deck is the normal 52 card deck.
mod deck;
/// Export `Deck`
pub use self::deck::Deck;

/// Flattened deck
mod flat_deck;
/// Export the trait and the result.
pub use self::flat_deck::{FlatDeck, Flattenable};

/// 5 Card hand ranking code.
mod rank;
/// Export the trait and the results.
pub use self::rank::{Rank, Rankable};
<|endoftext|>


<commit_before>//! This module contains the common driver code. Specific implementations for
//! different databases exist elsewhere.

use error::Error;
use value::*;
use query::Query;

pub trait Database {
  /// Connects to a database and returns a driver instance. After calling this
  /// the driver is ready to roll!
  fn connect(url: &str) -> Self;

  /// Set a value at a certain point in the driver.
  fn set(&self, pointer: Pointer, value: Value) -> Result<(), Error>;

  /// Get a value from a certain point in the driver. An optional query may be
  /// performed for more complex data selection.
  fn get(&self, pointer: Pointer, query: Option<Query>) -> Result<Value, Error>;

  /// Gets the schema for the driver. By default no schema is returned.
  fn get_schema(&self) -> Result<Schema, Error> {
    Ok(Schema::None)
  }
}
<commit_msg>feat: add get database function<commit_after>//! This module contains the common driver code. Specific implementations for
//! different databases exist elsewhere.

use error::Error;
use value::*;
use query::Query;

/// Gets the database from a URL string using the protocol. For example a URL
/// of `postgres://localhost:5432/test_db` would look for a
/// `ardite-database-postgres` crate, download the crate if it did not already
/// exist in the file system, and then return an instance initialized with the
/// `connect` static trait function.
pub fn get_database<D: Database>(url: &str) -> D {
  // TODO: implement
  unimplemented!();
}

pub trait Database {
  /// Connects to a database and returns a driver instance. After calling this
  /// the driver is ready to roll!
  fn connect(url: &str) -> Self;

  /// Set a value at a certain point in the driver.
  fn set(&self, pointer: Pointer, value: Value) -> Result<(), Error>;

  /// Get a value from a certain point in the driver. An optional query may be
  /// performed for more complex data selection.
  fn get(&self, pointer: Pointer, query: Option<Query>) -> Result<Value, Error>;

  /// Gets the schema for the driver. By default no schema is returned.
  fn get_schema(&self) -> Result<Schema, Error> {
    Ok(Schema::None)
  }
}
<|endoftext|>


<commit_before>use std::fmt;

use serde::de::Visitor;
use serde::{self, Deserialize};

use super::CellErrorType;

/// An enum to represent all different data types that can appear as
/// a value in a worksheet cell
#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    /// Unsigned integer
    Int(i64),
    /// Float
    Float(f64),
    /// String
    String(String),
    /// Boolean
    Bool(bool),
    /// Error
    Error(CellErrorType),
    /// Empty cell
    Empty,
}

impl Default for DataType {
    fn default() -> DataType {
        DataType::Empty
    }
}

impl DataType {
    /// Assess if `self == DataType::Empty`
    pub fn is_empty(&self) -> bool {
        *self == DataType::Empty
    }
}

impl PartialEq<str> for DataType {
    fn eq(&self, other: &str) -> bool {
        match *self {
            DataType::String(ref s) if s == other => true,
            _ => false,
        }
    }
}

impl PartialEq<f64> for DataType {
    fn eq(&self, other: &f64) -> bool {
        match *self {
            DataType::Float(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl PartialEq<bool> for DataType {
    fn eq(&self, other: &bool) -> bool {
        match *self {
            DataType::Bool(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl PartialEq<i64> for DataType {
    fn eq(&self, other: &i64) -> bool {
        match *self {
            DataType::Int(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
        match *self {
            DataType::Int(ref e) => write!(f, "{}", e),
            DataType::Float(ref e) => write!(f, "{}", e),
            DataType::String(ref e) => write!(f, "{}", e),
            DataType::Bool(ref e) => write!(f, "{}", e),
            DataType::Error(ref e) => write!(f, "{}", e),
            DataType::Empty => Ok(()),
        }
    }
}

impl<'de> Deserialize<'de> for DataType {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<DataType, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct DataTypeVisitor;

        impl<'de> Visitor<'de> for DataTypeVisitor {
            type Value = DataType;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("any valid JSON value")
            }

            #[inline]
            fn visit_bool<E>(self, value: bool) -> Result<DataType, E> {
                Ok(DataType::Bool(value))
            }

            #[inline]
            fn visit_i64<E>(self, value: i64) -> Result<DataType, E> {
                Ok(DataType::Int(value))
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<DataType, E> {
                Ok(DataType::Int(value as i64))
            }

            #[inline]
            fn visit_f64<E>(self, value: f64) -> Result<DataType, E> {
                Ok(DataType::Float(value))
            }

            #[inline]
            fn visit_str<E>(self, value: &str) -> Result<DataType, E>
            where
                E: serde::de::Error,
            {
                self.visit_string(String::from(value))
            }

            #[inline]
            fn visit_string<E>(self, value: String) -> Result<DataType, E> {
                Ok(DataType::String(value))
            }

            #[inline]
            fn visit_none<E>(self) -> Result<DataType, E> {
                Ok(DataType::Empty)
            }

            #[inline]
            fn visit_some<D>(self, deserializer: D) -> Result<DataType, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                Deserialize::deserialize(deserializer)
            }

            #[inline]
            fn visit_unit<E>(self) -> Result<DataType, E> {
                Ok(DataType::Empty)
            }
        }

        deserializer.deserialize_any(DataTypeVisitor)
    }
}

macro_rules! define_from {
    ($variant:path, $ty:ty) => {
        impl From<$ty> for DataType {
            fn from(v: $ty) -> Self {
                $variant(v)
            }
        }
    };
}

define_from!(DataType::Int, i64);
define_from!(DataType::Float, f64);
define_from!(DataType::String, String);
define_from!(DataType::Bool, bool);
define_from!(DataType::Error, CellErrorType);

impl<'a> From<&'a str> for DataType {
    fn from(v: &'a str) -> Self {
        DataType::String(String::from(v))
    }
}

impl From<()> for DataType {
    fn from(_: ()) -> Self {
        DataType::Empty
    }
}

impl<T> From<Option<T>> for DataType
where
    DataType: From<T>,
{
    fn from(v: Option<T>) -> Self {
        match v {
            Some(v) => From::from(v),
            None => DataType::Empty,
        }
    }
}
<commit_msg>add more DataType::is_... fn<commit_after>use std::fmt;

use serde::de::Visitor;
use serde::{self, Deserialize};

use super::CellErrorType;

/// An enum to represent all different data types that can appear as
/// a value in a worksheet cell
#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    /// Unsigned integer
    Int(i64),
    /// Float
    Float(f64),
    /// String
    String(String),
    /// Boolean
    Bool(bool),
    /// Error
    Error(CellErrorType),
    /// Empty cell
    Empty,
}

impl Default for DataType {
    fn default() -> DataType {
        DataType::Empty
    }
}

impl DataType {
    /// Assess if datatype is empty
    pub fn is_empty(&self) -> bool {
        *self == DataType::Empty
    }
    /// Assess if datatype is a int
    pub fn is_int(&self) -> bool {
        if let DataType::Int(_) = *self {
            true
        } else {
            false
        }
    }
    /// Assess if datatype is a float
    pub fn is_float(&self) -> bool {
        if let DataType::Float(_) = *self {
            true
        } else {
            false
        }
    }
    /// Assess if datatype is a bool
    pub fn is_bool(&self) -> bool {
        if let DataType::Bool(_) = *self {
            true
        } else {
            false
        }
    }
    /// Assess if datatype is a string
    pub fn is_string(&self) -> bool {
        if let DataType::String(_) = *self {
            true
        } else {
            false
        }
    }
}

impl PartialEq<str> for DataType {
    fn eq(&self, other: &str) -> bool {
        match *self {
            DataType::String(ref s) if s == other => true,
            _ => false,
        }
    }
}

impl PartialEq<f64> for DataType {
    fn eq(&self, other: &f64) -> bool {
        match *self {
            DataType::Float(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl PartialEq<bool> for DataType {
    fn eq(&self, other: &bool) -> bool {
        match *self {
            DataType::Bool(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl PartialEq<i64> for DataType {
    fn eq(&self, other: &i64) -> bool {
        match *self {
            DataType::Int(ref s) if *s == *other => true,
            _ => false,
        }
    }
}

impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
        match *self {
            DataType::Int(ref e) => write!(f, "{}", e),
            DataType::Float(ref e) => write!(f, "{}", e),
            DataType::String(ref e) => write!(f, "{}", e),
            DataType::Bool(ref e) => write!(f, "{}", e),
            DataType::Error(ref e) => write!(f, "{}", e),
            DataType::Empty => Ok(()),
        }
    }
}

impl<'de> Deserialize<'de> for DataType {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<DataType, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct DataTypeVisitor;

        impl<'de> Visitor<'de> for DataTypeVisitor {
            type Value = DataType;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("any valid JSON value")
            }

            #[inline]
            fn visit_bool<E>(self, value: bool) -> Result<DataType, E> {
                Ok(DataType::Bool(value))
            }

            #[inline]
            fn visit_i64<E>(self, value: i64) -> Result<DataType, E> {
                Ok(DataType::Int(value))
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<DataType, E> {
                Ok(DataType::Int(value as i64))
            }

            #[inline]
            fn visit_f64<E>(self, value: f64) -> Result<DataType, E> {
                Ok(DataType::Float(value))
            }

            #[inline]
            fn visit_str<E>(self, value: &str) -> Result<DataType, E>
            where
                E: serde::de::Error,
            {
                self.visit_string(String::from(value))
            }

            #[inline]
            fn visit_string<E>(self, value: String) -> Result<DataType, E> {
                Ok(DataType::String(value))
            }

            #[inline]
            fn visit_none<E>(self) -> Result<DataType, E> {
                Ok(DataType::Empty)
            }

            #[inline]
            fn visit_some<D>(self, deserializer: D) -> Result<DataType, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                Deserialize::deserialize(deserializer)
            }

            #[inline]
            fn visit_unit<E>(self) -> Result<DataType, E> {
                Ok(DataType::Empty)
            }
        }

        deserializer.deserialize_any(DataTypeVisitor)
    }
}

macro_rules! define_from {
    ($variant:path, $ty:ty) => {
        impl From<$ty> for DataType {
            fn from(v: $ty) -> Self {
                $variant(v)
            }
        }
    };
}

define_from!(DataType::Int, i64);
define_from!(DataType::Float, f64);
define_from!(DataType::String, String);
define_from!(DataType::Bool, bool);
define_from!(DataType::Error, CellErrorType);

impl<'a> From<&'a str> for DataType {
    fn from(v: &'a str) -> Self {
        DataType::String(String::from(v))
    }
}

impl From<()> for DataType {
    fn from(_: ()) -> Self {
        DataType::Empty
    }
}

impl<T> From<Option<T>> for DataType
where
    DataType: From<T>,
{
    fn from(v: Option<T>) -> Self {
        match v {
            Some(v) => From::from(v),
            None => DataType::Empty,
        }
    }
}
<|endoftext|>


<commit_before>use crate::{thread::ThreadHandle, Result};
use async_task::Task;
use crossbeam_channel::{Receiver, Sender};
use parking_lot::Mutex;
use std::{
    cell::RefCell, fmt, future::Future, ops::Deref, pin::Pin, sync::Arc,
    thread::Builder as ThreadBuilder,
};

thread_local!(static LAPIN_EXECUTOR_THREAD: RefCell<bool> = RefCell::new(false));

pub(crate) fn within_executor() -> bool {
    LAPIN_EXECUTOR_THREAD.with(|executor_thread| *executor_thread.borrow())
}

pub trait Executor: std::fmt::Debug + Send + Sync {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>);
}

impl Executor for Arc<dyn Executor> {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) {
        self.deref().spawn(f)
    }
}

#[derive(Clone)]
pub struct DefaultExecutor {
    sender: Sender<Option<Task<()>>>,
    receiver: Receiver<Option<Task<()>>>,
    threads: Arc<Mutex<Vec<ThreadHandle>>>,
}

impl DefaultExecutor {
    pub fn new(max_threads: usize) -> Result<Self> {
        let (sender, receiver) = crossbeam_channel::unbounded::<Option<Task<()>>>();
        let threads = Arc::new(Mutex::new(
            (1..=max_threads)
                .map(|id| {
                    let receiver = receiver.clone();
                    Ok(ThreadHandle::new(
                        ThreadBuilder::new()
                            .name(format!("executor {}", id))
                            .spawn(move || {
                                LAPIN_EXECUTOR_THREAD
                                    .with(|executor_thread| *executor_thread.borrow_mut() = true);
                                while let Ok(Some(task)) = receiver.recv() {
                                    task.run();
                                }
                                Ok(())
                            })?,
                    ))
                })
                .collect::<Result<Vec<_>>>()?,
        ));
        Ok(Self {
            sender,
            receiver,
            threads,
        })
    }

    pub(crate) fn default() -> Result<Arc<dyn Executor>> {
        Ok(Arc::new(Self::new(1)?))
    }
}

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

impl Executor for DefaultExecutor {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) {
        let sender = self.sender.clone();
        let schedule = move |task| sender.send(Some(task)).expect("executor failed");
        let (task, _) = async_task::spawn(f, schedule, ());
        task.schedule();
    }
}

impl Drop for DefaultExecutor {
    fn drop(&mut self) {
        if let Some(threads) = self.threads.try_lock() {
            for _ in threads.iter() {
                let _ = self.sender.send(None);
            }
            for thread in threads.iter() {
                if !thread.is_current() {
                    let _ = thread.wait("executor");
                }
            }
        }
    }
}
<commit_msg>Executor: split spawn_thread helper<commit_after>use crate::{thread::ThreadHandle, Result};
use async_task::Task;
use crossbeam_channel::{Receiver, Sender};
use parking_lot::Mutex;
use std::{
    cell::RefCell, fmt, future::Future, ops::Deref, pin::Pin, sync::Arc,
    thread::Builder as ThreadBuilder,
};

thread_local!(static LAPIN_EXECUTOR_THREAD: RefCell<bool> = RefCell::new(false));

pub(crate) fn within_executor() -> bool {
    LAPIN_EXECUTOR_THREAD.with(|executor_thread| *executor_thread.borrow())
}

fn spawn_thread(
    name: String,
    work: impl FnOnce() -> Result<()> + Send + 'static,
) -> Result<ThreadHandle> {
    Ok(ThreadHandle::new(ThreadBuilder::new().name(name).spawn(
        move || {
            LAPIN_EXECUTOR_THREAD.with(|executor_thread| *executor_thread.borrow_mut() = true);
            work()
        },
    )?))
}

pub trait Executor: std::fmt::Debug + Send + Sync {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>);
}

impl Executor for Arc<dyn Executor> {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) {
        self.deref().spawn(f)
    }
}

#[derive(Clone)]
pub struct DefaultExecutor {
    sender: Sender<Option<Task<()>>>,
    receiver: Receiver<Option<Task<()>>>,
    threads: Arc<Mutex<Vec<ThreadHandle>>>,
}

impl DefaultExecutor {
    pub fn new(max_threads: usize) -> Result<Self> {
        let (sender, receiver) = crossbeam_channel::unbounded::<Option<Task<()>>>();
        let threads = Arc::new(Mutex::new(
            (1..=max_threads)
                .map(|id| {
                    let receiver = receiver.clone();
                    spawn_thread(format!("executor {}", id), move || {
                        while let Ok(Some(task)) = receiver.recv() {
                            task.run();
                        }
                        Ok(())
                    })
                })
                .collect::<Result<Vec<_>>>()?,
        ));
        Ok(Self {
            sender,
            receiver,
            threads,
        })
    }

    pub(crate) fn default() -> Result<Arc<dyn Executor>> {
        Ok(Arc::new(Self::new(1)?))
    }
}

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

impl Executor for DefaultExecutor {
    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) {
        let sender = self.sender.clone();
        let schedule = move |task| sender.send(Some(task)).expect("executor failed");
        let (task, _) = async_task::spawn(f, schedule, ());
        task.schedule();
    }
}

impl Drop for DefaultExecutor {
    fn drop(&mut self) {
        if let Some(threads) = self.threads.try_lock() {
            for _ in threads.iter() {
                let _ = self.sender.send(None);
            }
            for thread in threads.iter() {
                if !thread.is_current() {
                    let _ = thread.wait("executor");
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (2015-2017) Michael 'ExpHP' Lamparski
//
// Licensed under the terms of the MIT License, available at:
//  http://opensource.org/licenses/MIT
// and also included in the file COPYING at the root of this distribution.
// This file may not be copied, modified, or distributed except according
// to those terms.

use std::default::Default;
use std::ops::Mul;
use std::cmp::{min,max};
use std::collections::BTreeMap;

use num;
use num::{One,FromPrimitive};
use num::Num;

use crate::FactorExt;

/// An integer stored as its prime factorization.
///
/// A `Factored` represents a non-negative integer stored in the form
///
/// ```text
/// pow(p1, n1) * pow(p2, n2) * ... * pow(pN, nN)
/// ```
///
/// where `p1, p2, ...` are prime numbers (or zero) and `n1, n2, ...` are positive
/// integers. Some properties are easier to compute in this form, such as the euler
/// totient, or a sum of divisors. Also of note is that because the prime factorization
/// of any given number is unique, any two `Factorization`s constructed from the same
/// `x` are equal.
///
/// Negative numbers, zero, as well as negative powers (i.e. rationals) are not
/// permitted.
///
/// One caveat:  It is not feasible for `Factorization` to enforce that the prime
///  factors it is built from are actually prime.  This is the job of the
///  `TryFactor` used to produce it!  The behavior of any mathematical method
///  on a `Factorization` with a composite factor is **undefined**. (in the sense
///  of nonsensical results; not in the sense that the safety guidelines of Rust
///  may be violated)
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Factored<X> {
    // powers are currently usize for consistency with the pow() function
    //  in the num crate.
    powers: BTreeMap<X, usize>,
}

// TODO: some of Factorization's methods need to be special cased for Zero

impl<X> Factored<X>
where
    X: Ord,
{
    /// Set the power of a prime factor in the `Factorization`. `prime` is
    ///  assumed to be prime. Note that while composite numbers
    ///  may be accepted, the behavior of the resulting `Factorization` is
    ///  ill-defined.
    // NOTE: No diagnostic is provided because it would require some sort
    //  of additional bound like Zero, One, or NumCast.
    pub fn set(&mut self, prime: X, exp: usize) {
        match exp {
            0 => self.powers.remove(&prime),
            _ => self.powers.insert(prime, exp),
        };
    }

    /// Get the power of a prime factor in the `Factorization`. `prime` is
    ///  assumed to be prime. The value returned for non-prime
    ///  keys is undefined.
    pub fn get(&self, prime: &X) -> usize {
        match self.powers.get(prime) {
            None => 0,
            Some(&exp) => exp,
        }
    }

    /// Create a `Factored` from a single prime.
    ///
    /// Do not use on a composite number (use `factor::factorize`)
    /// or one (use `One::one()`).
    pub fn from_prime(prime: X) -> Self {
        Factored {
            powers: ::std::iter::once((prime, 1)).collect(),
        }
    }

    /// Recover the integer represented by the `Factored`.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.product(), 20);
    /// ```
    pub fn product(&self) -> X
    where
        X: Clone + One,
    {
        self.iter().map(clone2).factor_product()
    }

    /// Compute the total number of positive integers which evenly divide
    ///  a number from its prime decomposition.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.divisor_count(), 6);
    /// ```
    pub fn divisor_count(&self) -> X
    where
        X: Clone + FromPrimitive + One,
    {
        self.iter().map(clone2).divisor_count()
    }

    /// Compute the sum of all positive integers which evenly divide the number
    ///  represented by the `Factored` (including 1 and the number itself).
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.divisor_sum(), 42);
    /// ```
    pub fn divisor_sum(&self) -> X
    where
        X: Clone + One + Num,
    {
        self.iter().map(clone2).divisor_sum()
    }

    /// Compute the Euler totient `phi(x)`, the total number of
    ///  positive integers less than `x` that are coprime to `x`.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.totient(), 8);
    /// ```
    pub fn totient(&self) -> X
    where
        X: Clone + One + Num,
    {
        self.iter().map(clone2).totient()
    }
}

impl<X> Factored<X>
where
    X: Ord,
{
    /// Get the square root of a perfect square.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let mut f = factorize(20u64);
    /// assert!(f.clone().sqrt().is_none());    // 20 is not square!
    ///
    /// f = f * factorize(5);
    /// assert_eq!(f.sqrt().unwrap().product(), 10);  // sqrt(100)
    /// ```
    pub fn sqrt(self) -> Option<Self> {
        self.root(2)
    }

    /// Get the nth root of a perfect nth power.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let mut f = factorize(20u64);
    /// assert!(f.clone().root(3).is_none());    // 20 is not a cube!
    ///
    /// f = f * factorize(50);
    /// assert_eq!(f.root(3).unwrap().product(), 10);  // cbrt(1000)
    /// ```
    pub fn root(mut self, n: usize) -> Option<Self> {
        for (_, v) in self.powers.iter_mut() {
            if *v % n == 1 {
                return None; // Not a root!  Abort!  Abort!
            };

            *v = *v / n;
        }
        Some(self)
    }

    // TODO: Docs & test
    pub fn pow(mut self, pwr: usize) -> Self
    where
        X: Clone,
    {
        for (_, v) in self.powers.iter_mut() {
            *v = *v * pwr;
        }
        self
    }

    /*
        // TODO: Docs & test
        pub fn gcd(mut self, other: mut Self) -> Self
         where X: Clone,
        {
            // Iterate through shorter list
            if other.powers.len() < self.powers.len() {
                return self.gcd(other);
            };

            let mut result: Self = One::one();
            for (k,v) in other {
                self.set(k.clone(), min(self.get(&k), v));
            };
            self
        }

        // TODO: Docs & test
        pub fn lcm(&self, other: &Self) -> Self
         where X: Clone,
        {
            let mut result = self.clone();
            for (k,v) in self.powers.clone().into_iter() {
                self.set(k.clone(), max(self.get(&k), v));
            };
            self
        }
    */

    /// Iterate over unique prime factors.
    ///
    /// Item type is `&X`.
    pub fn primes(&self) -> Primes<'_, X> {
        self.powers.keys()
    }

    /// Iterate over `(prime, power)` pairs.
    ///
    /// Item type is `(&X, usize)`.
    pub fn iter(&self) -> Iter<'_, X> {
        self.powers.iter()
    }

    /// Consume to iterate over the `(prime, power)` pairs.
    ///
    /// Item type is `(X, usize)`.
    pub fn into_iter(self) -> IntoIter<X> {
        self.powers.into_iter()
    }

    /// Immutably borrow the underlying map.
    pub fn as_btree_map(&self) -> &BTreeMap<X, usize> {
        &self.powers
    }
    /// Mutably borrow the underlying map.
    ///
    /// This is provided on the grounds of "eh, why the hell not."  After all,
    /// it's not exactly like `Factored` was doing a very good job at protecting
    /// any of its invariants to begin with.
    pub fn as_mut_btree_map(&mut self) -> &mut BTreeMap<X, usize> {
        &mut self.powers
    }
    /// Consume to obtain the underlying map.
    pub fn into_btree_map(self) -> BTreeMap<X, usize> {
        self.powers
    }

    /// Construct from a map of unique `(prime, power)` pairs.
    pub fn from_btree_map(map: BTreeMap<X, usize>) -> Self {
        Factored { powers: map }
    }

    /// Construct from an iterator of unique `(prime, power)` pairs.
    pub fn from_iter<I: IntoIterator<Item = (X, usize)>>(iter: I) -> Self {
        Factored::from_btree_map(iter.into_iter().collect())
    }

    // TODO: Reasonable (?) methods to implement
    // pub fn is_multiple_of(&self, other: &Self) -> bool
}

impl<X> One for Factored<X>
where
    X: Ord + Clone,
{
    /// Create a `Factored` representing `1`.
    fn one() -> Self {
        Self::from_btree_map(BTreeMap::new())
    }
}

impl<X> Default for Factored<X>
where
    X: Ord + Clone,
{
    /// Create a `Factored` representing `1`.
    fn default() -> Self {
        One::one()
    }
}

impl<X> Mul<Factored<X>> for Factored<X>
where
    X: Ord + Clone,
{
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        let mut result = self;
        for (k, v) in other.powers.into_iter() {
            let current = result.get(&k); // owned proxy
            result.set(k.clone(), current + v);
        }
        result
    }
}

//------------------------------------

pub type Iter<'a, T> = ::std::collections::btree_map::Iter<'a, T, usize>;
pub type IntoIter<T> = ::std::collections::btree_map::IntoIter<T, usize>;
pub type Primes<'a, T> = ::std::collections::btree_map::Keys<'a, T, usize>;

#[inline]
fn clone2<A, B>((a, b): (&A, &B)) -> (A, B)
where
    A: Clone,
    B: Clone,
{
    (a.clone(), b.clone())
}
<commit_msg>impl std::iter::Product for Factored<commit_after>// Copyright (2015-2017) Michael 'ExpHP' Lamparski
//
// Licensed under the terms of the MIT License, available at:
//  http://opensource.org/licenses/MIT
// and also included in the file COPYING at the root of this distribution.
// This file may not be copied, modified, or distributed except according
// to those terms.

use std::default::Default;
use std::ops::Mul;
use std::cmp::{min,max};
use std::collections::BTreeMap;

use num;
use num::{One,FromPrimitive};
use num::Num;

use crate::FactorExt;

/// An integer stored as its prime factorization.
///
/// A `Factored` represents a non-negative integer stored in the form
///
/// ```text
/// pow(p1, n1) * pow(p2, n2) * ... * pow(pN, nN)
/// ```
///
/// where `p1, p2, ...` are prime numbers (or zero) and `n1, n2, ...` are positive
/// integers. Some properties are easier to compute in this form, such as the euler
/// totient, or a sum of divisors. Also of note is that because the prime factorization
/// of any given number is unique, any two `Factorization`s constructed from the same
/// `x` are equal.
///
/// Negative numbers, zero, as well as negative powers (i.e. rationals) are not
/// permitted.
///
/// One caveat:  It is not feasible for `Factorization` to enforce that the prime
///  factors it is built from are actually prime.  This is the job of the
///  `TryFactor` used to produce it!  The behavior of any mathematical method
///  on a `Factorization` with a composite factor is **undefined**. (in the sense
///  of nonsensical results; not in the sense that the safety guidelines of Rust
///  may be violated)
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Factored<X> {
    // powers are currently usize for consistency with the pow() function
    //  in the num crate.
    powers: BTreeMap<X, usize>,
}

// TODO: some of Factorization's methods need to be special cased for Zero

impl<X> Factored<X>
where
    X: Ord,
{
    /// Set the power of a prime factor in the `Factorization`. `prime` is
    ///  assumed to be prime. Note that while composite numbers
    ///  may be accepted, the behavior of the resulting `Factorization` is
    ///  ill-defined.
    // NOTE: No diagnostic is provided because it would require some sort
    //  of additional bound like Zero, One, or NumCast.
    pub fn set(&mut self, prime: X, exp: usize) {
        match exp {
            0 => self.powers.remove(&prime),
            _ => self.powers.insert(prime, exp),
        };
    }

    /// Get the power of a prime factor in the `Factorization`. `prime` is
    ///  assumed to be prime. The value returned for non-prime
    ///  keys is undefined.
    pub fn get(&self, prime: &X) -> usize {
        match self.powers.get(prime) {
            None => 0,
            Some(&exp) => exp,
        }
    }

    /// Create a `Factored` from a single prime.
    ///
    /// Do not use on a composite number (use `factor::factorize`)
    /// or one (use `One::one()`).
    pub fn from_prime(prime: X) -> Self {
        Factored {
            powers: ::std::iter::once((prime, 1)).collect(),
        }
    }

    /// Recover the integer represented by the `Factored`.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.product(), 20);
    /// ```
    pub fn product(&self) -> X
    where
        X: Clone + One,
    {
        self.iter().map(clone2).factor_product()
    }

    /// Compute the total number of positive integers which evenly divide
    ///  a number from its prime decomposition.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.divisor_count(), 6);
    /// ```
    pub fn divisor_count(&self) -> X
    where
        X: Clone + FromPrimitive + One,
    {
        self.iter().map(clone2).divisor_count()
    }

    /// Compute the sum of all positive integers which evenly divide the number
    ///  represented by the `Factored` (including 1 and the number itself).
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.divisor_sum(), 42);
    /// ```
    pub fn divisor_sum(&self) -> X
    where
        X: Clone + One + Num,
    {
        self.iter().map(clone2).divisor_sum()
    }

    /// Compute the Euler totient `phi(x)`, the total number of
    ///  positive integers less than `x` that are coprime to `x`.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let f = factorize(20u64);
    /// assert_eq!(f.totient(), 8);
    /// ```
    pub fn totient(&self) -> X
    where
        X: Clone + One + Num,
    {
        self.iter().map(clone2).totient()
    }
}

impl<X> Factored<X>
where
    X: Ord,
{
    /// Get the square root of a perfect square.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let mut f = factorize(20u64);
    /// assert!(f.clone().sqrt().is_none());    // 20 is not square!
    ///
    /// f = f * factorize(5);
    /// assert_eq!(f.sqrt().unwrap().product(), 10);  // sqrt(100)
    /// ```
    pub fn sqrt(self) -> Option<Self> {
        self.root(2)
    }

    /// Get the nth root of a perfect nth power.
    ///
    /// # Example:
    ///
    /// ```
    /// use factor::factorize;
    ///
    /// let mut f = factorize(20u64);
    /// assert!(f.clone().root(3).is_none());    // 20 is not a cube!
    ///
    /// f = f * factorize(50);
    /// assert_eq!(f.root(3).unwrap().product(), 10);  // cbrt(1000)
    /// ```
    pub fn root(mut self, n: usize) -> Option<Self> {
        for (_, v) in self.powers.iter_mut() {
            if *v % n == 1 {
                return None; // Not a root!  Abort!  Abort!
            };

            *v = *v / n;
        }
        Some(self)
    }

    // TODO: Docs & test
    pub fn pow(mut self, pwr: usize) -> Self
    where
        X: Clone,
    {
        for (_, v) in self.powers.iter_mut() {
            *v = *v * pwr;
        }
        self
    }

    /*
        // TODO: Docs & test
        pub fn gcd(mut self, other: mut Self) -> Self
         where X: Clone,
        {
            // Iterate through shorter list
            if other.powers.len() < self.powers.len() {
                return self.gcd(other);
            };

            let mut result: Self = One::one();
            for (k,v) in other {
                self.set(k.clone(), min(self.get(&k), v));
            };
            self
        }

        // TODO: Docs & test
        pub fn lcm(&self, other: &Self) -> Self
         where X: Clone,
        {
            let mut result = self.clone();
            for (k,v) in self.powers.clone().into_iter() {
                self.set(k.clone(), max(self.get(&k), v));
            };
            self
        }
    */

    /// Iterate over unique prime factors.
    ///
    /// Item type is `&X`.
    pub fn primes(&self) -> Primes<'_, X> {
        self.powers.keys()
    }

    /// Iterate over `(prime, power)` pairs.
    ///
    /// Item type is `(&X, usize)`.
    pub fn iter(&self) -> Iter<'_, X> {
        self.powers.iter()
    }

    /// Consume to iterate over the `(prime, power)` pairs.
    ///
    /// Item type is `(X, usize)`.
    pub fn into_iter(self) -> IntoIter<X> {
        self.powers.into_iter()
    }

    /// Immutably borrow the underlying map.
    pub fn as_btree_map(&self) -> &BTreeMap<X, usize> {
        &self.powers
    }
    /// Mutably borrow the underlying map.
    ///
    /// This is provided on the grounds of "eh, why the hell not."  After all,
    /// it's not exactly like `Factored` was doing a very good job at protecting
    /// any of its invariants to begin with.
    pub fn as_mut_btree_map(&mut self) -> &mut BTreeMap<X, usize> {
        &mut self.powers
    }
    /// Consume to obtain the underlying map.
    pub fn into_btree_map(self) -> BTreeMap<X, usize> {
        self.powers
    }

    /// Construct from a map of unique `(prime, power)` pairs.
    pub fn from_btree_map(map: BTreeMap<X, usize>) -> Self {
        Factored { powers: map }
    }

    /// Construct from an iterator of unique `(prime, power)` pairs.
    pub fn from_iter<I: IntoIterator<Item = (X, usize)>>(iter: I) -> Self {
        Factored::from_btree_map(iter.into_iter().collect())
    }

    // TODO: Reasonable (?) methods to implement
    // pub fn is_multiple_of(&self, other: &Self) -> bool
}

impl<X> One for Factored<X>
where
    X: Ord + Clone,
{
    /// Create a `Factored` representing `1`.
    fn one() -> Self {
        Self::from_btree_map(BTreeMap::new())
    }
}

impl<X> Default for Factored<X>
where
    X: Ord + Clone,
{
    /// Create a `Factored` representing `1`.
    fn default() -> Self {
        One::one()
    }
}

impl<X> Mul<Factored<X>> for Factored<X>
where
    X: Ord + Clone,
{
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        let mut result = self;
        for (k, v) in other.powers.into_iter() {
            let current = result.get(&k); // owned proxy
            result.set(k.clone(), current + v);
        }
        result
    }
}

impl<X> std::iter::Product for Factored<X>
where
    X: Ord + Clone,
{
    fn product<I: Iterator<Item=Factored<X>>>(iter: I) -> Self {
        iter.fold(Default::default(), |acc, x| acc * x)
    }
}

//------------------------------------

pub type Iter<'a, T> = ::std::collections::btree_map::Iter<'a, T, usize>;
pub type IntoIter<T> = ::std::collections::btree_map::IntoIter<T, usize>;
pub type Primes<'a, T> = ::std::collections::btree_map::Keys<'a, T, usize>;

#[inline]
fn clone2<A, B>((a, b): (&A, &B)) -> (A, B)
where
    A: Clone,
    B: Clone,
{
    (a.clone(), b.clone())
}
<|endoftext|>