<commit_before>//! Database migrations

use error::Result as CratesfyiResult;
use postgres::{Connection, transaction::Transaction, Error as PostgresError};
use schemamama::{Migration, Migrator, Version};
use schemamama_postgres::{PostgresAdapter, PostgresMigration};
use std::rc::Rc;

enum ApplyMode {
    Permanent,
    Temporary,
}

struct MigrationContext {
    apply_mode: ApplyMode,
}

impl MigrationContext {
    fn format_query(&self, query: &str) -> String {
        query.replace("{create_table}", match self.apply_mode {
            ApplyMode::Permanent => "CREATE TABLE",
            ApplyMode::Temporary => "CREATE TEMPORARY TABLE",
        })
    }
}

/// Creates a new PostgresMigration from upgrade and downgrade queries.
/// Downgrade query should return database to previous state.
///
/// Example:
///
/// ```
/// let my_migration = migration!(100,
///                               "Create test table",
///                               "{create_table} test ( id SERIAL);",
///                               "DROP TABLE test;");
/// ```
macro_rules! migration {
    ($context:expr, $version:expr, $description:expr, $up:expr, $down:expr $(,)?) => {{
        struct Amigration {
            ctx: Rc<MigrationContext>,
        };
        impl Migration for Amigration {
            fn version(&self) -> Version {
                $version
            }
            fn description(&self) -> String {
                $description.to_owned()
            }
        }
        impl PostgresMigration for Amigration {
            fn up(&self, transaction: &Transaction) -> Result<(), PostgresError> {
                info!("Applying migration {}: {}", self.version(), self.description());
                transaction.batch_execute(&self.ctx.format_query($up)).map(|_| ())
            }
            fn down(&self, transaction: &Transaction) -> Result<(), PostgresError> {
                info!("Removing migration {}: {}", self.version(), self.description());
                transaction.batch_execute(&self.ctx.format_query($down)).map(|_| ())
            }
        }
        Box::new(Amigration { ctx: $context })
    }};
}

pub fn migrate(version: Option<Version>, conn: &Connection) -> CratesfyiResult<()> {
    migrate_inner(version, conn, ApplyMode::Permanent)
}

pub fn migrate_temporary(version: Option<Version>, conn: &Connection) -> CratesfyiResult<()> {
    migrate_inner(version, conn, ApplyMode::Temporary)
}

fn migrate_inner(version: Option<Version>, conn: &Connection, apply_mode: ApplyMode) -> CratesfyiResult<()> {
    let context = Rc::new(MigrationContext { apply_mode });

    conn.execute(
        &context.format_query(
            "{create_table} IF NOT EXISTS database_versions (version BIGINT PRIMARY KEY);"
        ),
        &[],
    )?;
    let adapter = PostgresAdapter::with_metadata_table(conn, "database_versions");

    let mut migrator = Migrator::new(adapter);

    let migrations: Vec<Box<dyn PostgresMigration>> = vec![
        migration!(
            context.clone(),
            // version
            1,
            // description
            "Initial database schema",
            // upgrade query
            "{create_table} crates (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255) UNIQUE NOT NULL,
                 latest_version_id INT DEFAULT 0,
                 versions JSON DEFAULT '[]',
                 downloads_total INT DEFAULT 0,
                 github_description VARCHAR(1024),
                 github_stars INT DEFAULT 0,
                 github_forks INT DEFAULT 0,
                 github_issues INT DEFAULT 0,
                 github_last_commit TIMESTAMP,
                 github_last_update TIMESTAMP,
                 content tsvector
             );
             {create_table} releases (
                 id SERIAL PRIMARY KEY,
                 crate_id INT NOT NULL REFERENCES crates(id),
                 version VARCHAR(100),
                 release_time TIMESTAMP,
                 dependencies JSON,
                 target_name VARCHAR(255),
                 yanked BOOL DEFAULT FALSE,
                 is_library BOOL DEFAULT TRUE,
                 build_status BOOL DEFAULT FALSE,
                 rustdoc_status BOOL DEFAULT FALSE,
                 test_status BOOL DEFAULT FALSE,
                 license VARCHAR(100),
                 repository_url VARCHAR(255),
                 homepage_url VARCHAR(255),
                 documentation_url VARCHAR(255),
                 description VARCHAR(1024),
                 description_long VARCHAR(51200),
                 readme VARCHAR(51200),
                 authors JSON,
                 keywords JSON,
                 have_examples BOOL DEFAULT FALSE,
                 downloads INT DEFAULT 0,
                 files JSON,
                 doc_targets JSON DEFAULT '[]',
                 doc_rustc_version VARCHAR(100) NOT NULL,
                 default_target VARCHAR(100),
                 UNIQUE (crate_id, version)
             );
             {create_table} authors (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255),
                 email VARCHAR(255),
                 slug VARCHAR(255) UNIQUE NOT NULL
             );
             {create_table} author_rels (
                 rid INT REFERENCES releases(id),
                 aid INT REFERENCES authors(id),
                 UNIQUE(rid, aid)
             );
             {create_table} keywords (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255),
                 slug VARCHAR(255) NOT NULL UNIQUE
             );
             {create_table} keyword_rels (
                 rid INT REFERENCES releases(id),
                 kid INT REFERENCES keywords(id),
                 UNIQUE(rid, kid)
             );
             {create_table} owners (
                 id SERIAL PRIMARY KEY,
                 login VARCHAR(255) NOT NULL UNIQUE,
                 avatar VARCHAR(255),
                 name VARCHAR(255),
                 email VARCHAR(255)
             );
             {create_table} owner_rels (
                 cid INT REFERENCES releases(id),
                 oid INT REFERENCES owners(id),
                 UNIQUE(cid, oid)
             );
             {create_table} builds (
                 id SERIAL,
                 rid INT NOT NULL REFERENCES releases(id),
                 rustc_version VARCHAR(100) NOT NULL,
                 cratesfyi_version VARCHAR(100) NOT NULL,
                 build_status BOOL NOT NULL,
                 build_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 output TEXT
             );
             {create_table} queue (
                 id SERIAL,
                 name VARCHAR(255),
                 version VARCHAR(100),
                 attempt INT DEFAULT 0,
                 date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 UNIQUE(name, version)
             );
             {create_table} files (
                 path VARCHAR(4096) NOT NULL PRIMARY KEY,
                 mime VARCHAR(100) NOT NULL,
                 date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 content BYTEA
             );
             {create_table} config (
                 name VARCHAR(100) NOT NULL PRIMARY KEY,
                 value JSON NOT NULL
             );
             CREATE INDEX ON releases (release_time DESC);
             CREATE INDEX content_idx ON crates USING gin(content);",
            // downgrade query
            "DROP TABLE authors, author_rels, keyword_rels, keywords, owner_rels,
                        owners, releases, crates, builds, queue, files, config;"
        ),
        migration!(
            context.clone(),
            // version
            2,
            // description
            "Added priority column to build queue",
            // upgrade query
            "ALTER TABLE queue ADD COLUMN priority INT DEFAULT 0;",
            // downgrade query
            "ALTER TABLE queue DROP COLUMN priority;"
        ),
        migration!(
            context.clone(),
            // version
            3,
            // description
            "Added sandbox_overrides table",
            // upgrade query
            "{create_table} sandbox_overrides (
                 crate_name VARCHAR NOT NULL PRIMARY KEY,
                 max_memory_bytes INTEGER,
                 timeout_seconds INTEGER
             );",
            // downgrade query
            "DROP TABLE sandbox_overrides;"
        ),
        migration!(
            context.clone(),
            4,
            "Make more fields not null",
            "ALTER TABLE releases ALTER COLUMN release_time SET NOT NULL,
                                  ALTER COLUMN yanked SET NOT NULL,
                                  ALTER COLUMN downloads SET NOT NULL",
            "ALTER TABLE releases ALTER COLUMN release_time DROP NOT NULL,
                                  ALTER COLUMN yanked DROP NOT NULL,
                                  ALTER COLUMN downloads DROP NOT NULL"
        ),
        migration!(
            context.clone(),
            // version
            5,
            // description
            "Make target_name non-nullable",
            // upgrade query
            "ALTER TABLE releases ALTER COLUMN target_name SET NOT NULL",
            // downgrade query
            "ALTER TABLE releases ALTER COLUMN target_name DROP NOT NULL",
        ),
    ];

    for migration in migrations {
        migrator.register(migration);
    }

    if let Some(version) = version {
        if version > migrator.current_version()?.unwrap_or(0) {
            migrator.up(Some(version))?;
        } else {
            migrator.down(Some(version))?;
        }
    } else {
        migrator.up(version)?;
    }

    Ok(())
}
<commit_msg>Don't use unnecessary Rc<commit_after>//! Database migrations

use error::Result as CratesfyiResult;
use postgres::{Connection, transaction::Transaction, Error as PostgresError};
use schemamama::{Migration, Migrator, Version};
use schemamama_postgres::{PostgresAdapter, PostgresMigration};

#[derive(Copy, Clone)]
enum ApplyMode {
    Permanent,
    Temporary,
}

#[derive(Copy, Clone)]
struct MigrationContext {
    apply_mode: ApplyMode,
}

impl MigrationContext {
    fn format_query(&self, query: &str) -> String {
        query.replace("{create_table}", match self.apply_mode {
            ApplyMode::Permanent => "CREATE TABLE",
            ApplyMode::Temporary => "CREATE TEMPORARY TABLE",
        })
    }
}

/// Creates a new PostgresMigration from upgrade and downgrade queries.
/// Downgrade query should return database to previous state.
///
/// Example:
///
/// ```
/// let my_migration = migration!(100,
///                               "Create test table",
///                               "{create_table} test ( id SERIAL);",
///                               "DROP TABLE test;");
/// ```
macro_rules! migration {
    ($context:expr, $version:expr, $description:expr, $up:expr, $down:expr $(,)?) => {{
        struct Amigration {
            ctx: MigrationContext,
        };
        impl Migration for Amigration {
            fn version(&self) -> Version {
                $version
            }
            fn description(&self) -> String {
                $description.to_owned()
            }
        }
        impl PostgresMigration for Amigration {
            fn up(&self, transaction: &Transaction) -> Result<(), PostgresError> {
                info!("Applying migration {}: {}", self.version(), self.description());
                transaction.batch_execute(&self.ctx.format_query($up)).map(|_| ())
            }
            fn down(&self, transaction: &Transaction) -> Result<(), PostgresError> {
                info!("Removing migration {}: {}", self.version(), self.description());
                transaction.batch_execute(&self.ctx.format_query($down)).map(|_| ())
            }
        }
        Box::new(Amigration { ctx: $context })
    }};
}

pub fn migrate(version: Option<Version>, conn: &Connection) -> CratesfyiResult<()> {
    migrate_inner(version, conn, ApplyMode::Permanent)
}

pub fn migrate_temporary(version: Option<Version>, conn: &Connection) -> CratesfyiResult<()> {
    migrate_inner(version, conn, ApplyMode::Temporary)
}

