<commit_before><commit_msg>implementing custom str type<commit_after>struct Str {
	data:Vec<char>,
	len:u32,
}

impl Str {
	fn new() -> Self {
		Str { data:Vec::new(),len:0 }
	}
	fn push(&mut self,letter:char) {
		self.data.push(letter);
	}
	fn len(&self) -> u32 {
		{self.len}
	}

	fn display(self) {
		for i in self.data {
			print!("{}",i);
		}
	}
 }

fn main() {
	let mut s1 = Str::new();
	s1.push('r');
	s1.push('u');
	s1.push('s');
	s1.push('t');
	s1.display();

}<|endoftext|>


<commit_before><commit_msg>Rust: Add a full keyset example<commit_after>#[cfg(test)]
mod elektra_examples {
    use crate::{KeyBuilder, ReadableKey, StringKey, WriteableKey};

    #[test]
    fn key_example() -> Result<(), Box<dyn std::error::Error>> {
        // This test should stay in sync with the example in the Readme
        // To create a simple key with a name and value
        let mut key = StringKey::new("user/test/language")?;
        key.set_value("rust");
        assert_eq!(key.name(), "user/test/language");
        assert_eq!(key.value(), "rust");

        // To iterate over the name
        for name in key.name_iter() {
            println!("Name: {}", name);
        }

        // Duplicate a key
        let key_duplicate = key.duplicate();

        // And compare them
        assert_eq!(key, key_duplicate);

        // To create a key with multiple meta values, use the KeyBuilder
        let mut key: StringKey = KeyBuilder::new("user/test/fruits")?
            .meta("banana", "🍌")?
            .meta("pineapple", "🍍")?
            .meta("strawberry", "🍓")?
            .build();
        assert_eq!(key.meta("pineapple")?.value(), "🍍");

        // We can iterate over the metakeys
        key.rewind_meta();
        for metakey in key.meta_iter() {
            println!("Key: {}, Value: {}", metakey.name(), metakey.value());
        }

        // Delete a metakey
        key.delete_meta("banana")?;

        // Check if key is in the user namespace
        assert!(key.is_user());

        Ok(())
    }

    use crate::{KeySet, LookupOption};

    #[test]
    fn keyset_example() -> Result<(), Box<dyn std::error::Error>> {
        // Create a new KeySet with enough preallocated space for 5 Keys
        let mut keyset = KeySet::with_capacity(5);

        // Append some keys
        keyset.append_key(
            KeyBuilder::<StringKey>::new("user/sw/app/#1/host")?
                .value("localhost")
                .build(),
        )?;
        keyset.append_key(
            KeyBuilder::<StringKey>::new("user/sw/app/#1/port")?
                .value("8080")
                .build(),
        )?;

        // Iterate the keyset
        keyset.rewind();
        for mut key in keyset.iter_mut() {
            // Add a metakey to each key
            key.set_meta("setby", "owner")?;
        }

        // Lookup a key by name and set a new value
        if let Some(mut found_key) =
            keyset.lookup_by_name("user/sw/app/#1/port", LookupOption::KDB_O_NONE)
        {
            found_key.set_value("5001");
        } else {
            panic!("Did not find the key!");
        }

        // Delete a key by passing the POP option
        keyset.lookup_by_name("user/sw/app/#1/host", LookupOption::KDB_O_POP);

        // Remove the last (and now only) key in the set
        let removed_key = keyset.pop().unwrap();

        assert_eq!(removed_key.value(), "5001");
        // Check that the meta information is set
        assert_eq!(removed_key.meta("setby")?.value(), "owner");

        // The keyset is now empty
        assert_eq!(keyset.size(), 0);

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


<commit_before><commit_msg>Upgrade to latest Rust.<commit_after><|endoftext|>


<commit_before><commit_msg>Add solution to problem 29<commit_after>#![feature(core)]
#[macro_use] extern crate libeuler;
extern crate num;

use num::traits::FromPrimitive;
use num::bigint::BigInt;
use num::pow;

use std::collections::HashSet;

/// Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
///
///     2^2=4, 2^3=8, 2^4=16, 2^5=32
///     3^2=9, 3^3=27, 3^4=81, 3^5=243
///     4^2=16, 4^3=64, 4^4=256, 4^5=1024
///     5^2=25, 5^3=125, 5^4=625, 5^5=3125
///
/// If they are then placed in numerical order, with any repeats removed, we get the following
/// sequence of 15 distinct terms:
///
/// 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
///
/// How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
fn main() {
    solutions! {
        inputs: (max: i32 = 100)
        sol naive {
            let mut set = HashSet::new();
            for a in 2..max+1 {
                for b in 2..max+1 {
                    set.insert(pow(BigInt::from_i32(a).unwrap(), b as usize));
                }
            }

            set.len()
        }
    }
}
<|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.

// .debug_gdb_scripts binary section.

use llvm;
use llvm::ValueRef;

use trans::common::{C_bytes, CrateContext, C_i32};
use trans::declare;
use trans::type_::Type;
use session::config::NoDebugInfo;

use std::ffi::CString;
use std::ptr;
use syntax::attr;

/// Inserts a side-effect free instruction sequence that makes sure that the
/// .debug_gdb_scripts global is referenced, so it isn't removed by the linker.
pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext) {
    if needs_gdb_debug_scripts_section(ccx) {
        let empty = CString::new("").unwrap();
        let gdb_debug_scripts_section_global =
            get_or_insert_gdb_debug_scripts_section_global(ccx);
        unsafe {
            // Load just the first byte as that's all that's necessary to force
            // LLVM to keep around the reference to the global.
            let indices = [C_i32(ccx, 0), C_i32(ccx, 0)];
            let element =
                llvm::LLVMBuildInBoundsGEP(ccx.raw_builder(),
                                           gdb_debug_scripts_section_global,
                                           indices.as_ptr(),
                                           indices.len() as ::libc::c_uint,
                                           empty.as_ptr());
            let volative_load_instruction =
                llvm::LLVMBuildLoad(ccx.raw_builder(),
                                    element,
                                    empty.as_ptr());
            llvm::LLVMSetVolatile(volative_load_instruction, llvm::True);
            llvm::LLVMSetAlignment(volative_load_instruction, 1);
        }
    }
}

/// Allocates the global variable responsible for the .debug_gdb_scripts binary
/// section.
pub fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext)
                                                  -> llvm::ValueRef {
    let section_var_name = "__rustc_debug_gdb_scripts_section__";

    let section_var = unsafe {
        llvm::LLVMGetNamedGlobal(ccx.llmod(),
                                 section_var_name.as_ptr() as *const _)
    };

    if section_var == ptr::null_mut() {
        let section_name = b".debug_gdb_scripts\0";
        let section_contents = b"\x01gdb_load_rust_pretty_printers.py\0";

        unsafe {
            let llvm_type = Type::array(&Type::i8(ccx),
                                        section_contents.len() as u64);

            let section_var = declare::define_global(ccx, section_var_name,
                                                     llvm_type).unwrap_or_else(||{
                ccx.sess().bug(&format!("symbol `{}` is already defined", section_var_name))
            });
            llvm::LLVMSetSection(section_var, section_name.as_ptr() as *const _);
            llvm::LLVMSetInitializer(section_var, C_bytes(ccx, section_contents));
            llvm::LLVMSetGlobalConstant(section_var, llvm::True);
            llvm::LLVMSetUnnamedAddr(section_var, llvm::True);
            llvm::SetLinkage(section_var, llvm::Linkage::LinkOnceODRLinkage);
            // This should make sure that the whole section is not larger than
            // the string it contains. Otherwise we get a warning from GDB.
            llvm::LLVMSetAlignment(section_var, 1);
            section_var
        }
    } else {
        section_var
    }
}

pub fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
    let omit_gdb_pretty_printer_section =
        attr::contains_name(&ccx.tcx()
                                .map
                                .krate()
                                .attrs,
                            "omit_gdb_pretty_printer_section");

    !omit_gdb_pretty_printer_section &&
    !ccx.sess().target.target.options.is_like_osx &&
    !ccx.sess().target.target.options.is_like_windows &&
    ccx.sess().opts.debuginfo != NoDebugInfo
}
<commit_msg>Use a proper C string for the gdb script section name<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.

// .debug_gdb_scripts binary section.

use llvm;
use llvm::ValueRef;

use trans::common::{C_bytes, CrateContext, C_i32};
use trans::declare;
use trans::type_::Type;
use session::config::NoDebugInfo;

use std::ffi::CString;
use std::ptr;
use syntax::attr;

/// Inserts a side-effect free instruction sequence that makes sure that the
/// .debug_gdb_scripts global is referenced, so it isn't removed by the linker.
pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext) {
    if needs_gdb_debug_scripts_section(ccx) {
        let empty = CString::new("").unwrap();
        let gdb_debug_scripts_section_global =
            get_or_insert_gdb_debug_scripts_section_global(ccx);
        unsafe {
            // Load just the first byte as that's all that's necessary to force
            // LLVM to keep around the reference to the global.
            let indices = [C_i32(ccx, 0), C_i32(ccx, 0)];
            let element =
                llvm::LLVMBuildInBoundsGEP(ccx.raw_builder(),
                                           gdb_debug_scripts_section_global,
                                           indices.as_ptr(),
                                           indices.len() as ::libc::c_uint,
                                           empty.as_ptr());
            let volative_load_instruction =
                llvm::LLVMBuildLoad(ccx.raw_builder(),
                                    element,
                                    empty.as_ptr());
            llvm::LLVMSetVolatile(volative_load_instruction, llvm::True);
            llvm::LLVMSetAlignment(volative_load_instruction, 1);
        }
    }
}

/// Allocates the global variable responsible for the .debug_gdb_scripts binary
/// section.
pub fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext)
                                                  -> llvm::ValueRef {
    let c_section_var_name = "__rustc_debug_gdb_scripts_section__\0";
    let section_var_name = &c_section_var_name[..c_section_var_name.len()-1];

    let section_var = unsafe {
        llvm::LLVMGetNamedGlobal(ccx.llmod(),
                                 c_section_var_name.as_ptr() as *const _)
    };

    if section_var == ptr::null_mut() {
        let section_name = b".debug_gdb_scripts\0";
        let section_contents = b"\x01gdb_load_rust_pretty_printers.py\0";

        unsafe {
            let llvm_type = Type::array(&Type::i8(ccx),
                                        section_contents.len() as u64);

            let section_var = declare::define_global(ccx, section_var_name,
                                                     llvm_type).unwrap_or_else(||{
                ccx.sess().bug(&format!("symbol `{}` is already defined", section_var_name))
            });
            llvm::LLVMSetSection(section_var, section_name.as_ptr() as *const _);
            llvm::LLVMSetInitializer(section_var, C_bytes(ccx, section_contents));
            llvm::LLVMSetGlobalConstant(section_var, llvm::True);
            llvm::LLVMSetUnnamedAddr(section_var, llvm::True);
            llvm::SetLinkage(section_var, llvm::Linkage::LinkOnceODRLinkage);
            // This should make sure that the whole section is not larger than
            // the string it contains. Otherwise we get a warning from GDB.
            llvm::LLVMSetAlignment(section_var, 1);
            section_var
        }
    } else {
        section_var
    }
}

