<commit_before>/// Easy to use Let's Encrypt client to issue and renew TLS certs

extern crate acme_client;
extern crate clap;
extern crate env_logger;

use std::io::{self, Write};
use acme_client::Directory;
use acme_client::error::Result;
use clap::{Arg, App, SubCommand, ArgMatches};

fn main() {
    let matches = App::new(env!("CARGO_PKG_NAME"))
        .version(env!("CARGO_PKG_VERSION"))
        .about(env!("CARGO_PKG_DESCRIPTION"))
        .usage("letsencrypt-rs sign -D example.org -P /var/www -k domain.key -o domain.crt\
                \n    letsencrypt-rs revoke -K user_or_domain.key -C signed.crt")
        .subcommand(SubCommand::with_name("sign")
            .about("Signs a certificate")
            .display_order(1)
            .arg(Arg::with_name("USER_KEY_PATH")
                .help("User private key path to use it in account registration.")
                .long("user-key")
                .short("U")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN_KEY_PATH")
                .help("Domain private key path to use it in CSR generation.")
                .short("K")
                .long("domain-key")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN")
                .help("Domain name to obtain certificate. You can use more than one domain name.")
                .short("D")
                .long("domain")
                .multiple(true)
                .required(true)
                .takes_value(true))
            .arg(Arg::with_name("PUBLIC_DIR")
                .help("Directory to save ACME simple http challenge. This option is required.")
                .short("P")
                .long("public-dir")
                .takes_value(true))
            .arg(Arg::with_name("EMAIL")
                .help("Contact email address (optional).")
                .short("E")
                .long("email")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN_CSR")
                .help("Path to domain certificate signing request.")
                .short("C")
                .long("domain-csr")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_USER_KEY")
                .help("Path to save private user key.")
                .long("save-user-key")
                .short("u")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_DOMAIN_KEY")
                .help("Path to save domain private key.")
                .short("k")
                .long("save-domain-key")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_DOMAIN_CSR")
                .help("Path to save domain certificate signing request.")
                .long("save-csr")
                .short("S")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_SIGNED_CERTIFICATE")
                .help("Path to save signed certificate. Default is STDOUT.")
                .short("o")
                .long("save-crt")
                .takes_value(true))
            .arg(Arg::with_name("CHAIN")
                .help("Chains the signed certificate with Let's Encrypt Authority X3 \
                       (IdenTrust cross-signed) intermediate certificate.")
                .short("c")
                .long("chain")
                .takes_value(false))
            .arg(Arg::with_name("DNS_CHALLENGE")
                 .help("Use DNS challenge instead of HTTP. This option requires user \
                        to generate a TXT record for domain")
                 .short("d")
                 .long("dns")
                 .takes_value(false)))
        .subcommand(SubCommand::with_name("revoke")
            .about("Revokes a signed certificate")
            .display_order(2)
            .arg(Arg::with_name("USER_KEY")
                .help("User or domain private key path.")
                .long("user-key")
                .short("K")
                .required(true)
                .takes_value(true))
            .arg(Arg::with_name("SIGNED_CRT")
                .help("Path to signed domain certificate to revoke.")
                .long("signed-crt")
                .short("C")
                .required(true)
                .takes_value(true)))
        .arg(Arg::with_name("verbose")
             .help("Show verbose output")
             .short("v")
             .multiple(true))
        .get_matches();

    init_logger(matches.occurrences_of("verbose"));

    let res = if let Some(matches) = matches.subcommand_matches("sign") {
        sign_certificate(matches)
    } else if let Some(matches) = matches.subcommand_matches("revoke") {
        revoke_certificate(matches)
    } else {
        println!("{}", matches.usage());
        Ok(())
    };

    if let Err(e) = res {
        writeln!(io::stderr(), "{}", e.description()).expect("Failed to write stderr");
        ::std::process::exit(1);
    }
}

fn sign_certificate(matches: &ArgMatches) -> Result<()> {
    let directory = Directory::lets_encrypt()?;

    let mut account_registration = directory.account_registration();

    if let Some(email) = matches.value_of("EMAIL") {
        account_registration = account_registration.email(email);
    }

    if let Some(user_key_path) = matches.value_of("USER_KEY_PATH") {
        account_registration = account_registration.pkey_from_file(user_key_path)?;
    }

    let account = account_registration.register()?;
    let domains: Vec<_> = matches.values_of("DOMAIN")
        .ok_or("You need to provide at least one domain name")?
        .collect();
    for domain in &domains {
        let authorization = account.authorization(domain)?;
        if !matches.is_present("DNS_CHALLENGE") {
            let challenge = authorization.get_http_challenge().ok_or("HTTP challenge not found")?;
            challenge.save_key_authorization(matches.value_of("PUBLIC_DIR")
                                                 .ok_or("--public-dir not defined. \
                                                            You need to define a public \
                                                            directory to use http challenge \
                                                            verification")?)?;
            challenge.validate()?;
        } else {
            let challenge = authorization.get_dns_challenge().ok_or("DNS challenge not found")?;
            println!("Please create a TXT record for _acme-challenge.{}: {}\n\
                      Press enter to continue",
                     domain,
                     challenge.signature()?);
            io::stdin().read_line(&mut String::new()).unwrap();
            challenge.validate()?;
        }
    }

    let mut certificate_signer = account.certificate_signer(&domains);

    if let Some(domain_key_path) = matches.value_of("DOMAIN_KEY_PATH") {
        if let Some(csr_path) = matches.value_of("DOMAIN_CSR") {
            certificate_signer = certificate_signer.csr_from_file(domain_key_path, csr_path)?;
        } else {
            certificate_signer = certificate_signer.pkey_from_file(domain_key_path)?;
        }
    }

    let certificate = certificate_signer.sign_certificate()?;
    let signed_certificate_path = matches.value_of("SAVE_SIGNED_CERTIFICATE")
        .ok_or("You need to save signed certificate")?;
    if matches.is_present("CHAIN") {
        certificate.save_signed_certificate_and_chain(None, signed_certificate_path)?;
    } else {
        certificate.save_signed_certificate(signed_certificate_path)?;
    }

    if let Some(path) = matches.value_of("SAVE_DOMAIN_KEY") {
        certificate.save_private_key(path)?;
    }
    if let Some(path) = matches.value_of("SAVE_DOMAIN_CSR") {
        certificate.save_csr(path)?;
    }
    if let Some(path) = matches.value_of("SAVE_USER_KEY") {
        account.save_private_key(path)?;
    }

    Ok(())
}

fn revoke_certificate(matches: &ArgMatches) -> Result<()> {
    let directory = Directory::lets_encrypt()?;
    let account = directory.account_registration()
        .pkey_from_file(matches.value_of("USER_KEY")
                            .ok_or("You need to provide user \
                                   or domain private key used \
                                   to sign certificate.")?)?
        .register()?;
    account.revoke_certificate_from_file(matches.value_of("SIGNED_CRT")
                                             .ok_or("You need to provide \
                                                    a signed certificate to \
                                                    revoke.")?)?;
    Ok(())
}

fn init_logger(level: u64) {
    let level = match level {
        0 => "",
        1 => "acme_client=info",
        _ => "acme_client=debug",
    };
    let mut builder = env_logger::LogBuilder::new();
    builder.parse(&::std::env::var("RUST_LOG").unwrap_or(level.to_owned()));
    let _ = builder.init();
}
<commit_msg>descriptive error output using display<commit_after>/// Easy to use Let's Encrypt client to issue and renew TLS certs

extern crate acme_client;
extern crate clap;
extern crate env_logger;

use std::io::{self, Write};
use acme_client::Directory;
use acme_client::error::Result;
use clap::{Arg, App, SubCommand, ArgMatches};