fn migrate_inner(version: Option<Version>, conn: &Connection, apply_mode: ApplyMode) -> CratesfyiResult<()> {
    let context = MigrationContext { apply_mode };

    conn.execute(
        &context.format_query(
            "{create_table} IF NOT EXISTS database_versions (version BIGINT PRIMARY KEY);"
        ),
        &[],
    )?;
    let adapter = PostgresAdapter::with_metadata_table(conn, "database_versions");

    let mut migrator = Migrator::new(adapter);

    let migrations: Vec<Box<dyn PostgresMigration>> = vec![
        migration!(
            context,
            // version
            1,
            // description
            "Initial database schema",
            // upgrade query
            "{create_table} crates (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255) UNIQUE NOT NULL,
                 latest_version_id INT DEFAULT 0,
                 versions JSON DEFAULT '[]',
                 downloads_total INT DEFAULT 0,
                 github_description VARCHAR(1024),
                 github_stars INT DEFAULT 0,
                 github_forks INT DEFAULT 0,
                 github_issues INT DEFAULT 0,
                 github_last_commit TIMESTAMP,
                 github_last_update TIMESTAMP,
                 content tsvector
             );
             {create_table} releases (
                 id SERIAL PRIMARY KEY,
                 crate_id INT NOT NULL REFERENCES crates(id),
                 version VARCHAR(100),
                 release_time TIMESTAMP,
                 dependencies JSON,
                 target_name VARCHAR(255),
                 yanked BOOL DEFAULT FALSE,
                 is_library BOOL DEFAULT TRUE,
                 build_status BOOL DEFAULT FALSE,
                 rustdoc_status BOOL DEFAULT FALSE,
                 test_status BOOL DEFAULT FALSE,
                 license VARCHAR(100),
                 repository_url VARCHAR(255),
                 homepage_url VARCHAR(255),
                 documentation_url VARCHAR(255),
                 description VARCHAR(1024),
                 description_long VARCHAR(51200),
                 readme VARCHAR(51200),
                 authors JSON,
                 keywords JSON,
                 have_examples BOOL DEFAULT FALSE,
                 downloads INT DEFAULT 0,
                 files JSON,
                 doc_targets JSON DEFAULT '[]',
                 doc_rustc_version VARCHAR(100) NOT NULL,
                 default_target VARCHAR(100),
                 UNIQUE (crate_id, version)
             );
             {create_table} authors (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255),
                 email VARCHAR(255),
                 slug VARCHAR(255) UNIQUE NOT NULL
             );
             {create_table} author_rels (
                 rid INT REFERENCES releases(id),
                 aid INT REFERENCES authors(id),
                 UNIQUE(rid, aid)
             );
             {create_table} keywords (
                 id SERIAL PRIMARY KEY,
                 name VARCHAR(255),
                 slug VARCHAR(255) NOT NULL UNIQUE
             );
             {create_table} keyword_rels (
                 rid INT REFERENCES releases(id),
                 kid INT REFERENCES keywords(id),
                 UNIQUE(rid, kid)
             );
             {create_table} owners (
                 id SERIAL PRIMARY KEY,
                 login VARCHAR(255) NOT NULL UNIQUE,
                 avatar VARCHAR(255),
                 name VARCHAR(255),
                 email VARCHAR(255)
             );
             {create_table} owner_rels (
                 cid INT REFERENCES releases(id),
                 oid INT REFERENCES owners(id),
                 UNIQUE(cid, oid)
             );
             {create_table} builds (
                 id SERIAL,
                 rid INT NOT NULL REFERENCES releases(id),
                 rustc_version VARCHAR(100) NOT NULL,
                 cratesfyi_version VARCHAR(100) NOT NULL,
                 build_status BOOL NOT NULL,
                 build_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 output TEXT
             );
             {create_table} queue (
                 id SERIAL,
                 name VARCHAR(255),
                 version VARCHAR(100),
                 attempt INT DEFAULT 0,
                 date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 UNIQUE(name, version)
             );
             {create_table} files (
                 path VARCHAR(4096) NOT NULL PRIMARY KEY,
                 mime VARCHAR(100) NOT NULL,
                 date_added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                 content BYTEA
             );
             {create_table} config (
                 name VARCHAR(100) NOT NULL PRIMARY KEY,
                 value JSON NOT NULL
             );
             CREATE INDEX ON releases (release_time DESC);
             CREATE INDEX content_idx ON crates USING gin(content);",
            // downgrade query
            "DROP TABLE authors, author_rels, keyword_rels, keywords, owner_rels,
                        owners, releases, crates, builds, queue, files, config;"
        ),
        migration!(
            context,
            // version
            2,
            // description
            "Added priority column to build queue",
            // upgrade query
            "ALTER TABLE queue ADD COLUMN priority INT DEFAULT 0;",
            // downgrade query
            "ALTER TABLE queue DROP COLUMN priority;"
        ),
        migration!(
            context,
            // version
            3,
            // description
            "Added sandbox_overrides table",
            // upgrade query
            "{create_table} sandbox_overrides (
                 crate_name VARCHAR NOT NULL PRIMARY KEY,
                 max_memory_bytes INTEGER,
                 timeout_seconds INTEGER
             );",
            // downgrade query
            "DROP TABLE sandbox_overrides;"
        ),
        migration!(
            context,
            4,
            "Make more fields not null",
            "ALTER TABLE releases ALTER COLUMN release_time SET NOT NULL,
                                  ALTER COLUMN yanked SET NOT NULL,
                                  ALTER COLUMN downloads SET NOT NULL",
            "ALTER TABLE releases ALTER COLUMN release_time DROP NOT NULL,
                                  ALTER COLUMN yanked DROP NOT NULL,
                                  ALTER COLUMN downloads DROP NOT NULL"
        ),
        migration!(
            context,
            // version
            5,
            // description
            "Make target_name non-nullable",
            // upgrade query
            "ALTER TABLE releases ALTER COLUMN target_name SET NOT NULL",
            // downgrade query
            "ALTER TABLE releases ALTER COLUMN target_name DROP NOT NULL",
        ),
    ];

    for migration in migrations {
        migrator.register(migration);
    }

    if let Some(version) = version {
        if version > migrator.current_version()?.unwrap_or(0) {
            migrator.up(Some(version))?;
        } else {
            migrator.down(Some(version))?;
        }
    } else {
        migrator.up(version)?;
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Interface for symbol table<commit_after>

pub trait StaticSymbolTable<'a>
{
	fn lookup_name(name: &str) -> Vec<Symbol<'a>>;
	fn lookup_namespace(namespace: &str) -> Vec<Symbol<'a>>;
	fn lookup_variable(namespace: &str, name: &str) -> Vec<Symbol<'a>>;

	fn add(symbol: Symbol<'a>);
}

pub enum SymbolLocation<'a>
{
	Register { name: &'a str },
	Memory { location: Location<'a> },
	Structured
}

pub enum SymbolClass
{
	Variable,
	Function,
	/// Includes class, enum, and interface
	Structure { subtype: String },
}

pub struct Symbol<'a>
{
	/// Namespace of this symbol, without the final "." or the name of this symbol
	pub namespace: &'a str,

	/// Identifier for the symbol (e.g. name of variable, function, class, etc. without it's namespace)
	pub name: &'a str,

	/// What this symbol represents (class, enum, variable, function, etc)
	pub symbol_class: SymbolClass,

	/// Type can be the return type of a method, the type of a variable, or None if it has no type (for instance if it is a class, enum, etc).
	pub symbol_type: Option<&'a str>,

	/// Memory location of this symbol. Methods will always map to a SymbolLocation::Memory label with a 0 offset
	pub location: SymbolLocation<'a>,
}

pub struct Location<'a>
{
	/// Label marking the base address where the symbol is stored
	pub label_name: &'a str,

	/// Offset from the base address to access the symbol. Methods will always have an offset of 0
	pub offset: u16,
}
<|endoftext|>


<commit_before>use utils::json::{JsonEncodable, JsonDecodable};

#[derive(Serialize, Deserialize, Clone)]
pub struct MyDidInfo {
    pub did: Option<String>,
    pub seed: Option<String>,
    pub crypto_type: Option<String>
}

impl MyDidInfo {
    pub fn new(did: Option<String>, seed: Option<String>, crypto_type: Option<String>) -> MyDidInfo {
        MyDidInfo {
            did,
            seed,
            crypto_type
        }
    }
}

impl JsonEncodable for MyDidInfo {}

impl<'a> JsonDecodable<'a> for MyDidInfo {}

#[derive(Serialize, Deserialize)]
pub struct MyKyesInfo {
    pub seed: Option<String>,
    pub crypto_type: Option<String>
}

impl MyKyesInfo {
    pub fn new(seed: Option<String>, crypto_type: Option<String>) -> MyKyesInfo {
        MyKyesInfo {
            seed: seed,
            crypto_type: crypto_type
        }
    }
}

impl JsonEncodable for MyKyesInfo {}

impl<'a> JsonDecodable<'a> for MyKyesInfo {}

#[derive(Serialize, Deserialize, Clone)]
pub struct MyDid {
    pub did: String,
    pub crypto_type: String,
    pub pk: String,
    pub sk: String,
    pub verkey: String,
    pub signkey: String
}

impl MyDid {
    pub fn new(did: String, crypto_type: String, pk: String, sk: String, verkey: String, signkey: String) -> MyDid {
        MyDid {
            did,
            crypto_type,
            pk,
            sk,
            verkey,
            signkey
        }
    }
}

impl JsonEncodable for MyDid {}

impl<'a> JsonDecodable<'a> for MyDid {}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TheirDidInfo {
    pub did: String,
    pub crypto_type: Option<String>,
    pub verkey: Option<String>
}

impl TheirDidInfo {
    pub fn new(did: String, crypto_type: Option<String>, verkey: Option<String>) -> TheirDidInfo {
        TheirDidInfo {
            did,
            crypto_type,
            verkey
        }
    }
}

impl JsonEncodable for TheirDidInfo {}

impl<'a> JsonDecodable<'a> for TheirDidInfo {}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TheirDid {
    pub did: String,
    pub crypto_type: String,
    pub verkey: Option<String>,
    pub pk: Option<String>
}

impl TheirDid {
    pub fn new(did: String, crypto_type: String, verkey: Option<String>, pk: Option<String>) -> TheirDid {
        TheirDid {
            did,
            crypto_type,
            verkey,
            pk
        }
    }
}

impl JsonEncodable for TheirDid {}

impl<'a> JsonDecodable<'a> for TheirDid {}<commit_msg>* Avoid structs shortage to be comatible with older rust versions<commit_after>use utils::json::{JsonEncodable, JsonDecodable};

#[derive(Serialize, Deserialize, Clone)]
pub struct MyDidInfo {
    pub did: Option<String>,
    pub seed: Option<String>,
    pub crypto_type: Option<String>
}

impl MyDidInfo {
    pub fn new(did: Option<String>, seed: Option<String>, crypto_type: Option<String>) -> MyDidInfo {
        MyDidInfo {
            did,
            seed,
            crypto_type
        }
    }
}

impl JsonEncodable for MyDidInfo {}

impl<'a> JsonDecodable<'a> for MyDidInfo {}

#[derive(Serialize, Deserialize)]
pub struct MyKyesInfo {
    pub seed: Option<String>,
    pub crypto_type: Option<String>
}

impl MyKyesInfo {
    pub fn new(seed: Option<String>, crypto_type: Option<String>) -> MyKyesInfo {
        MyKyesInfo {
            seed: seed,
            crypto_type: crypto_type
        }
    }
}

impl JsonEncodable for MyKyesInfo {}

impl<'a> JsonDecodable<'a> for MyKyesInfo {}

#[derive(Serialize, Deserialize, Clone)]
pub struct MyDid {
    pub did: String,
    pub crypto_type: String,
    pub pk: String,
    pub sk: String,
    pub verkey: String,
    pub signkey: String
}

impl MyDid {
    pub fn new(did: String, crypto_type: String, pk: String, sk: String, verkey: String, signkey: String) -> MyDid {
        MyDid {
            did: did,
            crypto_type: crypto_type,
            pk: pk,
            sk: sk,
            verkey: verkey,
            signkey: signkey
        }
    }
}

impl JsonEncodable for MyDid {}

impl<'a> JsonDecodable<'a> for MyDid {}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TheirDidInfo {
    pub did: String,
    pub crypto_type: Option<String>,
    pub verkey: Option<String>
}

impl TheirDidInfo {
    pub fn new(did: String, crypto_type: Option<String>, verkey: Option<String>) -> TheirDidInfo {
        TheirDidInfo {
            did: did,
            crypto_type: crypto_type,
            verkey: verkey
        }
    }
}

impl JsonEncodable for TheirDidInfo {}

impl<'a> JsonDecodable<'a> for TheirDidInfo {}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TheirDid {
    pub did: String,
    pub crypto_type: String,
    pub verkey: Option<String>,
    pub pk: Option<String>
}

impl TheirDid {
    pub fn new(did: String, crypto_type: String, verkey: Option<String>, pk: Option<String>) -> TheirDid {
        TheirDid {
            did: did,
            crypto_type: crypto_type,
            verkey: verkey,
            pk: pk
        }
    }
}

impl JsonEncodable for TheirDid {}

impl<'a> JsonDecodable<'a> for TheirDid {}<|endoftext|>


<commit_before><commit_msg>strings<commit_after>use std::mem;
use std::string;

fn main() {

    let str: & 'static str = "This is a simple static string with long text in it";
    let string = "This is a simple static string with long text in it";

    println!("Size of str is: {}", mem::size_of_val(str)); // always 16 with & and actual 51
    println!("Size of str is: {}", mem::size_of_val(string)); // always 16 with & and actual 51

}<|endoftext|>


<commit_before><commit_msg>Rollup merge of #60243 - davidtwco:issue-53249, r=cramertj<commit_after>// compile-pass
// edition:2018

#![feature(arbitrary_self_types, async_await, await_macro)]

use std::task::{self, Poll};
use std::future::Future;
use std::marker::Unpin;
use std::pin::Pin;

// This is a regression test for a ICE/unbounded recursion issue relating to async-await.

#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct Lazy<F> {
    f: Option<F>
}

impl<F> Unpin for Lazy<F> {}

pub fn lazy<F, R>(f: F) -> Lazy<F>
    where F: FnOnce(&mut task::Context) -> R,
{
    Lazy { f: Some(f) }
}

impl<R, F> Future for Lazy<F>
    where F: FnOnce(&mut task::Context) -> R,
{
    type Output = R;

    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<R> {
        Poll::Ready((self.f.take().unwrap())(cx))
    }
}

async fn __receive<WantFn, Fut>(want: WantFn) -> ()
    where Fut: Future<Output = ()>, WantFn: Fn(&Box<Send + 'static>) -> Fut,
{
    await!(lazy(|_| ()));
}

pub fn basic_spawn_receive() {
    async { await!(__receive(|_| async { () })) };
}

fn main() {}
<|endoftext|>


<commit_before>// Copyright 2015 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.

//! Networking primitives for TCP/UDP communication.

#![stable(feature = "rust1", since = "1.0.0")]

use prelude::v1::*;

use io::{self, Error, ErrorKind};
use sys_common::net as net_imp;

pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
pub use self::parser::AddrParseError;

mod ip;
mod addr;
mod tcp;
mod udp;
mod parser;
#[cfg(test)] mod test;

/// Possible values which can be passed to the `shutdown` method of `TcpStream`
/// and `UdpSocket`.
#[derive(Copy, Clone, PartialEq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Shutdown {
    /// Indicates that the reading portion of this stream/socket should be shut
    /// down. All currently blocked and future reads will return `Ok(0)`.
    #[stable(feature = "rust1", since = "1.0.0")]
    Read,
    /// Indicates that the writing portion of this stream/socket should be shut
    /// down. All currently blocked and future writes will return an error.
    #[stable(feature = "rust1", since = "1.0.0")]
    Write,
    /// Shut down both the reading and writing portions of this stream.
    ///
    /// See `Shutdown::Read` and `Shutdown::Write` for more information.
    #[stable(feature = "rust1", since = "1.0.0")]
    Both,
}

#[doc(hidden)]
trait NetInt {
    fn from_be(i: Self) -> Self;
    fn to_be(&self) -> Self;
}
macro_rules! doit {
    ($($t:ident)*) => ($(impl NetInt for $t {
        fn from_be(i: Self) -> Self { <$t>::from_be(i) }
        fn to_be(&self) -> Self { <$t>::to_be(*self) }
    })*)
}
doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }

fn hton<I: NetInt>(i: I) -> I { i.to_be() }
fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) }

fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
    where F: FnMut(&SocketAddr) -> io::Result<T>
{
    let mut last_err = None;
    for addr in try!(addr.to_socket_addrs()) {
        match f(&addr) {
            Ok(l) => return Ok(l),
            Err(e) => last_err = Some(e),
        }
    }
    Err(last_err.unwrap_or_else(|| {
        Error::new(ErrorKind::InvalidInput,
                   "could not resolve to any addresses")
    }))
}

/// An iterator over `SocketAddr` values returned from a host lookup operation.
#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
pub struct LookupHost(net_imp::LookupHost);

#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
impl Iterator for LookupHost {
    type Item = io::Result<SocketAddr>;
    fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() }
}

/// Resolve the host specified by `host` as a number of `SocketAddr` instances.
///
/// This method may perform a DNS query to resolve `host` and may also inspect
/// system configuration to resolve the specified hostname.
///
/// # Examples
///
/// ```no_run
/// # #![feature(lookup_host)]
/// use std::net;
///
/// # fn foo() -> std::io::Result<()> {
/// for host in try!(net::lookup_host("rust-lang.org")) {
///     println!("found address: {}", try!(host));
/// }
/// # Ok(())
/// # }
/// ```
#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
    net_imp::lookup_host(host).map(LookupHost)
}

/// Resolve the given address to a hostname.
///
/// This function may perform a DNS query to resolve `addr` and may also inspect
/// system configuration to resolve the specified address. If the address
/// cannot be resolved, it is returned in string format.
#[unstable(feature = "lookup_addr", reason = "recent addition")]
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
    net_imp::lookup_addr(addr)
}
<commit_msg>Remove mention of `UdpSocket` in `Shutdown` docs.<commit_after>// Copyright 2015 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.

//! Networking primitives for TCP/UDP communication.

#![stable(feature = "rust1", since = "1.0.0")]

use prelude::v1::*;

use io::{self, Error, ErrorKind};
use sys_common::net as net_imp;

pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
pub use self::parser::AddrParseError;

mod ip;
mod addr;
mod tcp;
mod udp;
mod parser;
#[cfg(test)] mod test;

/// Possible values which can be passed to the `shutdown` method of `TcpStream`.
#[derive(Copy, Clone, PartialEq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Shutdown {
    /// Indicates that the reading portion of this stream/socket should be shut
    /// down. All currently blocked and future reads will return `Ok(0)`.
    #[stable(feature = "rust1", since = "1.0.0")]
    Read,
    /// Indicates that the writing portion of this stream/socket should be shut
    /// down. All currently blocked and future writes will return an error.
    #[stable(feature = "rust1", since = "1.0.0")]
    Write,
    /// Shut down both the reading and writing portions of this stream.
    ///
    /// See `Shutdown::Read` and `Shutdown::Write` for more information.
    #[stable(feature = "rust1", since = "1.0.0")]
    Both,
}

#[doc(hidden)]
trait NetInt {
    fn from_be(i: Self) -> Self;
    fn to_be(&self) -> Self;
}
macro_rules! doit {
    ($($t:ident)*) => ($(impl NetInt for $t {
        fn from_be(i: Self) -> Self { <$t>::from_be(i) }
        fn to_be(&self) -> Self { <$t>::to_be(*self) }
    })*)
}
doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }

fn hton<I: NetInt>(i: I) -> I { i.to_be() }
fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) }

fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
    where F: FnMut(&SocketAddr) -> io::Result<T>
{
    let mut last_err = None;
    for addr in try!(addr.to_socket_addrs()) {
        match f(&addr) {
            Ok(l) => return Ok(l),
            Err(e) => last_err = Some(e),
        }
    }
    Err(last_err.unwrap_or_else(|| {
        Error::new(ErrorKind::InvalidInput,
                   "could not resolve to any addresses")
    }))
}

/// An iterator over `SocketAddr` values returned from a host lookup operation.
#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
pub struct LookupHost(net_imp::LookupHost);

#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
impl Iterator for LookupHost {
    type Item = io::Result<SocketAddr>;
    fn next(&mut self) -> Option<io::Result<SocketAddr>> { self.0.next() }
}

/// Resolve the host specified by `host` as a number of `SocketAddr` instances.
///
/// This method may perform a DNS query to resolve `host` and may also inspect
/// system configuration to resolve the specified hostname.
///
/// # Examples
///
/// ```no_run
/// # #![feature(lookup_host)]
/// use std::net;
///
/// # fn foo() -> std::io::Result<()> {
/// for host in try!(net::lookup_host("rust-lang.org")) {
///     println!("found address: {}", try!(host));
/// }
/// # Ok(())
/// # }
/// ```
#[unstable(feature = "lookup_host", reason = "unsure about the returned \
                                              iterator and returning socket \
                                              addresses")]
pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
    net_imp::lookup_host(host).map(LookupHost)
}

/// Resolve the given address to a hostname.
///
/// This function may perform a DNS query to resolve `addr` and may also inspect
/// system configuration to resolve the specified address. If the address
/// cannot be resolved, it is returned in string format.
#[unstable(feature = "lookup_addr", reason = "recent addition")]
pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
    net_imp::lookup_addr(addr)
}
<|endoftext|>


<commit_before><commit_msg>Start fake std<commit_after>extern crate core;
extern crate collections;

pub use core::*;
pub use collections;

/*
pub mod prelude {
    pub use ops::{ Drop, Fn, FnMut, FnOnce };
    pub use cmp::{ PartialEq, PartialOrd, Eq, Ord };
    pub use convert::{ AsRef, AsMut, Into, From };
    pub use option::Option::{ self, Some, None };
    pub use option::Result::{ self, Some, None };
    pub use collections::string::{ String, ToString };
    pub use Vec;
    // TODO: Box
    pub use iter::{ Iterator, Extend, IntoIterator, DoubleEndedIterator, ExactSizeIterator };
    pub use mem::drop;
    pub use clone::Clone;
    pub use default::Default;
}
*/