pub fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
    let omit_gdb_pretty_printer_section =
        attr::contains_name(&ccx.tcx()
                                .map
                                .krate()
                                .attrs,
                            "omit_gdb_pretty_printer_section");

    !omit_gdb_pretty_printer_section &&
    !ccx.sess().target.target.options.is_like_osx &&
    !ccx.sess().target.target.options.is_like_windows &&
    ccx.sess().opts.debuginfo != NoDebugInfo
}
<|endoftext|>


<commit_before><commit_msg>Rename CustomPacket to Unidentified - Well, is can maybe an unimplemented or just a custom user packet<commit_after><|endoftext|>


<commit_before><commit_msg>crypto: fix rustfmt<commit_after><|endoftext|>


<commit_before><commit_msg>Finished letter.rs example<commit_after>// This example is based off of the tutorial found here:
//
//   * https://takinginitiative.wordpress.com/2008/04/23/basic-neural-network-tutorial-c-implementation-and-source-code/
//
// The basic premise is recognizing a single letter ('A') given a large dataset
// of vectors which represent pixels on a screen. The dataset is found in the
// `data/` subfolder in this directory. It is formatted as a CSV, with the
// first character being the expected character (one of 26 from the English
// alphabet), and the next 16 integers form the input vector.

extern crate num;
extern crate csv;
extern crate time;
extern crate nnet;
extern crate rustc_serialize;
#[macro_use(ffnn)] extern crate nnet_macros;

use num::Float;
use time::PreciseTime;
use csv::{Reader, Result};
use nnet::trainer::backpropagation::*;
use nnet::params::{TanhNeuralNet, LogisticNeuralNet};
use nnet::prelude::{NeuralNetTrainer, NeuralNet, MomentumConstant, Layer,
  LearningRate, TrainingSetMember};

// Input  = 16
// Hidden = 8
// Output = 1
ffnn!([derive(RustcEncodable, RustcDecodable)]; LetterNeuralNet, 16, 8, 1);

struct MyTrainerParams;

impl MomentumConstant for MyTrainerParams {
  #[inline(always)] fn momentum() -> f64 { 0.4f64 }
}

impl LearningRate for MyTrainerParams {
  #[inline(always)] fn lrate() -> f64 { 0.1f64 }
}

/// Training set example. Expected is 0 or 1. 1 if the letter is 'A', and 0
/// otherwise.
///
#[derive(RustcDecodable)]
struct LetterData {
  expected: [f64; 1],
  input: [f64; 16]
}

impl TrainingSetMember for LetterData {
  #[inline(always)] fn input(&self) -> &[f64] { self.input.as_ref() }
  #[inline(always)] fn expected(&self) -> &[f64] { self.expected.as_ref() }
}

fn main() {
  // Change this flag to `true`, if you want to load an already trained
  // neural network. The training process takes a bit.
  let use_json = false;

  // Read the data and transform it into a vector of `LetterData` objects.
  let data = include_str!("data/letter-recognition.data");
  let rows = Reader::from_string(data)
    .has_headers(false)
    .decode()
    .map(|decoded: Result<(char, _)>| {
      match decoded {
        Ok((c, input)) => {
          let is_a = if c == 'A' { 1f64 } else { 0f64 };
          LetterData { expected: [is_a; 1], input: input }
        }
        Err(e) => panic!("unrecognzed data: {:?}", e)
      }
    })
    .collect::<Vec<LetterData>>();

  let mut nn: LetterNeuralNet<TanhNeuralNet> = if use_json {
    let json = include_str!("data/letter.json");
    ::rustc_serialize::json::decode(json).unwrap()
  } else {
    LetterNeuralNet::new()
  };

  // Use the first 2/3's of the dataset as the training set.
  let tset = 2 * rows.len() / 3;

  println!("found {:?} examples", rows.len());
  println!("using {:?} examples to train", tset);

  if !use_json {
    let start = PreciseTime::now();

    parallel
      ::BatchEpochTrainer::<_, _, MyTrainerParams, _>
      ::with_epochs(&mut nn, &rows[0..tset], 500)
        .train();

    println!("took = {:?} ms", start.to(PreciseTime::now()).num_milliseconds());
  }

  let mut failed_predictions = 0;

  for (i, x) in rows.iter().enumerate() {
    nn.predict(&x.input);

    let prediction = nn.layer(Layer::Output);

    if prediction[0].round() as usize != x.expected[0].round() as usize {
      println!(
        "{:?}  | predicted = {:?} / expected = {:?}",
        i,
        prediction[0].round() as usize,
        x.expected[0].round() as usize);

      failed_predictions += 1;
    }
  }

  println!("failed = {:?} / total = {:?}", failed_predictions, rows.len());
}<|endoftext|>


<commit_before><commit_msg>Added hello world example<commit_after><|endoftext|>


<commit_before><commit_msg>Expose docstring for JSON Responder impl.<commit_after><|endoftext|>


<commit_before>import std._io.stdio_reader;

fn in_range(char c, char lo, char hi) -> bool {
    ret lo <= c && c <= hi;
}

fn is_alpha(char c) -> bool {
    ret in_range(c, 'a', 'z') ||
        in_range(c, 'A', 'Z');
}

fn is_dec_digit(char c) -> bool {
    ret in_range(c, '0', '9');
}

fn is_hex_digit(char c) -> bool {
    ret in_range(c, '0', '9') ||
        in_range(c, 'a', 'f') ||
        in_range(c, 'A', 'F');
}

fn is_bin_digit(char c) -> bool {
    ret c == '0' || c == '1';
}

fn is_whitespace(char c) -> bool {
    ret c == ' ' || c == '\t' || c == '\r' || c == '\n';
}

fn consume_any_whitespace(stdio_reader rdr, char c) -> char {
    auto c1 = c;
    while (is_whitespace(c1)) {
        c1 = rdr.getc() as char;
    }
    be consume_any_line_comment(rdr, c1);
}

fn consume_any_line_comment(stdio_reader rdr, char c) -> char {
    auto c1 = c;
    if (c1 == '/') {
        auto c2 = rdr.getc() as char;
        if (c2 == '/') {
            while (c1 != '\n') {
                c1 = rdr.getc() as char;
            }
            // Restart whitespace munch.
            be consume_any_whitespace(rdr, c1);
        }
    }
    ret c;
}