fn main() {
    let matches = App::new(env!("CARGO_PKG_NAME"))
        .version(env!("CARGO_PKG_VERSION"))
        .about(env!("CARGO_PKG_DESCRIPTION"))
        .usage("letsencrypt-rs sign -D example.org -P /var/www -k domain.key -o domain.crt\
                \n    letsencrypt-rs revoke -K user_or_domain.key -C signed.crt")
        .subcommand(SubCommand::with_name("sign")
            .about("Signs a certificate")
            .display_order(1)
            .arg(Arg::with_name("USER_KEY_PATH")
                .help("User private key path to use it in account registration.")
                .long("user-key")
                .short("U")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN_KEY_PATH")
                .help("Domain private key path to use it in CSR generation.")
                .short("K")
                .long("domain-key")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN")
                .help("Domain name to obtain certificate. You can use more than one domain name.")
                .short("D")
                .long("domain")
                .multiple(true)
                .required(true)
                .takes_value(true))
            .arg(Arg::with_name("PUBLIC_DIR")
                .help("Directory to save ACME simple http challenge. This option is required.")
                .short("P")
                .long("public-dir")
                .takes_value(true))
            .arg(Arg::with_name("EMAIL")
                .help("Contact email address (optional).")
                .short("E")
                .long("email")
                .takes_value(true))
            .arg(Arg::with_name("DOMAIN_CSR")
                .help("Path to domain certificate signing request.")
                .short("C")
                .long("domain-csr")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_USER_KEY")
                .help("Path to save private user key.")
                .long("save-user-key")
                .short("u")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_DOMAIN_KEY")
                .help("Path to save domain private key.")
                .short("k")
                .long("save-domain-key")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_DOMAIN_CSR")
                .help("Path to save domain certificate signing request.")
                .long("save-csr")
                .short("S")
                .takes_value(true))
            .arg(Arg::with_name("SAVE_SIGNED_CERTIFICATE")
                .help("Path to save signed certificate. Default is STDOUT.")
                .short("o")
                .long("save-crt")
                .takes_value(true))
            .arg(Arg::with_name("CHAIN")
                .help("Chains the signed certificate with Let's Encrypt Authority X3 \
                       (IdenTrust cross-signed) intermediate certificate.")
                .short("c")
                .long("chain")
                .takes_value(false))
            .arg(Arg::with_name("DNS_CHALLENGE")
                 .help("Use DNS challenge instead of HTTP. This option requires user \
                        to generate a TXT record for domain")
                 .short("d")
                 .long("dns")
                 .takes_value(false)))
        .subcommand(SubCommand::with_name("revoke")
            .about("Revokes a signed certificate")
            .display_order(2)
            .arg(Arg::with_name("USER_KEY")
                .help("User or domain private key path.")
                .long("user-key")
                .short("K")
                .required(true)
                .takes_value(true))
            .arg(Arg::with_name("SIGNED_CRT")
                .help("Path to signed domain certificate to revoke.")
                .long("signed-crt")
                .short("C")
                .required(true)
                .takes_value(true)))
        .arg(Arg::with_name("verbose")
             .help("Show verbose output")
             .short("v")
             .multiple(true))
        .get_matches();

    init_logger(matches.occurrences_of("verbose"));

    let res = if let Some(matches) = matches.subcommand_matches("sign") {
        sign_certificate(matches)
    } else if let Some(matches) = matches.subcommand_matches("revoke") {
        revoke_certificate(matches)
    } else {
        println!("{}", matches.usage());
        Ok(())
    };

    if let Err(e) = res {
        writeln!(io::stderr(), "{}", e).expect("Failed to write stderr");
        ::std::process::exit(1);
    }
}

fn sign_certificate(matches: &ArgMatches) -> Result<()> {
    let directory = Directory::lets_encrypt()?;

    let mut account_registration = directory.account_registration();

    if let Some(email) = matches.value_of("EMAIL") {
        account_registration = account_registration.email(email);
    }

    if let Some(user_key_path) = matches.value_of("USER_KEY_PATH") {
        account_registration = account_registration.pkey_from_file(user_key_path)?;
    }

    let account = account_registration.register()?;
    let domains: Vec<_> = matches.values_of("DOMAIN")
        .ok_or("You need to provide at least one domain name")?
        .collect();
    for domain in &domains {
        let authorization = account.authorization(domain)?;
        if !matches.is_present("DNS_CHALLENGE") {
            let challenge = authorization.get_http_challenge().ok_or("HTTP challenge not found")?;
            challenge.save_key_authorization(matches.value_of("PUBLIC_DIR")
                                                 .ok_or("--public-dir not defined. \
                                                            You need to define a public \
                                                            directory to use http challenge \
                                                            verification")?)?;
            challenge.validate()?;
        } else {
            let challenge = authorization.get_dns_challenge().ok_or("DNS challenge not found")?;
            println!("Please create a TXT record for _acme-challenge.{}: {}\n\
                      Press enter to continue",
                     domain,
                     challenge.signature()?);
            io::stdin().read_line(&mut String::new()).unwrap();
            challenge.validate()?;
        }
    }

    let mut certificate_signer = account.certificate_signer(&domains);

    if let Some(domain_key_path) = matches.value_of("DOMAIN_KEY_PATH") {
        if let Some(csr_path) = matches.value_of("DOMAIN_CSR") {
            certificate_signer = certificate_signer.csr_from_file(domain_key_path, csr_path)?;
        } else {
            certificate_signer = certificate_signer.pkey_from_file(domain_key_path)?;
        }
    }

    let certificate = certificate_signer.sign_certificate()?;
    let signed_certificate_path = matches.value_of("SAVE_SIGNED_CERTIFICATE")
        .ok_or("You need to save signed certificate")?;
    if matches.is_present("CHAIN") {
        certificate.save_signed_certificate_and_chain(None, signed_certificate_path)?;
    } else {
        certificate.save_signed_certificate(signed_certificate_path)?;
    }

    if let Some(path) = matches.value_of("SAVE_DOMAIN_KEY") {
        certificate.save_private_key(path)?;
    }
    if let Some(path) = matches.value_of("SAVE_DOMAIN_CSR") {
        certificate.save_csr(path)?;
    }
    if let Some(path) = matches.value_of("SAVE_USER_KEY") {
        account.save_private_key(path)?;
    }

    Ok(())
}

fn revoke_certificate(matches: &ArgMatches) -> Result<()> {
    let directory = Directory::lets_encrypt()?;
    let account = directory.account_registration()
        .pkey_from_file(matches.value_of("USER_KEY")
                            .ok_or("You need to provide user \
                                   or domain private key used \
                                   to sign certificate.")?)?
        .register()?;
    account.revoke_certificate_from_file(matches.value_of("SIGNED_CRT")
                                             .ok_or("You need to provide \
                                                    a signed certificate to \
                                                    revoke.")?)?;
    Ok(())
}

fn init_logger(level: u64) {
    let level = match level {
        0 => "",
        1 => "acme_client=info",
        _ => "acme_client=debug",
    };
    let mut builder = env_logger::LogBuilder::new();
    builder.parse(&::std::env::var("RUST_LOG").unwrap_or(level.to_owned()));
    let _ = builder.init();
}
<|endoftext|>


<commit_before>mod ast_builder;
mod scanner;
mod tokenizer;

use ast::AstIndex;
use ast::token::Token;
use ast::token::Token::*;
use compiler::Compiler;
use compiler::compile_errors;
use compiler::source_data::{ByteIndex,ByteRange,ParseData,SourceIndex};
use indexed_vec::{Delta,IndexedVec};

pub(super) fn parse(compiler: &Compiler, source: SourceIndex) -> ParseData
{
    // Actual list of tokens
    let mut tokens: IndexedVec<Token,AstIndex> = Default::default();
    let mut token_ranges: IndexedVec<ByteRange,AstIndex> = Default::default();
    // Keeps track of open parentheses so we can close them appropriately
    let mut open_parens: Vec<AstIndex> = Default::default();

    // Loop through tokens, inserting term, then operator, then term, then operator ...
    let mut need_operand = true;
    let (identifiers, literals) = tokenizer::tokenize(compiler, source, |mut token, range| {
        // Put a MissingExpression or MissingInfix in between if we're missing something.
        match (need_operand, token.has_left_operand()) {
            (true, true) => {
                tokens.push(MissingExpression);
                token_ranges.push(range.start..range.start);
            },
            (false, false) => {
                tokens.push(MissingInfix);
                token_ranges.push(range.start..range.start);
            },
            (true,false)|(false,true) => {}
        }
        need_operand = token.has_right_operand();

        // Handle open/close parens
        match token {
            OpenParen(_) => open_parens.push(tokens.len()),
            CloseParen(ref mut close_delta) => {
                *close_delta = match open_parens.pop() {
                    Some(open_index) => {
                        let close_index = tokens.len();
                        match tokens[open_index] {
                            OpenParen(ref mut open_delta) => { *open_delta = close_index-open_index; *open_delta }
                            _ => unreachable!()
                        }
                    }
                    None => handle_close_without_open(&range, &mut tokens, &mut token_ranges, compiler, source),
                }
            },
            _ => {}
        }

        // Insert the tokens
        tokens.push(token);
        token_ranges.push(range);
    });

    // Add a "missing operand" if we still need an operand
    if need_operand {
        let end = match token_ranges.last() { Some(range) => range.end, None => ByteIndex(0) };
        tokens.push(MissingExpression);
        token_ranges.push(end..end);
    }
    // Close off any remaining open parens
    while let Some(open_index) = open_parens.pop() {
        handle_open_without_close(open_index, &mut tokens, &mut token_ranges, compiler, source);
    }

    let char_data = Default::default();
    ParseData { char_data, identifiers, literals, tokens, token_ranges }
}

fn handle_close_without_open(
    range: &ByteRange,
    tokens: &mut IndexedVec<Token,AstIndex>,
    token_ranges: &mut IndexedVec<ByteRange,AstIndex>,
    compiler: &Compiler,
    source: SourceIndex
) -> Delta<AstIndex> {
    let open_index = AstIndex(0);
    let open_loc = ByteIndex(0);
    // We're about to shift the close_index over, so we need to set the delta correctly.
    let close_index = tokens.len()+1;
    let delta = close_index-open_index;
    println!("  open/close: {}/{}", open_index, close_index);
    tokens.insert(open_index, OpenParen(delta));
    token_ranges.insert(open_index, open_loc..open_loc);
    compiler.report(compile_errors::CloseWithoutOpen { source, close: range.clone(), open: String::from("(") });
    delta
}

fn handle_open_without_close(
    open_index: AstIndex,
    tokens: &mut IndexedVec<Token,AstIndex>,
    token_ranges: &mut IndexedVec<ByteRange,AstIndex>,
    compiler: &Compiler,
    source: SourceIndex
) {
    let close_index = tokens.len();
    let close_loc = token_ranges[close_index-1].end;
    let delta = close_index-open_index;
    tokens.push(CloseParen(delta));
    token_ranges.push(close_loc..close_loc);
    if let OpenParen(ref mut open_delta) = tokens[open_index] {
        *open_delta = delta;
    } else {
        unreachable!()
    }

    compiler.report(compile_errors::OpenWithoutClose { source, open: token_ranges[open_index].clone(), close: String::from(")") });
}
<commit_msg>Fix reference to deleted module<commit_after>mod scanner;
mod tokenizer;