pub mod io;
pub mod fs;

<|endoftext|>


<commit_before>use column::{Alignment, Column, Cell};
use xattr::Attribute;
use dir::Dir;
use file::{File, GREY};
use options::{Columns, FileFilter, RecurseOptions};
use users::OSUsers;

use locale;
use ansi_term::Style::Plain;

#[derive(PartialEq, Debug, Copy)]
pub struct Details {
    pub columns: Columns,
    pub header: bool,
    pub recurse: Option<(RecurseOptions, FileFilter)>,
    pub xattr: bool,
}

impl Details {
    pub fn view(&self, dir: Option<&Dir>, files: &[File]) {
        // The output gets formatted into columns, which looks nicer. To
        // do this, we have to write the results into a table, instead of
        // displaying each file immediately, then calculating the maximum
        // width of each column based on the length of the results and
        // padding the fields during output.

        // Almost all the heavy lifting is done in a Table object, which
        // automatically calculates the width of each column and the
        // appropriate padding.
        let mut table = Table::with_columns(self.columns.for_dir(dir));
        if self.header { table.add_header() }

        self.add_files_to_table(&mut table, files, 0);
        table.print_table(self.xattr, self.recurse.is_some());
    }

    /// Adds files to the table - recursively, if the `recurse` option
    /// is present.
    fn add_files_to_table(&self, table: &mut Table, src: &[File], depth: usize) {
        for (index, file) in src.iter().enumerate() {
            table.add_row(file, depth, index == src.len() - 1);

            if let Some((r, filter)) = self.recurse {
                if r.tree == false || r.is_too_deep(depth) {
                    continue;
                }

                if let Some(ref dir) = file.this {
                    let mut files = dir.files(true);
                    filter.transform_files(&mut files);
                    self.add_files_to_table(table, &files, depth + 1);
                }
            }
        }
    }
}

struct Row {
    pub depth: usize,
    pub cells: Vec<Cell>,
    pub name: String,
    pub last: bool,
    pub attrs: Vec<Attribute>,
    pub children: bool,
}

type ColumnInfo = (usize, Alignment);

struct Table {
    columns: Vec<Column>,
    users: OSUsers,
    locale: UserLocale,
    rows: Vec<Row>,
}

impl Table {
    fn with_columns(columns: Vec<Column>) -> Table {
        Table {
            columns: columns,
            users: OSUsers::empty_cache(),
            locale: UserLocale::new(),
            rows: Vec::new(),
        }
    }

    fn add_header(&mut self) {
        let row = Row {
            depth: 0,
            cells: self.columns.iter().map(|c| Cell::paint(Plain.underline(), c.header())).collect(),
            name: Plain.underline().paint("Name").to_string(),
            last: false,
            attrs: Vec::new(),
            children: false,
        };

        self.rows.push(row);
    }

    fn cells_for_file(&mut self, file: &File) -> Vec<Cell> {
        self.columns.clone().iter()
                    .map(|c| file.display(c, &mut self.users, &self.locale))
                    .collect()
    }

    fn add_row(&mut self, file: &File, depth: usize, last: bool) {
        let row = Row {
            depth: depth,
            cells: self.cells_for_file(file),
            name: file.file_name_view(),
            last: last,
            attrs: file.xattrs.clone(),
            children: file.this.is_some(),
        };

        self.rows.push(row)
    }

    fn print_table(self, xattr: bool, show_children: bool) {
        let mut stack = Vec::new();

        let column_widths: Vec<usize> = range(0, self.columns.len())
            .map(|n| self.rows.iter().map(|row| row.cells[n].length).max().unwrap_or(0))
            .collect();

        for row in self.rows.iter() {
            for (n, width) in column_widths.iter().enumerate() {
                let padding = width - row.cells[n].length;
                print!("{} ", self.columns[n].alignment().pad_string(&row.cells[n].text, padding));
            }

            if show_children {
                stack.resize(row.depth + 1, TreePart::Edge);
                stack[row.depth] = if row.last { TreePart::Corner } else { TreePart::Edge };

                for i in 1 .. row.depth + 1 {
                    print!("{}", GREY.paint(stack[i].ascii_art()));
                }

                if row.children {
                    stack[row.depth] = if row.last { TreePart::Blank } else { TreePart::Line };
                }

                if row.depth != 0 {
                    print!(" ");
                }
            }

            print!("{}\n", row.name);

            if xattr {
                let width = row.attrs.iter().map(|a| a.name().len()).max().unwrap_or(0);
                for attr in row.attrs.iter() {
                    let name = attr.name();
                    println!("{}\t{}",
                        Alignment::Left.pad_string(name, width - name.len()),
                        attr.size()
                    )
                }
            }
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
enum TreePart {
    Edge,
    Corner,
    Blank,
    Line,
}

impl TreePart {
    fn ascii_art(&self) -> &'static str {
        match *self {
            TreePart::Edge   => "├──",
            TreePart::Line   => "│  ",
            TreePart::Corner => "└──",
            TreePart::Blank  => "   ",
        }
    }
}

pub struct UserLocale {
    pub time: locale::Time,
    pub numeric: locale::Numeric,
}

impl UserLocale {
    pub fn new() -> UserLocale {
        UserLocale {
            time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()),
            numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()),
        }
    }

    pub fn default() -> UserLocale {
        UserLocale {
            time: locale::Time::english(),
            numeric: locale::Numeric::english(),
        }
    }
}
<commit_msg>The Row struct's fields don't need to be pub<commit_after>use column::{Alignment, Column, Cell};
use xattr::Attribute;
use dir::Dir;
use file::{File, GREY};
use options::{Columns, FileFilter, RecurseOptions};
use users::OSUsers;

use locale;
use ansi_term::Style::Plain;

#[derive(PartialEq, Debug, Copy)]
pub struct Details {
    pub columns: Columns,
    pub header: bool,
    pub recurse: Option<(RecurseOptions, FileFilter)>,
    pub xattr: bool,
}

impl Details {
    pub fn view(&self, dir: Option<&Dir>, files: &[File]) {
        // The output gets formatted into columns, which looks nicer. To
        // do this, we have to write the results into a table, instead of
        // displaying each file immediately, then calculating the maximum
        // width of each column based on the length of the results and
        // padding the fields during output.

        // Almost all the heavy lifting is done in a Table object, which
        // automatically calculates the width of each column and the
        // appropriate padding.
        let mut table = Table::with_columns(self.columns.for_dir(dir));
        if self.header { table.add_header() }

        self.add_files_to_table(&mut table, files, 0);
        table.print_table(self.xattr, self.recurse.is_some());
    }

    /// Adds files to the table - recursively, if the `recurse` option
    /// is present.
    fn add_files_to_table(&self, table: &mut Table, src: &[File], depth: usize) {
        for (index, file) in src.iter().enumerate() {
            table.add_row(file, depth, index == src.len() - 1);

            if let Some((r, filter)) = self.recurse {
                if r.tree == false || r.is_too_deep(depth) {
                    continue;
                }

                if let Some(ref dir) = file.this {
                    let mut files = dir.files(true);
                    filter.transform_files(&mut files);
                    self.add_files_to_table(table, &files, depth + 1);
                }
            }
        }
    }
}

struct Row {
    depth: usize,
    cells: Vec<Cell>,
    name: String,
    last: bool,
    attrs: Vec<Attribute>,
    children: bool,
}

type ColumnInfo = (usize, Alignment);

struct Table {
    columns: Vec<Column>,
    users: OSUsers,
    locale: UserLocale,
    rows: Vec<Row>,
}

impl Table {
    fn with_columns(columns: Vec<Column>) -> Table {
        Table {
            columns: columns,
            users: OSUsers::empty_cache(),
            locale: UserLocale::new(),
            rows: Vec::new(),
        }
    }

    fn add_header(&mut self) {
        let row = Row {
            depth: 0,
            cells: self.columns.iter().map(|c| Cell::paint(Plain.underline(), c.header())).collect(),
            name: Plain.underline().paint("Name").to_string(),
            last: false,
            attrs: Vec::new(),
            children: false,
        };

        self.rows.push(row);
    }

    fn cells_for_file(&mut self, file: &File) -> Vec<Cell> {
        self.columns.clone().iter()
                    .map(|c| file.display(c, &mut self.users, &self.locale))
                    .collect()
    }

    fn add_row(&mut self, file: &File, depth: usize, last: bool) {
        let row = Row {
            depth: depth,
            cells: self.cells_for_file(file),
            name: file.file_name_view(),
            last: last,
            attrs: file.xattrs.clone(),
            children: file.this.is_some(),
        };

        self.rows.push(row)
    }

    fn print_table(self, xattr: bool, show_children: bool) {
        let mut stack = Vec::new();

        let column_widths: Vec<usize> = range(0, self.columns.len())
            .map(|n| self.rows.iter().map(|row| row.cells[n].length).max().unwrap_or(0))
            .collect();

        for row in self.rows.iter() {
            for (n, width) in column_widths.iter().enumerate() {
                let padding = width - row.cells[n].length;
                print!("{} ", self.columns[n].alignment().pad_string(&row.cells[n].text, padding));
            }

            if show_children {
                stack.resize(row.depth + 1, TreePart::Edge);
                stack[row.depth] = if row.last { TreePart::Corner } else { TreePart::Edge };

                for i in 1 .. row.depth + 1 {
                    print!("{}", GREY.paint(stack[i].ascii_art()));
                }

                if row.children {
                    stack[row.depth] = if row.last { TreePart::Blank } else { TreePart::Line };
                }

                if row.depth != 0 {
                    print!(" ");
                }
            }

            print!("{}\n", row.name);

            if xattr {
                let width = row.attrs.iter().map(|a| a.name().len()).max().unwrap_or(0);
                for attr in row.attrs.iter() {
                    let name = attr.name();
                    println!("{}\t{}",
                        Alignment::Left.pad_string(name, width - name.len()),
                        attr.size()
                    )
                }
            }
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
enum TreePart {
    Edge,
    Corner,
    Blank,
    Line,
}

impl TreePart {
    fn ascii_art(&self) -> &'static str {
        match *self {
            TreePart::Edge   => "├──",
            TreePart::Line   => "│  ",
            TreePart::Corner => "└──",
            TreePart::Blank  => "   ",
        }
    }
}

pub struct UserLocale {
    pub time: locale::Time,
    pub numeric: locale::Numeric,
}

impl UserLocale {
    pub fn new() -> UserLocale {
        UserLocale {
            time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()),
            numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()),
        }
    }