fn next_token(stdio_reader rdr) -> token.token {
    auto eof = (-1) as char;
    auto c = rdr.getc() as char;
    auto accum_str = "";
    auto accum_int = 0;

    fn next(stdio_reader rdr) -> char {
        ret rdr.getc() as char;
    }

    fn forget(stdio_reader rdr, char c) {
        rdr.ungetc(c as int);
    }

    c = consume_any_whitespace(rdr, c);

    if (c == eof) { ret token.EOF(); }

    if (is_alpha(c)) {
        while (is_alpha(c)) {
            accum_str += (c as u8);
            c = next(rdr);
        }
        forget(rdr, c);
        ret token.IDENT(accum_str);
    }

    if (is_dec_digit(c)) {
        if (c == '0') {
        } else {
            while (is_dec_digit(c)) {
                accum_int *= 10;
                accum_int += (c as int) - ('0' as int);
                c = next(rdr);
            }
            forget(rdr, c);
            ret token.LIT_INT(accum_int);
        }
    }

    fn op_or_opeq(stdio_reader rdr, char c2,
                  token.op op) -> token.token {
        if (c2 == '=') {
            ret token.OPEQ(op);
        } else {
            forget(rdr, c2);
            ret token.OP(op);
        }
    }

    alt (c) {
        // One-byte tokens.
        case (';') { ret token.SEMI(); }
        case (',') { ret token.COMMA(); }
        case ('.') { ret token.DOT(); }
        case ('(') { ret token.LPAREN(); }
        case (')') { ret token.RPAREN(); }
        case ('{') { ret token.LBRACE(); }
        case ('}') { ret token.RBRACE(); }
        case ('[') { ret token.LBRACKET(); }
        case (']') { ret token.RBRACKET(); }
        case ('@') { ret token.AT(); }
        case ('#') { ret token.POUND(); }

        // Multi-byte tokens.
        case ('=') {
            auto c2 = next(rdr);
            if (c2 == '=') {
                ret token.OP(token.EQEQ());
            } else {
                forget(rdr, c2);
                ret token.OP(token.EQ());
            }
        }

        case ('\'') {
            // FIXME: general utf8-consumption support.
            auto c2 = next(rdr);
            if (c2 == '\\') {
                c2 = next(rdr);
                alt (c2) {
                    case ('n') { c2 = '\n'; }
                    case ('r') { c2 = '\r'; }
                    case ('t') { c2 = '\t'; }
                    case ('\\') { c2 = '\\'; }
                    case ('\'') { c2 = '\''; }
                    // FIXME: unicode numeric escapes.
                    case (_) {
                        log "unknown character escape";
                        log c2;
                        fail;
                    }
                }
            }
            if (next(rdr) != '\'') {
                log "unterminated character constant";
                fail;
            }
            ret token.LIT_CHAR(c2);
        }

        case ('"') {
            // FIXME: general utf8-consumption support.
            auto c2 = next(rdr);
            while (c2 != '"') {
                alt (c2) {
                    case ('\\') {
                        c2 = next(rdr);
                        alt (c2) {
                            case ('n') { accum_str += '\n' as u8; }
                            case ('r') { accum_str += '\r' as u8; }
                            case ('t') { accum_str += '\t' as u8; }
                            case ('\\') { accum_str += '\\' as u8; }
                            case ('"') { accum_str += '"' as u8; }
                            // FIXME: unicode numeric escapes.
                            case (_) {
                                log "unknown string escape";
                                log c2;
                                fail;
                            }
                        }
                    }
                    case (_) {
                        accum_str += c2 as u8;
                    }
                }
                c2 = next(rdr);
            }
            ret token.LIT_STR(accum_str);
        }

        case ('-') {
            auto c2 = next(rdr);
            if (c2 == '>') {
                ret token.RARROW();
            } else {
                ret op_or_opeq(rdr, c2, token.MINUS());
            }
        }

        case ('&') {
            auto c2 = next(rdr);
            if (c2 == '&') {
                ret token.OP(token.ANDAND());
            } else {
                ret op_or_opeq(rdr, c2, token.AND());
            }
        }

        case ('+') {
            ret op_or_opeq(rdr, next(rdr), token.PLUS());
        }

        case ('*') {
            ret op_or_opeq(rdr, next(rdr), token.STAR());
        }

        case ('/') {
            ret op_or_opeq(rdr, next(rdr), token.STAR());
        }

        case ('!') {
            ret op_or_opeq(rdr, next(rdr), token.NOT());
        }

        case ('^') {
            ret op_or_opeq(rdr, next(rdr), token.CARET());
        }

        case ('%') {
            ret op_or_opeq(rdr, next(rdr), token.PERCENT());
        }

    }

    log "lexer stopping at ";
    log c;
    ret token.EOF();
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>Add lexer.reader to rustc for tracking position, char conversion, holding keyword tables.<commit_after>import std._io.stdio_reader;
import std._str;
import std.map;
import std.map.hashmap;

fn new_str_hash[V]() -> map.hashmap[str,V] {
    let map.hashfn[str] hasher = _str.hash;
    let map.eqfn[str] eqer = _str.eq;
    ret map.mk_hashmap[str,V](hasher, eqer);
}

type reader = obj {
              fn is_eof() -> bool;
              fn peek() -> char;
              fn bump();
              fn get_pos() -> tup(str,uint,uint);
              fn get_keywords() -> hashmap[str,token.token];
              fn get_reserved() -> hashmap[str,()];
};

fn new_reader(stdio_reader rdr, str filename) -> reader
{
    obj reader(stdio_reader rdr,
               str filename,
               mutable char c,
               mutable uint line,
               mutable uint col,
               hashmap[str,token.token] keywords,
               hashmap[str,()] reserved)
        {
            fn is_eof() -> bool {
                ret c == (-1) as char;
            }

            fn get_pos() -> tup(str,uint,uint) {
                ret tup(filename, line, col);
            }

            fn peek() -> char {
                ret c;
            }

            fn bump() {
                c = rdr.getc() as char;
                if (c == '\n') {
                    line += 1u;
                    col = 0u;
                } else {
                    col += 1u;
                }
            }

            fn get_keywords() -> hashmap[str,token.token] {
                ret keywords;
            }

            fn get_reserved() -> hashmap[str,()] {
                ret reserved;
            }
        }

    auto keywords = new_str_hash[token.token]();
    auto reserved = new_str_hash[()]();

    keywords.insert("mod", token.MOD());
    keywords.insert("use", token.USE());
    keywords.insert("meta", token.META());
    keywords.insert("auth", token.AUTH());

    keywords.insert("syntax", token.SYNTAX());

    keywords.insert("if", token.IF());
    keywords.insert("else", token.ELSE());
    keywords.insert("while", token.WHILE());
    keywords.insert("do", token.DO());
    keywords.insert("alt", token.ALT());
    keywords.insert("case", token.CASE());

    keywords.insert("for", token.FOR());
    keywords.insert("each", token.EACH());
    keywords.insert("put", token.PUT());
    keywords.insert("ret", token.RET());
    keywords.insert("be", token.BE());

    ret reader(rdr, filename, rdr.getc() as char, 1u, 1u,
               keywords, reserved);
}

fn in_range(char c, char lo, char hi) -> bool {
    ret lo <= c && c <= hi;
}

fn is_alpha(char c) -> bool {
    ret in_range(c, 'a', 'z') ||
        in_range(c, 'A', 'Z');
}

fn is_dec_digit(char c) -> bool {
    ret in_range(c, '0', '9');
}

fn is_hex_digit(char c) -> bool {
    ret in_range(c, '0', '9') ||
        in_range(c, 'a', 'f') ||
        in_range(c, 'A', 'F');
}

fn is_bin_digit(char c) -> bool {
    ret c == '0' || c == '1';
}

fn is_whitespace(char c) -> bool {
    ret c == ' ' || c == '\t' || c == '\r' || c == '\n';
}

fn consume_any_whitespace(stdio_reader rdr, char c) -> char {
    auto c1 = c;
    while (is_whitespace(c1)) {
        c1 = rdr.getc() as char;
    }
    be consume_any_line_comment(rdr, c1);
}

fn consume_any_line_comment(stdio_reader rdr, char c) -> char {
    auto c1 = c;
    if (c1 == '/') {
        auto c2 = rdr.getc() as char;
        if (c2 == '/') {
            while (c1 != '\n') {
                c1 = rdr.getc() as char;
            }
            // Restart whitespace munch.
            be consume_any_whitespace(rdr, c1);
        }
    }
    ret c;
}

fn next_token(stdio_reader rdr) -> token.token {
    auto eof = (-1) as char;
    auto c = rdr.getc() as char;
    auto accum_str = "";
    auto accum_int = 0;

    fn next(stdio_reader rdr) -> char {
        ret rdr.getc() as char;
    }

    fn forget(stdio_reader rdr, char c) {
        rdr.ungetc(c as int);
    }

    c = consume_any_whitespace(rdr, c);

    if (c == eof) { ret token.EOF(); }

    if (is_alpha(c)) {
        while (is_alpha(c)) {
            accum_str += (c as u8);
            c = next(rdr);
        }
        forget(rdr, c);
        ret token.IDENT(accum_str);
    }

    if (is_dec_digit(c)) {
        if (c == '0') {
        } else {
            while (is_dec_digit(c)) {
                accum_int *= 10;
                accum_int += (c as int) - ('0' as int);
                c = next(rdr);
            }
            forget(rdr, c);
            ret token.LIT_INT(accum_int);
        }
    }

    fn op_or_opeq(stdio_reader rdr, char c2,
                  token.op op) -> token.token {
        if (c2 == '=') {
            ret token.OPEQ(op);
        } else {
            forget(rdr, c2);
            ret token.OP(op);
        }
    }

    alt (c) {
        // One-byte tokens.
        case (';') { ret token.SEMI(); }
        case (',') { ret token.COMMA(); }
        case ('.') { ret token.DOT(); }
        case ('(') { ret token.LPAREN(); }
        case (')') { ret token.RPAREN(); }
        case ('{') { ret token.LBRACE(); }
        case ('}') { ret token.RBRACE(); }
        case ('[') { ret token.LBRACKET(); }
        case (']') { ret token.RBRACKET(); }
        case ('@') { ret token.AT(); }
        case ('#') { ret token.POUND(); }

        // Multi-byte tokens.
        case ('=') {
            auto c2 = next(rdr);
            if (c2 == '=') {
                ret token.OP(token.EQEQ());
            } else {
                forget(rdr, c2);
                ret token.OP(token.EQ());
            }
        }

        case ('\'') {
            // FIXME: general utf8-consumption support.
            auto c2 = next(rdr);
            if (c2 == '\\') {
                c2 = next(rdr);
                alt (c2) {
                    case ('n') { c2 = '\n'; }
                    case ('r') { c2 = '\r'; }
                    case ('t') { c2 = '\t'; }
                    case ('\\') { c2 = '\\'; }
                    case ('\'') { c2 = '\''; }
                    // FIXME: unicode numeric escapes.
                    case (_) {
                        log "unknown character escape";
                        log c2;
                        fail;
                    }
                }
            }
            if (next(rdr) != '\'') {
                log "unterminated character constant";
                fail;
            }
            ret token.LIT_CHAR(c2);
        }

        case ('"') {
            // FIXME: general utf8-consumption support.
            auto c2 = next(rdr);
            while (c2 != '"') {
                alt (c2) {
                    case ('\\') {
                        c2 = next(rdr);
                        alt (c2) {
                            case ('n') { accum_str += '\n' as u8; }
                            case ('r') { accum_str += '\r' as u8; }
                            case ('t') { accum_str += '\t' as u8; }
                            case ('\\') { accum_str += '\\' as u8; }
                            case ('"') { accum_str += '"' as u8; }
                            // FIXME: unicode numeric escapes.
                            case (_) {
                                log "unknown string escape";
                                log c2;
                                fail;
                            }
                        }
                    }
                    case (_) {
                        accum_str += c2 as u8;
                    }
                }
                c2 = next(rdr);
            }
            ret token.LIT_STR(accum_str);
        }

        case ('-') {
            auto c2 = next(rdr);
            if (c2 == '>') {
                ret token.RARROW();
            } else {
                ret op_or_opeq(rdr, c2, token.MINUS());
            }
        }

        case ('&') {
            auto c2 = next(rdr);
            if (c2 == '&') {
                ret token.OP(token.ANDAND());
            } else {
                ret op_or_opeq(rdr, c2, token.AND());
            }
        }

        case ('+') {
            ret op_or_opeq(rdr, next(rdr), token.PLUS());
        }

        case ('*') {
            ret op_or_opeq(rdr, next(rdr), token.STAR());
        }

        case ('/') {
            ret op_or_opeq(rdr, next(rdr), token.STAR());
        }

        case ('!') {
            ret op_or_opeq(rdr, next(rdr), token.NOT());
        }

        case ('^') {
            ret op_or_opeq(rdr, next(rdr), token.CARET());
        }

        case ('%') {
            ret op_or_opeq(rdr, next(rdr), token.PERCENT());
        }

    }

    log "lexer stopping at ";
    log c;
    ret token.EOF();
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>Adapt fileman example from C to Rust.<commit_after>extern crate readline;

use std::env;
use std::fs;
use std::io;
use std::process::Command;

type Func = fn(&[&str]) -> Result<bool, String>;

struct COMMAND {
   name: &'static str,  /* User printable name of the function. */
   func: Func,          /* Function to call to do the job. */
   expected_args: u32, /* number of expected args */
   doc: &'static str,  /* Documentation for this function.  */
}

fn io_error_to_string(err: io::Error) -> String {
    format!("{}", err)
}

fn com_cd(args: &[&str]) -> Result<bool, String> {
    let path = args[0];

    try!(env::set_current_dir(path).map_err(io_error_to_string));
    Ok(true)
}

fn com_delete(args: &[&str]) -> Result<bool, String> {
    let path = args[0];
    let metadata = try!(fs::metadata(path).map_err(io_error_to_string));

    if metadata.is_dir() {
        try!(fs::remove_dir(path).map_err(io_error_to_string));
    }
    else {
        try!(fs::remove_file(path).map_err(io_error_to_string));
    }

    Ok(true)
}

fn com_help(args: &[&str]) -> Result<bool, String> {
    let item = try!(find_command(args[0]).ok_or("no matching command".to_string()));
    println!("{}", item.doc);
    Ok(true)
}

fn com_list(args: &[&str]) -> Result<bool, String> {
    let path = args[0];

    let iter = try!(fs::read_dir(path).map_err(io_error_to_string));

    for entry in iter {
        let entry = try!(entry.map_err(io_error_to_string));
        println!("{}", entry.path().display());
    }

    Ok(true)
}

fn com_pwd(_: &[&str]) -> Result<bool, String> {
    let cwd = try!(env::current_dir().map_err(io_error_to_string));
    println!("{}", cwd.display());
    Ok(true)
}

fn com_quit(_: &[&str]) -> Result<bool, String> {
    Ok(false)
}

fn com_rename(args: &[&str]) -> Result<bool, String> {
    let src = args[0];
    let dest = args[1];

    println!("Rename {} to {}", src, dest);

    try!(fs::rename(src, dest).map_err(io_error_to_string));

    Ok(true)
}

fn com_stat(args: &[&str]) -> Result<bool, String> {
    let path = args[0];

    let result = try!(fs::metadata(path).map_err(io_error_to_string));

    println!("Is File: {}", result.is_file());
    println!("Size: {}", result.len());

    Ok(true)
}

fn com_view(args: &[&str]) -> Result<bool, String> {
    let path = args[0];

    let status = Command::new("more")
                         .arg(path)
                         .status()
                         .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
    if ! status.success() {
        println!("Attempt to view {} failed", path);
    }

    Ok(true)
}

fn com_history(_: &[&str]) -> Result<bool, String> {
    let values: Vec<String> = readline::history();
    println!("{:?}", values);

    Ok(true)
}

static COMMANDS_TABLE: [COMMAND; 12] = [
   COMMAND { name: "cd", func: com_cd,
             expected_args: 1, doc: "Change to directory DIR" },
   COMMAND { name: "delete", func: com_delete,
             expected_args: 1, doc: "Delete FILE" },
   COMMAND { name: "help", func: com_help,
             expected_args: 1, doc: "Display this text" },
   COMMAND { name: "?", func: com_help,
             expected_args: 0, doc: "Synonym for `help'" },
   COMMAND { name: "list",   func: com_list,
             expected_args: 1, doc: "List files in DIR" },
   COMMAND { name: "ls",     func: com_list,
             expected_args: 1, doc: "Synonym for `list'" },
   COMMAND { name: "pwd",    func: com_pwd,
             expected_args: 0, doc: "Print the current working directory" },
   COMMAND { name: "quit",   func: com_quit,
             expected_args: 0, doc: "Quit using Fileman" },
   COMMAND { name: "rename", func: com_rename,
             expected_args: 2, doc: "Rename FILE to NEWNAME" },
   COMMAND { name: "stat",   func: com_stat,
             expected_args: 1, doc: "Print out statistics on FILE" },
   COMMAND { name: "view",   func: com_view,
             expected_args: 1, doc: "View the contents f FILE" },
   COMMAND { name: "history", func: com_history,
             expected_args: 0, doc: "List editline history" },
];

fn main () {

    readline::stifle_history(10);
    if ! readline::history_is_stifled() {
        panic!("Failed to stifle history");
    }

    loop {
        let input = match readline::readline ("FileMan: ") {
            Some(line) => line.trim().to_string(),
            None => {
                break;
            },
        };

        if input.is_empty() {
            continue;
        }

        let command = match readline::history_expand(input.as_ref()) {
            // no expansion, just use the input
            Ok(None) => input.to_string(),
            // expansion found, use it
            Ok(Some(expansion)) => expansion,
            Err(_) => {
                continue;
            },
        };

        readline::add_history(command.as_ref());

        match execute_line(&command) {
            Ok(keep_going) => {
                if ! keep_going {
                    break;
                }
            },
            Err(e) => {
                println!("Failed to execute: {}", e);
            },
        }
    }
}

fn execute_line (line: &String) -> Result<bool,String> {
    let pieces: Vec<_> = line.split(" ").collect();
    let word = pieces[0];

    match find_command (word) {
        Some(command) => {
            let args = &pieces[1..];
            if args.len() as u32 != command.expected_args {
                println!("Error: expected {} given {}", command.expected_args, args.len());
                return Ok(true);
            }
            ((*command).func)(args).or_else(|e| {
                println!("Error: {}", e);
                Ok(true)  // ignore the error and return Ok
            })
        },
        None => {
            return Err(format!("Failed to find: {}", word));
        },
    }
}

fn find_command (name: &str) -> Option<&COMMAND> {
   for i in 0..COMMANDS_TABLE.len() {
        if COMMANDS_TABLE[i].name == name {
            return Some(&COMMANDS_TABLE[i]);
        }
    }

    None
}
<|endoftext|>


<commit_before><commit_msg>Refactor: simplify core mod<commit_after><|endoftext|>


<commit_before><commit_msg>added a basic example in examples folder (not just docs)<commit_after>extern crate iron;
extern crate url;
extern crate iron_vhosts;

use iron::{Handler, IronResult, Request, Response, status};
use iron_vhosts::Vhosts;

fn main () {
    //Default handler passed to new
    let mut vhosts = Vhosts::new(|_: &mut Request| Ok(Response::with((status::Ok, "vhost"))));

    //Add any host specific handlers
    vhosts.add_host("localhost", localhost_handler);

    fn localhost_handler(_: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, "localhost")))
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix the hello example<commit_after><|endoftext|>


<commit_before><commit_msg>ext: remove `Splits`, `Split` is stable in std<commit_after><|endoftext|>


<commit_before><commit_msg>Add codegen test<commit_after>#![crate_type = "lib"]

// compile-flags: -O

use std::slice::Windows;

// CHECK-LABEL: @naive_string_search
#[no_mangle]
pub fn naive_string_search(haystack: &str, needle: &str) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }
    // CHECK-NOT: panic
    // CHECK-NOT: fail
    haystack
        .as_bytes()
        .windows(needle.len())
        .position(|sub| sub == needle.as_bytes())
}