use ast::AstIndex;
use ast::token::Token;
use ast::token::Token::*;
use compiler::Compiler;
use compiler::compile_errors;
use compiler::source_data::{ByteIndex,ByteRange,ParseData,SourceIndex};
use indexed_vec::{Delta,IndexedVec};

pub(super) fn parse(compiler: &Compiler, source: SourceIndex) -> ParseData
{
    // Actual list of tokens
    let mut tokens: IndexedVec<Token,AstIndex> = Default::default();
    let mut token_ranges: IndexedVec<ByteRange,AstIndex> = Default::default();
    // Keeps track of open parentheses so we can close them appropriately
    let mut open_parens: Vec<AstIndex> = Default::default();

    // Loop through tokens, inserting term, then operator, then term, then operator ...
    let mut need_operand = true;
    let (identifiers, literals) = tokenizer::tokenize(compiler, source, |mut token, range| {
        // Put a MissingExpression or MissingInfix in between if we're missing something.
        match (need_operand, token.has_left_operand()) {
            (true, true) => {
                tokens.push(MissingExpression);
                token_ranges.push(range.start..range.start);
            },
            (false, false) => {
                tokens.push(MissingInfix);
                token_ranges.push(range.start..range.start);
            },
            (true,false)|(false,true) => {}
        }
        need_operand = token.has_right_operand();

        // Handle open/close parens
        match token {
            OpenParen(_) => open_parens.push(tokens.len()),
            CloseParen(ref mut close_delta) => {
                *close_delta = match open_parens.pop() {
                    Some(open_index) => {
                        let close_index = tokens.len();
                        match tokens[open_index] {
                            OpenParen(ref mut open_delta) => { *open_delta = close_index-open_index; *open_delta }
                            _ => unreachable!()
                        }
                    }
                    None => handle_close_without_open(&range, &mut tokens, &mut token_ranges, compiler, source),
                }
            },
            _ => {}
        }

        // Insert the tokens
        tokens.push(token);
        token_ranges.push(range);
    });

    // Add a "missing operand" if we still need an operand
    if need_operand {
        let end = match token_ranges.last() { Some(range) => range.end, None => ByteIndex(0) };
        tokens.push(MissingExpression);
        token_ranges.push(end..end);
    }
    // Close off any remaining open parens
    while let Some(open_index) = open_parens.pop() {
        handle_open_without_close(open_index, &mut tokens, &mut token_ranges, compiler, source);
    }

    let char_data = Default::default();
    ParseData { char_data, identifiers, literals, tokens, token_ranges }
}

fn handle_close_without_open(
    range: &ByteRange,
    tokens: &mut IndexedVec<Token,AstIndex>,
    token_ranges: &mut IndexedVec<ByteRange,AstIndex>,
    compiler: &Compiler,
    source: SourceIndex
) -> Delta<AstIndex> {
    let open_index = AstIndex(0);
    let open_loc = ByteIndex(0);
    // We're about to shift the close_index over, so we need to set the delta correctly.
    let close_index = tokens.len()+1;
    let delta = close_index-open_index;
    println!("  open/close: {}/{}", open_index, close_index);
    tokens.insert(open_index, OpenParen(delta));
    token_ranges.insert(open_index, open_loc..open_loc);
    compiler.report(compile_errors::CloseWithoutOpen { source, close: range.clone(), open: String::from("(") });
    delta
}

fn handle_open_without_close(
    open_index: AstIndex,
    tokens: &mut IndexedVec<Token,AstIndex>,
    token_ranges: &mut IndexedVec<ByteRange,AstIndex>,
    compiler: &Compiler,
    source: SourceIndex
) {
    let close_index = tokens.len();
    let close_loc = token_ranges[close_index-1].end;
    let delta = close_index-open_index;
    tokens.push(CloseParen(delta));
    token_ranges.push(close_loc..close_loc);
    if let OpenParen(ref mut open_delta) = tokens[open_index] {
        *open_delta = delta;
    } else {
        unreachable!()
    }

    compiler.report(compile_errors::OpenWithoutClose { source, open: token_ranges[open_index].clone(), close: String::from(")") });
}
<|endoftext|>


<commit_before>extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1, 101);
    loop {
        println!("Please input your guess");
        let mut guess = String::new();
        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");
        let guessed_number: u32 = guess.trim().parse()
            .expect("Should be a number!");
        match guessed_number.cmp(&secret_number) {
            Ordering::Equal => {
                println!("You win!");
                break;
            },
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!")
        }
    }
    println!("The secret number is: {}", secret_number);
}
<commit_msg>Do not panick on input format error<commit_after>extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1, 101);
    loop {
        println!("Please input your guess");
        let mut guess = String::new();
        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");
        let guessed_number: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("You must type a number!");
                continue
            }
        };
        match guessed_number.cmp(&secret_number) {
            Ordering::Equal => {
                println!("You win!");
                break;
            },
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!")
        }
    }
    println!("The secret number is: {}", secret_number);
}
<|endoftext|>


<commit_before>use std::io;

fn main() {
    ${0:println!("Hello, world!");}
}
<commit_msg>removed unused use in "file-template rust main"<commit_after>fn main() {
    ${0:println!("Hello, world!");}
}
<|endoftext|>


<commit_before>pub fn is_power_of_two(n: i32) -> bool {
    if n == 0 {
        return false;
    }
    let mut a: i32 = 0b1;
    for _ in 0..31 {
        if a & n == n {
            return true;
        }
        a <<= 1;
    }
    return false;
}

fn main() {
    assert!(is_power_of_two(16));
    assert!(is_power_of_two(1));
    assert!(!is_power_of_two(3));
    assert!(is_power_of_two(4));
    assert!(!is_power_of_two(5));
    assert!(!is_power_of_two(0));
    assert!(!is_power_of_two(-2147483648))
}
<commit_msg>new method<commit_after>pub fn is_power_of_two(n: i32) -> bool {
    if n == 0 {
        return false;
    }
    let mut a: i32 = 0b1;
    for _ in 0..31 {
        if a & n == n {
            return true;
        }
        a <<= 1;
    }
    return false;
}

pub fn is_power_of_two2(n: i32) -> bool {
    n != 0 && (n as i64).count_ones() == 1
}

fn main() {
    assert!(is_power_of_two(16));
    assert!(is_power_of_two(1));
    assert!(!is_power_of_two(3));
    assert!(is_power_of_two(4));
    assert!(!is_power_of_two(5));
    assert!(!is_power_of_two(0));
    assert!(!is_power_of_two(-2147483648));

    assert!(is_power_of_two2(16));
    assert!(is_power_of_two2(1));
    assert!(!is_power_of_two2(3));
    assert!(is_power_of_two2(4));
    assert!(!is_power_of_two2(5));
    assert!(!is_power_of_two2(0));
    assert!(!is_power_of_two2(-2147483648))
}
<|endoftext|>


<commit_before>use inflector::Inflector;
use lazy_static::lazy_static;
use linked_hash_map::LinkedHashMap;
use regex::Regex;
use std::collections::HashSet;

use crate::options::Options;
use crate::shape::{self, Shape};
use crate::util::type_case;

pub struct Ctxt {
    options: Options,
    type_names: HashSet<String>,
}

pub type Ident = String;
pub type Code = String;

pub fn typescript_types(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) {
    let mut ctxt = Ctxt {
        options,
        type_names: HashSet::new(),
    };

    type_from_shape(&mut ctxt, name, shape)
}

fn type_from_shape(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    use crate::shape::Shape::*;
    match *shape {
        Null | Any | Bottom => ("any".into(), None),
        Bool => ("boolean".into(), None),
        StringT => ("string".into(), None),
        Integer => ("number".into(), None),
        Floating => ("number".into(), None),
        Tuple(ref shapes, _n) => {
            let folded = shape::fold_shapes(shapes.clone());
            if folded == Any && shapes.iter().any(|s| s != &Any) {
                generate_tuple_type(ctxt, path, shapes)
            } else {
                generate_vec_type(ctxt, path, &folded)
            }
        }
        VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e),
        Struct { fields: ref map } => generate_struct_from_field_shapes(ctxt, path, map),
        MapT { val_type: ref v } => generate_map_type(ctxt, path, v),
        Opaque(ref t) => (t.clone(), None),
        Optional(ref e) => {
            let (inner, defs) = type_from_shape(ctxt, path, e);
            if ctxt.options.use_default_for_missing_fields {
                (inner, defs)
            } else {
                (format!("{} | undefined", inner), defs)
            }
        }
    }
}

fn generate_vec_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    let singular = path.to_singular();
    let (inner, defs) = type_from_shape(ctxt, &singular, shape);
    (format!("{}[]", inner), defs)
}

fn generate_map_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    let singular = path.to_singular();
    let (inner, defs) = type_from_shape(ctxt, &singular, shape);
    (format!("{{ [key: string]: {} }}", inner), defs)
}

fn generate_tuple_type(ctxt: &mut Ctxt, path: &str, shapes: &[Shape]) -> (Ident, Option<Code>) {
    let mut types = Vec::new();
    let mut defs = Vec::new();

    for shape in shapes {
        let (typ, def) = type_from_shape(ctxt, path, shape);
        types.push(typ);
        if let Some(code) = def {
            defs.push(code)
        }
    }

    (format!("[{}]", types.join(", ")), Some(defs.join("\n\n")))
}

