<commit_before>use bit_vec::BitVec;

use avr_bit_vec;
use emulator::Emulator;
use emulator::AvrDataMemory;
use emulator::get_register_index;

fn print_bit_vec(bv: &BitVec) {
    println!("BV: {}{}{}{}{}{}{}{}", bv[7], bv[6], bv[5], bv[4], bv[3], bv[2], bv[1], bv[0]);
}

pub fn perform<'a>(emulator: &Emulator<'a>, rd: &str, rr: &str) -> Emulator<'a> {
    let rd_index = get_register_index(rd);
    let rr_index = get_register_index(rr);

    let registers = &emulator.data_memory.registers;
    let result = (registers[rd_index] as u16) + (registers[rr_index] as u16);
    println!("ADD RESULT: {}", result);

    let mut new_registers = registers.to_vec();
    let register_result = result as u8;
    new_registers[rd_index] = register_result;

    let io = &emulator.data_memory.io;
    let mut new_io = emulator.data_memory.io.to_vec();
    let mut sreg = avr_bit_vec::from_u8(io[63]);
    let r_vec = avr_bit_vec::from_u8(register_result);
    print_bit_vec(&r_vec);

    // SREG N
    sreg.set(2, r_vec[7]);

    // SREG Z
    sreg.set(1, (register_result == 0));

    // SREG C
    sreg.set(0, (result >= 256));

    new_io[63] = avr_bit_vec::to_u8(sreg);

    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: new_io,
            ram: data_memory.ram.to_vec()
        },
        program_pointer: &emulator.program_pointer+1,
        machine_code: emulator.machine_code.clone()
    }
}

#[cfg(test)]
mod tests {
  use avr_bit_vec;
  use emulator::Emulator;

  use super::*;

  #[test]
  fn can_add() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);
      emulator.data_memory.registers[1] = 2;
      emulator.data_memory.registers[2] = 3;

      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(5, emulator.data_memory.registers[1]);
      assert_eq!(3, emulator.data_memory.registers[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(0, emulator.data_memory.registers[1]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 2;
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(1, emulator.data_memory.registers[1]);
  }

  #[test]
  fn updates_program_pointer() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(1, emulator.program_pointer);
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(2, emulator.program_pointer);
  }

  #[test]
  fn updates_sreg_n() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 126;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 127;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 254;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 129;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);
  }

  #[test]
  fn updates_sreg_z() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 0;
      emulator.data_memory.registers[2] = 0;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[1]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[1]);

      emulator.data_memory.registers[1] = 1;
      emulator.data_memory.registers[2] = 0;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[1]);
  }

  #[test]
  fn updates_sreg_c() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 127;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[0]);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);

      emulator.data_memory.registers[1] = 1;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);
  }
}
<commit_msg>SREG updates in ADD are complete<commit_after>use bit_vec::BitVec;

use avr_bit_vec;
use emulator::Emulator;
use emulator::AvrDataMemory;
use emulator::get_register_index;

pub fn perform<'a>(emulator: &Emulator<'a>, rd: &str, rr: &str) -> Emulator<'a> {
    let rd_index = get_register_index(rd);
    let rr_index = get_register_index(rr);

    ///////////////////////////////////////////////////
    // Update Rd //////////////////////////////////////
    ///////////////////////////////////////////////////
    let registers = &emulator.data_memory.registers;
    let result = (registers[rd_index] as u16) + (registers[rr_index] as u16);

    let mut new_registers = registers.to_vec();
    let register_result = result as u8;
    new_registers[rd_index] = register_result;

    ///////////////////////////////////////////////////
    // Update SREG flags //////////////////////////////
    ///////////////////////////////////////////////////
    let io = &emulator.data_memory.io;
    let mut new_io = emulator.data_memory.io.to_vec();
    let mut sreg = avr_bit_vec::from_u8(io[63]);
    let r_vec = avr_bit_vec::from_u8(register_result);
    let rd_vec = avr_bit_vec::from_u8(registers[rd_index]);
    let rr_vec = avr_bit_vec::from_u8(registers[rr_index]);

    // SREG C
    // This is the same as:
    // let carry = result >= 256
    let carry =
      (rd_vec[7] && rr_vec[7]) ||
      (rr_vec[7] && !r_vec[7]) ||
      (rd_vec[7] && !r_vec[7]);
    sreg.set(0, carry);

    // SREG Z
    sreg.set(1, (register_result == 0));

    // SREG N
    sreg.set(2, r_vec[7]);

    // SREG V
    let twos_complement_overflow =
      (rd_vec[7] && rr_vec[7] && !r_vec[7]) ||
      (!rd_vec[7] && !rr_vec[7] && r_vec[7]);
    sreg.set(3, twos_complement_overflow);

    // SREG S
    let n_xor_v = sreg[2] ^ sreg[3];
    sreg.set(4, n_xor_v);

    // SREG H
    let mid_carry =
      (rd_vec[3] && rr_vec[3]) ||
      (rr_vec[3] && !r_vec[3]) ||
      (rd_vec[3] && !r_vec[3]);
    sreg.set(5, mid_carry);

    new_io[63] = avr_bit_vec::to_u8(sreg);

    ///////////////////////////////////////////////////
    // Build and return new emulator state ////////////
    ///////////////////////////////////////////////////
    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: new_io,
            ram: data_memory.ram.to_vec()
        },
        program_pointer: &emulator.program_pointer+1,
        machine_code: emulator.machine_code.clone()
    }
}

#[cfg(test)]
mod tests {
  use avr_bit_vec;
  use emulator::Emulator;

  use super::*;

  #[test]
  fn can_add() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);
      emulator.data_memory.registers[1] = 2;
      emulator.data_memory.registers[2] = 3;

      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(5, emulator.data_memory.registers[1]);
      assert_eq!(3, emulator.data_memory.registers[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(0, emulator.data_memory.registers[1]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 2;
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(1, emulator.data_memory.registers[1]);
  }

  #[test]
  fn updates_program_pointer() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(1, emulator.program_pointer);
      emulator = perform(&emulator, "r1", "r2");
      assert_eq!(2, emulator.program_pointer);
  }

  #[test]
  fn updates_sreg_c() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 127;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[0]);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);

      emulator.data_memory.registers[1] = 1;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[0]);
  }

  #[test]
  fn updates_sreg_z() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 0;
      emulator.data_memory.registers[2] = 0;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[1]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[1]);

      emulator.data_memory.registers[1] = 1;
      emulator.data_memory.registers[2] = 0;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[1]);
  }

  #[test]
  fn updates_sreg_n() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 126;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 127;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 254;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 129;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);
  }

  #[test]
  fn updates_sreg_v() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 64;
      emulator.data_memory.registers[2] = 63;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[3]);

      emulator.data_memory.registers[1] = 64;
      emulator.data_memory.registers[2] = 64;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[3]);

      emulator.data_memory.registers[1] = 127;
      emulator.data_memory.registers[2] = 127;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[3]);

      emulator.data_memory.registers[1] = 127;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[3]);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 127;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[3]);

      emulator.data_memory.registers[1] = 128;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[3]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[3]);
  }

  #[test]
  fn updates_sreg_s() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 0;
      emulator.data_memory.registers[2] = 0;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);
      assert_eq!(false, sreg[3]);
      assert_eq!(false, sreg[4]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 255;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);
      assert_eq!(false, sreg[3]);
      assert_eq!(true, sreg[4]);

      emulator.data_memory.registers[1] = 255;
      emulator.data_memory.registers[2] = 128;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[2]);
      assert_eq!(true, sreg[3]);
      assert_eq!(true, sreg[4]);

      emulator.data_memory.registers[1] = 127;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[2]);
      assert_eq!(true, sreg[3]);
      assert_eq!(false, sreg[4]);
    }

  #[test]
  fn updates_sreg_h() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 8;
      emulator.data_memory.registers[2] = 7;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(false, sreg[5]);

      emulator.data_memory.registers[1] = 15;
      emulator.data_memory.registers[2] = 15;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[5]);

      emulator.data_memory.registers[1] = 15;
      emulator.data_memory.registers[2] = 1;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[5]);

      emulator.data_memory.registers[1] = 1;
      emulator.data_memory.registers[2] = 15;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[5]);

      emulator.data_memory.registers[1] = 24;
      emulator.data_memory.registers[2] = 8;
      emulator = perform(&emulator, "r1", "r2");
      let sreg = avr_bit_vec::from_u8(emulator.data_memory.io[63]);
      assert_eq!(true, sreg[5]);
  }
}
<|endoftext|>