// CHECK-LABEL: @next
#[no_mangle]
pub fn next<'a>(w: &mut Windows<'a, u32>) -> Option<&'a [u32]> {
    // CHECK-NOT: panic
    // CHECK-NOT: fail
    w.next()
}

// CHECK-LABEL: @next_back
#[no_mangle]
pub fn next_back<'a>(w: &mut Windows<'a, u32>) -> Option<&'a [u32]> {
    // CHECK-NOT: panic
    // CHECK-NOT: fail
    w.next_back()
}
<|endoftext|>


<commit_before><commit_msg>nbt: Revives the `types::nbt` file for a `Protocol` implementation.<commit_after>//! A protocol implementation for `NbtBlob`s.

use std::io;
use nbt::NbtBlob;
use packet::Protocol;

impl Protocol for NbtBlob {
    type Clean = NbtBlob;

    fn proto_len(value: &NbtBlob) -> usize {
        value.len()
    }

    fn proto_encode(value: &NbtBlob, mut dst: &mut io::Write) -> io::Result<()> {
        Ok(try!(value.write(dst)))
    }

    fn proto_decode(mut src: &mut io::Read) -> io::Result<NbtBlob> {
        Ok(try!(NbtBlob::from_reader(src)))
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement Effect::run<commit_after><|endoftext|>


<commit_before><commit_msg>Don't redraw when size is set to the current value<commit_after><|endoftext|>


<commit_before><commit_msg>finish rust version<commit_after>fn judge_square_sum(input: i32) -> bool {
    if input == 0 {
        return true;
    }

    if input < 0 {
        return false;
    }

    let input_cnvrt = input as f32;

    for i in 0..input_cnvrt.sqrt() as i32 + 1 {
        let temp_i = i.pow(2);
        let mut temp_rest = (input - temp_i) as f32;
        temp_rest = temp_rest.sqrt();
        //println!("{}", temp_rest);
        if temp_rest == temp_rest.round() {
            return true;
        }
    }

    false
}
fn main() {
    println!("{}", judge_square_sum(0));
    println!("{}", judge_square_sum(5));
    println!("{}", judge_square_sum(2));

    println!("{}", judge_square_sum(3));
}
<|endoftext|>


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

//! A standard, garbage-collected linked list.

#[deriving(Clone, Eq)]
#[allow(missing_doc)]
pub enum List<T> {
    Cons(T, @List<T>),
    Nil,
}

#[deriving(Eq)]
#[allow(missing_doc)]
pub enum MutList<T> {
    MutCons(T, @mut MutList<T>),
    MutNil,
}

/// Create a list from a vector
pub fn from_vec<T:Clone + 'static>(v: &[T]) -> @List<T> {
    v.rev_iter().fold(@Nil::<T>, |t, h| @Cons((*h).clone(), t))
}

/**
 * Left fold
 *
 * Applies `f` to `u` and the first element in the list, then applies `f` to
 * the result of the previous call and the second element, and so on,
 * returning the accumulated result.
 *
 * # Arguments
 *
 * * ls - The list to fold
 * * z - The initial value
 * * f - The function to apply
 */
pub fn foldl<T:Clone,U>(z: T, ls: @List<U>, f: |&T, &U| -> T) -> T {
    let mut accum: T = z;
    iter(ls, |elt| accum = f(&accum, elt));
    accum
}

/**
 * Search for an element that matches a given predicate
 *
 * Apply function `f` to each element of `v`, starting from the first.
 * When function `f` returns true then an option containing the element
 * is returned. If `f` matches no elements then none is returned.
 */
pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
    let mut ls = ls;
    loop {
        ls = match *ls {
          Cons(ref hd, tl) => {
            if f(hd) { return Some((*hd).clone()); }
            tl
          }
          Nil => return None
        }
    };
}

/// Returns true if a list contains an element with the given value
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
    let mut found = false;
    each(ls, |e| {
        if *e == elt { found = true; false } else { true }
    });
    return found;
}

/// Returns true if the list is empty
pub fn is_empty<T>(ls: @List<T>) -> bool {
    match *ls {
        Nil => true,
        _ => false
    }
}

/// Returns the length of a list
pub fn len<T>(ls: @List<T>) -> uint {
    let mut count = 0u;
    iter(ls, |_e| count += 1u);
    count
}

/// Returns all but the first element of a list
pub fn tail<T>(ls: @List<T>) -> @List<T> {
    match *ls {
        Cons(_, tl) => return tl,
        Nil => fail!("list empty")
    }
}

/// Returns the first element of a list
pub fn head<T:Clone>(ls: @List<T>) -> T {
    match *ls {
      Cons(ref hd, _) => (*hd).clone(),
      // makes me sad
      _ => fail!("head invoked on empty list")
    }
}

/// Appends one list to another
pub fn append<T:Clone + 'static>(l: @List<T>, m: @List<T>) -> @List<T> {
    match *l {
      Nil => return m,
      Cons(ref x, xs) => {
        let rest = append(xs, m);
        return @Cons((*x).clone(), rest);
      }
    }
}

/*
/// Push one element into the front of a list, returning a new list
/// THIS VERSION DOESN'T ACTUALLY WORK
fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
    ll = &mut @cons(vv, *ll)
}
*/

/// Iterate over a list
pub fn iter<T>(l: @List<T>, f: |&T|) {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            f(hd);
            tl
          }
          Nil => break
        }
    }
}