fn type_name(name: &str, used_names: &HashSet<String>) -> Ident {
    let name = name.trim();
    let mut output_name = if let Some(c) = name.chars().next() {
        if c.is_ascii() && c.is_numeric() {
            let temp = String::from("n") + name;
            type_case(&temp)
        } else {
            type_case(name)
        }
    } else {
        type_case(name)
    };
    if output_name == "" {
        output_name.push_str("GeneratedType");
    }
    if !used_names.contains(&output_name) {
        return output_name;
    }
    for n in 2.. {
        let temp = format!("{}{}", output_name, n);
        if !used_names.contains(&temp) {
            return temp;
        }
    }
    unreachable!()
}

fn collapse_option(typ: &Shape) -> (bool, &Shape) {
    if let Shape::Optional(inner) = typ {
        return (true, &**inner);
    }
    (false, typ)
}

const RESERVED_WORDS_ARR: &[&str] = &["break", "case", "catch", "class", "const",
    "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false",
    "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return",
    "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with",
    "implements", "interface", "let", "package", "private", "protected", "public", "static",
    "yield"];

lazy_static! {
    static ref RESERVED_WORDS: HashSet<&'static str> =
        { RESERVED_WORDS_ARR.iter().cloned().collect() };
}

fn is_ts_identifier(s: &str) -> bool {
    lazy_static! {
        static ref JS_IDENTIFIER_RE: Regex = Regex::new(r"[a-zA-Z_$][a-zA-Z_$0-9]*").unwrap();
    }
    JS_IDENTIFIER_RE.is_match(s) && !RESERVED_WORDS.contains(s)
}

fn generate_struct_from_field_shapes(
    ctxt: &mut Ctxt,
    path: &str,
    map: &LinkedHashMap<String, Shape>,
) -> (Ident, Option<Code>) {
    let type_name = type_name(path, &ctxt.type_names);
    ctxt.type_names.insert(type_name.clone());

    let mut defs = Vec::new();

    let fields: Vec<Code> = map
        .iter()
        .map(|(name, typ)| {
            let (was_optional, collapsed) = collapse_option(typ);

            let (field_type, child_defs) = type_from_shape(ctxt, name, collapsed);

            if let Some(code) = child_defs {
                defs.push(code);
            }

            let escape_name = !is_ts_identifier(name);

            format!(
                "    {}{}{}{}: {};",
                if escape_name { "\"" } else { "" },
                name,
                if escape_name { "\"" } else { "" },
                if was_optional { "?" } else { "" },
                field_type
            )
        })
        .collect();

    let mut code = format!("interface {} {{\n", type_name);

    if !fields.is_empty() {
        code += &fields.join("\n");
        code += "\n";
    }
    code += "}";

    if !defs.is_empty() {
        code += "\n\n";
        code += &defs.join("\n\n");
    }

    (type_name, Some(code))
}
<commit_msg>TS: Fix missing quotes around invalid identifiers<commit_after>use inflector::Inflector;
use lazy_static::lazy_static;
use linked_hash_map::LinkedHashMap;
use regex::Regex;
use std::collections::HashSet;

use crate::options::Options;
use crate::shape::{self, Shape};
use crate::util::type_case;

pub struct Ctxt {
    options: Options,
    type_names: HashSet<String>,
}

pub type Ident = String;
pub type Code = String;

pub fn typescript_types(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) {
    let mut ctxt = Ctxt {
        options,
        type_names: HashSet::new(),
    };

    type_from_shape(&mut ctxt, name, shape)
}

fn type_from_shape(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    use crate::shape::Shape::*;
    match *shape {
        Null | Any | Bottom => ("any".into(), None),
        Bool => ("boolean".into(), None),
        StringT => ("string".into(), None),
        Integer => ("number".into(), None),
        Floating => ("number".into(), None),
        Tuple(ref shapes, _n) => {
            let folded = shape::fold_shapes(shapes.clone());
            if folded == Any && shapes.iter().any(|s| s != &Any) {
                generate_tuple_type(ctxt, path, shapes)
            } else {
                generate_vec_type(ctxt, path, &folded)
            }
        }
        VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e),
        Struct { fields: ref map } => generate_struct_from_field_shapes(ctxt, path, map),
        MapT { val_type: ref v } => generate_map_type(ctxt, path, v),
        Opaque(ref t) => (t.clone(), None),
        Optional(ref e) => {
            let (inner, defs) = type_from_shape(ctxt, path, e);
            if ctxt.options.use_default_for_missing_fields {
                (inner, defs)
            } else {
                (format!("{} | undefined", inner), defs)
            }
        }
    }
}

fn generate_vec_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    let singular = path.to_singular();
    let (inner, defs) = type_from_shape(ctxt, &singular, shape);
    (format!("{}[]", inner), defs)
}

fn generate_map_type(ctxt: &mut Ctxt, path: &str, shape: &Shape) -> (Ident, Option<Code>) {
    let singular = path.to_singular();
    let (inner, defs) = type_from_shape(ctxt, &singular, shape);
    (format!("{{ [key: string]: {} }}", inner), defs)
}

fn generate_tuple_type(ctxt: &mut Ctxt, path: &str, shapes: &[Shape]) -> (Ident, Option<Code>) {
    let mut types = Vec::new();
    let mut defs = Vec::new();

    for shape in shapes {
        let (typ, def) = type_from_shape(ctxt, path, shape);
        types.push(typ);
        if let Some(code) = def {
            defs.push(code)
        }
    }

    (format!("[{}]", types.join(", ")), Some(defs.join("\n\n")))
}

fn type_name(name: &str, used_names: &HashSet<String>) -> Ident {
    let name = name.trim();
    let mut output_name = if let Some(c) = name.chars().next() {
        if c.is_ascii() && c.is_numeric() {
            let temp = String::from("n") + name;
            type_case(&temp)
        } else {
            type_case(name)
        }
    } else {
        type_case(name)
    };
    if output_name == "" {
        output_name.push_str("GeneratedType");
    }
    if !used_names.contains(&output_name) {
        return output_name;
    }
    for n in 2.. {
        let temp = format!("{}{}", output_name, n);
        if !used_names.contains(&temp) {
            return temp;
        }
    }
    unreachable!()
}

fn collapse_option(typ: &Shape) -> (bool, &Shape) {
    if let Shape::Optional(inner) = typ {
        return (true, &**inner);
    }
    (false, typ)
}

const RESERVED_WORDS_ARR: &[&str] = &["break", "case", "catch", "class", "const",
    "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false",
    "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return",
    "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with",
    "implements", "interface", "let", "package", "private", "protected", "public", "static",
    "yield"];

lazy_static! {
    static ref RESERVED_WORDS: HashSet<&'static str> =
        { RESERVED_WORDS_ARR.iter().cloned().collect() };
}

fn is_ts_identifier(s: &str) -> bool {
    lazy_static! {
        static ref JS_IDENTIFIER_RE: Regex = Regex::new(r"^[a-zA-Z_$][a-zA-Z_$0-9]*$").unwrap();
    }
    JS_IDENTIFIER_RE.is_match(s) && !RESERVED_WORDS.contains(s)
}

fn generate_struct_from_field_shapes(
    ctxt: &mut Ctxt,
    path: &str,
    map: &LinkedHashMap<String, Shape>,
) -> (Ident, Option<Code>) {
    let type_name = type_name(path, &ctxt.type_names);
    ctxt.type_names.insert(type_name.clone());

    let mut defs = Vec::new();

    let fields: Vec<Code> = map
        .iter()
        .map(|(name, typ)| {
            let (was_optional, collapsed) = collapse_option(typ);

            let (field_type, child_defs) = type_from_shape(ctxt, name, collapsed);

            if let Some(code) = child_defs {
                defs.push(code);
            }

            let escape_name = !is_ts_identifier(name);

            format!(
                "    {}{}{}{}: {};",
                if escape_name { "\"" } else { "" },
                name,
                if escape_name { "\"" } else { "" },
                if was_optional { "?" } else { "" },
                field_type
            )
        })
        .collect();

    let mut code = format!("interface {} {{\n", type_name);

    if !fields.is_empty() {
        code += &fields.join("\n");
        code += "\n";
    }
    code += "}";

    if !defs.is_empty() {
        code += "\n\n";
        code += &defs.join("\n\n");
    }

    (type_name, Some(code))
}

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

    #[test]
    fn test_is_ts_identifier() {
        // Valid:
        assert!(is_ts_identifier("foobar"));
        assert!(is_ts_identifier("FOOBAR"));
        assert!(is_ts_identifier("foo_bar"));
        assert!(is_ts_identifier("$"));
        assert!(is_ts_identifier("foobar1"));

        // Invalid:
        assert!(!is_ts_identifier("1foobar"));
        assert!(!is_ts_identifier(""));
        assert!(!is_ts_identifier(" "));
        assert!(!is_ts_identifier(" foobar"));
        assert!(!is_ts_identifier("foobar "));
        assert!(!is_ts_identifier("foo bar"));
        assert!(!is_ts_identifier("foo.bar"));
        assert!(!is_ts_identifier("true"));
    }
}
<|endoftext|>


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

use prelude::v1::*;