<commit_before><commit_msg>#321: Add snake example<commit_after><|endoftext|>


<commit_before><commit_msg>Add media preview endpoint.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a basic example<commit_after>extern crate exitcode;

use std::process;

pub fn parse_int_or_return_error_exitcode(s: String) -> Result<i32, exitcode::ExitCode> {
    match s.parse::<i32>() {
        Ok(i) => Ok(i),
        Err(_) => Err(exitcode::USAGE)
    }

}

pub fn main() {

    match parse_int_or_return_error_exitcode("123".to_string()) {
        Ok(i) => println!("Parsed: {}", i),
        Err(code) => {
            println!("Parse error.  Exiting with code: {}", code);
            process::exit(code);
        }
    }

    match parse_int_or_return_error_exitcode("foo".to_string()) {
        Ok(i) => println!("Parsed: {}", i),
        Err(code) => {
            println!("Parse error.  Exiting with code: {}", code);
            process::exit(code);
        }
    }

    println!("Exiting with code: {}", exitcode::OK);
    process::exit(exitcode::OK);

}
<|endoftext|>


<commit_before>extern mod std;
extern mod glfw3;
use glfw3::*;

fn main() {
    if (glfwInit() == 0) {
        fail(~"glfwInit() failed\n");
    }

    let dt_mode = glfwGetDesktopMode();
    io::println(~"Desktop mode:\n" + mode_str(dt_mode));

    let modes = glfwGetVideoModes();

    io::println(~"Available modes:");
    modes.map(|m| { io::println(mode_str(m)) });

    glfwTerminate();
}

fn mode_str(mode: GLFWvidmode) -> ~str {
    fmt!("%d x %d\t%d (%d %d %d)",
         mode.width as int, mode.height as int,
         (mode.redBits + mode.blueBits + mode.greenBits) as int,
         mode.redBits as int, mode.blueBits as int, mode.greenBits as int)
}<commit_msg>Change argument to pointer<commit_after>extern mod std;
extern mod glfw3;
use glfw3::*;

fn main() {
    if (glfwInit() == 0) {
        fail(~"glfwInit() failed\n");
    }

    let dt_mode = glfwGetDesktopMode();
    io::println(~"Desktop mode:\n" + mode_str(&dt_mode));

    let modes = glfwGetVideoModes();

    io::println(~"Available modes:");
    modes.map(|m| io::println(mode_str(m)));

    glfwTerminate();
}

fn mode_str(mode: &GLFWvidmode) -> ~str {
    fmt!("%? x %?\t%? (%? %? %?)",
         mode.width, mode.height,
         (mode.redBits + mode.blueBits + mode.greenBits),
         mode.redBits, mode.blueBits, mode.greenBits)
}<|endoftext|>


<commit_before><commit_msg>Add a testkit for HTTP cache integration tests.<commit_after>use std::cell::Cell;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};

fn global_test_root() -> PathBuf {
    let mut path = env::current_exe().unwrap();
    path.pop(); // chop off exe name
    path.pop(); // chop off 'debug'

    // If `cargo test` is run manually then our path looks like
    // `target/debug/foo`, in which case our `path` is already pointing at
    // `target`. If, however, `cargo test --target $target` is used then the
    // output is `target/$target/debug/foo`, so our path is pointing at
    // `target/$target`. Here we conditionally pop the `$target` name.
    if path.file_name().and_then(|s| s.to_str()) != Some("target") {
        path.pop();
    }

    path.join("int-test")
}

fn test_root() -> PathBuf {
    let root = global_test_root();

    static NEXT_TEST_NUM: AtomicUsize = ATOMIC_USIZE_INIT;
    thread_local!(static TEST_NUM: usize = NEXT_TEST_NUM.fetch_add(1, Ordering::SeqCst));
    let root = root.join(&TEST_NUM.with(|my_id| format!("t{}", my_id)));

    thread_local!(static TEST_ROOT_INIT: Cell<bool> = Cell::new(false));
    TEST_ROOT_INIT.with(|i| {
        if i.get() {
            return;
        }
        i.set(true);
        fs::remove_dir_all(&root).expect("removing root");
        debug!("deleted root {}", root.display());
    });

    root
}

pub fn test_home() -> PathBuf {
    test_root().join("home")
}
<|endoftext|>


<commit_before><commit_msg>Missing file.<commit_after>// Copyright 2014 Christopher Schröder, Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

use htslib;

pub struct Pileup {
    inner: Vec<htslib::bam_pileup1_t>,
    pub tid: u32,
    pub pos: u32,
}

pub struct Pileups {
    itr: htslib::bam_plp_t,
}

impl Pileups {
    pub fn new(itr: htslib::bam_plp_t) -> Self {
        Pileups { itr: itr }
    }
}

impl Iterator for Pileups {
    type Item = Pileup;

    fn next(&mut self) -> Option<Pileup> {
        let (mut tid, mut pos, mut len) = (0i32, 0i32, 0i32);
        let inner = unsafe {
            htslib::bam_plp_auto(self.itr, &mut tid, &mut pos, &mut len)
        };

        if inner.is_null() {
            None
        }
        else {
            Some(Pileup {
                inner: unsafe {
                    Vec::from_raw_parts(inner as *mut htslib::bam_pileup1_t, len as usize, len as usize)
                },
                tid: tid as u32,
                pos: pos as u32,
            })
        }
    }
}

impl Drop for Pileups {
    fn drop(&mut self) {
        unsafe {
            htslib::bam_plp_destroy(self.itr);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Unused import<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unnecessary references to Lines<commit_after><|endoftext|>


<commit_before><commit_msg>fast kiyoshi<commit_after><|endoftext|>


<commit_before><commit_msg>added returns/test so possible code consolidation is safer<commit_after><|endoftext|>


<commit_before><commit_msg>Added a level system<commit_after><|endoftext|>


<commit_before><commit_msg>Split some utils into math.rs<commit_after>use euclid::*;

use types::*;

pub mod math {
    use num::Integer;
    use types::*;
    use gameplay_constants::*;

    #[inline]
    pub fn coerce_up(v: ChildVec) -> UVec {
        UVec::new(v.x, v.y)
    }

    #[inline]
    pub fn truncate_up(v: ChildVec) -> UVec {
        UVec::new(
            v.x.div_floor(&(ZOOM_SCALE as i32)),
            v.y.div_floor(&(ZOOM_SCALE as i32)),
        )
    }

    #[inline]
    pub fn mod_up(v: ChildVec) -> ChildVec {
        ChildVec::new(v.x % ZOOM_SCALE as i32, v.y % ZOOM_SCALE as i32)
    }

    #[inline]
    pub fn split_up(v: ChildVec) -> (UVec, ChildVec) {
        (truncate_up(v), mod_up(v))
    }

    #[inline]
    pub fn shift_down(v: UVec) -> ChildVec {
        ChildVec::new(v.x * (ZOOM_SCALE as i32), v.y * (ZOOM_SCALE as i32))
    }

    #[inline]
    pub fn coerce_down(v: UVec) -> ChildVec {
        ChildVec::new(v.x, v.y)
    }
}

pub mod transform {
    use euclid::*;
    use types::*;

    #[inline]
    pub fn screen_to_gl(
        resolution: TypedSize2D<u32, ScreenSpace>,
    ) -> TypedTransform2D<f32, ScreenSpace, GLSpace> {
        let scalex = 1.0 / (resolution.width as f32);
        let scaley = 1.0 / (resolution.height as f32);

        TypedTransform2D::create_scale(scalex, scaley)
    }

    #[inline]
    pub fn rect_to_rect<U, U2>(
        source: TypedRect<f32, U>,
        target: TypedRect<f32, U2>,
    ) -> TypedTransform2D<f32, U, U2> {
        let x_scale = target.size.width / source.size.width;
        let y_scale = target.size.height / source.size.height;
        let translation = TypedVector2D::from_untyped(&(target.origin.to_untyped() - source.origin.to_untyped()));
        TypedTransform2D::create_scale(x_scale, y_scale).post_translate(translation)
    }

    // TODO: doesn't have to be f32
    #[inline]
    pub fn fit_rect_in<U, U2>(
        source: TypedRect<f32, U>,
        target: TypedRect<f32, U2>,
    ) -> TypedTransform2D<f32, U, U2> {
        let source_ratio = source.size.width / source.size.height;
        let target_ratio = target.size.width / target.size.height;

        if source_ratio > target_ratio {
            // source is wider than target, so fills target width
            let image_height = target.size.width / source_ratio;
            let image_origin_y = (target.origin.y + target.size.height / 2.0) - (image_height / 2.0);

            let image = TypedRect::new(
                TypedPoint2D::new(target.origin.x, image_origin_y),
                TypedSize2D::new(target.size.width, image_height),
            );

            rect_to_rect(source, image)
        } else {
            // source is thinner than target
            let image_width = target.size.height * source_ratio;
            let image_origin_x = (target.origin.x + target.size.width / 2.0) - (image_width / 2.0);

            let image = TypedRect::new(
                TypedPoint2D::new(image_origin_x, target.origin.y),
                TypedSize2D::new(image_width, target.size.height),
            );

            rect_to_rect(source, image)
        }
    }
}

pub trait To2dGlTransform {
    fn to_gl_mat3(&self) -> [[f32; 3]; 3];
}

impl<U> To2dGlTransform for TypedTransform2D<f32, U, GLSpace> {
    fn to_gl_mat3(&self) -> [[f32; 3]; 3] {
        let [m11, m12, m21, m22, m31, m32] = self.to_row_major_array();

        #[rustfmt_skip]
        [[m11, m12, 0.0],
         [m21, m22, 0.0],
         [m31, m32, 1.0]]
    }
}
<|endoftext|>


<commit_before><commit_msg>Clean up usage of too many fixed length arrays<commit_after><|endoftext|>


<commit_before><commit_msg>Removed inconsistent DocumentPosition functions.<commit_after><|endoftext|>


<commit_before>use std::mem;

struct Fibonacci {
    curr: uint,
    next: uint,
}

// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
    // The 'Iterator' trait only requires the 'next' method to be defined. The
    // return type is 'Option<T>', 'None' is returned when the 'Iterator' is
    // over, otherwise the next value is returned wrapped in 'Some'
    fn next(&mut self) -> Option<uint> {
        let new_next = self.curr + self.next;
        let new_curr = mem::replace(&mut self.next, new_next);

        // 'Some' is always returned, this is an infinite value generator
        Some(mem::replace(&mut self.curr, new_curr))
    }
}

// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 1, next: 1 }
}

fn main() {
    // Iterator that generates: 0, 1 and 2
    let mut sequence = range(0u, 3);

    println!("Four consecutive `next` calls on range(0, 3)")
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());