    pub fn default() -> UserLocale {
        UserLocale {
            time: locale::Time::english(),
            numeric: locale::Numeric::english(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement lexing of parens and simple numbers.<commit_after><|endoftext|>


<commit_before><commit_msg>Add Arr<L, T> tests.<commit_after><|endoftext|>


<commit_before><commit_msg>Added utils module to export macro<commit_after>#[macro_use]
pub mod log;
<|endoftext|>


<commit_before><commit_msg>Always inline 'force'<commit_after><|endoftext|>


<commit_before><commit_msg>Use of impl trait in an impl as the valoe for an associated type in a dyn<commit_after>// check-pass

#![feature(type_alias_impl_trait)]
#![allow(dead_code)]

type Foo = Box<dyn Iterator<Item = impl Send>>;

fn make_foo() -> Foo {
    Box::new(vec![1, 2, 3].into_iter())
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add rust code for tournament project<commit_after>use std::collections::HashMap;
use std::cmp::Ordering;

#[derive(Debug)]
struct Record {
    win: u32,
    draw: u32,
    lose: u32,
}

impl Record {
    fn new(win: u32, draw: u32, lose: u32) -> Record {
        Record {
            win: win,
            draw: draw,
            lose: lose,
        }
    }

    fn win(&mut self) {
        self.win += 1
    }

    fn draw(&mut self) {
        self.draw += 1;
    }

    fn lose(&mut self) {
        self.lose += 1;
    }

    fn matches(&self) -> u32 {
        self.win + self.draw + self.lose
    }

    fn scores(&self) -> u32 {
        self.win * 3 + self.draw
    }
}

fn add_winer(matches: &mut HashMap<String, Record>, team: &str) {
    matches
        .entry(team.to_string())
        .or_insert_with(|| Record::new(0, 0, 0))
        .win();
}

fn add_loser(matches: &mut HashMap<String, Record>, team: &str) {
    matches
        .entry(team.to_string())
        .or_insert_with(|| Record::new(0, 0, 0))
        .lose();
}

fn add_drawn(matches: &mut HashMap<String, Record>, team: &str) {
    matches
        .entry(team.to_string())
        .or_insert_with(|| Record::new(0, 0, 0))
        .draw();
}

pub fn tally(input: &str) -> String {
    let mut matches = HashMap::new();

    for text in input.lines() {
        let cmd = text.split(';').collect::<Vec<_>>();

        match cmd[2] {
            "win" => {
                add_winer(&mut matches, cmd[0]);
                add_loser(&mut matches, cmd[1])
            }
            "draw" => {
                add_drawn(&mut matches, cmd[0]);
                add_drawn(&mut matches, cmd[1])
            }
            "loss" => {
                add_loser(&mut matches, cmd[0]);
                add_winer(&mut matches, cmd[1])
            }
            _ => (),
        };
    }

    let mut teams = matches.iter().collect::<Vec<_>>();

    teams.sort_by(|&(ateam, ascore), &(bteam, bscore)| {
        let ascores = ascore.scores();
        let bscores = bscore.scores();
        let r = bscores.cmp(&ascores);
        match r {
            Ordering::Equal => ateam.cmp(bteam),
            _ => r,
        }
    });

    let mut result = "Team                           | MP |  W |  D |  L |  P".to_string();
    for (team, score) in teams {
        result.push('\n');

        result += &format!(
            "{:30} | {:2} | {:2} | {:2} | {:2} | {:2}",
            team,
            score.matches(),
            score.win,
            score.draw,
            score.lose,
            score.scores()
        );
    }

    result
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue 953<commit_after>use serde_json::Value;

#[test]
fn test() {
    let x1 = serde_json::from_str::<Value>("18446744073709551615.");
    assert!(x1.is_err());
    let x2 = serde_json::from_str::<Value>("18446744073709551616.");
    assert!(x2.is_err());
}
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;

use clap::ArgMatches;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagrt::runtime::Runtime;
use libimagerror::trace::MapErrTrace;
use libimagutil::debug_result::*;

pub fn retrieve(rt: &Runtime) {
    rt.cli()
        .subcommand_matches("retrieve")
        .map(|scmd| {
            // unwrap() is safe as arg is required
            let id    = scmd.value_of("id").unwrap();
            let path  = PathBuf::from(id);
            let store = Some(rt.store().path().clone());
            let path  = try!(StoreId::new(store, path).map_err_trace_exit(1));
            debug!("path = {:?}", path);

            rt.store()
                .retrieve(path)
                .map(|e| print_entry(rt, scmd, e))
                .map_dbg_str("No entry")
                .map_dbg(|e| format!("{:?}", e))
                .map_err_trace()
        });
}

pub fn print_entry(rt: &Runtime, scmd: &ArgMatches, e: FileLockEntry) {
    if do_print_raw(scmd) {
        debug!("Printing raw content...");
        println!("{}", e.to_str());
    } else if do_filter(scmd) {
        debug!("Filtering...");
        warn!("Filtering via header specs is currently now supported.");
        warn!("Will fail now!");
        unimplemented!()
    } else {
        debug!("Printing structured...");
        if do_print_header(scmd) {
            debug!("Printing header...");
            if do_print_header_as_json(rt.cli()) {
                debug!("Printing header as json...");
                warn!("Printing as JSON currently not supported.");
                warn!("Will fail now!");
                unimplemented!()
            } else {
                debug!("Printing header as TOML...");
                println!("{}", e.get_header())
            }
        }

        if do_print_content(scmd) {
            debug!("Printing content...");
            println!("{}", e.get_content());
        }

    }
}

fn do_print_header(m: &ArgMatches) -> bool {
    m.is_present("header")
}

fn do_print_header_as_json(m: &ArgMatches) -> bool {
    m.is_present("header-json")
}

fn do_print_content(m: &ArgMatches) -> bool {
    m.is_present("content")
}

fn do_print_raw(m: &ArgMatches) -> bool {
    m.is_present("raw")
}

fn do_filter(m: &ArgMatches) -> bool {
    m.subcommand_matches("filter-header").is_some()
}

<commit_msg>Replace uses of try!() macro with "?" operator<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;

use clap::ArgMatches;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagrt::runtime::Runtime;
use libimagerror::trace::MapErrTrace;
use libimagutil::debug_result::*;

pub fn retrieve(rt: &Runtime) {
    rt.cli()
        .subcommand_matches("retrieve")
        .map(|scmd| {
            // unwrap() is safe as arg is required
            let id    = scmd.value_of("id").unwrap();
            let path  = PathBuf::from(id);
            let store = Some(rt.store().path().clone());
            let path  = StoreId::new(store, path).map_err_trace_exit(1)?;
            debug!("path = {:?}", path);

            rt.store()
                .retrieve(path)
                .map(|e| print_entry(rt, scmd, e))
                .map_dbg_str("No entry")
                .map_dbg(|e| format!("{:?}", e))
                .map_err_trace()
        });
}

pub fn print_entry(rt: &Runtime, scmd: &ArgMatches, e: FileLockEntry) {
    if do_print_raw(scmd) {
        debug!("Printing raw content...");
        println!("{}", e.to_str());
    } else if do_filter(scmd) {
        debug!("Filtering...");
        warn!("Filtering via header specs is currently now supported.");
        warn!("Will fail now!");
        unimplemented!()
    } else {
        debug!("Printing structured...");
        if do_print_header(scmd) {
            debug!("Printing header...");
            if do_print_header_as_json(rt.cli()) {
                debug!("Printing header as json...");
                warn!("Printing as JSON currently not supported.");
                warn!("Will fail now!");
                unimplemented!()
            } else {
                debug!("Printing header as TOML...");
                println!("{}", e.get_header())
            }
        }

        if do_print_content(scmd) {
            debug!("Printing content...");
            println!("{}", e.get_content());
        }

    }
}

fn do_print_header(m: &ArgMatches) -> bool {
    m.is_present("header")
}

fn do_print_header_as_json(m: &ArgMatches) -> bool {
    m.is_present("header-json")
}

fn do_print_content(m: &ArgMatches) -> bool {
    m.is_present("content")
}

fn do_print_raw(m: &ArgMatches) -> bool {
    m.is_present("raw")
}

fn do_filter(m: &ArgMatches) -> bool {
    m.subcommand_matches("filter-header").is_some()
}

<|endoftext|>


<commit_before><commit_msg>refactor(filtering): handle variable_declaration<commit_after><|endoftext|>


<commit_before><commit_msg>Regression test.<commit_after>// Copyright 2015 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.

// Ensure that we reject code when a nonlocal exit (`break`,
// `continue`) causes us to pop over a needed assignment.

pub fn main() {
    foo1();
    foo2();
}

pub fn foo1() {
    let x: i32;
    loop { x = break; }
    println!("{}", x); //~ ERROR use of possibly uninitialized variable: `x`
}

pub fn foo2() {
    let x: i32;
    for _ in 0..10 { x = continue; }
    println!("{}", x); //~ ERROR use of possibly uninitialized variable: `x`
}
<|endoftext|>


<commit_before>// Copyright 2013 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.

//! Runtime environment settings

use from_str::FromStr;
use option::{Some, None};
use os;

// Note that these are all accessed without any synchronization.
// They are expected to be initialized once then left alone.

static mut MIN_STACK: uint = 4000000;
static mut DEBUG_BORROW: bool = false;
static mut POISON_ON_FREE: bool = false;

pub fn init() {
    unsafe {
        match os::getenv("RUST_MIN_STACK") {
            Some(s) => match FromStr::from_str(s) {
                Some(i) => MIN_STACK = i,
                None => ()
            },
            None => ()
        }
        match os::getenv("RUST_DEBUG_BORROW") {
            Some(_) => DEBUG_BORROW = true,
            None => ()
        }
        match os::getenv("RUST_POISON_ON_FREE") {
            Some(_) => POISON_ON_FREE = true,
            None => ()
        }
    }
}

pub fn min_stack() -> uint {
    unsafe { MIN_STACK }
}

pub fn debug_borrow() -> bool {
    unsafe { DEBUG_BORROW }
}

pub fn poison_on_free() -> bool {
    unsafe { POISON_ON_FREE }
}
<commit_msg>Decrease the default stack size back to 2MB<commit_after>// Copyright 2013 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.

//! Runtime environment settings

use from_str::FromStr;
use option::{Some, None};
use os;

// Note that these are all accessed without any synchronization.
// They are expected to be initialized once then left alone.

static mut MIN_STACK: uint = 2000000;
static mut DEBUG_BORROW: bool = false;
static mut POISON_ON_FREE: bool = false;

pub fn init() {
    unsafe {
        match os::getenv("RUST_MIN_STACK") {
            Some(s) => match FromStr::from_str(s) {
                Some(i) => MIN_STACK = i,
                None => ()
            },
            None => ()
        }
        match os::getenv("RUST_DEBUG_BORROW") {
            Some(_) => DEBUG_BORROW = true,
            None => ()
        }
        match os::getenv("RUST_POISON_ON_FREE") {
            Some(_) => POISON_ON_FREE = true,
            None => ()
        }
    }
}

pub fn min_stack() -> uint {
    unsafe { MIN_STACK }
}

pub fn debug_borrow() -> bool {
    unsafe { DEBUG_BORROW }
}

pub fn poison_on_free() -> bool {
    unsafe { POISON_ON_FREE }
}
<|endoftext|>


<commit_before><commit_msg>Calculate size of input inside a field<commit_after><|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>

//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.

use std::net::{ToSocketAddrs, SocketAddr};
use std::convert::From;
use std::io::{self, Read, Write, BufWriter};

use hyper::server;
use hyper;
use hyper::http;
use hyper::buffer::BufReader;
use hyper::server::{Request, Response, Handler};
use hyper::header::{Connection, Headers, Expect};
use hyper::version::HttpVersion;
use hyper::net::{NetworkListener, NetworkStream};
use hyper::status::StatusCode;
use hyper::uri::RequestUri::AbsolutePath;
use hyper::error::Error;
use hyper::method::Method;

use net::http::conn::{HttpListener, HttpsListener, Ssl};

use scheduler::Scheduler;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
#[derive(Debug)]
pub struct Server<L = HttpListener> {
    listener: L,
}

impl<L: NetworkListener> Server<L> {
    /// Creates a new server with the provided handler.
    #[inline]
    pub fn new(listener: L) -> Server<L> {
        Server {
            listener: listener,
        }
    }
}

impl Server<HttpListener> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn http<To: ToSocketAddrs>(addr: To) -> hyper::Result<Server<HttpListener>> {
        HttpListener::new(addr).map(Server::new).map_err(From::from)
    }
}

impl<S: Ssl + Clone + Send> Server<HttpsListener<S>> {
    /// Creates a new server that will handle `HttpStream`s over SSL.
    ///
    /// You can use any SSL implementation, as long as implements `hyper::net::Ssl`.
    pub fn https<A: ToSocketAddrs>(addr: A, ssl: S) -> hyper::Result<Server<HttpsListener<S>>> {
        HttpsListener::new(addr, ssl).map(Server::new)
    }
}

impl<L: NetworkListener + Send + 'static> Server<L> {
    /// Binds to a socket.
    pub fn listen<H: Handler + Copy + 'static>(mut self, handler: H) -> hyper::Result<SocketAddr> {
        let socket = try!(self.listener.local_addr());

        Scheduler::spawn(move|| {
            loop {
                let mut stream = self.listener.accept().unwrap();

                Scheduler::spawn(move|| Worker(&handler).handle_connection(&mut stream));
            }
        });

        Ok(socket)
    }
}

struct Worker<'a, H: Handler + 'static>(&'a H);

impl<'a, H: Handler + 'static> Worker<'a, H> {

    fn handle_connection<S>(&self, mut stream: &mut S) where S: NetworkStream + Clone {
        debug!("Incoming stream");
        let addr = match stream.peer_addr() {
            Ok(addr) => addr,
            Err(e) => {
                error!("Peer Name error: {:?}", e);
                return;
            }
        };

        // FIXME: Use Type ascription
        let stream_clone: &mut NetworkStream = &mut stream.clone();
        let rdr = BufReader::new(stream_clone);
        let wrt = BufWriter::new(stream);

        self.keep_alive_loop(rdr, wrt, addr);
        debug!("keep_alive loop ending for {}", addr);
    }

    fn keep_alive_loop<W: Write>(&self, mut rdr: BufReader<&mut NetworkStream>, mut wrt: W, addr: SocketAddr) {
        let mut keep_alive = true;
        while keep_alive {
            let req = match Request::new(&mut rdr, addr) {
                Ok(req) => req,
                Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::ConnectionAborted => {
                    trace!("tcp closed, cancelling keep-alive loop");
                    break;
                }
                Err(Error::Io(e)) => {
                    debug!("ioerror in keepalive loop = {:?}", e);
                    break;
                }
                Err(e) => {
                    //TODO: send a 400 response
                    error!("request error = {:?}", e);
                    break;
                }
            };

            if !self.handle_expect(&req, &mut wrt) {
                break;
            }

            keep_alive = http::should_keep_alive(req.version, &req.headers);
            let version = req.version;
            let mut res_headers = Headers::new();
            if !keep_alive {
                res_headers.set(Connection::close());
            }
            {
                let mut res = Response::new(&mut wrt, &mut res_headers);
                res.version = version;
                self.0.handle(req, res);
            }

            // if the request was keep-alive, we need to check that the server agrees
            // if it wasn't, then the server cannot force it to be true anyways
            if keep_alive {
                keep_alive = http::should_keep_alive(version, &res_headers);
            }

            debug!("keep_alive = {:?} for {}", keep_alive, addr);
        }

    }

    fn handle_expect<W: Write>(&self, req: &Request, wrt: &mut W) -> bool {
         if req.version == HttpVersion::Http11 && req.headers.get() == Some(&Expect::Continue) {
            let status = self.0.check_continue((&req.method, &req.uri, &req.headers));
            match write!(wrt, "{} {}\r\n\r\n", HttpVersion::Http11, status) {
                Ok(..) => (),
                Err(e) => {
                    error!("error writing 100-continue: {:?}", e);
                    return false;
                }
            }

            if status != StatusCode::Continue {
                debug!("non-100 status ({}) for Expect 100 request", status);
                return false;
            }
        }

        true
    }
}

macro_rules! try_return(
    ($e:expr) => {{
        match $e {
            Ok(v) => v,
            Err(e) => { println!("Error: {}", e); return; }
        }
    }}
);
<commit_msg>handler does not need to be copyable<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>

//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.

use std::net::{ToSocketAddrs, SocketAddr};
use std::convert::From;
use std::io::{self, Read, Write, BufWriter};

use hyper::server;
use hyper;
use hyper::http;
use hyper::buffer::BufReader;
use hyper::server::{Request, Response, Handler};
use hyper::header::{Connection, Headers, Expect};
use hyper::version::HttpVersion;
use hyper::net::{NetworkListener, NetworkStream};
use hyper::status::StatusCode;
use hyper::uri::RequestUri::AbsolutePath;
use hyper::error::Error;
use hyper::method::Method;

use net::http::conn::{HttpListener, HttpsListener, Ssl};

use scheduler::Scheduler;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
#[derive(Debug)]
pub struct Server<L = HttpListener> {
    listener: L,
}

impl<L: NetworkListener> Server<L> {
    /// Creates a new server with the provided handler.
    #[inline]
    pub fn new(listener: L) -> Server<L> {
        Server {
            listener: listener,
        }
    }
}

impl Server<HttpListener> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn http<To: ToSocketAddrs>(addr: To) -> hyper::Result<Server<HttpListener>> {
        HttpListener::new(addr).map(Server::new).map_err(From::from)
    }
}

impl<S: Ssl + Clone + Send> Server<HttpsListener<S>> {
    /// Creates a new server that will handle `HttpStream`s over SSL.
    ///
    /// You can use any SSL implementation, as long as implements `hyper::net::Ssl`.
    pub fn https<A: ToSocketAddrs>(addr: A, ssl: S) -> hyper::Result<Server<HttpsListener<S>>> {
        HttpsListener::new(addr, ssl).map(Server::new)
    }
}

impl<L: NetworkListener + Send + 'static> Server<L> {
    /// Binds to a socket.
    pub fn listen<H: Handler + 'static>(mut self, handler: H) -> hyper::Result<SocketAddr> {
        let socket = try!(self.listener.local_addr());

        Scheduler::spawn(move|| {
            use std::sync::Arc;
            use std::ops::Deref;

            let handler = Arc::new(handler);
            loop {
                let mut stream = self.listener.accept().unwrap();

                let handler = handler.clone();
                Scheduler::spawn(move|| Worker(handler.deref()).handle_connection(&mut stream));
            }
        });

        Ok(socket)
    }
}