use ffi::{CStr, CString};
use fmt;
use io::{self, Error, ErrorKind};
use libc::{self, c_int, c_char, c_void, socklen_t};
use mem;
use net::{SocketAddr, Shutdown, IpAddr};
use str::from_utf8;
use sys::c;
use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
use sys_common::{AsInner, FromInner, IntoInner};
use time::Duration;

////////////////////////////////////////////////////////////////////////////////
// sockaddr and misc bindings
////////////////////////////////////////////////////////////////////////////////

pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
                     payload: T) -> io::Result<()> {
    unsafe {
        let payload = &payload as *const T as *const c_void;
        try!(cvt(libc::setsockopt(*sock.as_inner(), opt, val, payload,
                                  mem::size_of::<T>() as socklen_t)));
        Ok(())
    }
}

pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
                       val: c_int) -> io::Result<T> {
    unsafe {
        let mut slot: T = mem::zeroed();
        let mut len = mem::size_of::<T>() as socklen_t;
        try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
                               &mut slot as *mut _ as *mut _,
                               &mut len)));
        assert_eq!(len as usize, mem::size_of::<T>());
        Ok(slot)
    }
}

fn sockname<F>(f: F) -> io::Result<SocketAddr>
    where F: FnOnce(*mut libc::sockaddr, *mut socklen_t) -> c_int
{
    unsafe {
        let mut storage: libc::sockaddr_storage = mem::zeroed();
        let mut len = mem::size_of_val(&storage) as socklen_t;
        try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
        sockaddr_to_addr(&storage, len as usize)
    }
}

fn sockaddr_to_addr(storage: &libc::sockaddr_storage,
                    len: usize) -> io::Result<SocketAddr> {
    match storage.ss_family as libc::c_int {
        libc::AF_INET => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in>());
            Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in)
            })))
        }
        libc::AF_INET6 => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in6>());
            Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in6)
            })))
        }
        _ => {
            Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// get_host_addresses
////////////////////////////////////////////////////////////////////////////////

extern "system" {
    fn getaddrinfo(node: *const c_char, service: *const c_char,
                   hints: *const libc::addrinfo,
                   res: *mut *mut libc::addrinfo) -> c_int;
    fn freeaddrinfo(res: *mut libc::addrinfo);
}

pub struct LookupHost {
    original: *mut libc::addrinfo,
    cur: *mut libc::addrinfo,
}

impl Iterator for LookupHost {
    type Item = io::Result<SocketAddr>;
    fn next(&mut self) -> Option<io::Result<SocketAddr>> {
        unsafe {
            if self.cur.is_null() { return None }
            let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
                                       (*self.cur).ai_addrlen as usize);
            self.cur = (*self.cur).ai_next as *mut libc::addrinfo;
            Some(ret)
        }
    }
}

impl Drop for LookupHost {
    fn drop(&mut self) {
        unsafe { freeaddrinfo(self.original) }
    }
}

pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
    init();

    let c_host = try!(CString::new(host));
    let mut res = 0 as *mut _;
    unsafe {
        try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _,
                                 &mut res)));
        Ok(LookupHost { original: res, cur: res })
    }
}

////////////////////////////////////////////////////////////////////////////////
// lookup_addr
////////////////////////////////////////////////////////////////////////////////

extern "system" {
    fn getnameinfo(sa: *const libc::sockaddr, salen: socklen_t,
                   host: *mut c_char, hostlen: libc::size_t,
                   serv: *mut c_char, servlen: libc::size_t,
                   flags: c_int) -> c_int;
}

const NI_MAXHOST: usize = 1025;

pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
    init();

    let saddr = SocketAddr::new(*addr, 0);
    let (inner, len) = saddr.into_inner();
    let mut hostbuf = [0 as c_char; NI_MAXHOST];

    let data = unsafe {
        try!(cvt_gai(getnameinfo(inner, len,
                                 hostbuf.as_mut_ptr(), NI_MAXHOST as libc::size_t,
                                 0 as *mut _, 0, 0)));

        CStr::from_ptr(hostbuf.as_ptr())
    };

    match from_utf8(data.to_bytes()) {
        Ok(name) => Ok(name.to_string()),
        Err(_) => Err(io::Error::new(io::ErrorKind::Other,
                                     "failed to lookup address information"))
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP streams
////////////////////////////////////////////////////////////////////////////////

pub struct TcpStream {
    inner: Socket,
}

impl TcpStream {
    pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        let (addrp, len) = addr.into_inner();
        try!(cvt_r(|| unsafe { libc::connect(*sock.as_inner(), addrp, len) }));
        Ok(TcpStream { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
    }

    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let ret = try!(cvt(unsafe {
            libc::send(*self.inner.as_inner(),
                       buf.as_ptr() as *const c_void,
                       buf.len() as wrlen_t,
                       0)
        }));
        Ok(ret as usize)
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getpeername(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        use libc::consts::os::bsd44::SHUT_RDWR;

        let how = match how {
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Both => SHUT_RDWR,
        };
        try!(cvt(unsafe { libc::shutdown(*self.inner.as_inner(), how) }));
        Ok(())
    }

    pub fn duplicate(&self) -> io::Result<TcpStream> {
        self.inner.duplicate().map(|s| TcpStream { inner: s })
    }
}

impl FromInner<Socket> for TcpStream {
    fn from_inner(socket: Socket) -> TcpStream {
        TcpStream { inner: socket }
    }
}

impl fmt::Debug for TcpStream {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("TcpStream");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        if let Ok(peer) = self.peer_addr() {
            res.field("peer", &peer);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////

pub struct TcpListener {
    inner: Socket,
}

impl TcpListener {
    pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        // On platforms with Berkeley-derived sockets, this allows
        // to quickly rebind a socket, without needing to wait for
        // the OS to clean up the previous one.
        if !cfg!(windows) {
            try!(setsockopt(&sock, libc::SOL_SOCKET, libc::SO_REUSEADDR,
                            1 as c_int));
        }

        // Bind our new socket
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));

        // Start listening
        try!(cvt(unsafe { libc::listen(*sock.as_inner(), 128) }));
        Ok(TcpListener { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut len = mem::size_of_val(&storage) as socklen_t;
        let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
                                          &mut len));
        let addr = try!(sockaddr_to_addr(&storage, len as usize));
        Ok((TcpStream { inner: sock, }, addr))
    }

    pub fn duplicate(&self) -> io::Result<TcpListener> {
        self.inner.duplicate().map(|s| TcpListener { inner: s })
    }
}

impl FromInner<Socket> for TcpListener {
    fn from_inner(socket: Socket) -> TcpListener {
        TcpListener { inner: socket }
    }
}

impl fmt::Debug for TcpListener {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("TcpListener");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}

////////////////////////////////////////////////////////////////////////////////
// UDP
////////////////////////////////////////////////////////////////////////////////

pub struct UdpSocket {
    inner: Socket,
}

impl UdpSocket {
    pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_DGRAM));
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));
        Ok(UdpSocket { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut addrlen = mem::size_of_val(&storage) as socklen_t;

        let n = try!(cvt(unsafe {
            libc::recvfrom(*self.inner.as_inner(),
                           buf.as_mut_ptr() as *mut c_void,
                           buf.len() as wrlen_t, 0,
                           &mut storage as *mut _ as *mut _, &mut addrlen)
        }));
        Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
    }

    pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
        let (dstp, dstlen) = dst.into_inner();
        let ret = try!(cvt(unsafe {
            libc::sendto(*self.inner.as_inner(),
                         buf.as_ptr() as *const c_void, buf.len() as wrlen_t,
                         0, dstp, dstlen)
        }));
        Ok(ret as usize)
    }

    pub fn duplicate(&self) -> io::Result<UdpSocket> {
        self.inner.duplicate().map(|s| UdpSocket { inner: s })
    }

    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
    }

    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }
}

impl FromInner<Socket> for UdpSocket {
    fn from_inner(socket: Socket) -> UdpSocket {
        UdpSocket { inner: socket }
    }
}

impl fmt::Debug for UdpSocket {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("UdpSocket");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}
<commit_msg>Add Send/Sync traits on LookupHost struct<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use prelude::v1::*;

use ffi::{CStr, CString};
use fmt;
use io::{self, Error, ErrorKind};
use libc::{self, c_int, c_char, c_void, socklen_t};
use mem;
use net::{SocketAddr, Shutdown, IpAddr};
use str::from_utf8;
use sys::c;
use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
use sys_common::{AsInner, FromInner, IntoInner};
use time::Duration;

////////////////////////////////////////////////////////////////////////////////
// sockaddr and misc bindings
////////////////////////////////////////////////////////////////////////////////

pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
                     payload: T) -> io::Result<()> {
    unsafe {
        let payload = &payload as *const T as *const c_void;
        try!(cvt(libc::setsockopt(*sock.as_inner(), opt, val, payload,
                                  mem::size_of::<T>() as socklen_t)));
        Ok(())
    }
}

pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
                       val: c_int) -> io::Result<T> {
    unsafe {
        let mut slot: T = mem::zeroed();
        let mut len = mem::size_of::<T>() as socklen_t;
        try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
                               &mut slot as *mut _ as *mut _,
                               &mut len)));
        assert_eq!(len as usize, mem::size_of::<T>());
        Ok(slot)
    }
}

fn sockname<F>(f: F) -> io::Result<SocketAddr>
    where F: FnOnce(*mut libc::sockaddr, *mut socklen_t) -> c_int
{
    unsafe {
        let mut storage: libc::sockaddr_storage = mem::zeroed();
        let mut len = mem::size_of_val(&storage) as socklen_t;
        try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
        sockaddr_to_addr(&storage, len as usize)
    }
}