    // The for construct will iterate an 'Iterator' until it returns 'None'.
    // Every 'Some' value is unwrapped and bound to a variable.
    println!("Iterate over range(0, 3) using for");
    for i in range(0u, 3) {
        println!("> {}", i);
    }

    // The 'take(n)' method will reduce an iterator to its first 'n' terms,
    // which is pretty useful for infinite value generators
    println!("The first four terms of the Fibonacci sequence are: ");
    for i in fibonacci().take(4) {
        println!("> {}", i);
    }

    // The 'skip(n)' method will shorten an iterator by dropping its first 'n'
    // terms
    println!("The next four terms of the Fibonacci sequence are: ");
    for i in fibonacci().skip(4).take(4) {
        println!("> {}", i);
    }

    let array = [1u, 3, 3, 7];

    // The 'iter' method produces an 'Iterator' over an array/slice
    println!("Iterate the following array {}", array.as_slice());
    for i in array.iter() {
        println!("> {}", i);
    }
}
<commit_msg>Missing the semicolon symbol<commit_after>use std::mem;

struct Fibonacci {
    curr: uint,
    next: uint,
}

// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
    // The 'Iterator' trait only requires the 'next' method to be defined. The
    // return type is 'Option<T>', 'None' is returned when the 'Iterator' is
    // over, otherwise the next value is returned wrapped in 'Some'
    fn next(&mut self) -> Option<uint> {
        let new_next = self.curr + self.next;
        let new_curr = mem::replace(&mut self.next, new_next);

        // 'Some' is always returned, this is an infinite value generator
        Some(mem::replace(&mut self.curr, new_curr))
    }
}

// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 1, next: 1 }
}