struct Worker<'a, H: Handler + 'static>(&'a H);

impl<'a, H: Handler + 'static> Worker<'a, H> {

    fn handle_connection<S>(&self, mut stream: &mut S) where S: NetworkStream + Clone {
        debug!("Incoming stream");
        let addr = match stream.peer_addr() {
            Ok(addr) => addr,
            Err(e) => {
                error!("Peer Name error: {:?}", e);
                return;
            }
        };

        // FIXME: Use Type ascription
        let stream_clone: &mut NetworkStream = &mut stream.clone();
        let rdr = BufReader::new(stream_clone);
        let wrt = BufWriter::new(stream);

        self.keep_alive_loop(rdr, wrt, addr);
        debug!("keep_alive loop ending for {}", addr);
    }

    fn keep_alive_loop<W: Write>(&self, mut rdr: BufReader<&mut NetworkStream>, mut wrt: W, addr: SocketAddr) {
        let mut keep_alive = true;
        while keep_alive {
            let req = match Request::new(&mut rdr, addr) {
                Ok(req) => req,
                Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::ConnectionAborted => {
                    trace!("tcp closed, cancelling keep-alive loop");
                    break;
                }
                Err(Error::Io(e)) => {
                    debug!("ioerror in keepalive loop = {:?}", e);
                    break;
                }
                Err(e) => {
                    //TODO: send a 400 response
                    error!("request error = {:?}", e);
                    break;
                }
            };

            if !self.handle_expect(&req, &mut wrt) {
                break;
            }

            keep_alive = http::should_keep_alive(req.version, &req.headers);
            let version = req.version;
            let mut res_headers = Headers::new();
            if !keep_alive {
                res_headers.set(Connection::close());
            }
            {
                let mut res = Response::new(&mut wrt, &mut res_headers);
                res.version = version;
                self.0.handle(req, res);
            }

            // if the request was keep-alive, we need to check that the server agrees
            // if it wasn't, then the server cannot force it to be true anyways
            if keep_alive {
                keep_alive = http::should_keep_alive(version, &res_headers);
            }

            debug!("keep_alive = {:?} for {}", keep_alive, addr);
        }

    }

    fn handle_expect<W: Write>(&self, req: &Request, wrt: &mut W) -> bool {
         if req.version == HttpVersion::Http11 && req.headers.get() == Some(&Expect::Continue) {
            let status = self.0.check_continue((&req.method, &req.uri, &req.headers));
            match write!(wrt, "{} {}\r\n\r\n", HttpVersion::Http11, status) {
                Ok(..) => (),
                Err(e) => {
                    error!("error writing 100-continue: {:?}", e);
                    return false;
                }
            }

            if status != StatusCode::Continue {
                debug!("non-100 status ({}) for Expect 100 request", status);
                return false;
            }
        }

        true
    }
}

macro_rules! try_return(
    ($e:expr) => {{
        match $e {
            Ok(v) => v,
            Err(e) => { println!("Error: {}", e); return; }
        }
    }}
);
<|endoftext|>


<commit_before><commit_msg>Add instrumentation.<commit_after><|endoftext|>


<commit_before><commit_msg>Reminder: Allow multiple commands per Handler<commit_after><|endoftext|>


<commit_before><commit_msg>06 - expressions<commit_after>fn main() {
    let x = 5u;

    let y = {
        let x_squared = x * x;
        let x_cube = x_squared * x;

        // This expression will be assigned to `y`
        x_cube + x_squared + x
    };

    let z = {
        // The semicolon suppresses this expression and `()` is assigned to `z`
        2 * x;
    };

    println!("x is {}", x);
    println!("y is {}", y);
    println!("z is {}", z);
}
<|endoftext|>


<commit_before>use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    static ref SIZE_CAPTURES: Regex = { Regex::new(r"(?i)^([+-])(\d+)(b|[kmgt]i?b?)$").unwrap() };
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SizeFilter {
    Max(u64),
    Min(u64),
}

// SI prefixes (powers of 10)
const KILO: u64 = 1000;
const MEGA: u64 = KILO * 1000;
const GIGA: u64 = MEGA * 1000;
const TERA: u64 = GIGA * 1000;

// Binary prefixes (powers of 2)
const KIBI: u64 = 1024;
const MEBI: u64 = KIBI * 1024;
const GIBI: u64 = MEBI * 1024;
const TEBI: u64 = GIBI * 1024;