/// Iterate over a list
pub fn each<T>(l: @List<T>, f: |&T| -> bool) -> bool {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            if !f(hd) { return false; }
            tl
          }
          Nil => { return true; }
        }
    }
}

impl<T> MutList<T> {
    /// Iterate over a mutable list
    pub fn each(@mut self, f: |&mut T| -> bool) -> bool {
        let mut cur = self;
        loop {
            let borrowed = &mut *cur;
            cur = match *borrowed {
                MutCons(ref mut hd, tl) => {
                    if !f(hd) {
                        return false;
                    }
                    tl
                }
                MutNil => break
            }
        }
        return true;
    }
}

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

    use std::option;

    #[test]
    fn test_is_empty() {
        let empty : @list::List<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert!(is_empty(empty));
        assert!(!is_empty(full1));
        assert!(!is_empty(full2));
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert_eq!(head(l), 0);

        let tail_l = tail(l);
        assert_eq!(head(tail_l), 1);

        let tail_tail_l = tail(tail_l);
        assert_eq!(head(tail_tail_l), 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : @list::List<int> = from_vec([]);
        assert_eq!(empty, @list::Nil::<int>);
    }

    #[test]
    fn test_foldl() {
        fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::foldl(0u, l, add), 10u);
        assert_eq!(list::foldl(0u, empty, add), 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(a: &int, b: &int) -> int {
            *a - *b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert_eq!(list::foldl(0, l, sub), -10);
    }

    #[test]
    fn test_find_success() {
        fn match_(i: &int) -> bool { return *i == 2; }
        let l = from_vec([0, 1, 2]);
        assert_eq!(list::find(l, match_), option::Some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match_(_i: &int) -> bool { return false; }
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::find(l, match_), option::None::<int>);
        assert_eq!(list::find(empty, match_), option::None::<int>);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = @list::Nil::<int>;
        assert!((list::has(l, 5)));
        assert!((!list::has(l, 7)));
        assert!((list::has(l, 8)));
        assert!((!list::has(empty, 5)));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::len(l), 3u);
        assert_eq!(list::len(empty), 0u);
    }

    #[test]
    fn test_append() {
        assert!(from_vec([1,2,3,4])
            == list::append(list::from_vec([1,2]), list::from_vec([3,4])));
    }
}
<commit_msg>libextra: Remove `MutList`, as it's inexorably tied to `@mut`<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A standard, garbage-collected linked list.

#[deriving(Clone, Eq)]
#[allow(missing_doc)]
pub enum List<T> {
    Cons(T, @List<T>),
    Nil,
}

/// Create a list from a vector
pub fn from_vec<T:Clone + 'static>(v: &[T]) -> @List<T> {
    v.rev_iter().fold(@Nil::<T>, |t, h| @Cons((*h).clone(), t))
}

/**
 * Left fold
 *
 * Applies `f` to `u` and the first element in the list, then applies `f` to
 * the result of the previous call and the second element, and so on,
 * returning the accumulated result.
 *
 * # Arguments
 *
 * * ls - The list to fold
 * * z - The initial value
 * * f - The function to apply
 */
pub fn foldl<T:Clone,U>(z: T, ls: @List<U>, f: |&T, &U| -> T) -> T {
    let mut accum: T = z;
    iter(ls, |elt| accum = f(&accum, elt));
    accum
}

/**
 * Search for an element that matches a given predicate
 *
 * Apply function `f` to each element of `v`, starting from the first.
 * When function `f` returns true then an option containing the element
 * is returned. If `f` matches no elements then none is returned.
 */
pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
    let mut ls = ls;
    loop {
        ls = match *ls {
          Cons(ref hd, tl) => {
            if f(hd) { return Some((*hd).clone()); }
            tl
          }
          Nil => return None
        }
    };
}

/// Returns true if a list contains an element with the given value
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
    let mut found = false;
    each(ls, |e| {
        if *e == elt { found = true; false } else { true }
    });
    return found;
}

/// Returns true if the list is empty
pub fn is_empty<T>(ls: @List<T>) -> bool {
    match *ls {
        Nil => true,
        _ => false
    }
}

/// Returns the length of a list
pub fn len<T>(ls: @List<T>) -> uint {
    let mut count = 0u;
    iter(ls, |_e| count += 1u);
    count
}

/// Returns all but the first element of a list
pub fn tail<T>(ls: @List<T>) -> @List<T> {
    match *ls {
        Cons(_, tl) => return tl,
        Nil => fail!("list empty")
    }
}

/// Returns the first element of a list
pub fn head<T:Clone>(ls: @List<T>) -> T {
    match *ls {
      Cons(ref hd, _) => (*hd).clone(),
      // makes me sad
      _ => fail!("head invoked on empty list")
    }
}

/// Appends one list to another
pub fn append<T:Clone + 'static>(l: @List<T>, m: @List<T>) -> @List<T> {
    match *l {
      Nil => return m,
      Cons(ref x, xs) => {
        let rest = append(xs, m);
        return @Cons((*x).clone(), rest);
      }
    }
}

/*
/// Push one element into the front of a list, returning a new list
/// THIS VERSION DOESN'T ACTUALLY WORK
fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
    ll = &mut @cons(vv, *ll)
}
*/

/// Iterate over a list
pub fn iter<T>(l: @List<T>, f: |&T|) {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            f(hd);
            tl
          }
          Nil => break
        }
    }
}