fn sockaddr_to_addr(storage: &libc::sockaddr_storage,
                    len: usize) -> io::Result<SocketAddr> {
    match storage.ss_family as libc::c_int {
        libc::AF_INET => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in>());
            Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in)
            })))
        }
        libc::AF_INET6 => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in6>());
            Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in6)
            })))
        }
        _ => {
            Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// get_host_addresses
////////////////////////////////////////////////////////////////////////////////

extern "system" {
    fn getaddrinfo(node: *const c_char, service: *const c_char,
                   hints: *const libc::addrinfo,
                   res: *mut *mut libc::addrinfo) -> c_int;
    fn freeaddrinfo(res: *mut libc::addrinfo);
}

pub struct LookupHost {
    original: *mut libc::addrinfo,
    cur: *mut libc::addrinfo,
}

impl Iterator for LookupHost {
    type Item = io::Result<SocketAddr>;
    fn next(&mut self) -> Option<io::Result<SocketAddr>> {
        unsafe {
            if self.cur.is_null() { return None }
            let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
                                       (*self.cur).ai_addrlen as usize);
            self.cur = (*self.cur).ai_next as *mut libc::addrinfo;
            Some(ret)
        }
    }
}

unsafe impl Sync for LookupHost {}
unsafe impl Send for LookupHost {}

impl Drop for LookupHost {
    fn drop(&mut self) {
        unsafe { freeaddrinfo(self.original) }
    }
}

pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
    init();

    let c_host = try!(CString::new(host));
    let mut res = 0 as *mut _;
    unsafe {
        try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _,
                                 &mut res)));
        Ok(LookupHost { original: res, cur: res })
    }
}

////////////////////////////////////////////////////////////////////////////////
// lookup_addr
////////////////////////////////////////////////////////////////////////////////

extern "system" {
    fn getnameinfo(sa: *const libc::sockaddr, salen: socklen_t,
                   host: *mut c_char, hostlen: libc::size_t,
                   serv: *mut c_char, servlen: libc::size_t,
                   flags: c_int) -> c_int;
}

const NI_MAXHOST: usize = 1025;

pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
    init();

    let saddr = SocketAddr::new(*addr, 0);
    let (inner, len) = saddr.into_inner();
    let mut hostbuf = [0 as c_char; NI_MAXHOST];

    let data = unsafe {
        try!(cvt_gai(getnameinfo(inner, len,
                                 hostbuf.as_mut_ptr(), NI_MAXHOST as libc::size_t,
                                 0 as *mut _, 0, 0)));

        CStr::from_ptr(hostbuf.as_ptr())
    };

    match from_utf8(data.to_bytes()) {
        Ok(name) => Ok(name.to_string()),
        Err(_) => Err(io::Error::new(io::ErrorKind::Other,
                                     "failed to lookup address information"))
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP streams
////////////////////////////////////////////////////////////////////////////////

pub struct TcpStream {
    inner: Socket,
}

impl TcpStream {
    pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        let (addrp, len) = addr.into_inner();
        try!(cvt_r(|| unsafe { libc::connect(*sock.as_inner(), addrp, len) }));
        Ok(TcpStream { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
    }

    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let ret = try!(cvt(unsafe {
            libc::send(*self.inner.as_inner(),
                       buf.as_ptr() as *const c_void,
                       buf.len() as wrlen_t,
                       0)
        }));
        Ok(ret as usize)
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getpeername(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        use libc::consts::os::bsd44::SHUT_RDWR;

        let how = match how {
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Both => SHUT_RDWR,
        };
        try!(cvt(unsafe { libc::shutdown(*self.inner.as_inner(), how) }));
        Ok(())
    }

    pub fn duplicate(&self) -> io::Result<TcpStream> {
        self.inner.duplicate().map(|s| TcpStream { inner: s })
    }
}

impl FromInner<Socket> for TcpStream {
    fn from_inner(socket: Socket) -> TcpStream {
        TcpStream { inner: socket }
    }
}

impl fmt::Debug for TcpStream {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("TcpStream");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        if let Ok(peer) = self.peer_addr() {
            res.field("peer", &peer);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////

pub struct TcpListener {
    inner: Socket,
}

impl TcpListener {
    pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        // On platforms with Berkeley-derived sockets, this allows
        // to quickly rebind a socket, without needing to wait for
        // the OS to clean up the previous one.
        if !cfg!(windows) {
            try!(setsockopt(&sock, libc::SOL_SOCKET, libc::SO_REUSEADDR,
                            1 as c_int));
        }

        // Bind our new socket
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));

        // Start listening
        try!(cvt(unsafe { libc::listen(*sock.as_inner(), 128) }));
        Ok(TcpListener { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut len = mem::size_of_val(&storage) as socklen_t;
        let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
                                          &mut len));
        let addr = try!(sockaddr_to_addr(&storage, len as usize));
        Ok((TcpStream { inner: sock, }, addr))
    }

    pub fn duplicate(&self) -> io::Result<TcpListener> {
        self.inner.duplicate().map(|s| TcpListener { inner: s })
    }
}

impl FromInner<Socket> for TcpListener {
    fn from_inner(socket: Socket) -> TcpListener {
        TcpListener { inner: socket }
    }
}

impl fmt::Debug for TcpListener {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("TcpListener");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}

////////////////////////////////////////////////////////////////////////////////
// UDP
////////////////////////////////////////////////////////////////////////////////

pub struct UdpSocket {
    inner: Socket,
}

impl UdpSocket {
    pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_DGRAM));
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));
        Ok(UdpSocket { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn into_socket(self) -> Socket { self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut addrlen = mem::size_of_val(&storage) as socklen_t;

        let n = try!(cvt(unsafe {
            libc::recvfrom(*self.inner.as_inner(),
                           buf.as_mut_ptr() as *mut c_void,
                           buf.len() as wrlen_t, 0,
                           &mut storage as *mut _ as *mut _, &mut addrlen)
        }));
        Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
    }

    pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
        let (dstp, dstlen) = dst.into_inner();
        let ret = try!(cvt(unsafe {
            libc::sendto(*self.inner.as_inner(),
                         buf.as_ptr() as *const c_void, buf.len() as wrlen_t,
                         0, dstp, dstlen)
        }));
        Ok(ret as usize)
    }

    pub fn duplicate(&self) -> io::Result<UdpSocket> {
        self.inner.duplicate().map(|s| UdpSocket { inner: s })
    }

    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
    }

    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_RCVTIMEO)
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.timeout(libc::SO_SNDTIMEO)
    }
}

impl FromInner<Socket> for UdpSocket {
    fn from_inner(socket: Socket) -> UdpSocket {
        UdpSocket { inner: socket }
    }
}

impl fmt::Debug for UdpSocket {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = f.debug_struct("UdpSocket");

        if let Ok(addr) = self.socket_addr() {
            res.field("addr", &addr);
        }

        let name = if cfg!(windows) {"socket"} else {"fd"};
        res.field(name, &self.inner.as_inner())
            .finish()
    }
}
<|endoftext|>


<commit_before>use seed::prelude::*;
use crate::Msg;

pub fn render() -> seed::dom_types::Node<Msg> {

    div![
        h1!["Status"],
        br![],
        br![],
        br![],
        table![
            tbody![
                tr![
                    td!["Number of verified primes:"],
                    td!["1.4 billion"],
                ],
                tr![
                    td!["Website build status:"],
                    td![
                        img![attrs!{At::Src => "https://travis-ci.org/craigmayhew/bigprimes.net-rust-wasm.svg?branch=master"}],
                    ],
                ]
            ]
        ],
    ]
}<commit_msg>Fixed status badge as it was using the old repo name<commit_after>use seed::prelude::*;
use crate::Msg;

pub fn render() -> seed::dom_types::Node<Msg> {

    div![
        h1!["Status"],
        br![],
        br![],
        br![],
        table![
            tbody![
                tr![
                    td!["Number of verified primes:"],
                    td!["1.4 billion"],
                ],
                tr![
                    td!["Website build status:"],
                    td![
                        img![attrs!{At::Src => "https://travis-ci.org/craigmayhew/bigprimes.net.svg?branch=master"}],
                    ],
                ]
            ]
        ],
    ]
}<|endoftext|>


<commit_before>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::os::unix::io::{AsRawFd, RawFd};

use crate::virtio::test_utils::VirtQueue as GuestQ;
use crate::virtio::vsock::device::{RXQ_INDEX, TXQ_INDEX};
use crate::virtio::vsock::packet::{VsockPacket, VSOCK_PKT_HDR_SIZE};
use crate::virtio::{
    QueueError, VirtioDevice, Vsock, VsockBackend, VsockChannel, VsockEpollListener, VsockError,
    VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE,
};
use crate::Error as DeviceError;
use core::result;
use utils::epoll::{EpollEvent, EventSet};
use utils::eventfd::EventFd;
use vm_memory::{GuestAddress, GuestMemoryMmap};

type Result<T> = std::result::Result<T, VsockError>;

pub struct TestBackend {
    pub evfd: EventFd,
    pub rx_err: Option<VsockError>,
    pub tx_err: Option<VsockError>,
    pub pending_rx: bool,
    pub rx_ok_cnt: usize,
    pub tx_ok_cnt: usize,
    pub evset: Option<EventSet>,
}