impl SizeFilter {
    pub fn from_string(s: &str) -> Option<Self> {
        if !SIZE_CAPTURES.is_match(s) {
            return None;
        }

        let captures = SIZE_CAPTURES.captures(s)?;
        let limit_kind = captures.get(1).map_or("+", |m| m.as_str());
        let quantity = captures
            .get(2)
            .and_then(|v| v.as_str().parse::<u64>().ok())?;

        let multiplier = match &captures.get(3).map_or("b", |m| m.as_str()).to_lowercase()[..] {
            v if v.starts_with("ki") => KIBI,
            v if v.starts_with('k') => KILO,
            v if v.starts_with("mi") => MEBI,
            v if v.starts_with('m') => MEGA,
            v if v.starts_with("gi") => GIBI,
            v if v.starts_with('g') => GIGA,
            v if v.starts_with("ti") => TEBI,
            v if v.starts_with('t') => TERA,
            "b" => 1,
            _ => return None,
        };

        let size = quantity * multiplier;
        Some(match limit_kind {
            "+" => SizeFilter::Min(size),
            _ => SizeFilter::Max(size),
        })
    }

    pub fn is_within(&self, size: u64) -> bool {
        match *self {
            SizeFilter::Max(limit) => size <= limit,
            SizeFilter::Min(limit) => size >= limit,
        }
    }
}

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

    macro_rules! gen_size_filter_parse_test {
        ($($name: ident: $val: expr,)*) => {
            $(
                #[test]
                fn $name() {
                    let (txt, expected) = $val;
                    let actual = SizeFilter::from_string(txt).unwrap();
                    assert_eq!(actual, expected);
                }
            )*
        };
    }

    // Parsing and size conversion tests data. Ensure that each type gets properly interpreted.
    // Call with higher base values to ensure expected multiplication (only need a couple)
    gen_size_filter_parse_test! {
        byte_plus:                ("+1b",     SizeFilter::Min(1)),
        byte_plus_multiplier:     ("+10b",    SizeFilter::Min(10)),
        byte_minus:               ("-1b",     SizeFilter::Max(1)),
        kilo_plus:                ("+1k",     SizeFilter::Min(1000)),
        kilo_plus_suffix:         ("+1kb",    SizeFilter::Min(1000)),
        kilo_minus:               ("-1k",     SizeFilter::Max(1000)),
        kilo_minus_multiplier:    ("-100k",   SizeFilter::Max(100000)),
        kilo_minus_suffix:        ("-1kb",    SizeFilter::Max(1000)),
        kilo_plus_upper:          ("+1K",     SizeFilter::Min(1000)),
        kilo_plus_suffix_upper:   ("+1KB",    SizeFilter::Min(1000)),
        kilo_minus_upper:         ("-1K",     SizeFilter::Max(1000)),
        kilo_minus_suffix_upper:  ("-1Kb",    SizeFilter::Max(1000)),
        kibi_plus:                ("+1ki",    SizeFilter::Min(1024)),
        kibi_plus_multiplier:     ("+10ki",   SizeFilter::Min(10240)),
        kibi_plus_suffix:         ("+1kib",   SizeFilter::Min(1024)),
        kibi_minus:               ("-1ki",    SizeFilter::Max(1024)),
        kibi_minus_multiplier:    ("-100ki",  SizeFilter::Max(102400)),
        kibi_minus_suffix:        ("-1kib",   SizeFilter::Max(1024)),
        kibi_plus_upper:          ("+1KI",    SizeFilter::Min(1024)),
        kibi_plus_suffix_upper:   ("+1KiB",   SizeFilter::Min(1024)),
        kibi_minus_upper:         ("-1Ki",    SizeFilter::Max(1024)),
        kibi_minus_suffix_upper:  ("-1KIB",   SizeFilter::Max(1024)),
        mega_plus:                ("+1m",     SizeFilter::Min(1000000)),
        mega_plus_suffix:         ("+1mb",    SizeFilter::Min(1000000)),
        mega_minus:               ("-1m",     SizeFilter::Max(1000000)),
        mega_minus_suffix:        ("-1mb",    SizeFilter::Max(1000000)),
        mega_plus_upper:          ("+1M",     SizeFilter::Min(1000000)),
        mega_plus_suffix_upper:   ("+1MB",    SizeFilter::Min(1000000)),
        mega_minus_upper:         ("-1M",     SizeFilter::Max(1000000)),
        mega_minus_suffix_upper:  ("-1Mb",    SizeFilter::Max(1000000)),
        mebi_plus:                ("+1mi",    SizeFilter::Min(1048576)),
        mebi_plus_suffix:         ("+1mib",   SizeFilter::Min(1048576)),
        mebi_minus:               ("-1mi",    SizeFilter::Max(1048576)),
        mebi_minus_suffix:        ("-1mib",   SizeFilter::Max(1048576)),
        mebi_plus_upper:          ("+1MI",    SizeFilter::Min(1048576)),
        mebi_plus_suffix_upper:   ("+1MiB",   SizeFilter::Min(1048576)),
        mebi_minus_upper:         ("-1Mi",    SizeFilter::Max(1048576)),
        mebi_minus_suffix_upper:  ("-1MIB",   SizeFilter::Max(1048576)),
        giga_plus:                ("+1g",     SizeFilter::Min(1000000000)),
        giga_plus_suffix:         ("+1gb",    SizeFilter::Min(1000000000)),
        giga_minus:               ("-1g",     SizeFilter::Max(1000000000)),
        giga_minus_suffix:        ("-1gb",    SizeFilter::Max(1000000000)),
        giga_plus_upper:          ("+1G",     SizeFilter::Min(1000000000)),
        giga_plus_suffix_upper:   ("+1GB",    SizeFilter::Min(1000000000)),
        giga_minus_upper:         ("-1G",     SizeFilter::Max(1000000000)),
        giga_minus_suffix_upper:  ("-1Gb",    SizeFilter::Max(1000000000)),
        gibi_plus:                ("+1gi",    SizeFilter::Min(1073741824)),
        gibi_plus_suffix:         ("+1gib",   SizeFilter::Min(1073741824)),
        gibi_minus:               ("-1gi",    SizeFilter::Max(1073741824)),
        gibi_minus_suffix:        ("-1gib",   SizeFilter::Max(1073741824)),
        gibi_plus_upper:          ("+1GI",    SizeFilter::Min(1073741824)),
        gibi_plus_suffix_upper:   ("+1GiB",   SizeFilter::Min(1073741824)),
        gibi_minus_upper:         ("-1Gi",    SizeFilter::Max(1073741824)),
        gibi_minus_suffix_upper:  ("-1GIB",   SizeFilter::Max(1073741824)),
        tera_plus:                ("+1t",     SizeFilter::Min(1000000000000)),
        tera_plus_suffix:         ("+1tb",    SizeFilter::Min(1000000000000)),
        tera_minus:               ("-1t",     SizeFilter::Max(1000000000000)),
        tera_minus_suffix:        ("-1tb",    SizeFilter::Max(1000000000000)),
        tera_plus_upper:          ("+1T",     SizeFilter::Min(1000000000000)),
        tera_plus_suffix_upper:   ("+1TB",    SizeFilter::Min(1000000000000)),
        tera_minus_upper:         ("-1T",     SizeFilter::Max(1000000000000)),
        tera_minus_suffix_upper:  ("-1Tb",    SizeFilter::Max(1000000000000)),
        tebi_plus:                ("+1ti",    SizeFilter::Min(1099511627776)),
        tebi_plus_suffix:         ("+1tib",   SizeFilter::Min(1099511627776)),
        tebi_minus:               ("-1ti",    SizeFilter::Max(1099511627776)),
        tebi_minus_suffix:        ("-1tib",   SizeFilter::Max(1099511627776)),
        tebi_plus_upper:          ("+1TI",    SizeFilter::Min(1099511627776)),
        tebi_plus_suffix_upper:   ("+1TiB",   SizeFilter::Min(1099511627776)),
        tebi_minus_upper:         ("-1Ti",    SizeFilter::Max(1099511627776)),
        tebi_minus_suffix_upper:  ("-1TIB",   SizeFilter::Max(1099511627776)),
    }

    /// Invalid parse testing
    macro_rules! gen_size_filter_failure {
        ($($name:ident: $value:expr,)*) => {
            $(
                #[test]
                fn $name() {
                    let i = SizeFilter::from_string($value);
                    assert!(i.is_none());
                }
            )*
        };
    }

    // Invalid parse data
    gen_size_filter_failure! {
        ensure_missing_symbol_returns_none: "10M",
        ensure_missing_number_returns_none: "+g",
        ensure_missing_unit_returns_none: "+18",
        ensure_bad_format_returns_none_1: "$10M",
        ensure_bad_format_returns_none_2: "badval",
        ensure_bad_format_returns_none_3: "9999",
        ensure_invalid_unit_returns_none_1: "+50a",
        ensure_invalid_unit_returns_none_2: "-10v",
        ensure_invalid_unit_returns_none_3: "+1Mv",
        ensure_bib_format_returns_none: "+1bib",
        ensure_bb_format_returns_none: "+1bb",
    }

    #[test]
    fn is_within_less_than() {
        let f = SizeFilter::from_string("-1k").unwrap();
        assert!(f.is_within(999));
    }

    #[test]
    fn is_within_less_than_equal() {
        let f = SizeFilter::from_string("-1k").unwrap();
        assert!(f.is_within(1000));
    }

    #[test]
    fn is_within_greater_than() {
        let f = SizeFilter::from_string("+1k").unwrap();
        assert!(f.is_within(1001));
    }

    #[test]
    fn is_within_greater_than_equal() {
        let f = SizeFilter::from_string("+1K").unwrap();
        assert!(f.is_within(1000));
    }
}
<commit_msg>Fix "unnecessary braces" warning<commit_after>use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    static ref SIZE_CAPTURES: Regex = Regex::new(r"(?i)^([+-])(\d+)(b|[kmgt]i?b?)$").unwrap();
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SizeFilter {
    Max(u64),
    Min(u64),
}

// SI prefixes (powers of 10)
const KILO: u64 = 1000;
const MEGA: u64 = KILO * 1000;
const GIGA: u64 = MEGA * 1000;
const TERA: u64 = GIGA * 1000;

// Binary prefixes (powers of 2)
const KIBI: u64 = 1024;
const MEBI: u64 = KIBI * 1024;
const GIBI: u64 = MEBI * 1024;
const TEBI: u64 = GIBI * 1024;

impl SizeFilter {
    pub fn from_string(s: &str) -> Option<Self> {
        if !SIZE_CAPTURES.is_match(s) {
            return None;
        }

        let captures = SIZE_CAPTURES.captures(s)?;
        let limit_kind = captures.get(1).map_or("+", |m| m.as_str());
        let quantity = captures
            .get(2)
            .and_then(|v| v.as_str().parse::<u64>().ok())?;

        let multiplier = match &captures.get(3).map_or("b", |m| m.as_str()).to_lowercase()[..] {
            v if v.starts_with("ki") => KIBI,
            v if v.starts_with('k') => KILO,
            v if v.starts_with("mi") => MEBI,
            v if v.starts_with('m') => MEGA,
            v if v.starts_with("gi") => GIBI,
            v if v.starts_with('g') => GIGA,
            v if v.starts_with("ti") => TEBI,
            v if v.starts_with('t') => TERA,
            "b" => 1,
            _ => return None,
        };

        let size = quantity * multiplier;
        Some(match limit_kind {
            "+" => SizeFilter::Min(size),
            _ => SizeFilter::Max(size),
        })
    }