fn main() {
    // Iterator that generates: 0, 1 and 2
    let mut sequence = range(0u, 3);

    println!("Four consecutive `next` calls on range(0, 3)");
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());
    println!("> {}", sequence.next());

    // The for construct will iterate an 'Iterator' until it returns 'None'.
    // Every 'Some' value is unwrapped and bound to a variable.
    println!("Iterate over range(0, 3) using for");
    for i in range(0u, 3) {
        println!("> {}", i);
    }

    // The 'take(n)' method will reduce an iterator to its first 'n' terms,
    // which is pretty useful for infinite value generators
    println!("The first four terms of the Fibonacci sequence are: ");
    for i in fibonacci().take(4) {
        println!("> {}", i);
    }

    // The 'skip(n)' method will shorten an iterator by dropping its first 'n'
    // terms
    println!("The next four terms of the Fibonacci sequence are: ");
    for i in fibonacci().skip(4).take(4) {
        println!("> {}", i);
    }

    let array = [1u, 3, 3, 7];

    // The 'iter' method produces an 'Iterator' over an array/slice
    println!("Iterate the following array {}", array.as_slice());
    for i in array.iter() {
        println!("> {}", i);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for #60407.<commit_after>// check-pass

#![feature(existential_type)]

existential type Debuggable: core::fmt::Debug;

static mut TEST: Option<Debuggable> = None;

fn main() {
    unsafe { TEST = Some(foo()) }
}

fn foo() -> Debuggable {
    0u32
}
<|endoftext|>


<commit_before><commit_msg>Add run-fail/adjust_empty.rs test<commit_after><|endoftext|>


<commit_before><commit_msg>Test that fn preconditions get typechecked<commit_after>// Tests that the typechecker checks constraints
// error-pattern:mismatched types: expected uint but found u8
use std;
import std::uint;

fn enum_chars(start:u8, end:u8) : uint::le(start, end) -> [char] {
    let i = start;
    let r = [];
    while (i <= end) {
        r += [i as char];
        i += (1u as u8);
    }
    ret r;
}

fn main() {
    log (enum_chars('a' as u8, 'z' as u8));
}<|endoftext|>


<commit_before><commit_msg>Continue Vulkan initialisation<commit_after><|endoftext|>


<commit_before><commit_msg>Tighten up the image memory barrier between pass, but with no change in the rendering<commit_after><|endoftext|>


<commit_before><commit_msg>chat: Now serializes formatting.<commit_after><|endoftext|>


<commit_before><commit_msg>Run base::internalize_symbols() even for single-codegen-unit crates.<commit_after><|endoftext|>


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

#[doc(keyword = "as")]
//
/// The type coercion keyword.
///
/// `as` is most commonly used to turn primitive types into other primitive types, but it has other
/// uses that include turning pointers into addresses, addresses into pointers, and pointers into
/// other pointers.
///
/// ```rust
/// let thing1: u8 = 89.0 as u8;
/// assert_eq!('B' as u32, 66);
/// assert_eq!(thing1 as char, 'Y');
/// let thing2: f32 = thing1 as f32 + 10.5;
/// assert_eq!(true as u8 + thing2 as u8, 100);
/// ```
///
/// In general, any coercion that can be performed via writing out type hints can also be done
/// using `as`, so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (Note:
/// `let x = 123u32` would be best in that situation). The same is not true in the other direction,
/// however, explicitly using `as` allows a few more coercions that aren't allowed implicitly, such
/// as changing the type of a raw pointer or turning closures into raw pointers.
///
/// For more information on what `as` is capable of, see the [Reference]
///
/// [Reference]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
mod as_keyword { }

#[doc(keyword = "const")]
//
/// The keyword for defining constants.
///
/// Sometimes a certain value is used many times throughout a program, and it can become
/// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
/// make it a variable that gets carried around to each function that needs it. In these cases, the
/// `const` keyword provides a convenient alternative to code duplication.
///
/// ```rust
/// const THING: u32 = 0xABAD1DEA;
///
/// let foo = 123 + THING;
/// ```
///
/// Constants must be explicitly typed, unlike with `let` you can't ignore its type and let the
/// compiler figure it out. Any constant value can be defined in a const, which in practice happens
/// to be most things that would be reasonable to have a constant. For example, you can't have a
/// File as a `const`.
///
/// The only lifetime allowed in a constant is 'static, which is the lifetime that encompasses all
/// others in a Rust program. For example, if you wanted to define a constant string, it would look
/// like this:
///
/// ```rust
/// const WORDS: &'static str = "hello rust!";
/// ```
///
/// Thanks to static lifetime elision, you usually don't have to explicitly use 'static:
///
/// ```rust
/// const WORDS: &str = "hello convenience!";
/// ```
///
/// `const` items looks remarkably similar to [`static`] items, which introduces some confusion as
/// to which one should be used at which times. To put it simply, constants are inlined wherever
/// they're used, making using them identical to simply replacing the name of the const with its
/// value. Static variables on the other hand point to a single location in memory, which all
/// accesses share. This means that, unlike with constants, they can't have destructors, but it
/// also means that (via unsafe code) they can be mutable, which is useful for the rare situations
/// in which you can't avoid using global state.
///
/// Constants, as with statics, should always be in SCREAMING_SNAKE_CASE.
///
/// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
/// T` and `*mut T`. More about that can be read at the [pointer] primitive part of the Rust docs.
///
/// For more detail on `const`, see the [Rust Book] or the [Reference]
///
/// [`static`]: keyword.static.html
/// [pointer]: primitive.pointer.html
/// [Rust Book]: https://doc.rust-lang.org/stable/book/2018-edition/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
/// [Reference]: https://doc.rust-lang.org/reference/items/constant-items.html
mod const_keyword { }

#[doc(keyword = "crate")]
//
/// The `crate` keyword.
///
/// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
/// used to specify a dependency on a crate external to the one it's declared in. Crates are the
/// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
/// be read about crates in the [Reference].
///
/// ```rust ignore
/// extern crate rand;
/// extern crate my_crate as thing;
/// extern crate std; // implicitly added to the root of every Rust project
/// ```
///
/// The `as` keyword can be used to change what the crate is referred to as in your project. If a
/// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
///
/// `crate` is also used as in conjunction with [`pub`] to signify that the item it's attached to
/// is public only to other members of the same crate it's in.
///
/// ```rust
/// # #[allow(unused_imports)]
/// pub(crate) use std::io::Error as IoError;
/// pub(crate) enum CoolMarkerType { }
/// pub struct PublicThing {
///     pub(crate) semi_secret_thing: bool,
/// }
/// ```
///
/// [Reference]: https://doc.rust-lang.org/reference/items/extern-crates.html
/// [`pub`]: keyword.pub.html
mod crate_keyword { }

#[doc(keyword = "fn")]
//
/// The `fn` keyword.
///
/// The `fn` keyword is used to declare a function.
///
/// Example:
///
/// ```rust
/// fn some_function() {
///     // code goes in here
/// }
/// ```
///
/// For more information about functions, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-03-how-functions-work.html
mod fn_keyword { }

#[doc(keyword = "let")]
//
/// The `let` keyword.
///
/// The `let` keyword is used to declare a variable.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let x = 3; // We create a variable named `x` with the value `3`.
/// ```
///
/// By default, all variables are **not** mutable. If you want a mutable variable,
/// you'll have to use the `mut` keyword.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let mut x = 3; // We create a mutable variable named `x` with the value `3`.
///
/// x += 4; // `x` is now equal to `7`.
/// ```
///
/// For more information about the `let` keyword, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-01-variables-and-mutability.html
mod let_keyword { }

#[doc(keyword = "struct")]
//
/// The keyword used to define structs.
///
/// Structs in Rust come in three flavours: Regular structs, tuple structs,
/// and empty structs.
///
/// ```rust
/// struct Regular {
///     field1: f32,
///     field2: String,
///     pub field3: bool
/// }
///
/// struct Tuple(u32, String);
///
/// struct Empty;
/// ```
///
/// Regular structs are the most commonly used. Each field defined within them has a name and a
/// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
/// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
/// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
/// directly accessed and modified.
///
/// Tuple structs are similar to regular structs, but its fields have no names. They are used like
/// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax.  For accessing
/// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
/// etc, starting at zero.
///
/// Empty structs, or unit-like structs, are most commonly used as markers, for example
/// [`PhantomData`]. Empty structs have a size of zero bytes, but unlike empty enums they can be
/// instantiated, making them similar to the unit type `()`. Unit-like structs are useful when you
/// need to implement a trait on something, but don't need to store any data inside it.
///
/// # Instantiation
///
/// Structs can be instantiated in a manner of different ways, each of which can be mixed and
/// matched as needed. The most common way to make a new struct is via a constructor method such as
/// `new()`, but when that isn't available (or you're writing the constructor itself), struct
/// literal syntax is used:
///
/// ```rust
/// # struct Foo { field1: f32, field2: String, etc: bool }
/// let example = Foo {
///     field1: 42.0,
///     field2: "blah".to_string(),
///     etc: true,
/// };
/// ```
///
/// It's only possible to directly instantiate a struct using struct literal syntax when all of its
/// fields are visible to you.
///
/// There are a handful of shortcuts provided to make writing constructors more convenient, most
/// common of which is the Field Init shorthand. When there is a variable and a field of the same
/// name, the assignment can be simplified from `field: field` into simply `field`. The following
/// example of a hypothetical constructor demonstrates this:
///
/// ```rust
/// struct User {
///     name: String,
///     admin: bool,
/// }
///
/// impl User {
///     pub fn new(name: String) -> Self {
///         Self {
///             name,
///             admin: false,
///         }
///     }
/// }
/// ```
///
/// Another shortcut for struct instantiation is available, used when you need to make a new
/// struct that has the same values as most of a previous struct of the same type, called struct
/// update syntax:
///
/// ```rust
/// # struct Foo { field1: String, field2: () }
/// # let thing = Foo { field1: "".to_string(), field2: () };
/// let updated_thing = Foo {
///     field1: "a new value".to_string(),
///     ..thing
/// };
/// ```
///
/// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
/// name as a prefix: `Foo(123, false, 0.1)`.
///
/// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
/// EmptyStruct;`
///
/// # Style conventions
///
/// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
/// struct's list of fields can be omitted, it's usually kept for convenience in adding and
/// removing fields down the line.
///
/// For more information on structs, take a look at the [Rust Book][book] or the
/// [Reference][reference].
///
/// [`PhantomData`]: marker/struct.PhantomData.html
/// [book]: https://doc.rust-lang.org/book/second-edition/ch05-01-defining-structs.html
/// [reference]: https://doc.rust-lang.org/reference/items/structs.html
mod struct_keyword { }
<commit_msg>Add keyword docs on `enum`<commit_after>// Copyright 2018 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.

#[doc(keyword = "as")]
//
/// The type coercion keyword.
///
/// `as` is most commonly used to turn primitive types into other primitive types, but it has other
/// uses that include turning pointers into addresses, addresses into pointers, and pointers into
/// other pointers.
///
/// ```rust
/// let thing1: u8 = 89.0 as u8;
/// assert_eq!('B' as u32, 66);
/// assert_eq!(thing1 as char, 'Y');
/// let thing2: f32 = thing1 as f32 + 10.5;
/// assert_eq!(true as u8 + thing2 as u8, 100);
/// ```
///
/// In general, any coercion that can be performed via writing out type hints can also be done
/// using `as`, so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (Note:
/// `let x = 123u32` would be best in that situation). The same is not true in the other direction,
/// however, explicitly using `as` allows a few more coercions that aren't allowed implicitly, such
/// as changing the type of a raw pointer or turning closures into raw pointers.
///
/// For more information on what `as` is capable of, see the [Reference]
///
/// [Reference]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
mod as_keyword { }

#[doc(keyword = "const")]
//
/// The keyword for defining constants.
///
/// Sometimes a certain value is used many times throughout a program, and it can become
/// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
/// make it a variable that gets carried around to each function that needs it. In these cases, the
/// `const` keyword provides a convenient alternative to code duplication.
///
/// ```rust
/// const THING: u32 = 0xABAD1DEA;
///
/// let foo = 123 + THING;
/// ```
///
/// Constants must be explicitly typed, unlike with `let` you can't ignore its type and let the
/// compiler figure it out. Any constant value can be defined in a const, which in practice happens
/// to be most things that would be reasonable to have a constant. For example, you can't have a
/// File as a `const`.
///
/// The only lifetime allowed in a constant is 'static, which is the lifetime that encompasses all
/// others in a Rust program. For example, if you wanted to define a constant string, it would look
/// like this:
///
/// ```rust
/// const WORDS: &'static str = "hello rust!";
/// ```
///
/// Thanks to static lifetime elision, you usually don't have to explicitly use 'static:
///
/// ```rust
/// const WORDS: &str = "hello convenience!";
/// ```
///
/// `const` items looks remarkably similar to [`static`] items, which introduces some confusion as
/// to which one should be used at which times. To put it simply, constants are inlined wherever
/// they're used, making using them identical to simply replacing the name of the const with its
/// value. Static variables on the other hand point to a single location in memory, which all
/// accesses share. This means that, unlike with constants, they can't have destructors, but it
/// also means that (via unsafe code) they can be mutable, which is useful for the rare situations
/// in which you can't avoid using global state.
///
/// Constants, as with statics, should always be in SCREAMING_SNAKE_CASE.
///
/// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
/// T` and `*mut T`. More about that can be read at the [pointer] primitive part of the Rust docs.
///
/// For more detail on `const`, see the [Rust Book] or the [Reference]
///
/// [`static`]: keyword.static.html
/// [pointer]: primitive.pointer.html
/// [Rust Book]: https://doc.rust-lang.org/stable/book/2018-edition/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
/// [Reference]: https://doc.rust-lang.org/reference/items/constant-items.html
mod const_keyword { }

#[doc(keyword = "crate")]
//
/// The `crate` keyword.
///
/// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
/// used to specify a dependency on a crate external to the one it's declared in. Crates are the
/// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
/// be read about crates in the [Reference].
///
/// ```rust ignore
/// extern crate rand;
/// extern crate my_crate as thing;
/// extern crate std; // implicitly added to the root of every Rust project
/// ```
///
/// The `as` keyword can be used to change what the crate is referred to as in your project. If a
/// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
///
/// `crate` is also used as in conjunction with [`pub`] to signify that the item it's attached to
/// is public only to other members of the same crate it's in.
///
/// ```rust
/// # #[allow(unused_imports)]
/// pub(crate) use std::io::Error as IoError;
/// pub(crate) enum CoolMarkerType { }
/// pub struct PublicThing {
///     pub(crate) semi_secret_thing: bool,
/// }
/// ```
///
/// [Reference]: https://doc.rust-lang.org/reference/items/extern-crates.html
/// [`pub`]: keyword.pub.html
mod crate_keyword { }

#[doc(keyword = "enum")]
//
/// For defining enumerations.
///
/// Enums in Rust are similar to those of other compiled languages like C, but have important
/// differences that make them considerably more powerful. What Rust calls enums are more commonly
/// known as Algebraic Data Types if you're coming from a functional programming background, but
/// the important part is that data can go with the enum variants.
///
/// ```rust
/// # struct Coord;
/// enum SimpleEnum {
///     FirstVariant,
///     SecondVariant,
///     ThirdVariant,
/// }
///
/// enum Location {
///     Unknown,
///     Anonymous,
///     Known(Coord),
/// }
///
/// enum ComplexEnum {
///     Nothing,
///     Something(u32),
///     LotsOfThings {
///         usual_struct_stuff: bool,
///         blah: String,
///     }
/// }
///
/// enum EmptyEnum { }
/// ```
///
/// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
/// shows off a hypothetical example of something storing location data, with Coord being any other
/// type that's needed, for example a struct. The third example demonstrates the kind of variant a
/// variant can store, ranging from nothing, to a tuple, to an anonymous struct.
///
/// Instantiating enum variants involves explicitly using the enum's name as its namespace,
/// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
/// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
/// is added as the type describes, for example `Option::Some(123)`. The same follows with
/// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
/// true, blah: "hello!".to_string(), }`. Empty Enums are similar to () in that they cannot be
/// instantiated at all, and are used mainly to mess with the type system in interesting ways.
///
/// For more information, take a look at the [Rust Book] or the [Reference]
///
/// [`Option`]: option/enum.Option.html
/// [Rust Book]: https://doc.rust-lang.org/book/second-edition/ch06-01-defining-an-enum.html
/// [Reference]: https://doc.rust-lang.org/reference/items/enumerations.html
mod enum_keyword { }

#[doc(keyword = "fn")]
//
/// The `fn` keyword.
///
/// The `fn` keyword is used to declare a function.
///
/// Example:
///
/// ```rust
/// fn some_function() {
///     // code goes in here
/// }
/// ```
///
/// For more information about functions, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-03-how-functions-work.html
mod fn_keyword { }

#[doc(keyword = "let")]
//
/// The `let` keyword.
///
/// The `let` keyword is used to declare a variable.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let x = 3; // We create a variable named `x` with the value `3`.
/// ```
///
/// By default, all variables are **not** mutable. If you want a mutable variable,
/// you'll have to use the `mut` keyword.
///
/// Example:
///
/// ```rust
/// # #![allow(unused_assignments)]
/// let mut x = 3; // We create a mutable variable named `x` with the value `3`.
///
/// x += 4; // `x` is now equal to `7`.
/// ```
///
/// For more information about the `let` keyword, take a look at the [Rust Book][book].
///
/// [book]: https://doc.rust-lang.org/book/second-edition/ch03-01-variables-and-mutability.html
mod let_keyword { }

#[doc(keyword = "struct")]
//
/// The keyword used to define structs.
///
/// Structs in Rust come in three flavours: Regular structs, tuple structs,
/// and empty structs.
///
/// ```rust
/// struct Regular {
///     field1: f32,
///     field2: String,
///     pub field3: bool
/// }
///
/// struct Tuple(u32, String);
///
/// struct Empty;
/// ```
///
/// Regular structs are the most commonly used. Each field defined within them has a name and a
/// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
/// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
/// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
/// directly accessed and modified.
///
/// Tuple structs are similar to regular structs, but its fields have no names. They are used like
/// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax.  For accessing
/// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
/// etc, starting at zero.
///
/// Empty structs, or unit-like structs, are most commonly used as markers, for example
/// [`PhantomData`]. Empty structs have a size of zero bytes, but unlike empty enums they can be
/// instantiated, making them similar to the unit type `()`. Unit-like structs are useful when you
/// need to implement a trait on something, but don't need to store any data inside it.
///
/// # Instantiation
///
/// Structs can be instantiated in a manner of different ways, each of which can be mixed and
/// matched as needed. The most common way to make a new struct is via a constructor method such as
/// `new()`, but when that isn't available (or you're writing the constructor itself), struct
/// literal syntax is used:
///
/// ```rust
/// # struct Foo { field1: f32, field2: String, etc: bool }
/// let example = Foo {
///     field1: 42.0,
///     field2: "blah".to_string(),
///     etc: true,
/// };
/// ```
///
/// It's only possible to directly instantiate a struct using struct literal syntax when all of its
/// fields are visible to you.
///
/// There are a handful of shortcuts provided to make writing constructors more convenient, most
/// common of which is the Field Init shorthand. When there is a variable and a field of the same
/// name, the assignment can be simplified from `field: field` into simply `field`. The following
/// example of a hypothetical constructor demonstrates this:
///
/// ```rust
/// struct User {
///     name: String,
///     admin: bool,
/// }
///
/// impl User {
///     pub fn new(name: String) -> Self {
///         Self {
///             name,
///             admin: false,
///         }
///     }
/// }
/// ```
///
/// Another shortcut for struct instantiation is available, used when you need to make a new
/// struct that has the same values as most of a previous struct of the same type, called struct
/// update syntax:
///
/// ```rust
/// # struct Foo { field1: String, field2: () }
/// # let thing = Foo { field1: "".to_string(), field2: () };
/// let updated_thing = Foo {
///     field1: "a new value".to_string(),
///     ..thing
/// };
/// ```
///
/// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
/// name as a prefix: `Foo(123, false, 0.1)`.
///
/// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
/// EmptyStruct;`
///
/// # Style conventions
///
/// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
/// struct's list of fields can be omitted, it's usually kept for convenience in adding and
/// removing fields down the line.
///
/// For more information on structs, take a look at the [Rust Book][book] or the
/// [Reference][reference].
///
/// [`PhantomData`]: marker/struct.PhantomData.html
/// [book]: https://doc.rust-lang.org/book/second-edition/ch05-01-defining-structs.html
/// [reference]: https://doc.rust-lang.org/reference/items/structs.html
mod struct_keyword { }
<|endoftext|>


<commit_before><commit_msg>writer mod: Add a TODO regarding entry order<commit_after><|endoftext|>


<commit_before><commit_msg>shut up warning<commit_after><|endoftext|>


<commit_before><commit_msg>am/pm<commit_after><|endoftext|>


<commit_before><commit_msg>continued cleaning up iterator_provider<commit_after><|endoftext|>


<commit_before><commit_msg>Some better option parsing and todos<commit_after><|endoftext|>


<commit_before><commit_msg>Optimize implementation<commit_after><|endoftext|>


<commit_before><commit_msg>Add a regression test for issue-66501<commit_after>// check-pass

#![allow(unreachable_patterns)]

fn main() {
    const CONST: &[Option<()>; 1] = &[Some(())];
    match &[Some(())] {
        &[None] => {}
        CONST => {}
        &[Some(())] => {}
    }
}
<|endoftext|>


<commit_before><commit_msg>Add Rust solution for byte_format<commit_after>const UNITS: [&'static str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];

fn byte_format(n: usize) -> String {
    let mut id = 0;
    let factor = 1024.0;
    let mut n = n as f64;
    while n > factor {
        n = n / factor;
        id += 1
    }
    format!("{:.2} {}",n, UNITS[id])
}

fn main() {
assert_eq!(byte_format(156833213), "149.57 MB".to_owned());
assert_eq!(byte_format(8101), "7.91 KB".to_owned());
assert_eq!(byte_format(12331), "12.04 KB".to_owned());
}
<|endoftext|>


<commit_before><commit_msg>Make "urls" positional argument<commit_after><|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.

// Test equality constraints in a where clause where the type being
// equated appears in a supertrait.

pub trait Vehicle {
    type Color;

    fn go(&self) {  }
}

pub trait Box {
    type Color;

    fn mail(&self) {  }
}

pub trait BoxCar : Box + Vehicle {
}

fn dent<C:BoxCar>(c: C, color: C::Color) {
    //~^ ERROR ambiguous associated type `Color` in bounds of `C`
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

fn dent_object<COLOR>(c: BoxCar<Color=COLOR>) {
    //~^ ERROR ambiguous associated type
    //~| ERROR the value of the associated type `Color` (from the trait `Vehicle`) must be specified
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

fn paint<C:BoxCar>(c: C, d: C::Color) {
    //~^ ERROR ambiguous associated type `Color` in bounds of `C`
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

pub fn main() { }
<commit_msg>updated unit test!<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.

// Test equality constraints in a where clause where the type being
// equated appears in a supertrait.

pub trait Vehicle {
    type Color;

    fn go(&self) {  }
}

pub trait Box {
    type Color;

    fn mail(&self) {  }
}

pub trait BoxCar : Box + Vehicle {
}

fn dent<C:BoxCar>(c: C, color: C::Color) {
    //~^ ERROR ambiguous associated type `Color` in bounds of `C`
    //~| NOTE ambiguous associated type `Color`
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

fn dent_object<COLOR>(c: BoxCar<Color=COLOR>) {
    //~^ ERROR ambiguous associated type
    //~| ERROR the value of the associated type `Color` (from the trait `Vehicle`) must be specified
    //~| NOTE ambiguous associated type `Color`
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

fn paint<C:BoxCar>(c: C, d: C::Color) {
    //~^ ERROR ambiguous associated type `Color` in bounds of `C`
    //~| NOTE ambiguous associated type `Color`
    //~| NOTE could derive from `Vehicle`
    //~| NOTE could derive from `Box`
}

pub fn main() { }
<|endoftext|>


<commit_before><commit_msg>impl { PartialEq, PartialOrd, Eq, Ord } for Vec<commit_after><|endoftext|>


<commit_before><commit_msg>rust queue<commit_after>struct Queue<T> {
    data: Vec<T>
}

impl<T> Queue<T> {
    fn new() -> Queue<T> {
        Queue{data: vec![]}
    }

    fn enqueue(&mut self, e: T) {
        self.data.push(e)
    }

    fn dequeue(&mut self) -> Option<T> {
        if self.data.is_empty() {
            return None;
        }
        Some(self.data.remove(0))
    }

    fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    fn peek(&self) -> Option<&T> {
        if self.data.is_empty() {
            return None;
        }
        let e = &self.data[0];
        Some(e)
    }
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate futuremio;
extern crate env_logger;

use std::net::TcpStream;
use std::thread;
use std::io::{Read, Write};

use futures::Future;
use futures::stream::Stream;
use futures::io;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
    })
}

#[test]
fn echo_server() {
    drop(env_logger::init());

    let mut l = t!(futuremio::Loop::new());
    let srv = l.handle().tcp_listen(&"127.0.0.1:0".parse().unwrap());
    let srv = t!(l.run(srv));
    let addr = t!(srv.local_addr());

    let msg = "foo bar baz";
    let t = thread::spawn(move || {
        let mut s = t!(TcpStream::connect(&addr));

        let t2 = thread::spawn(move || {
            let mut s = t!(TcpStream::connect(&addr));
            let mut b = Vec::new();
            t!(s.read_to_end(&mut b));
            b
        });

        let mut expected = Vec::<u8>::new();
        for _i in 0..1024 {
            expected.extend(msg.as_bytes());
            assert_eq!(t!(s.write(msg.as_bytes())), msg.len());
        }
        (expected, t2)
    });

    let clients = srv.incoming().take(2).map(|e| e.0).collect();
    let copied = clients.and_then(|clients| {
        let mut clients = clients.into_iter();
        let a = io::BufReader::new(clients.next().unwrap());
        let b = io::BufWriter::new(clients.next().unwrap());
        io::copy(a, b)
    });

    let amt = t!(l.run(copied));
    let (expected, t2) = t.join().unwrap();
    let actual = t2.join().unwrap();

    assert!(expected == actual);
    assert_eq!(amt, msg.len() as u64 * 1024);
}
<commit_msg>Limit the reader on the buffered test<commit_after>extern crate futures;
extern crate futuremio;
extern crate env_logger;

use std::net::TcpStream;
use std::thread;
use std::io::{Read, Write};

use futures::Future;
use futures::stream::Stream;
use futures::io;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
    })
}

#[test]
fn echo_server() {
    const N: usize = 1024;
    drop(env_logger::init());

    let mut l = t!(futuremio::Loop::new());
    let srv = l.handle().tcp_listen(&"127.0.0.1:0".parse().unwrap());
    let srv = t!(l.run(srv));
    let addr = t!(srv.local_addr());

    let msg = "foo bar baz";
    let t = thread::spawn(move || {
        let mut s = t!(TcpStream::connect(&addr));

        let t2 = thread::spawn(move || {
            let mut s = t!(TcpStream::connect(&addr));
            let mut b = vec![0; msg.len() * N];
            t!(s.read_exact(&mut b));
            b
        });

        let mut expected = Vec::<u8>::new();
        for _i in 0..N {
            expected.extend(msg.as_bytes());
            assert_eq!(t!(s.write(msg.as_bytes())), msg.len());
        }
        (expected, t2)
    });

    let clients = srv.incoming().take(2).map(|e| e.0).collect();
    let copied = clients.and_then(|clients| {
        let mut clients = clients.into_iter();
        let a = io::BufReader::new(clients.next().unwrap());
        let b = io::BufWriter::new(clients.next().unwrap());
        io::copy(a, b)
    });

    let amt = t!(l.run(copied));
    let (expected, t2) = t.join().unwrap();
    let actual = t2.join().unwrap();

    assert!(expected == actual);
    assert_eq!(amt, msg.len() as u64 * 1024);
}
<|endoftext|>


<commit_before><commit_msg>Problem 39<commit_after>fn primes(start: uint, end: uint) -> ~[uint] {
    let mut primes = ~[2];
    let mut i = 3;
    while i < end {
        while primes.iter().any(|&x| i%x == 0) {
            i += 2;
        }
        primes.push(i);
    }
    primes.move_iter().filter(|&p| p >= start && p < end).to_owned_vec()
}

fn main() {
    println!("{:?}", primes(2, 7920).len());
}

<|endoftext|>


<commit_before><commit_msg>Codeforces 761A<commit_after>macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

fn main() {
    read_line!(even;i64, odd;i64);
    if odd == 0 && even == 0 {
        println!("NO"); // There must be one staircase
        return
    }
    if (odd - even).abs() <= 1 {
        // Valid count
        println!("YES")
    } else {
        println!("NO")
    }
}<|endoftext|>


<commit_before>use super::*;
use redox::*;

impl Editor {
    /// Redraw the window
    pub fn redraw(&mut self) {
        // TODO: Only draw when relevant for the window
        let x = self.x();
        let y = self.y();
        // Redraw window
        self.window.set(Color::BLACK);

        self.window.rect(8 * (x - self.scroll_y) as isize,
                         16 * (y - self.scroll_x) as isize,
                         8,
                         16,
                         Color::WHITE);

        let mut string = false;

        for (y, row) in self.text.iter().enumerate() {
            for (x, &c) in row.iter().enumerate() {
                // TODO: Move outta here
                let color = match c {
                    '\'' | '"' => {
                        string = !string;
                        (226, 225, 167) //(167, 222, 156)
                    },
                    _ if string => (226, 225, 167), //(167, 222, 156)
                    '!' | '@' | '#' | '$' | '%' | '^' | '&' | '|' | '*' | '+' | '-' | '/' | ':' | '=' | '<' | '>' => (198, 83, 83), //(228, 190, 175), //(194, 106, 71),
                    '.' | ',' => (241, 213, 226),
                    '(' | ')' | '[' | ']' | '{' | '}' => (164, 212, 125), //(195, 139, 75),
                    '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => (209, 209, 177),
                    _ => (255, 255, 255),
                };

                if self.x() == x && self.y() == y {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     c,
                                     Color::rgb(color.0 / 3, color.1 / 3, color.2 / 3));
                } else {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     c,
                                     Color::rgb(color.0, color.1, color.2));
                }
            }
        }
        let h = self.window.height();
        let w = self.window.width();
        self.window.rect(0, h as isize - 18, w, 18, Color::rgba(74, 74, 74, 255));

        for (n, c) in (if self.status_bar.mode.len() > w / (8 * 4) {
            self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>()
        } else {
            self.status_bar.mode.chars().collect()
        }).into_iter().enumerate() {

            self.window.char(n as isize * 8, h as isize - 16 - 1, if c == '\t' { ' ' } else { c }, Color::WHITE);
        }

        self.window.sync();
    }
}