/// Iterate over a list
pub fn each<T>(l: @List<T>, f: |&T| -> bool) -> bool {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            if !f(hd) { return false; }
            tl
          }
          Nil => { return true; }
        }
    }
}

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

    use std::option;

    #[test]
    fn test_is_empty() {
        let empty : @list::List<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert!(is_empty(empty));
        assert!(!is_empty(full1));
        assert!(!is_empty(full2));
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert_eq!(head(l), 0);

        let tail_l = tail(l);
        assert_eq!(head(tail_l), 1);

        let tail_tail_l = tail(tail_l);
        assert_eq!(head(tail_tail_l), 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : @list::List<int> = from_vec([]);
        assert_eq!(empty, @list::Nil::<int>);
    }

    #[test]
    fn test_foldl() {
        fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::foldl(0u, l, add), 10u);
        assert_eq!(list::foldl(0u, empty, add), 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(a: &int, b: &int) -> int {
            *a - *b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert_eq!(list::foldl(0, l, sub), -10);
    }

    #[test]
    fn test_find_success() {
        fn match_(i: &int) -> bool { return *i == 2; }
        let l = from_vec([0, 1, 2]);
        assert_eq!(list::find(l, match_), option::Some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match_(_i: &int) -> bool { return false; }
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::find(l, match_), option::None::<int>);
        assert_eq!(list::find(empty, match_), option::None::<int>);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = @list::Nil::<int>;
        assert!((list::has(l, 5)));
        assert!((!list::has(l, 7)));
        assert!((list::has(l, 8)));
        assert!((!list::has(empty, 5)));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::len(l), 3u);
        assert_eq!(list::len(empty), 0u);
    }

    #[test]
    fn test_append() {
        assert!(from_vec([1,2,3,4])
            == list::append(list::from_vec([1,2]), list::from_vec([3,4])));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add time<commit_after><|endoftext|>


<commit_before><commit_msg>Add a few impls for small tuples<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify match expression in `utils`<commit_after><|endoftext|>


<commit_before><commit_msg>video.reportComment method<commit_after><|endoftext|>


<commit_before><commit_msg>fixes #696 pushd problem (#717)<commit_after><|endoftext|>


<commit_before><commit_msg>feat(geektime_algo): 16 binary search for search in rotated sorted array<commit_after>// leetcode 33 Search in Rotated Sorted Array (https://leetcode.com/problems/search-in-rotated-sorted-array/)
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
    if nums.is_empty() { return -1; }

    let mut low = 0;
    let mut high = nums.len() - 1;

    while low <= high {
        let mid = low + ((high - low) >> 1);
        if nums[mid] == target { return mid as i32; }

        // left is order
        if nums[low] <= nums[mid] {
            // target is in left array
            if nums[low] <= target && target <= nums[mid] {
                high = mid - 1;
            }  else {
                low = mid + 1;
            }
        } else {
            if nums[mid] <= target && target <= nums[high] {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
    }
    -1
}

fn main() {
    let nums = vec![4,5,6,7,0,1,2];
    let n = search(nums, 0);
    println!("{:?}", n);
}
<|endoftext|>


<commit_before><commit_msg>Problem: new RPC scheme does not require us to serialize transaction<commit_after><|endoftext|>


<commit_before><commit_msg>Add initial version of store interface<commit_after>use std::result::Result as RResult;
use std::string;

pub use entry::Entry;
pub use error::StoreError;

pub type Result<T> = RResult<T, StoreError>;
pub type LockedEntry = SingleUseLock<Entry>;

pub trait Store {
    fn create(&self, entry : Entry) -> Result<()>;
    fn retrieve(&self, id : string) -> Result<LockedEntry>;
    fn retrieve_copy(&self, id : string) -> Result<Entry>;
    fn update(&self, LockedEntry) -> Result<()>;
    fn delete(&self, id : string) -> Result<()>;
}

<|endoftext|>


<commit_before><commit_msg>refactor(pane/pid): Use an integer type for PID<commit_after><|endoftext|>


<commit_before><commit_msg>Fix broken test<commit_after><|endoftext|>


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

#![feature(unboxed_closures)]
use std::ops::Fn;

struct Foo<T>(T);

impl<T: Copy> Fn<(), T> for Foo<T> {
    extern "rust-call" fn call(&self, _: ()) -> T {
      match *self {
        Foo(t) => t
      }
    }
}

fn main() {
  let t: u8 = 1;
  println!("{}", Foo(t)());
}
<|endoftext|>


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

#![forbid(warnings)]

// Pretty printing tests complain about `use std::predule::*`
#![allow(unused_imports)]

// A var moved into a proc, that has a mutable loan path should
// not trigger a misleading unused_mut warning.

use std::thread;

pub fn main() {
    let mut stdin = std::old_io::stdin();
    thread::spawn(move|| {
        let _ = stdin.read_to_end();
    });
}
<commit_msg>Ignore issue #16671 test on android (again)<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// DON'T REENABLE THIS UNLESS YOU'VE ACTUALLY FIXED THE UNDERLYING ISSUE
// ignore-android seems to block forever

#![forbid(warnings)]

// Pretty printing tests complain about `use std::predule::*`
#![allow(unused_imports)]

// A var moved into a proc, that has a mutable loan path should
// not trigger a misleading unused_mut warning.

use std::thread;

pub fn main() {
    let mut stdin = std::old_io::stdin();
    thread::spawn(move|| {
        let _ = stdin.read_to_end();
    });
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #29071<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.
fn ret() -> u32 {
    static x: u32 = 10;
    x & if true { 10u32 } else { 20u32 } & x
}

fn ret2() -> &'static u32 {
    static x: u32 = 10;
    if true { 10u32; } else { 20u32; }
    &x
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #62085 - JohnTitor:add-test-for-issue-38591, r=Centril<commit_after>// run-pass

struct S<T> {
    t : T,
    s : Box<S<fn(u : T)>>
}

fn f(x : S<u32>) {}

fn main () {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #62994 - iluuu1994:test-for-43398, r=nikomatsakis<commit_after>// run-pass

#![feature(core_intrinsics)]
#![feature(repr128)]

#[repr(i128)]
enum Big { A, B }

fn main() {
    unsafe {
        println!("{} {:?}",
            std::intrinsics::discriminant_value(&Big::A),
            std::mem::discriminant(&Big::B));
    }
}
<|endoftext|>


<commit_before><commit_msg>fix: add run module<commit_after>
extern crate notify;
extern crate yaml_rust;
extern crate glob;

use std::{thread, time};
use std::process::Command as ShellCommand;
use std::error::Error;

use self::notify::{RecommendedWatcher, Watcher};
use self::yaml_rust::{Yaml, YamlLoader};

use cli::Command;
use yaml;

pub const FILENAME: &'static str = ".watch.yaml";

/// # `RunCommand`
///
/// Executes commands in an interval of time
///
pub struct RunCommand {
    command: String,
    interval: u64,
}

impl RunCommand {
    pub fn new(command: String, interval: u64) -> Self {
        RunCommand { command: command, interval: interval }
    }
}

impl Command for RunCommand {
    fn execute(&self) -> Result<(), String> {
        let mut command_line: Vec<&str> = self.command.split_whitespace().collect();
        println!("{:?}", command_line);
        let mut command = ShellCommand::new(command_line.remove(0));
        command.args(&command_line);

        loop {
            println!("{:?}", command);
            if let Err(error) = command.status() {
                println!("{}", error);
                return Err(String::from(error.description()));
            }
            let wait = time::Duration::from_secs(self.interval);
            thread::sleep(wait)
        }
    }
}
<|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.

use visitor::FmtVisitor;
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};

use syntax::ast;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::print::pprust;

use {IDEAL_WIDTH, MAX_WIDTH};

// TODO change import lists with one item to a single import
//      remove empty lists (if they're even possible)
// TODO (some day) remove unused imports, expand globs, compress many single imports into a list import

impl<'a> FmtVisitor<'a> {
    // Basically just pretty prints a multi-item import.
    pub fn rewrite_use_list(&mut self,
                            path: &ast::Path,
                            path_list: &[ast::PathListItem],
                            visibility: ast::Visibility,
                            vp_span: Span) -> String {
        // FIXME check indentation
        let l_loc = self.codemap.lookup_char_pos(vp_span.lo);

        let path_str = pprust::path_to_string(&path);

        let vis = match visibility {
            ast::Public => "pub ",
            _ => ""
        };

        // 1 = {
        let mut indent = l_loc.col.0 + path_str.len() + 1;
        if path_str.len() > 0 {
            // 2 = ::
            indent += 2;
        }
        // 2 = } + ;
        let used_width = indent + 2 + vis.len();
        let budget = if used_width >= IDEAL_WIDTH {
            if used_width < MAX_WIDTH {
                MAX_WIDTH - used_width
            } else {
                // Give up
                return String::new();
            }
        } else {
            IDEAL_WIDTH - used_width
        };
        let fmt = ListFormatting {
            tactic: ListTactic::Mixed,
            separator: ",",
            trailing_separator: SeparatorTactic::Never,
            indent: indent,
            h_width: budget,
            v_width: budget,
        };

        // TODO handle any comments inbetween items.
        // If `self` is in the list, put it first.
        let head = if path_list.iter().any(|vpi|
            if let ast::PathListItem_::PathListMod{ .. } = vpi.node {
                true
            } else {
                false
            }
        ) {
            Some(("self".to_owned(), String::new()))
        } else {
            None
        };

        let items: Vec<_> = head.into_iter().chain(path_list.iter().filter_map(|vpi| {
            match vpi.node {
                ast::PathListItem_::PathListIdent{ name, .. } => {
                    Some((token::get_ident(name).to_string(), String::new()))
                }
                // Skip `self`, because we added it above.
                ast::PathListItem_::PathListMod{ .. } => None,
            }
        })).collect();
        if path_str.len() == 0 {
            format!("{}use {{{}}};", vis, write_list(&items, &fmt))
        } else {
            format!("{}use {}::{{{}}};", vis, path_str, write_list(&items, &fmt))
        }
    }
}
<commit_msg>Change import lists with one item to single import<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.

use visitor::FmtVisitor;
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};

use syntax::ast;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::print::pprust;

use {IDEAL_WIDTH, MAX_WIDTH};

// TODO remove empty lists (if they're even possible)
// TODO (some day) remove unused imports, expand globs, compress many single imports into a list import

fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem, vis: &str) -> String {
    if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
        let name_str = token::get_ident(name).to_string();
        if path_str.len() == 0 {
            format!("{}use {};", vis, name_str)
        } else {
            format!("{}use {}::{};", vis, path_str, name_str)
        }
    } else {
        if path_str.len() != 0 {
            format!("{}use {};", vis, path_str)
        } else {
            // This catches the import: use {self}, which is a compiler error, so we just
            // leave it alone.
            format!("{}use {{self}};", vis)
        }
    }
}

impl<'a> FmtVisitor<'a> {
    // Basically just pretty prints a multi-item import.
    pub fn rewrite_use_list(&mut self,
                            path: &ast::Path,
                            path_list: &[ast::PathListItem],
                            visibility: ast::Visibility,
                            vp_span: Span) -> String {
        let path_str = pprust::path_to_string(&path);

        let vis = match visibility {
            ast::Public => "pub ",
            _ => ""
        };

        if path_list.len() == 1 {
            return rewrite_single_use_list(path_str, path_list[0], vis);
        }

        // FIXME check indentation
        let l_loc = self.codemap.lookup_char_pos(vp_span.lo);

        // 1 = {
        let mut indent = l_loc.col.0 + path_str.len() + 1;
        if path_str.len() > 0 {
            // 2 = ::
            indent += 2;
        }
        // 2 = } + ;
        let used_width = indent + 2 + vis.len();
        let budget = if used_width >= IDEAL_WIDTH {
            if used_width < MAX_WIDTH {
                MAX_WIDTH - used_width
            } else {
                // Give up
                return String::new();
            }
        } else {
            IDEAL_WIDTH - used_width
        };
        let fmt = ListFormatting {
            tactic: ListTactic::Mixed,
            separator: ",",
            trailing_separator: SeparatorTactic::Never,
            indent: indent,
            h_width: budget,
            v_width: budget,
        };

        // TODO handle any comments inbetween items.
        // If `self` is in the list, put it first.
        let head = if path_list.iter().any(|vpi|
            if let ast::PathListItem_::PathListMod{ .. } = vpi.node {
                true
            } else {
                false
            }
        ) {
            Some(("self".to_owned(), String::new()))
        } else {
            None
        };

        let items: Vec<_> = head.into_iter().chain(path_list.iter().filter_map(|vpi| {
            match vpi.node {
                ast::PathListItem_::PathListIdent{ name, .. } => {
                    Some((token::get_ident(name).to_string(), String::new()))
                }
                // Skip `self`, because we added it above.
                ast::PathListItem_::PathListMod{ .. } => None,
            }
        })).collect();
        if path_str.len() == 0 {
            format!("{}use {{{}}};", vis, write_list(&items, &fmt))
        } else {
            format!("{}use {}::{{{}}};", vis, path_str, write_list(&items, &fmt))
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Make hsalsa20 a freefloating public function.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement background color bug<commit_after><|endoftext|>


<commit_before>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate log;
extern crate shared_library;
extern crate gfx_core;
extern crate vk_sys as vk;

use std::{fmt, iter, mem, ptr};
use std::cell::RefCell;
use std::sync::Arc;
use std::ffi::CStr;
use shared_library::dynamic_library::DynamicLibrary;

pub use self::command::{GraphicsQueue, Buffer as CommandBuffer};
pub use self::factory::Factory;

mod command;
pub mod data;
mod factory;
mod native;

struct PhysicalDeviceInfo {
    device: vk::PhysicalDevice,
    _properties: vk::PhysicalDeviceProperties,
    queue_families: Vec<vk::QueueFamilyProperties>,
    memory: vk::PhysicalDeviceMemoryProperties,
    _features: vk::PhysicalDeviceFeatures,
}

impl PhysicalDeviceInfo {
    pub fn new(dev: vk::PhysicalDevice, vk: &vk::InstancePointers) -> PhysicalDeviceInfo {
        PhysicalDeviceInfo {
            device: dev,
            _properties: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceProperties(dev, &mut out);
                out
            },
            queue_families: unsafe {
                let mut num = 4;
                let mut families = Vec::with_capacity(num as usize);
                vk.GetPhysicalDeviceQueueFamilyProperties(dev, &mut num, families.as_mut_ptr());
                families.set_len(num as usize);
                families
            },
            memory: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceMemoryProperties(dev, &mut out);
                out
            },
            _features: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceFeatures(dev, &mut out);
                out
            },
        }
    }
}

pub struct Share {
    _dynamic_lib: DynamicLibrary,
    _library: vk::Static,
    instance: vk::Instance,
    inst_pointers: vk::InstancePointers,
    device: vk::Device,
    dev_pointers: vk::DevicePointers,
    handles: RefCell<gfx_core::handle::Manager<Resources>>,
}

pub type SharePointer = Arc<Share>;

impl Share {
    pub fn get_instance(&self) -> (vk::Instance, &vk::InstancePointers) {
        (self.instance, &self.inst_pointers)
    }
    pub fn get_device(&self) -> (vk::Device, &vk::DevicePointers) {
        (self.device, &self.dev_pointers)
    }
}

const SURFACE_EXTENSIONS: &'static [&'static str] = &[
    // Platform-specific WSI extensions
    "VK_KHR_xlib_surface",
    "VK_KHR_xcb_surface",
    "VK_KHR_wayland_surface",
    "VK_KHR_mir_surface",
    "VK_KHR_android_surface",
    "VK_KHR_win32_surface",
];