impl TestBackend {
    pub fn new() -> Self {
        Self {
            evfd: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
            rx_err: None,
            tx_err: None,
            pending_rx: false,
            rx_ok_cnt: 0,
            tx_ok_cnt: 0,
            evset: None,
        }
    }

    pub fn set_rx_err(&mut self, err: Option<VsockError>) {
        self.rx_err = err;
    }
    pub fn set_tx_err(&mut self, err: Option<VsockError>) {
        self.tx_err = err;
    }
    pub fn set_pending_rx(&mut self, prx: bool) {
        self.pending_rx = prx;
    }
}

impl Default for TestBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl VsockChannel for TestBackend {
    fn recv_pkt(&mut self, _pkt: &mut VsockPacket) -> Result<()> {
        let cool_buf = [0xDu8, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF];
        match self.rx_err.take() {
            None => {
                if let Some(buf) = _pkt.buf_mut() {
                    for i in 0..buf.len() {
                        buf[i] = cool_buf[i % cool_buf.len()];
                    }
                }
                self.rx_ok_cnt += 1;
                Ok(())
            }
            Some(e) => Err(e),
        }
    }

    fn send_pkt(&mut self, _pkt: &VsockPacket) -> Result<()> {
        match self.tx_err.take() {
            None => {
                self.tx_ok_cnt += 1;
                Ok(())
            }
            Some(e) => Err(e),
        }
    }

    fn has_pending_rx(&self) -> bool {
        self.pending_rx
    }
}

impl AsRawFd for TestBackend {
    fn as_raw_fd(&self) -> RawFd {
        self.evfd.as_raw_fd()
    }
}

impl VsockEpollListener for TestBackend {
    fn get_polled_evset(&self) -> EventSet {
        EventSet::IN
    }
    fn notify(&mut self, evset: EventSet) {
        self.evset = Some(evset);
    }
}
impl VsockBackend for TestBackend {}

pub struct TestContext {
    pub cid: u64,
    pub mem: GuestMemoryMmap,
    pub mem_size: usize,
    pub device: Vsock<TestBackend>,
}

impl TestContext {
    pub fn new() -> Self {
        const CID: u64 = 52;
        const MEM_SIZE: usize = 1024 * 1024 * 128;
        let mem = GuestMemoryMmap::from_ranges(&[(GuestAddress(0), MEM_SIZE)]).unwrap();
        Self {
            cid: CID,
            mem,
            mem_size: MEM_SIZE,
            device: Vsock::new(CID, TestBackend::new()).unwrap(),
        }
    }

    pub fn create_event_handler_context(&self) -> EventHandlerContext {
        const QSIZE: u16 = 256;

        let guest_rxvq = GuestQ::new(GuestAddress(0x0010_0000), &self.mem, QSIZE as u16);
        let guest_txvq = GuestQ::new(GuestAddress(0x0020_0000), &self.mem, QSIZE as u16);
        let guest_evvq = GuestQ::new(GuestAddress(0x0030_0000), &self.mem, QSIZE as u16);
        let rxvq = guest_rxvq.create_queue();
        let txvq = guest_txvq.create_queue();
        let evvq = guest_evvq.create_queue();

        // Set up one available descriptor in the RX queue.
        guest_rxvq.dtable[0].set(
            0x0040_0000,
            VSOCK_PKT_HDR_SIZE as u32,
            VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT,
            1,
        );
        guest_rxvq.dtable[1].set(0x0040_1000, 4096, VIRTQ_DESC_F_WRITE, 0);

        guest_rxvq.avail.ring[0].set(0);
        guest_rxvq.avail.idx.set(1);

        // Set up one available descriptor in the TX queue.
        guest_txvq.dtable[0].set(0x0050_0000, VSOCK_PKT_HDR_SIZE as u32, VIRTQ_DESC_F_NEXT, 1);
        guest_txvq.dtable[1].set(0x0050_1000, 4096, 0, 0);
        guest_txvq.avail.ring[0].set(0);
        guest_txvq.avail.idx.set(1);

        let queues = vec![rxvq, txvq, evvq];
        EventHandlerContext {
            guest_rxvq,
            guest_txvq,
            guest_evvq,
            device: Vsock::with_queues(self.cid, TestBackend::new(), queues).unwrap(),
        }
    }
}

impl Default for TestContext {
    fn default() -> Self {
        Self::new()
    }
}

pub struct EventHandlerContext<'a> {
    pub device: Vsock<TestBackend>,
    pub guest_rxvq: GuestQ<'a>,
    pub guest_txvq: GuestQ<'a>,
    pub guest_evvq: GuestQ<'a>,
}

impl<'a> EventHandlerContext<'a> {
    pub fn mock_activate(&mut self, mem: GuestMemoryMmap) {
        // Artificially activate the device.
        self.device.activate(mem).unwrap();
    }

    pub fn signal_txq_event(&mut self) {
        self.device.queue_events[TXQ_INDEX].write(1).unwrap();
        self.device
            .handle_txq_event(&EpollEvent::new(EventSet::IN, 0));
    }
    pub fn signal_rxq_event(&mut self) {
        self.device.queue_events[RXQ_INDEX].write(1).unwrap();
        self.device
            .handle_rxq_event(&EpollEvent::new(EventSet::IN, 0));
    }
}

impl<B> Vsock<B>
where
    B: VsockBackend,
{
    pub fn write_element_in_queue(
        vsock: &Vsock<B>,
        idx: usize,
        val: u64,
    ) -> result::Result<(), DeviceError> {
        if idx > vsock.queue_events.len() {
            return Err(DeviceError::QueueError(QueueError::DescIndexOutOfBounds(
                idx as u16,
            )));
        }
        vsock.queue_events[idx].write(val).unwrap();
        Ok(())
    }

    pub fn get_element_from_queue(
        vsock: &Vsock<B>,
        idx: usize,
    ) -> result::Result<u64, DeviceError> {
        if idx > vsock.queue_events.len() {
            return Err(DeviceError::QueueError(QueueError::DescIndexOutOfBounds(
                idx as u16,
            )));
        }
        Ok(vsock.queue_events[idx].as_raw_fd() as u64)
    }
}
<commit_msg>[vsock]test_utils: expand aux function<commit_after>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::os::unix::io::{AsRawFd, RawFd};

use crate::virtio::test_utils::VirtQueue as GuestQ;
use crate::virtio::vsock::device::{RXQ_INDEX, TXQ_INDEX};
use crate::virtio::vsock::packet::{VsockPacket, VSOCK_PKT_HDR_SIZE};
use crate::virtio::{
    VirtioDevice, Vsock, VsockBackend, VsockChannel, VsockEpollListener, VsockError,
    VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE,
};
use utils::epoll::{EpollEvent, EventSet};
use utils::eventfd::EventFd;
use vm_memory::{GuestAddress, GuestMemoryMmap};

type Result<T> = std::result::Result<T, VsockError>;

pub struct TestBackend {
    pub evfd: EventFd,
    pub rx_err: Option<VsockError>,
    pub tx_err: Option<VsockError>,
    pub pending_rx: bool,
    pub rx_ok_cnt: usize,
    pub tx_ok_cnt: usize,
    pub evset: Option<EventSet>,
}

impl TestBackend {
    pub fn new() -> Self {
        Self {
            evfd: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
            rx_err: None,
            tx_err: None,
            pending_rx: false,
            rx_ok_cnt: 0,
            tx_ok_cnt: 0,
            evset: None,
        }
    }

    pub fn set_rx_err(&mut self, err: Option<VsockError>) {
        self.rx_err = err;
    }
    pub fn set_tx_err(&mut self, err: Option<VsockError>) {
        self.tx_err = err;
    }
    pub fn set_pending_rx(&mut self, prx: bool) {
        self.pending_rx = prx;
    }
}

impl Default for TestBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl VsockChannel for TestBackend {
    fn recv_pkt(&mut self, _pkt: &mut VsockPacket) -> Result<()> {
        let cool_buf = [0xDu8, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF];
        match self.rx_err.take() {
            None => {
                if let Some(buf) = _pkt.buf_mut() {
                    for i in 0..buf.len() {
                        buf[i] = cool_buf[i % cool_buf.len()];
                    }
                }
                self.rx_ok_cnt += 1;
                Ok(())
            }
            Some(e) => Err(e),
        }
    }

    fn send_pkt(&mut self, _pkt: &VsockPacket) -> Result<()> {
        match self.tx_err.take() {
            None => {
                self.tx_ok_cnt += 1;
                Ok(())
            }
            Some(e) => Err(e),
        }
    }

    fn has_pending_rx(&self) -> bool {
        self.pending_rx
    }
}

impl AsRawFd for TestBackend {
    fn as_raw_fd(&self) -> RawFd {
        self.evfd.as_raw_fd()
    }
}

impl VsockEpollListener for TestBackend {
    fn get_polled_evset(&self) -> EventSet {
        EventSet::IN
    }
    fn notify(&mut self, evset: EventSet) {
        self.evset = Some(evset);
    }
}
impl VsockBackend for TestBackend {}

pub struct TestContext {
    pub cid: u64,
    pub mem: GuestMemoryMmap,
    pub mem_size: usize,
    pub device: Vsock<TestBackend>,
}

impl TestContext {
    pub fn new() -> Self {
        const CID: u64 = 52;
        const MEM_SIZE: usize = 1024 * 1024 * 128;
        let mem = GuestMemoryMmap::from_ranges(&[(GuestAddress(0), MEM_SIZE)]).unwrap();
        Self {
            cid: CID,
            mem,
            mem_size: MEM_SIZE,
            device: Vsock::new(CID, TestBackend::new()).unwrap(),
        }
    }