/// The statubar (showing various info about the current state of the editor)
pub struct StatusBar {
    /// The current mode
    pub mode: String,
    /// The cureent char
    pub file: String,
    /// The current command
    pub cmd: String,
    /// A message (such as an error or other info to the user)
    pub msg: String,
}

impl StatusBar {
    /// Create new status bar
    pub fn new() -> Self {
        StatusBar {
            mode: "Normal".to_string(),
            file: String::new(),
            cmd: String::new(),
            msg: String::new(),
        }
    }
}
<commit_msg>Change bg color<commit_after>use super::*;
use redox::*;

impl Editor {
    /// Redraw the window
    pub fn redraw(&mut self) {
        // TODO: Only draw when relevant for the window
        let x = self.x();
        let y = self.y();
        // Redraw window
        self.window.set(Color::rgb(25, 25, 25));

        self.window.rect(8 * (x - self.scroll_y) as isize,
                         16 * (y - self.scroll_x) as isize,
                         8,
                         16,
                         Color::WHITE);

        let mut string = false;

        for (y, row) in self.text.iter().enumerate() {
            for (x, &c) in row.iter().enumerate() {
                // TODO: Move outta here
                let color = match c {
                    '\'' | '"' => {
                        string = !string;
                        (226, 225, 167) //(167, 222, 156)
                    },
                    _ if string => (226, 225, 167), //(167, 222, 156)
                    '!' | '@' | '#' | '$' | '%' | '^' | '&' | '|' | '*' | '+' | '-' | '/' | ':' | '=' | '<' | '>' => (198, 83, 83), //(228, 190, 175), //(194, 106, 71),
                    '.' | ',' => (241, 213, 226),
                    '(' | ')' | '[' | ']' | '{' | '}' => (164, 212, 125), //(195, 139, 75),
                    '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => (209, 209, 177),
                    _ => (255, 255, 255),
                };

                if self.x() == x && self.y() == y {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     c,
                                     Color::rgb(color.0 / 3, color.1 / 3, color.2 / 3));
                } else {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     c,
                                     Color::rgb(color.0, color.1, color.2));
                }
            }
        }
        let h = self.window.height();
        let w = self.window.width();
        self.window.rect(0, h as isize - 18, w, 18, Color::rgba(74, 74, 74, 255));

        for (n, c) in (if self.status_bar.mode.len() > w / (8 * 4) {
            self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>()
        } else {
            self.status_bar.mode.chars().collect()
        }).into_iter().enumerate() {

            self.window.char(n as isize * 8, h as isize - 16 - 1, if c == '\t' { ' ' } else { c }, Color::WHITE);
        }

        self.window.sync();
    }
}