pub fn create(app_name: &str, app_version: u32, layers: &[&str], extensions: &[&str],
              dev_extensions: &[&str]) -> (command::GraphicsQueue, factory::Factory, SharePointer) {
    use std::ffi::CString;
    use std::path::Path;

    let dynamic_lib = DynamicLibrary::open(Some(
            if cfg!(target_os = "windows") {
                Path::new("vulkan-1.dll")
            } else {
                Path::new("libvulkan.so.1")
            }
        )).expect("Unable to open vulkan shared library");
    let lib = vk::Static::load(|name| unsafe {
        let name = name.to_str().unwrap();
        dynamic_lib.symbol(name).unwrap()
    });
    let entry_points = vk::EntryPoints::load(|name| unsafe {
        mem::transmute(lib.GetInstanceProcAddr(0, name.as_ptr()))
    });

    let app_info = vk::ApplicationInfo {
        sType: vk::STRUCTURE_TYPE_APPLICATION_INFO,
        pNext: ptr::null(),
        pApplicationName: app_name.as_ptr() as *const _,
        applicationVersion: app_version,
        pEngineName: "gfx-rs".as_ptr() as *const _,
        engineVersion: 0x1000, //TODO
        apiVersion: 0x400000, //TODO
    };

    let instance_extensions = {
        let mut num = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.EnumerateInstanceExtensionProperties(ptr::null(), &mut num, ptr::null_mut())
        });
        let mut out = Vec::with_capacity(num as usize);
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.EnumerateInstanceExtensionProperties(ptr::null(), &mut num, out.as_mut_ptr())
        });
        unsafe { out.set_len(num as usize); }
        out
    };

    // Check our surface extensions against the available extensions
    let surface_extensions = SURFACE_EXTENSIONS.iter().filter(|ext| {
        for inst_ext in instance_extensions.iter() {
            unsafe {
                if CStr::from_ptr(inst_ext.extensionName.as_ptr()) == CStr::from_ptr(ext.as_ptr() as *const i8) {
                    return true;
                }
            }
        }
        false
    }).map(|s| *s).collect::<Vec<_>>();

    let instance = {
        let cstrings = layers.iter().chain(extensions.iter())
                                    .chain(surface_extensions.iter())
                         .map(|&s| CString::new(s).unwrap())
                         .collect::<Vec<_>>();
        let str_pointers = cstrings.iter()
                                   .map(|s| s.as_ptr())
                                   .collect::<Vec<_>>();

        let create_info = vk::InstanceCreateInfo {
            sType: vk::STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            pApplicationInfo: &app_info,
            enabledLayerCount: layers.len() as u32,
            ppEnabledLayerNames: str_pointers.as_ptr(),
            enabledExtensionCount: (extensions.len() + surface_extensions.len()) as u32,
            ppEnabledExtensionNames: str_pointers[layers.len()..].as_ptr(),
        };
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.CreateInstance(&create_info, ptr::null(), &mut out)
        });
        out
    };

    let inst_pointers = vk::InstancePointers::load(|name| unsafe {
        mem::transmute(lib.GetInstanceProcAddr(instance, name.as_ptr()))
    });

    let mut physical_devices: [vk::PhysicalDevice; 4] = unsafe { mem::zeroed() };
    let mut num = physical_devices.len() as u32;
    assert_eq!(vk::SUCCESS, unsafe {
        inst_pointers.EnumeratePhysicalDevices(instance, &mut num, physical_devices.as_mut_ptr())
    });
    let devices = physical_devices[..num as usize].iter()
        .map(|dev| PhysicalDeviceInfo::new(*dev, &inst_pointers))
        .collect::<Vec<_>>();

    let (dev, (qf_id, _))  = devices.iter()
        .flat_map(|d| iter::repeat(d).zip(d.queue_families.iter().enumerate()))
        .find(|&(_, (_, qf))| qf.queueFlags & vk::QUEUE_GRAPHICS_BIT != 0)
        .unwrap();
    info!("Chosen physical device {:?} with queue family {}", dev.device, qf_id);

    let mvid_id = dev.memory.memoryTypes.iter().take(dev.memory.memoryTypeCount as usize)
                            .position(|mt| (mt.propertyFlags & vk::MEMORY_PROPERTY_DEVICE_LOCAL_BIT != 0)
                                        && (mt.propertyFlags & vk::MEMORY_PROPERTY_HOST_VISIBLE_BIT != 0))
                            .unwrap() as u32;
    let msys_id = dev.memory.memoryTypes.iter().take(dev.memory.memoryTypeCount as usize)
                            .position(|mt| mt.propertyFlags & vk::MEMORY_PROPERTY_HOST_COHERENT_BIT != 0)
                            .unwrap() as u32;

    let device = {
        let cstrings = dev_extensions.iter()
                                     .map(|&s| CString::new(s).unwrap())
                                     .collect::<Vec<_>>();
        let str_pointers = cstrings.iter().map(|s| s.as_ptr())
                                   .collect::<Vec<_>>();

        let queue_info = vk::DeviceQueueCreateInfo {
            sType: vk::STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            queueFamilyIndex: qf_id as u32,
            queueCount: 1,
            pQueuePriorities: &1.0,
        };
        let features = unsafe{ mem::zeroed() };

        let dev_info = vk::DeviceCreateInfo {
            sType: vk::STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            queueCreateInfoCount: 1,
            pQueueCreateInfos: &queue_info,
            enabledLayerCount: 0,
            ppEnabledLayerNames: ptr::null(),
            enabledExtensionCount: str_pointers.len() as u32,
            ppEnabledExtensionNames: str_pointers.as_ptr(),
            pEnabledFeatures: &features,
        };
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            inst_pointers.CreateDevice(dev.device, &dev_info, ptr::null(), &mut out)
        });
        out
    };

    let dev_pointers = vk::DevicePointers::load(|name| unsafe {
        inst_pointers.GetDeviceProcAddr(device, name.as_ptr()) as *const _
    });
    let queue = unsafe {
        let mut out = mem::zeroed();
        dev_pointers.GetDeviceQueue(device, qf_id as u32, 0, &mut out);
        out
    };

    let share = Arc::new(Share {
        _dynamic_lib: dynamic_lib,
        _library: lib,
        instance: instance,
        inst_pointers: inst_pointers,
        device: device,
        dev_pointers: dev_pointers,
        handles: RefCell::new(gfx_core::handle::Manager::new()),
    });
    let gfx_device = command::GraphicsQueue::new(share.clone(), queue, qf_id as u32);
    let gfx_factory = factory::Factory::new(share.clone(), qf_id as u32, mvid_id, msys_id);

    (gfx_device, gfx_factory, share)
}

#[derive(Clone, PartialEq, Eq)]
pub struct Error(pub vk::Result);

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self.0 {
            vk::SUCCESS => "success",
            vk::NOT_READY => "not ready",
            vk::TIMEOUT => "timeout",
            vk::EVENT_SET => "event_set",
            vk::EVENT_RESET => "event_reset",
            vk::INCOMPLETE => "incomplete",
            vk::ERROR_OUT_OF_HOST_MEMORY => "out of host memory",
            vk::ERROR_OUT_OF_DEVICE_MEMORY => "out of device memory",
            vk::ERROR_INITIALIZATION_FAILED => "initialization failed",
            vk::ERROR_DEVICE_LOST => "device lost",
            vk::ERROR_MEMORY_MAP_FAILED => "memory map failed",
            vk::ERROR_LAYER_NOT_PRESENT => "layer not present",
            vk::ERROR_EXTENSION_NOT_PRESENT => "extension not present",
            vk::ERROR_FEATURE_NOT_PRESENT => "feature not present",
            vk::ERROR_INCOMPATIBLE_DRIVER => "incompatible driver",
            vk::ERROR_TOO_MANY_OBJECTS => "too many objects",
            vk::ERROR_FORMAT_NOT_SUPPORTED => "format not supported",
            vk::ERROR_SURFACE_LOST_KHR => "surface lost (KHR)",
            vk::ERROR_NATIVE_WINDOW_IN_USE_KHR => "native window in use (KHR)",
            vk::SUBOPTIMAL_KHR => "suboptimal (KHR)",
            vk::ERROR_OUT_OF_DATE_KHR => "out of date (KHR)",
            vk::ERROR_INCOMPATIBLE_DISPLAY_KHR => "incompatible display (KHR)",
            vk::ERROR_VALIDATION_FAILED_EXT => "validation failed (EXT)",
            _ => "unknown",
        })
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}

impl gfx_core::Resources for Resources {
    type Buffer               = native::Buffer;
    type Shader               = vk::ShaderModule;
    type Program              = native::Program;
    type PipelineStateObject  = native::Pipeline;
    type Texture              = native::Texture;
    type ShaderResourceView   = native::TextureView; //TODO: buffer view
    type UnorderedAccessView  = ();
    type RenderTargetView     = native::TextureView;
    type DepthStencilView     = native::TextureView;
    type Sampler              = vk::Sampler;
    type Fence                = vk::Fence;
}
<commit_msg>Vulkan: Improve physical device initialization<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate log;
extern crate shared_library;
extern crate gfx_core;
extern crate vk_sys as vk;

use std::{fmt, iter, mem, ptr};
use std::cell::RefCell;
use std::sync::Arc;
use std::ffi::CStr;
use shared_library::dynamic_library::DynamicLibrary;

pub use self::command::{GraphicsQueue, Buffer as CommandBuffer};
pub use self::factory::Factory;

mod command;
pub mod data;
mod factory;
mod native;

struct PhysicalDeviceInfo {
    device: vk::PhysicalDevice,
    _properties: vk::PhysicalDeviceProperties,
    queue_families: Vec<vk::QueueFamilyProperties>,
    memory: vk::PhysicalDeviceMemoryProperties,
    _features: vk::PhysicalDeviceFeatures,
}

impl PhysicalDeviceInfo {
    pub fn new(dev: vk::PhysicalDevice, vk: &vk::InstancePointers) -> PhysicalDeviceInfo {
        PhysicalDeviceInfo {
            device: dev,
            _properties: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceProperties(dev, &mut out);
                out
            },
            queue_families: unsafe {
                let mut num = 0;
                vk.GetPhysicalDeviceQueueFamilyProperties(dev, &mut num, ptr::null_mut());
                let mut families = Vec::with_capacity(num as usize);
                vk.GetPhysicalDeviceQueueFamilyProperties(dev, &mut num, families.as_mut_ptr());
                families.set_len(num as usize);
                families
            },
            memory: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceMemoryProperties(dev, &mut out);
                out
            },
            _features: unsafe {
                let mut out = mem::zeroed();
                vk.GetPhysicalDeviceFeatures(dev, &mut out);
                out
            },
        }
    }
}

pub struct Share {
    _dynamic_lib: DynamicLibrary,
    _library: vk::Static,
    instance: vk::Instance,
    inst_pointers: vk::InstancePointers,
    device: vk::Device,
    dev_pointers: vk::DevicePointers,
    handles: RefCell<gfx_core::handle::Manager<Resources>>,
}

pub type SharePointer = Arc<Share>;

impl Share {
    pub fn get_instance(&self) -> (vk::Instance, &vk::InstancePointers) {
        (self.instance, &self.inst_pointers)
    }
    pub fn get_device(&self) -> (vk::Device, &vk::DevicePointers) {
        (self.device, &self.dev_pointers)
    }
}