    pub fn create_event_handler_context(&self) -> EventHandlerContext {
        const QSIZE: u16 = 256;

        let guest_rxvq = GuestQ::new(GuestAddress(0x0010_0000), &self.mem, QSIZE as u16);
        let guest_txvq = GuestQ::new(GuestAddress(0x0020_0000), &self.mem, QSIZE as u16);
        let guest_evvq = GuestQ::new(GuestAddress(0x0030_0000), &self.mem, QSIZE as u16);
        let rxvq = guest_rxvq.create_queue();
        let txvq = guest_txvq.create_queue();
        let evvq = guest_evvq.create_queue();

        // Set up one available descriptor in the RX queue.
        guest_rxvq.dtable[0].set(
            0x0040_0000,
            VSOCK_PKT_HDR_SIZE as u32,
            VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT,
            1,
        );
        guest_rxvq.dtable[1].set(0x0040_1000, 4096, VIRTQ_DESC_F_WRITE, 0);

        guest_rxvq.avail.ring[0].set(0);
        guest_rxvq.avail.idx.set(1);

        // Set up one available descriptor in the TX queue.
        guest_txvq.dtable[0].set(0x0050_0000, VSOCK_PKT_HDR_SIZE as u32, VIRTQ_DESC_F_NEXT, 1);
        guest_txvq.dtable[1].set(0x0050_1000, 4096, 0, 0);
        guest_txvq.avail.ring[0].set(0);
        guest_txvq.avail.idx.set(1);

        let queues = vec![rxvq, txvq, evvq];
        EventHandlerContext {
            guest_rxvq,
            guest_txvq,
            guest_evvq,
            device: Vsock::with_queues(self.cid, TestBackend::new(), queues).unwrap(),
        }
    }
}

impl Default for TestContext {
    fn default() -> Self {
        Self::new()
    }
}

pub struct EventHandlerContext<'a> {
    pub device: Vsock<TestBackend>,
    pub guest_rxvq: GuestQ<'a>,
    pub guest_txvq: GuestQ<'a>,
    pub guest_evvq: GuestQ<'a>,
}

impl<'a> EventHandlerContext<'a> {
    pub fn mock_activate(&mut self, mem: GuestMemoryMmap) {
        // Artificially activate the device.
        self.device.activate(mem).unwrap();
    }

    pub fn signal_txq_event(&mut self) {
        self.device.queue_events[TXQ_INDEX].write(1).unwrap();
        self.device
            .handle_txq_event(&EpollEvent::new(EventSet::IN, 0));
    }
    pub fn signal_rxq_event(&mut self) {
        self.device.queue_events[RXQ_INDEX].write(1).unwrap();
        self.device
            .handle_rxq_event(&EpollEvent::new(EventSet::IN, 0));
    }
}

impl<B> Vsock<B>
where
    B: VsockBackend,
{
    pub fn write_element_in_queue(vsock: &Vsock<B>, idx: usize, val: u64) {
        if idx > vsock.queue_events.len() - 1 {
            panic!("Index bigger than the number of queues of this device");
        }
        vsock.queue_events[idx].write(val).unwrap();
    }

    pub fn get_element_from_interest_list(vsock: &Vsock<B>, idx: usize) -> u64 {
        match idx {
            0..=2 => vsock.queue_events[idx].as_raw_fd() as u64,
            3 => vsock.backend.as_raw_fd() as u64,
            4 => vsock.activate_evt.as_raw_fd() as u64,
            _ => panic!("Index bigger than interest list"),
        }
    }
}
<|endoftext|>


<commit_before>use regex::Regex;
use parser::parse;
use normalizer::normalize;
use parser::span::parse_spans;
use parser::Block;
use parser::Block::{Header, Paragraph, Blockquote};
use parser::Span;
use parser::Span::{Break, Text, Emphasis, Strong, Code, Link, Image};

static ATX_HEADER      : Regex = regex!(r"^(?P<level>#{1,6})\s(?P<text>.*)");
static SETEXT_HEADER_1 : Regex = regex!(r"(?P<text>.+)\n===+");
static SETEXT_HEADER_2 : Regex = regex!(r"(?P<text>.+)\n---+");
static BLOCKQUOTE      : Regex = regex!(r"(?m)^> ?");

pub fn parse_block (text : &str) -> Option<Block>{
    if text.is_empty(){
        return None;
    }else if BLOCKQUOTE.is_match(text){
        // remove top-level >s
        let caps = BLOCKQUOTE.replace_all(text, "");
        return Some(
            Blockquote(parse(caps.as_slice()))
        );
    }else if ATX_HEADER.is_match(text){
        let caps = ATX_HEADER.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                caps.name("level").len()
                )
            );
    }else if SETEXT_HEADER_1.is_match(text){
        let caps = SETEXT_HEADER_1.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                1
                )
            );
    }else if SETEXT_HEADER_2.is_match(text){
        let caps = SETEXT_HEADER_2.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                2
                )
            );
    }
    return Some(Paragraph(parse_spans(text)));
}

#[test]
fn parse_atx_header_test() {
    assert_eq!(
        parse_block("### Test").unwrap(),
        Header(vec![Text("Test".to_string())], 3)
    );

    assert_eq!(
        parse_block("# Test").unwrap(),
        Header(vec![Text("Test".to_string())], 1)
    );

    assert_eq!(
        parse_block("###### Test").unwrap(),
        Header(vec![Text("Test".to_string())], 6)
    );

    assert_eq!(
        parse_block("####### Test").unwrap(),
        Paragraph(vec![Text("####### Test".to_string())])
    );
}

#[test]
fn parse_blockquote_test() {
    assert_eq!(
        parse_block("> One Paragraph\n>\n> > Another blockquote\n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]),
                   Blockquote(vec![Paragraph(vec![Text("Another blockquote".to_string())])])])
    );

    assert_eq!(
        parse_block("> One Paragraph\n>\n> ## H2 \n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]), Header(vec![Text("H2 ".to_string())], 2)])
    );
}

<commit_msg>More blockquote tests<commit_after>use regex::Regex;
use parser::parse;
use normalizer::normalize;
use parser::span::parse_spans;
use parser::Block;
use parser::Block::{Header, Paragraph, Blockquote};
use parser::Span;
use parser::Span::{Break, Text, Emphasis, Strong, Code, Link, Image};

static ATX_HEADER      : Regex = regex!(r"^(?P<level>#{1,6})\s(?P<text>.*)");
static SETEXT_HEADER_1 : Regex = regex!(r"(?P<text>.+)\n===+");
static SETEXT_HEADER_2 : Regex = regex!(r"(?P<text>.+)\n---+");
static BLOCKQUOTE      : Regex = regex!(r"(?m)^> ?");

pub fn parse_block (text : &str) -> Option<Block>{
    if text.is_empty(){
        return None;
    }else if BLOCKQUOTE.is_match(text){
        // remove top-level >s
        let caps = BLOCKQUOTE.replace_all(text, "");
        return Some(
            Blockquote(parse(caps.as_slice()))
        );
    }else if ATX_HEADER.is_match(text){
        let caps = ATX_HEADER.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                caps.name("level").len()
                )
            );
    }else if SETEXT_HEADER_1.is_match(text){
        let caps = SETEXT_HEADER_1.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                1
                )
            );
    }else if SETEXT_HEADER_2.is_match(text){
        let caps = SETEXT_HEADER_2.captures(text).unwrap();
        return Some(
            Header(
                parse_spans(caps.name("text")),
                2
                )
            );
    }
    return Some(Paragraph(parse_spans(text)));
}

#[test]
fn parse_atx_header_test() {
    assert_eq!(
        parse_block("### Test").unwrap(),
        Header(vec![Text("Test".to_string())], 3)
    );

    assert_eq!(
        parse_block("# Test").unwrap(),
        Header(vec![Text("Test".to_string())], 1)
    );

    assert_eq!(
        parse_block("###### Test").unwrap(),
        Header(vec![Text("Test".to_string())], 6)
    );

    assert_eq!(
        parse_block("####### Test").unwrap(),
        Paragraph(vec![Text("####### Test".to_string())])
    );
}

#[test]
fn parse_blockquote_test() {
    assert_eq!(
        parse_block("> One Paragraph\n>\n> ## H2 \n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]), Header(vec![Text("H2 ".to_string())], 2)])
    );

    assert_eq!(
        parse_block("> One Paragraph\n>\n> > Another blockquote\n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]),
                   Blockquote(vec![Paragraph(vec![Text("Another blockquote".to_string())])])])
    );

    assert_eq!(
        parse_block("> > One Paragraph\n> >\n> > Another blockquote\n>\n").unwrap(),
        Blockquote(vec![Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]),
                   Paragraph(vec![Text("Another blockquote".to_string())])])])
    );

    assert_eq!(
        parse_block("> One Paragraph, just > text \n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph, just > text ".to_string())])])
    );

    assert_eq!(
        parse_block("> One Paragraph,\n just\n > text ").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph,\n just\n > text ".to_string())])])
    );

    assert_eq!(
        parse_block("> One Paragraph\n>\n> just > text \n>\n").unwrap(),
        Blockquote(vec![Paragraph(vec![Text("One Paragraph".to_string())]),Paragraph(vec![Text("just > text ".to_string())])])
    );
}

<|endoftext|>