/// The statubar (showing various info about the current state of the editor)
pub struct StatusBar {
    /// The current mode
    pub mode: String,
    /// The cureent char
    pub file: String,
    /// The current command
    pub cmd: String,
    /// A message (such as an error or other info to the user)
    pub msg: String,
}

impl StatusBar {
    /// Create new status bar
    pub fn new() -> Self {
        StatusBar {
            mode: "Normal".to_string(),
            file: String::new(),
            cmd: String::new(),
            msg: String::new(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>day 15 solved.<commit_after>use std::cmp::max;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;

struct Ingr {
    cap: i32,
    dur: i32,
    flv: i32,
    txt: i32,
    cal: i32
}

impl Ingr {
    fn new(cap: i32, dur: i32, flv: i32, txt: i32, cal: i32) -> Ingr {
        Ingr {
            cap: cap,
            dur: dur,
            flv: flv,
            txt: txt,
            cal: cal
        }
    }

    fn score(&self) -> i32 {
        max(0, self.cap) * max(0, self.dur) * max(0, self.flv) * max(0, self.txt)
    }
}

fn partition(ingrs: &Vec<Ingr>, tot: usize, cal_lim: i32) -> i32 {
    fn partition_internal(ingrs: &Vec<Ingr>, index: usize, rem: usize, cal_lim: i32, stored: &mut Vec<usize>) -> i32 {
        if index == ingrs.len() - 1 {
            stored.push(rem);
            let super_ingr = ingrs.iter().enumerate().fold(Ingr::new(0, 0, 0, 0, 0), |acc, (i, ingr)| {
                Ingr::new(acc.cap + stored[i] as i32 * ingr.cap,
                          acc.dur + stored[i] as i32 * ingr.dur,
                          acc.flv + stored[i] as i32 * ingr.flv,
                          acc.txt + stored[i] as i32 * ingr.txt,
                          acc.cal + stored[i] as i32 * ingr.cal)
            });
            stored.pop();
            if cal_lim == -1 || super_ingr.cal == cal_lim {
                super_ingr.score()
            } else {
                0
            }
        } else {
            let mut ret = 0;
            for amt in 0..(rem + 1) {
                stored.push(amt);
                ret = max(ret, partition_internal(&ingrs, index + 1, rem - amt, cal_lim, stored));
                stored.pop();
            }
            ret
        }
    };
    partition_internal(ingrs, 0, tot, cal_lim, &mut Vec::new())
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let tot = 100;
    let mut ingrs = Vec::new();

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();

        let mut cap_str = parts[2].to_string().clone(); cap_str.pop();
        let mut dur_str = parts[4].to_string().clone(); dur_str.pop();
        let mut flv_str = parts[6].to_string().clone(); flv_str.pop();
        let mut txt_str = parts[8].to_string().clone(); txt_str.pop();
        let cal_str = parts[10];

        let cap = cap_str.parse().ok().expect("Could not parse into an integer!");
        let dur = dur_str.parse().ok().expect("Could not parse into an integer!");
        let flv = flv_str.parse().ok().expect("Could not parse into an integer!");
        let txt = txt_str.parse().ok().expect("Could not parse into an integer!");
        let cal = cal_str.parse().ok().expect("Could not parse into an integer!");

        ingrs.push(Ingr::new(cap, dur, flv, txt, cal));
    }

    let ret = partition(&ingrs, tot, -1);

    println!("The optimal total score is {}.", ret);

    let cal_lim = 500;

    let ret = partition(&ingrs, tot, cal_lim);

    println!("The optimal total score with the calory constraint is {}.", ret);
}<|endoftext|>


<commit_before><commit_msg>Add problem #35<commit_after>extern mod euler;
use euler::prime::{ Prime };
use euler::calc::{ num_to_digits };

fn is_circular_prime(n: uint, ps: &Prime) -> bool {
    let buf = num_to_digits(n);

    for uint::range(1, buf.len()) |i| {
        let mut num = 0;
        for uint::range(0, buf.len()) |j| {
            num = num * 10 + (buf[(i + j) % buf.len()] as uint);
        }
        if !ps.is_prime(num) { return false; }
    }
    return true;
}

fn main() {
    let ps = Prime();
    let mut cnt = 0;
    for ps.each() |p| {
        if p >= 1000000 { break; }
        if is_circular_prime(p, &ps) {
            io::println(fmt!("%u", p));
            cnt += 1;
        }
    }
    io::println(fmt!("answer: %u", cnt));
}
<|endoftext|>


<commit_before><commit_msg>Use deref instead of casts<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #27379 - jeehoonkang:master, r=steveklabnik<commit_after><|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.

/// Entry point of thread panic, for details, see std::macros
#[macro_export]
macro_rules! panic {
    () => (
        panic!("explicit panic")
    );
    ($msg:expr) => ({
        static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
        ::core::panicking::panic(&_MSG_FILE_LINE)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        // The leading _'s are to avoid dead code warnings if this is
        // used inside a dead function. Just `#[allow(dead_code)]` is
        // insufficient, since the user may have
        // `#[forbid(dead_code)]` and which cannot be overridden.
        static _FILE_LINE: (&'static str, u32) = (file!(), line!());
        ::core::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
///
/// assert!(some_computation());
///
/// // assert with a custom message
/// let x = true;
/// assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert {
    ($cond:expr) => (
        if !$cond {
            panic!(concat!("assertion failed: ", stringify!($cond)))
        }
    );
    ($cond:expr, $($arg:tt)+) => (
        if !$cond {
            panic!($($arg)+)
        }
    );
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert_eq {
    ($left:expr , $right:expr) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`)", *left_val, *right_val)
                }
            }
        }
    })
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// let x = true;
/// debug_assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
}

/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! debug_assert_eq {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
}

/// Short circuiting evaluation on Err
///
/// `libstd` contains a more general `try!` macro that uses `From<E>`.
#[macro_export]
macro_rules! try {
    ($e:expr) => ({
        use $crate::result::Result::{Ok, Err};

        match $e {
            Ok(e) => e,
            Err(e) => return Err(e),
        }
    })
}

/// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
/// See `std::fmt` for more information.
///
/// # Examples
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test");
/// write!(&mut w, "formatted {}", "arguments");
/// ```
#[macro_export]
macro_rules! write {
    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}

/// Equivalent to the `write!` macro, except that a newline is appended after
/// the message is written.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
    ($dst:expr, $fmt:expr) => (
        write!($dst, concat!($fmt, "\n"))
    );
    ($dst:expr, $fmt:expr, $($arg:tt)*) => (
        write!($dst, concat!($fmt, "\n"), $($arg)*)
    );
}

/// A utility macro for indicating unreachable code.
///
/// This is useful any time that the compiler can't determine that some code is unreachable. For
/// example:
///
/// * Match arms with guard conditions.
/// * Loops that dynamically terminate.
/// * Iterators that dynamically terminate.
///
/// # Panics
///
/// This will always panic.
///
/// # Examples
///
/// Match arms:
///
/// ```
/// fn foo(x: Option<i32>) {
///     match x {
///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
///         Some(n) if n <  0 => println!("Some(Negative)"),
///         Some(_)           => unreachable!(), // compile error if commented out
///         None              => println!("None")
///     }
/// }
/// ```
///
/// Iterators:
///
/// ```
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
///     for i in 0.. {
///         if 3*i < i { panic!("u32 overflow"); }
///         if x < 3*i { return i-1; }
///     }
///     unreachable!();
/// }
/// ```
#[macro_export]
#[unstable(feature = "core",
           reason = "relationship with panic is unclear")]
macro_rules! unreachable {
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
}

/// A standardised placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
#[macro_export]
#[unstable(feature = "core",
           reason = "relationship with panic is unclear")]
macro_rules! unimplemented {
    () => (panic!("not yet implemented"))
}
<commit_msg>Writer -> Write in macro docs<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.

/// Entry point of thread panic, for details, see std::macros
#[macro_export]
macro_rules! panic {
    () => (
        panic!("explicit panic")
    );
    ($msg:expr) => ({
        static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
        ::core::panicking::panic(&_MSG_FILE_LINE)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        // The leading _'s are to avoid dead code warnings if this is
        // used inside a dead function. Just `#[allow(dead_code)]` is
        // insufficient, since the user may have
        // `#[forbid(dead_code)]` and which cannot be overridden.
        static _FILE_LINE: (&'static str, u32) = (file!(), line!());
        ::core::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
///
/// assert!(some_computation());
///
/// // assert with a custom message
/// let x = true;
/// assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert {
    ($cond:expr) => (
        if !$cond {
            panic!(concat!("assertion failed: ", stringify!($cond)))
        }
    );
    ($cond:expr, $($arg:tt)+) => (
        if !$cond {
            panic!($($arg)+)
        }
    );
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert_eq {
    ($left:expr , $right:expr) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`)", *left_val, *right_val)
                }
            }
        }
    })
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// let x = true;
/// debug_assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
}

/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
/// On panic, this macro will print the values of the expressions.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
macro_rules! debug_assert_eq {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
}

/// Short circuiting evaluation on Err
///
/// `libstd` contains a more general `try!` macro that uses `From<E>`.
#[macro_export]
macro_rules! try {
    ($e:expr) => ({
        use $crate::result::Result::{Ok, Err};

        match $e {
            Ok(e) => e,
            Err(e) => return Err(e),
        }
    })
}

/// Use the `format!` syntax to write data into a buffer of type `&mut Write`.
/// See `std::fmt` for more information.
///
/// # Examples
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test");
/// write!(&mut w, "formatted {}", "arguments");
/// ```
#[macro_export]
macro_rules! write {
    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}

/// Equivalent to the `write!` macro, except that a newline is appended after
/// the message is written.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
    ($dst:expr, $fmt:expr) => (
        write!($dst, concat!($fmt, "\n"))
    );
    ($dst:expr, $fmt:expr, $($arg:tt)*) => (
        write!($dst, concat!($fmt, "\n"), $($arg)*)
    );
}

/// A utility macro for indicating unreachable code.
///
/// This is useful any time that the compiler can't determine that some code is unreachable. For
/// example:
///
/// * Match arms with guard conditions.
/// * Loops that dynamically terminate.
/// * Iterators that dynamically terminate.
///
/// # Panics
///
/// This will always panic.
///
/// # Examples
///
/// Match arms:
///
/// ```
/// fn foo(x: Option<i32>) {
///     match x {
///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
///         Some(n) if n <  0 => println!("Some(Negative)"),
///         Some(_)           => unreachable!(), // compile error if commented out
///         None              => println!("None")
///     }
/// }
/// ```
///
/// Iterators:
///
/// ```
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
///     for i in 0.. {
///         if 3*i < i { panic!("u32 overflow"); }
///         if x < 3*i { return i-1; }
///     }
///     unreachable!();
/// }
/// ```
#[macro_export]
#[unstable(feature = "core",
           reason = "relationship with panic is unclear")]
macro_rules! unreachable {
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
}

/// A standardised placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
#[macro_export]
#[unstable(feature = "core",
           reason = "relationship with panic is unclear")]
macro_rules! unimplemented {
    () => (panic!("not yet implemented"))
}
<|endoftext|>