const SURFACE_EXTENSIONS: &'static [&'static str] = &[
    // Platform-specific WSI extensions
    "VK_KHR_xlib_surface",
    "VK_KHR_xcb_surface",
    "VK_KHR_wayland_surface",
    "VK_KHR_mir_surface",
    "VK_KHR_android_surface",
    "VK_KHR_win32_surface",
];

pub fn create(app_name: &str, app_version: u32, layers: &[&str], extensions: &[&str],
              dev_extensions: &[&str]) -> (command::GraphicsQueue, factory::Factory, SharePointer) {
    use std::ffi::CString;
    use std::path::Path;

    let dynamic_lib = DynamicLibrary::open(Some(
            if cfg!(target_os = "windows") {
                Path::new("vulkan-1.dll")
            } else {
                Path::new("libvulkan.so.1")
            }
        )).expect("Unable to open vulkan shared library");
    let lib = vk::Static::load(|name| unsafe {
        let name = name.to_str().unwrap();
        dynamic_lib.symbol(name).unwrap()
    });
    let entry_points = vk::EntryPoints::load(|name| unsafe {
        mem::transmute(lib.GetInstanceProcAddr(0, name.as_ptr()))
    });

    let app_info = vk::ApplicationInfo {
        sType: vk::STRUCTURE_TYPE_APPLICATION_INFO,
        pNext: ptr::null(),
        pApplicationName: app_name.as_ptr() as *const _,
        applicationVersion: app_version,
        pEngineName: "gfx-rs".as_ptr() as *const _,
        engineVersion: 0x1000, //TODO
        apiVersion: 0x400000, //TODO
    };

    let instance_extensions = {
        let mut num = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.EnumerateInstanceExtensionProperties(ptr::null(), &mut num, ptr::null_mut())
        });
        let mut out = Vec::with_capacity(num as usize);
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.EnumerateInstanceExtensionProperties(ptr::null(), &mut num, out.as_mut_ptr())
        });
        unsafe { out.set_len(num as usize); }
        out
    };

    // Check our surface extensions against the available extensions
    let surface_extensions = SURFACE_EXTENSIONS.iter().filter(|ext| {
        for inst_ext in instance_extensions.iter() {
            unsafe {
                if CStr::from_ptr(inst_ext.extensionName.as_ptr()) == CStr::from_ptr(ext.as_ptr() as *const i8) {
                    return true;
                }
            }
        }
        false
    }).map(|s| *s).collect::<Vec<_>>();

    let instance = {
        let cstrings = layers.iter().chain(extensions.iter())
                                    .chain(surface_extensions.iter())
                         .map(|&s| CString::new(s).unwrap())
                         .collect::<Vec<_>>();
        let str_pointers = cstrings.iter()
                                   .map(|s| s.as_ptr())
                                   .collect::<Vec<_>>();

        let create_info = vk::InstanceCreateInfo {
            sType: vk::STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            pApplicationInfo: &app_info,
            enabledLayerCount: layers.len() as u32,
            ppEnabledLayerNames: str_pointers.as_ptr(),
            enabledExtensionCount: (extensions.len() + surface_extensions.len()) as u32,
            ppEnabledExtensionNames: str_pointers[layers.len()..].as_ptr(),
        };
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            entry_points.CreateInstance(&create_info, ptr::null(), &mut out)
        });
        out
    };

    let inst_pointers = vk::InstancePointers::load(|name| unsafe {
        mem::transmute(lib.GetInstanceProcAddr(instance, name.as_ptr()))
    });

    let physical_devices = {
        let mut num = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            inst_pointers.EnumeratePhysicalDevices(instance, &mut num, ptr::null_mut())
        });
        let mut devices = Vec::with_capacity(num as usize);
        assert_eq!(vk::SUCCESS, unsafe {
            inst_pointers.EnumeratePhysicalDevices(instance, &mut num, devices.as_mut_ptr())
        });
        unsafe { devices.set_len(num as usize); }
        devices
    };

    let devices = physical_devices.iter()
        .map(|dev| PhysicalDeviceInfo::new(*dev, &inst_pointers))
        .collect::<Vec<_>>();

    let (dev, (qf_id, _))  = devices.iter()
        .flat_map(|d| iter::repeat(d).zip(d.queue_families.iter().enumerate()))
        .find(|&(_, (_, qf))| qf.queueFlags & vk::QUEUE_GRAPHICS_BIT != 0)
        .unwrap();
    info!("Chosen physical device {:?} with queue family {}", dev.device, qf_id);

    let mvid_id = dev.memory.memoryTypes.iter().take(dev.memory.memoryTypeCount as usize)
                            .position(|mt| (mt.propertyFlags & vk::MEMORY_PROPERTY_DEVICE_LOCAL_BIT != 0)
                                        && (mt.propertyFlags & vk::MEMORY_PROPERTY_HOST_VISIBLE_BIT != 0))
                            .unwrap() as u32;
    let msys_id = dev.memory.memoryTypes.iter().take(dev.memory.memoryTypeCount as usize)
                            .position(|mt| mt.propertyFlags & vk::MEMORY_PROPERTY_HOST_COHERENT_BIT != 0)
                            .unwrap() as u32;

    let device = {
        let cstrings = dev_extensions.iter()
                                     .map(|&s| CString::new(s).unwrap())
                                     .collect::<Vec<_>>();
        let str_pointers = cstrings.iter().map(|s| s.as_ptr())
                                   .collect::<Vec<_>>();

        let queue_info = vk::DeviceQueueCreateInfo {
            sType: vk::STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            queueFamilyIndex: qf_id as u32,
            queueCount: 1,
            pQueuePriorities: &1.0,
        };
        let features = unsafe{ mem::zeroed() };

        let dev_info = vk::DeviceCreateInfo {
            sType: vk::STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0,
            queueCreateInfoCount: 1,
            pQueueCreateInfos: &queue_info,
            enabledLayerCount: 0,
            ppEnabledLayerNames: ptr::null(),
            enabledExtensionCount: str_pointers.len() as u32,
            ppEnabledExtensionNames: str_pointers.as_ptr(),
            pEnabledFeatures: &features,
        };
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            inst_pointers.CreateDevice(dev.device, &dev_info, ptr::null(), &mut out)
        });
        out
    };

    let dev_pointers = vk::DevicePointers::load(|name| unsafe {
        inst_pointers.GetDeviceProcAddr(device, name.as_ptr()) as *const _
    });
    let queue = unsafe {
        let mut out = mem::zeroed();
        dev_pointers.GetDeviceQueue(device, qf_id as u32, 0, &mut out);
        out
    };

    let share = Arc::new(Share {
        _dynamic_lib: dynamic_lib,
        _library: lib,
        instance: instance,
        inst_pointers: inst_pointers,
        device: device,
        dev_pointers: dev_pointers,
        handles: RefCell::new(gfx_core::handle::Manager::new()),
    });
    let gfx_device = command::GraphicsQueue::new(share.clone(), queue, qf_id as u32);
    let gfx_factory = factory::Factory::new(share.clone(), qf_id as u32, mvid_id, msys_id);

    (gfx_device, gfx_factory, share)
}

#[derive(Clone, PartialEq, Eq)]
pub struct Error(pub vk::Result);

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self.0 {
            vk::SUCCESS => "success",
            vk::NOT_READY => "not ready",
            vk::TIMEOUT => "timeout",
            vk::EVENT_SET => "event_set",
            vk::EVENT_RESET => "event_reset",
            vk::INCOMPLETE => "incomplete",
            vk::ERROR_OUT_OF_HOST_MEMORY => "out of host memory",
            vk::ERROR_OUT_OF_DEVICE_MEMORY => "out of device memory",
            vk::ERROR_INITIALIZATION_FAILED => "initialization failed",
            vk::ERROR_DEVICE_LOST => "device lost",
            vk::ERROR_MEMORY_MAP_FAILED => "memory map failed",
            vk::ERROR_LAYER_NOT_PRESENT => "layer not present",
            vk::ERROR_EXTENSION_NOT_PRESENT => "extension not present",
            vk::ERROR_FEATURE_NOT_PRESENT => "feature not present",
            vk::ERROR_INCOMPATIBLE_DRIVER => "incompatible driver",
            vk::ERROR_TOO_MANY_OBJECTS => "too many objects",
            vk::ERROR_FORMAT_NOT_SUPPORTED => "format not supported",
            vk::ERROR_SURFACE_LOST_KHR => "surface lost (KHR)",
            vk::ERROR_NATIVE_WINDOW_IN_USE_KHR => "native window in use (KHR)",
            vk::SUBOPTIMAL_KHR => "suboptimal (KHR)",
            vk::ERROR_OUT_OF_DATE_KHR => "out of date (KHR)",
            vk::ERROR_INCOMPATIBLE_DISPLAY_KHR => "incompatible display (KHR)",
            vk::ERROR_VALIDATION_FAILED_EXT => "validation failed (EXT)",
            _ => "unknown",
        })
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}

impl gfx_core::Resources for Resources {
    type Buffer               = native::Buffer;
    type Shader               = vk::ShaderModule;
    type Program              = native::Program;
    type PipelineStateObject  = native::Pipeline;
    type Texture              = native::Texture;
    type ShaderResourceView   = native::TextureView; //TODO: buffer view
    type UnorderedAccessView  = ();
    type RenderTargetView     = native::TextureView;
    type DepthStencilView     = native::TextureView;
    type Sampler              = vk::Sampler;
    type Fence                = vk::Fence;
}
<|endoftext|>


<commit_before><commit_msg>This is a regression test for #54478.<commit_after>// Issue #54478: regression test showing that we can demonstrate
// `#[global_allocator]` in code blocks built by `rustdoc`.
//
// ## Background
//
// Changes in lang-item visibility injected failures that were only
// exposed when compiling with `-C prefer-dynamic`. But `rustdoc` used
// `-C prefer-dynamic` (and had done so for years, for reasons we did
// not document at that time).
//
// Rather than try to revise the visbility semanics, we instead
// decided to change `rustdoc` to behave more like the compiler's
// default setting, by leaving off `-C prefer-dynamic`.

// compile-flags:--test

//! This is a doc comment
//!
//! ```rust
//! use std::alloc::*;
//!
//! #[global_allocator]
//! static ALLOC: A = A;
//!
//! static mut HIT: bool = false;
//!
//! struct A;
//!
//! unsafe impl GlobalAlloc for A {
//!     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
//!         HIT = true;
//!         System.alloc(layout)
//!     }
//!     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
//!         System.dealloc(ptr, layout);
//!     }
//! }
//!
//! fn main() {
//!     assert!(unsafe { HIT });
//! }
//! ```
<|endoftext|>