    pub fn is_within(&self, size: u64) -> bool {
        match *self {
            SizeFilter::Max(limit) => size <= limit,
            SizeFilter::Min(limit) => size >= limit,
        }
    }
}

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

    macro_rules! gen_size_filter_parse_test {
        ($($name: ident: $val: expr,)*) => {
            $(
                #[test]
                fn $name() {
                    let (txt, expected) = $val;
                    let actual = SizeFilter::from_string(txt).unwrap();
                    assert_eq!(actual, expected);
                }
            )*
        };
    }

    // Parsing and size conversion tests data. Ensure that each type gets properly interpreted.
    // Call with higher base values to ensure expected multiplication (only need a couple)
    gen_size_filter_parse_test! {
        byte_plus:                ("+1b",     SizeFilter::Min(1)),
        byte_plus_multiplier:     ("+10b",    SizeFilter::Min(10)),
        byte_minus:               ("-1b",     SizeFilter::Max(1)),
        kilo_plus:                ("+1k",     SizeFilter::Min(1000)),
        kilo_plus_suffix:         ("+1kb",    SizeFilter::Min(1000)),
        kilo_minus:               ("-1k",     SizeFilter::Max(1000)),
        kilo_minus_multiplier:    ("-100k",   SizeFilter::Max(100000)),
        kilo_minus_suffix:        ("-1kb",    SizeFilter::Max(1000)),
        kilo_plus_upper:          ("+1K",     SizeFilter::Min(1000)),
        kilo_plus_suffix_upper:   ("+1KB",    SizeFilter::Min(1000)),
        kilo_minus_upper:         ("-1K",     SizeFilter::Max(1000)),
        kilo_minus_suffix_upper:  ("-1Kb",    SizeFilter::Max(1000)),
        kibi_plus:                ("+1ki",    SizeFilter::Min(1024)),
        kibi_plus_multiplier:     ("+10ki",   SizeFilter::Min(10240)),
        kibi_plus_suffix:         ("+1kib",   SizeFilter::Min(1024)),
        kibi_minus:               ("-1ki",    SizeFilter::Max(1024)),
        kibi_minus_multiplier:    ("-100ki",  SizeFilter::Max(102400)),
        kibi_minus_suffix:        ("-1kib",   SizeFilter::Max(1024)),
        kibi_plus_upper:          ("+1KI",    SizeFilter::Min(1024)),
        kibi_plus_suffix_upper:   ("+1KiB",   SizeFilter::Min(1024)),
        kibi_minus_upper:         ("-1Ki",    SizeFilter::Max(1024)),
        kibi_minus_suffix_upper:  ("-1KIB",   SizeFilter::Max(1024)),
        mega_plus:                ("+1m",     SizeFilter::Min(1000000)),
        mega_plus_suffix:         ("+1mb",    SizeFilter::Min(1000000)),
        mega_minus:               ("-1m",     SizeFilter::Max(1000000)),
        mega_minus_suffix:        ("-1mb",    SizeFilter::Max(1000000)),
        mega_plus_upper:          ("+1M",     SizeFilter::Min(1000000)),
        mega_plus_suffix_upper:   ("+1MB",    SizeFilter::Min(1000000)),
        mega_minus_upper:         ("-1M",     SizeFilter::Max(1000000)),
        mega_minus_suffix_upper:  ("-1Mb",    SizeFilter::Max(1000000)),
        mebi_plus:                ("+1mi",    SizeFilter::Min(1048576)),
        mebi_plus_suffix:         ("+1mib",   SizeFilter::Min(1048576)),
        mebi_minus:               ("-1mi",    SizeFilter::Max(1048576)),
        mebi_minus_suffix:        ("-1mib",   SizeFilter::Max(1048576)),
        mebi_plus_upper:          ("+1MI",    SizeFilter::Min(1048576)),
        mebi_plus_suffix_upper:   ("+1MiB",   SizeFilter::Min(1048576)),
        mebi_minus_upper:         ("-1Mi",    SizeFilter::Max(1048576)),
        mebi_minus_suffix_upper:  ("-1MIB",   SizeFilter::Max(1048576)),
        giga_plus:                ("+1g",     SizeFilter::Min(1000000000)),
        giga_plus_suffix:         ("+1gb",    SizeFilter::Min(1000000000)),
        giga_minus:               ("-1g",     SizeFilter::Max(1000000000)),
        giga_minus_suffix:        ("-1gb",    SizeFilter::Max(1000000000)),
        giga_plus_upper:          ("+1G",     SizeFilter::Min(1000000000)),
        giga_plus_suffix_upper:   ("+1GB",    SizeFilter::Min(1000000000)),
        giga_minus_upper:         ("-1G",     SizeFilter::Max(1000000000)),
        giga_minus_suffix_upper:  ("-1Gb",    SizeFilter::Max(1000000000)),
        gibi_plus:                ("+1gi",    SizeFilter::Min(1073741824)),
        gibi_plus_suffix:         ("+1gib",   SizeFilter::Min(1073741824)),
        gibi_minus:               ("-1gi",    SizeFilter::Max(1073741824)),
        gibi_minus_suffix:        ("-1gib",   SizeFilter::Max(1073741824)),
        gibi_plus_upper:          ("+1GI",    SizeFilter::Min(1073741824)),
        gibi_plus_suffix_upper:   ("+1GiB",   SizeFilter::Min(1073741824)),
        gibi_minus_upper:         ("-1Gi",    SizeFilter::Max(1073741824)),
        gibi_minus_suffix_upper:  ("-1GIB",   SizeFilter::Max(1073741824)),
        tera_plus:                ("+1t",     SizeFilter::Min(1000000000000)),
        tera_plus_suffix:         ("+1tb",    SizeFilter::Min(1000000000000)),
        tera_minus:               ("-1t",     SizeFilter::Max(1000000000000)),
        tera_minus_suffix:        ("-1tb",    SizeFilter::Max(1000000000000)),
        tera_plus_upper:          ("+1T",     SizeFilter::Min(1000000000000)),
        tera_plus_suffix_upper:   ("+1TB",    SizeFilter::Min(1000000000000)),
        tera_minus_upper:         ("-1T",     SizeFilter::Max(1000000000000)),
        tera_minus_suffix_upper:  ("-1Tb",    SizeFilter::Max(1000000000000)),
        tebi_plus:                ("+1ti",    SizeFilter::Min(1099511627776)),
        tebi_plus_suffix:         ("+1tib",   SizeFilter::Min(1099511627776)),
        tebi_minus:               ("-1ti",    SizeFilter::Max(1099511627776)),
        tebi_minus_suffix:        ("-1tib",   SizeFilter::Max(1099511627776)),
        tebi_plus_upper:          ("+1TI",    SizeFilter::Min(1099511627776)),
        tebi_plus_suffix_upper:   ("+1TiB",   SizeFilter::Min(1099511627776)),
        tebi_minus_upper:         ("-1Ti",    SizeFilter::Max(1099511627776)),
        tebi_minus_suffix_upper:  ("-1TIB",   SizeFilter::Max(1099511627776)),
    }

    /// Invalid parse testing
    macro_rules! gen_size_filter_failure {
        ($($name:ident: $value:expr,)*) => {
            $(
                #[test]
                fn $name() {
                    let i = SizeFilter::from_string($value);
                    assert!(i.is_none());
                }
            )*
        };
    }

    // Invalid parse data
    gen_size_filter_failure! {
        ensure_missing_symbol_returns_none: "10M",
        ensure_missing_number_returns_none: "+g",
        ensure_missing_unit_returns_none: "+18",
        ensure_bad_format_returns_none_1: "$10M",
        ensure_bad_format_returns_none_2: "badval",
        ensure_bad_format_returns_none_3: "9999",
        ensure_invalid_unit_returns_none_1: "+50a",
        ensure_invalid_unit_returns_none_2: "-10v",
        ensure_invalid_unit_returns_none_3: "+1Mv",
        ensure_bib_format_returns_none: "+1bib",
        ensure_bb_format_returns_none: "+1bb",
    }

    #[test]
    fn is_within_less_than() {
        let f = SizeFilter::from_string("-1k").unwrap();
        assert!(f.is_within(999));
    }

    #[test]
    fn is_within_less_than_equal() {
        let f = SizeFilter::from_string("-1k").unwrap();
        assert!(f.is_within(1000));
    }

    #[test]
    fn is_within_greater_than() {
        let f = SizeFilter::from_string("+1k").unwrap();
        assert!(f.is_within(1001));
    }

    #[test]
    fn is_within_greater_than_equal() {
        let f = SizeFilter::from_string("+1K").unwrap();
        assert!(f.is_within(1000));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add many-clients example<commit_after>extern crate session_types;
extern crate rand;

use session_types::*;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread::spawn;
use rand::random;

type Server = Recv<u8, Choose<Send<u8, Eps>, Eps>>;
type Client = Send<u8, Offer<Recv<u8, Eps>, Eps>>;

fn handler(c: Chan<(), Server>) {
    let (c, n) = c.recv();
    match n.checked_add(42) {
        Some(n) => c.sel1().send(n).close(),
        None => c.sel2().close(),
    }
}

fn server(rx: Receiver<Chan<(), Server>>) {
    let mut count = 0;
    loop {
        match borrow_request(&rx) {
            Some(c) => {
                spawn(move || handler(c));
                count += 1;
            },
            None => break,
        }
    }
    println!("Handled {} connections", count);
}

fn client(tx: Sender<Chan<(), Server>>) {
    let c = accept(tx).unwrap();

    let n = random();
    match c.send(n).offer() {
        Ok(c) => {
            let (c, n2) = c.recv();
            c.close();
            println!("{} + 42 = {}", n, n2);
        },
        Err(c) => {
            c.close();
            println!("{} + 42 is an overflow :(", n);
        }
    }
}

fn main() {
    let (tx, rx) = channel();
    let mut buf = Vec::new();

    let n: u8 = random();
    println!("Spawning {} clients", n);
    for _ in 0..n {
        let tmp = tx.clone();
        buf.push(spawn(move || client(tmp)));
    }
    drop(tx);

    server(rx);
    for t in buf {
        t.join().unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for module ambiguity<commit_after>// ignore-tidy-linelength

#![deny(intra_doc_link_resolution_failure)]

pub fn foo() {

}

pub mod foo {}
// @has intra_doc_link_mod_ambiguity/struct.A.html '//a/@href' '../intra_doc_link_mod_ambiguity/foo/index.html'
/// Module is [`module@foo`]
pub struct A;

// @has intra_doc_link_mod_ambiguity/struct.B.html '//a/@href' '../intra_doc_link_mod_ambiguity/fn.foo.html'
/// Function is [`fn@foo`]
pub struct B;
<|endoftext|>