<commit_before>extern crate clap;
extern crate vcpkg;

use clap::{App, AppSettings, Arg, SubCommand};
use std::env;

fn main() {
    let app = App::new("vcpkg library finder")
        .about("Allows examining what vcpkg will find in a build script")
        .setting(AppSettings::SubcommandRequired)
        .arg(
            Arg::with_name("target")
                .short("t")
                .long("target")
                .value_name("TARGET TRIPLE")
                .help("the rust toolchain triple to find libraries for")
                .takes_value(true)
                .default_value("x86_64-pc-windows-msvc"),
        ).subcommand(
            SubCommand::with_name("probe")
                .about("try to find a package")
                .arg(
                    Arg::with_name("package")
                        .index(1)
                        .required(true)
                        .help("probe for a library and display paths and cargo metadata"),
                ).arg(
                    Arg::with_name("linkage")
                        .short("l")
                        .long("linkage")
                        .takes_value(true)
                        .possible_values(&["dll", "static"]),
                ),
        );

    let matches = app.get_matches();

    // set TARGET as if we are running under cargo
    env::set_var("TARGET", matches.value_of("target").unwrap());

    if let Some(matches) = matches.subcommand_matches("probe") {
        let lib_name = matches.value_of("package").unwrap();

        let mut cfg = vcpkg::Config::new();
        cfg.cargo_metadata(false);
        cfg.copy_dlls(false);
        if let Some(linkage) = matches.value_of("linkage") {
            match &linkage {
                &"dll" => {
                    // do nothing
                }
                &"static" => {
                    env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");
                }
                _ => unreachable!(),
            }
        }

        match cfg.find_package(lib_name) {
            Ok(lib) => {
                println!("Found library {}", lib_name);

                if !lib.include_paths.is_empty() {
                    println!("Include paths:");
                    for line in &lib.include_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.link_paths.is_empty() {
                    println!("Library paths:");
                    for line in &lib.link_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.link_paths.is_empty() {
                    println!("Runtime Library paths:");
                    for line in &lib.dll_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.cargo_metadata.is_empty() {
                    println!("Cargo metadata:");
                    for line in &lib.cargo_metadata {
                        println!("  {}", line);
                    }
                }
                if !lib.found_dlls.is_empty() {
                    println!("Found DLLs:");
                    for line in &lib.found_dlls {
                        println!("  {}", line.display());
                    }
                }
                if !lib.found_libs.is_empty() {
                    println!("Found libs:");
                    for line in &lib.found_libs {
                        println!("  {}", line.display());
                    }
                }
            }
            Err(err) => {
                println!("Failed:  {}", err);
            }
        }
    }
}
<commit_msg>fix command line override for searching for dll<commit_after>extern crate clap;
extern crate vcpkg;

use clap::{App, AppSettings, Arg, SubCommand};
use std::env;

fn main() {
    let app = App::new("vcpkg library finder")
        .about("Allows examining what vcpkg will find in a build script")
        .setting(AppSettings::SubcommandRequired)
        .arg(
            Arg::with_name("target")
                .short("t")
                .long("target")
                .value_name("RUST TARGET TRIPLE")
                .help("the rust toolchain triple to find libraries for")
                .takes_value(true)
                .default_value("x86_64-pc-windows-msvc"),
        )
        .subcommand(
            SubCommand::with_name("probe")
                .about("try to find a package")
                .arg(
                    Arg::with_name("package")
                        .index(1)
                        .required(true)
                        .help("probe for a library and display paths and cargo metadata"),
                )
                .arg(
                    Arg::with_name("linkage")
                        .short("l")
                        .long("linkage")
                        .takes_value(true)
                        .possible_values(&["dll", "static"]),
                ),
        );

    let matches = app.get_matches();

    // set TARGET as if we are running under cargo
    env::set_var("TARGET", matches.value_of("target").unwrap());

    if let Some(matches) = matches.subcommand_matches("probe") {
        let lib_name = matches.value_of("package").unwrap();

        let mut cfg = vcpkg::Config::new();
        cfg.cargo_metadata(false);
        cfg.copy_dlls(false);
        if let Some(linkage) = matches.value_of("linkage") {
            match &linkage {
                &"dll" => {
                    remove_vars();
                    env::set_var("VCPKGRS_DYNAMIC", "1");
                }
                &"static" => {
                    remove_vars();
                    env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");
                }
                _ => unreachable!(),
            }
        }

        match cfg.find_package(lib_name) {
            Ok(lib) => {
                println!("Found library {}", lib_name);

                if !lib.include_paths.is_empty() {
                    println!("Include paths:");
                    for line in &lib.include_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.link_paths.is_empty() {
                    println!("Library paths:");
                    for line in &lib.link_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.link_paths.is_empty() {
                    println!("Runtime Library paths:");
                    for line in &lib.dll_paths {
                        println!("  {}", line.as_os_str().to_str().unwrap());
                    }
                }

                if !lib.cargo_metadata.is_empty() {
                    println!("Cargo metadata:");
                    for line in &lib.cargo_metadata {
                        println!("  {}", line);
                    }
                }
                if !lib.found_dlls.is_empty() {
                    println!("Found DLLs:");
                    for line in &lib.found_dlls {
                        println!("  {}", line.display());
                    }
                }
                if !lib.found_libs.is_empty() {
                    println!("Found libs:");
                    for line in &lib.found_libs {
                        println!("  {}", line.display());
                    }
                }
            }
            Err(err) => {
                println!("Failed:  {}", err);
            }
        }
    }
}

fn remove_vars() {
    env::remove_var("VCPKGRS_DYNAMIC");
    env::remove_var("CARGO_CFG_TARGET_FEATURE");
}<|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.

use spec::{LinkerFlavor, Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::haiku_base::opts();
    base.cpu = "x86-64".to_string();
    base.max_atomic_width = Some(64);
    base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
    base.stack_probes = true;

    Ok(Target {
        llvm_target: "x86_64-unknown-haiku".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "64".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
        arch: "x86_64".to_string(),
        target_os: "haiku".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<commit_msg>Haiku: make it explicit that Haiku uses position independent executables on x86_64<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.

use spec::{LinkerFlavor, Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::haiku_base::opts();
    base.cpu = "x86-64".to_string();
    base.max_atomic_width = Some(64);
    base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
    base.stack_probes = true;
    // This option is required to build executables on Haiku x86_64
    base.position_independent_executables = true;

    Ok(Target {
        llvm_target: "x86_64-unknown-haiku".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "64".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".to_string(),
        arch: "x86_64".to_string(),
        target_os: "haiku".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;

use std::cmp::{max, min};
use std::fmt;
use std::io::{self, Read};
use std::mem::swap;

use anyhow::{anyhow, bail, Result};

fn main() -> Result<()> {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;

    println!("Part 1: {}", part1(&input)?);
    println!("Part 2: {}", part2(&input)?);
    Ok(())
}

#[derive(Clone, PartialEq)]
enum Seat {
    Floor,
    Empty,
    Occupied,
}

impl fmt::Debug for Seat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Seat::Floor => ".",
            Seat::Empty => "L",
            Seat::Occupied => "#",
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
struct Map {
    data: Vec<Vec<Seat>>,
    width: usize,
    height: usize,
}

impl std::fmt::Display for Map {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Ok(for row in self.data.iter() {
            for col in row {
                write!(f, "{:?}", col)?;
            }
            write!(f, "\n")?;
        })
    }
}

impl Map {
    fn is_occupied(&self, row: i32, col: i32) -> u8 {
        if col >= self.width as i32 || row >= self.height as i32 || row < 0 || col < 0 {
            return 0;
        }
        (*self
            .data
            .get(row as usize)
            .unwrap()
            .get(col as usize)
            .unwrap()
            == Seat::Occupied) as u8
    }
}

fn get_map(input: &str) -> Result<Map> {
    let mut lines = input.lines().peekable();
    let width = lines.peek().unwrap().chars().count();
    let mut ret = Map {
        data: Vec::new(),
        width,
        height: 0,
    };
    for line in lines {
        let mut row = Vec::with_capacity(width);
        for value in line.chars() {
            let seat = match value {
                '.' => Seat::Floor,
                'L' => Seat::Empty,
                '#' => Seat::Occupied,
                _ => bail!("Invalid seat character"),
            };
            row.push(seat);
        }
        ret.data.push(row);
        ret.height += 1;
    }
    Ok(ret)
}

fn count_neighbors(map: &Map, row: i32, col: i32) -> u8 {
    map.is_occupied(row - 1, col)
        + map.is_occupied(row + 1, col)
        + map.is_occupied(row - 1, col - 1)
        + map.is_occupied(row, col - 1)
        + map.is_occupied(row + 1, col - 1)
        + map.is_occupied(row - 1, col + 1)
        + map.is_occupied(row, col + 1)
        + map.is_occupied(row + 1, col + 1)
}

fn evolve(map: &Map, new_map: &mut Map) {
    new_map.clone_from(map);

    for (row_idx, row) in map.data.iter().enumerate() {
        for (col_idx, value) in row.iter().enumerate() {
            if *value == Seat::Floor {
                continue;
            }
            let num_neighbors = count_neighbors(map, row_idx as i32, col_idx as i32);
            let new_value = match num_neighbors {
                1..=3 => continue,
                0 => Seat::Occupied,
                4..=8 => Seat::Empty,
                _ => panic!("How did you get 9 neighbors on an 2D surface?"),
            };

            *new_map
                .data
                .get_mut(row_idx)
                .unwrap()
                .get_mut(col_idx)
                .unwrap() = new_value;
        }
    }
}

fn part1(input: &str) -> Result<usize> {
    let mut map = get_map(input)?;
    let mut new_map = map.clone();

    //println!("{}", new_map);
    loop {
        evolve(&map, &mut new_map);
        if map == new_map {
            break;
        }
        //println!("{}", new_map);
        swap(&mut map, &mut new_map);
    }

    Ok(map.data.iter().flatten().filter(|&x| *x == Seat::Occupied).count())
}

fn part2(input: &str) -> Result<u32> {
    Ok(0)
}
<commit_msg>day11: solve part2<commit_after>#[macro_use]
extern crate lazy_static;

use std::cmp::{max, min};
use std::fmt;
use std::io::{self, Read};
use std::mem::swap;

use anyhow::{anyhow, bail, Result};

fn main() -> Result<()> {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;

    println!("Part 1: {}", part1(&input)?);
    println!("Part 2: {}", part2(&input)?);
    Ok(())
}

#[derive(Clone, PartialEq, Copy)]
enum Seat {
    Floor,
    Empty,
    Occupied,
}

impl fmt::Debug for Seat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Seat::Floor => ".",
            Seat::Empty => "L",
            Seat::Occupied => "#",
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
struct Map {
    data: Vec<Vec<Seat>>,
    width: usize,
    height: usize,
}

impl std::fmt::Display for Map {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Ok(for row in self.data.iter() {
            for col in row {
                write!(f, "{:?}", col)?;
            }
            write!(f, "\n")?;
        })
    }
}

impl Map {
    fn get_value(&self, row: i32, col: i32) -> Option<Seat> {
        if col >= self.width as i32 || row >= self.height as i32 || row < 0 || col < 0 {
            return None;
        }
        Some(
            *self
                .data
                .get(row as usize)
                .unwrap()
                .get(col as usize)
                .unwrap(),
        )
    }

    fn is_occupied(&self, row: i32, col: i32) -> Option<u8> {
        self.get_value(row, col)
            .map(|x| (x == Seat::Occupied) as u8)
    }

    fn dir_is_occupied(&self, pos: (i32, i32), dir: (i32, i32)) -> Option<u8> {
        let mut curr_pos = (pos.0 + dir.0, pos.1 + dir.1);
        //println!("\tDirection {:?}", dir);
        while let Some(value) = self.get_value(curr_pos.0, curr_pos.1) {
            match value {
                Seat::Floor => {}
                Seat::Empty => {
                    //println!("\t\tEmpty");
                    return Some(0);
                }
                Seat::Occupied => {
                    //println!("\t\tOccupied");
                    return Some(1);
                }
            }
            curr_pos.0 += dir.0;
            curr_pos.1 += dir.1;
            //println!("\tNew pos {:?}", curr_pos);
        }
        //println!("\t\tOut Of Bounds");
        None
    }
}

fn get_map(input: &str) -> Result<Map> {
    let mut lines = input.lines().peekable();
    let width = lines.peek().unwrap().chars().count();
    let mut ret = Map {
        data: Vec::new(),
        width,
        height: 0,
    };
    for line in lines {
        let mut row = Vec::with_capacity(width);
        for value in line.chars() {
            let seat = match value {
                '.' => Seat::Floor,
                'L' => Seat::Empty,
                '#' => Seat::Occupied,
                _ => bail!("Invalid seat character"),
            };
            row.push(seat);
        }
        ret.data.push(row);
        ret.height += 1;
    }
    Ok(ret)
}

fn count_neighbors1(map: &Map, row: i32, col: i32) -> u8 {
    map.is_occupied(row - 1, col).unwrap_or(0)
        + map.is_occupied(row + 1, col).unwrap_or(0)
        + map.is_occupied(row - 1, col - 1).unwrap_or(0)
        + map.is_occupied(row, col - 1).unwrap_or(0)
        + map.is_occupied(row + 1, col - 1).unwrap_or(0)
        + map.is_occupied(row - 1, col + 1).unwrap_or(0)
        + map.is_occupied(row, col + 1).unwrap_or(0)
        + map.is_occupied(row + 1, col + 1).unwrap_or(0)
}

fn count_neighbors2(map: &Map, row: i32, col: i32) -> u8 {
    //println!("Position ({}, {})", row, col);
    map.dir_is_occupied((row, col), (-1, 0)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (0, -1)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (0, 1)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (1, 0)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (1, -1)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (-1, 1)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (-1, -1)).unwrap_or(0)
        + map.dir_is_occupied((row, col), (1, 1)).unwrap_or(0)
}

fn evolve1(map: &Map, new_map: &mut Map) {
    new_map.clone_from(map);

    for (row_idx, row) in map.data.iter().enumerate() {
        for (col_idx, value) in row.iter().enumerate() {
            if *value == Seat::Floor {
                continue;
            }
            let num_neighbors = count_neighbors1(map, row_idx as i32, col_idx as i32);
            let new_value = match num_neighbors {
                1..=3 => continue,
                0 => Seat::Occupied,
                4..=8 => Seat::Empty,
                _ => panic!("How did you get 9 neighbors on an 2D surface?"),
            };

            *new_map
                .data
                .get_mut(row_idx)
                .unwrap()
                .get_mut(col_idx)
                .unwrap() = new_value;
        }
    }
}

fn evolve2(map: &Map, new_map: &mut Map) {
    new_map.clone_from(map);

    for (row_idx, row) in map.data.iter().enumerate() {
        for (col_idx, value) in row.iter().enumerate() {
            if *value == Seat::Floor {
                continue;
            }
            let num_neighbors = count_neighbors2(map, row_idx as i32, col_idx as i32);
            let new_value = match num_neighbors {
                1..=4 => continue,
                0 => Seat::Occupied,
                5..=8 => Seat::Empty,
                _ => panic!("How did you get 9 neighbors on an 2D surface?"),
            };

            *new_map
                .data
                .get_mut(row_idx)
                .unwrap()
                .get_mut(col_idx)
                .unwrap() = new_value;
        }
    }
}

fn part1(input: &str) -> Result<usize> {
    let mut map = get_map(input)?;
    let mut new_map = map.clone();

    //println!("{}", new_map);
    loop {
        evolve1(&map, &mut new_map);
        if map == new_map {
            break;
        }
        //println!("{}", new_map);
        swap(&mut map, &mut new_map);
    }

    Ok(map
        .data
        .iter()
        .flatten()
        .filter(|&x| *x == Seat::Occupied)
        .count())
}

fn part2(input: &str) -> Result<usize> {
    let mut map = get_map(input)?;
    let mut new_map = map.clone();

    //println!("{}", new_map);
    loop {
        evolve2(&map, &mut new_map);
        if map == new_map {
            break;
        }
        //println!("{}", new_map);
        swap(&mut map, &mut new_map);
    }

    Ok(map
        .data
        .iter()
        .flatten()
        .filter(|&x| *x == Seat::Occupied)
        .count())
}
<|endoftext|>


<commit_before>#![feature(box_syntax, libc, core)]
extern crate libc;
extern crate core;
extern crate time;
use time::PreciseTime;
use time::Duration;
use std::ffi::CString;
use std::collections::HashMap;
use std::num::Wrapping;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::path::Path;

// Benchmarking IP lookup in Rust. This currently requires using a nightly, since it uses unstable APIs,
// which are prohibited by beta.

// Some simple functions from C needed to read IP addresses.
extern {
    fn inet_pton(family: i32,
                 addr: *const libc::c_char,
                 ret: *mut u32) -> u32;
    fn ntohl(addr: u32) -> u32;
}

const TBL_SIZE: usize =  ((1u64 << 24) + 1) as usize;
const TBL_LONG_MASK: u16 = 0x8000;
const LENGTHS:usize = 33;
const AF_INET: i32 = 2;

// FIB structure
struct FIB {
    pub tbl24:[u16; TBL_SIZE],
    pub tbl_long:[u16; TBL_SIZE],
}

impl FIB {
    // Given a set of address, length mappings create the FIB structure.
    fn create_fib(&mut self,
                  rib: &[HashMap<u32, u16>] ) {
      let mut current_tbl_long:usize = 0;
      for l in 0..25 {
        for (addr, nhop) in rib[l].iter() {
          let start: usize = (*addr >> 8) as usize;
          let end: usize = start + (1 << (24 - l));
          for pfx in start..end {
            self.tbl24[pfx] = *nhop;
          }
        }
      }
      for l in 25..LENGTHS {
        for (addr, nhop) in rib[l].iter() {
          let tbl24dest = self.tbl24[(*addr >> 8) as usize];
          if (tbl24dest & TBL_LONG_MASK) == 0 {
            let start:usize = current_tbl_long + ((*addr & 0xff) as usize);
            let end:usize = start + (1 << (32 - l));
            for pfx in current_tbl_long..(current_tbl_long + 256) {
              if pfx < start || pfx >= end {
                self.tbl_long[pfx] = tbl24dest;
              } else {
                self.tbl_long[pfx] = *nhop;
              }
            }
            self.tbl24[(*addr << 8) as usize] = ((current_tbl_long >> 8) as u16) | TBL_LONG_MASK;
            current_tbl_long += 256;
          } else {
            let long_idx = ((tbl24dest & !(TBL_LONG_MASK)) << 8) as usize;
            let start:usize = long_idx + ((*addr & 0xff) as usize);
            let end:usize = start + (1 << (32 - l));
            for pfx in start..end {
              self.tbl_long[pfx] = *nhop;
            }
          }
        }
      }
    }

    // Lookup IP address.
    #[inline]
    fn lookup(&self,
              ip: u32) -> u16{
      let tbl24_idx: u32 = ip >> 8;
      let tbl24_result = self.tbl24[tbl24_idx as usize];
      if (tbl24_result & TBL_LONG_MASK) > 0 {
        let idx: u32 = (((tbl24_result & !(TBL_LONG_MASK)) << 8) as u32) + (ip & 0xff);
        return self.tbl_long[idx as usize];
      } else {
        return tbl24_result;
      }
    }
}

// Convert IPv4 string to uint32.
#[inline]
fn str_to_ipv4(addr: &str) -> u32 {
  let addr_cstring = CString::new(addr.as_bytes()).unwrap();
  unsafe {
    let mut ret = 0u32;
    {
        inet_pton(AF_INET,
              addr_cstring.as_ptr(),
              &mut ret);
    }
    return ntohl(ret);
  }
}

// Do not call from many threads, makes things sad
#[inline]
fn rand_fast() -> u32 {
  // Wrapping since there are overflows, and we really want overflow here.
  static mut seed:Wrapping<u64> = Wrapping(0u64);
  // Unsafe since using a static mutable, which Rust requires to be unsafe.
  unsafe {
    seed = seed * Wrapping(1103515245u64) +  Wrapping(12345u64);
    return (seed.0 >> 32) as u32;
  }
}

#[inline]
fn benchmark(fib: &Box<FIB>,
             warm: i64,
             batch: u64,
             batches: u32) {
  let mut start = PreciseTime::now();
  while start.to(PreciseTime::now()) < Duration::seconds(warm) {
    fib.lookup(rand_fast());
  }
  let mut done = 0u32;
  let mut lookups = 0u64;
  start = PreciseTime::now();
  while done < batches {
    for _ in 0u64..batch {
      fib.lookup(rand_fast());
      lookups = lookups + 1;
    }
    if start.to(PreciseTime::now()) >= Duration::seconds(1) {
      println!("{} {} {}", start.to(PreciseTime::now()), batch, lookups);
      done = done + 1;
      start = PreciseTime::now();
    }
  }
}

#[inline]
fn new_ip_hash() -> HashMap<u32, u16> {
  return HashMap::new();
}

fn main() {
    //let hash = [HashMap::new(); 33]
    let args:Vec<String> = std::env::args().collect();
    if args.len() < 2 {
      println!("Usage: {} rib", args[0]);
      return;
    }
    let ref fname = args[1];
    println!("Should use {0} as rib", fname);

    let mut hash: Vec<HashMap<u32, u16>> = (0..33).map(|_|{new_ip_hash()}).collect();
    {
        let path = Path::new(fname);
        let file = BufReader::new(File::open(&path).unwrap());
        for line in file.lines() {
          let l = line.unwrap();
          let parts:Vec<&str> = l.split(" ").collect();
          if parts.len() == 2 {
            let addr_parts:Vec<&str> = parts[0].split("/").collect();
            if addr_parts.len() == 2 {
              let len = addr_parts[1].parse::<usize>().unwrap();
              let addr = str_to_ipv4(addr_parts[0]);
              let nhop = parts[1].parse::<u16>().unwrap();
              hash[len].insert(addr, nhop);
              println!("Inserting {}({}) {} {}", addr_parts[0], addr, len, nhop);
            }
          }
        }
    }
    //let self = Box<FIB>
    println!("Creating FIB");
    let mut fib = box FIB{tbl24: [0u16;TBL_SIZE], tbl_long: [0u16;TBL_SIZE]};
    {
        fib.create_fib(&hash[..]);
    }
    println!("Done creating FIB");
    const WARM:i64 = 1;
    const BATCH_SIZE:u64 = 10;
    const BATCHES:u32 = 5;
    for exp in 0..BATCH_SIZE {
      benchmark(&fib, WARM, (1u64 << exp), BATCHES);
    }
}
<commit_msg>Fix some main.rs problems from c38<commit_after>#![feature(box_syntax, libc, core)]
extern crate libc;
extern crate core;
extern crate time;
use time::PreciseTime;
use time::Duration;
use std::ffi::CString;
use std::collections::HashMap;
use std::num::Wrapping;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::path::Path;

// Benchmarking IP lookup in Rust. This currently requires using a nightly, since it uses unstable APIs,
// which are prohibited by beta.

// Some simple functions from C needed to read IP addresses.
extern {
    fn inet_pton(family: i32,
                 addr: *const libc::c_char,
                 ret: *mut u32) -> u32;
    fn ntohl(addr: u32) -> u32;
}

const TBL_SIZE: usize =  ((1u64 << 24) + 1) as usize;
const TBL_LONG_MASK: u16 = 0x8000;
const LENGTHS:usize = 33;
const AF_INET: i32 = 2;

// FIB structure
struct FIB {
    pub tbl24:[u16; TBL_SIZE],
    pub tbl_long:[u16; TBL_SIZE],
}

impl FIB {
    // Given a set of address, length mappings create the FIB structure.
    fn create_fib(&mut self,
                  rib: &[HashMap<u32, u16>] ) {
      let mut current_tbl_long:usize = 0;
      for l in 0..25 {
        for (addr, nhop) in rib[l].iter() {
          let start: usize = (*addr >> 8) as usize;
          let end: usize = start + (1 << (24 - l));
          for pfx in start..end {
            self.tbl24[pfx] = *nhop;
          }
        }
      }
      for l in 25..LENGTHS {
        for (addr, nhop) in rib[l].iter() {
          let tbl24dest = self.tbl24[(*addr >> 8) as usize];
          if (tbl24dest & TBL_LONG_MASK) == 0 {
            let start:usize = current_tbl_long + ((*addr & 0xff) as usize);
            let end:usize = start + (1 << (32 - l));
            for pfx in current_tbl_long..(current_tbl_long + 256) {
              if pfx < start || pfx >= end {
                self.tbl_long[pfx] = tbl24dest;
              } else {
                self.tbl_long[pfx] = *nhop;
              }
            }
            self.tbl24[(*addr >> 8) as usize] = ((current_tbl_long >> 8) as u16) | TBL_LONG_MASK;
            current_tbl_long += 256;
          } else {
            let long_idx = ((tbl24dest & !(TBL_LONG_MASK)) << 8) as usize;
            let start:usize = long_idx + ((*addr & 0xff) as usize);
            let end:usize = start + (1 << (32 - l));
            for pfx in start..end {
              self.tbl_long[pfx] = *nhop;
            }
          }
        }
      }
    }

    // Lookup IP address.
    #[inline]
    fn lookup(&self,
              ip: u32) -> u16{
      let tbl24_idx: u32 = ip >> 8;
      let tbl24_result = self.tbl24[tbl24_idx as usize];
      if (tbl24_result & TBL_LONG_MASK) > 0 {
        let idx: u32 = (((tbl24_result & !(TBL_LONG_MASK)) << 8) as u32) + (ip & 0xff);
        return self.tbl_long[idx as usize];
      } else {
        return tbl24_result;
      }
    }
}

// Convert IPv4 string to uint32.
#[inline]
fn str_to_ipv4(addr: &str) -> u32 {
  let addr_cstring = CString::new(addr.as_bytes()).unwrap();
  unsafe {
    let mut ret = 0u32;
    {
        inet_pton(AF_INET,
              addr_cstring.as_ptr(),
              &mut ret);
    }
    return ntohl(ret);
  }
}

// Do not call from many threads, makes things sad
#[inline]
fn rand_fast() -> u32 {
  // Wrapping since there are overflows, and we really want overflow here.
  static mut seed:Wrapping<u64> = Wrapping(0u64);
  // Unsafe since using a static mutable, which Rust requires to be unsafe.
  unsafe {
    seed = seed * Wrapping(1103515245u64) +  Wrapping(12345u64);
    return (seed.0 >> 32) as u32;
  }
}

#[inline]
fn benchmark(fib: &Box<FIB>,
             warm: i64,
             batch: u64,
             batches: u32) {
  let mut start = PreciseTime::now();
  while start.to(PreciseTime::now()) < Duration::seconds(warm) {
    fib.lookup(rand_fast());
  }
  let mut done = 0u32;
  let mut lookups = 0u64;
  start = PreciseTime::now();
  while done < batches {
    for _ in 0u64..batch {
      fib.lookup(rand_fast());
      lookups = lookups + 1;
    }
    if start.to(PreciseTime::now()) >= Duration::seconds(1) {
      println!("{} {} {}", start.to(PreciseTime::now()), batch, lookups);
      done = done + 1;
      start = PreciseTime::now();
      lookups = 0;
    }
  }
}

#[inline]
fn new_ip_hash() -> HashMap<u32, u16> {
  return HashMap::new();
}

fn main() {
    //let hash = [HashMap::new(); 33]
    let args:Vec<String> = std::env::args().collect();
    if args.len() < 2 {
      println!("Usage: {} rib", args[0]);
      return;
    }
    let ref fname = args[1];
    println!("Should use {0} as rib", fname);

    let mut hash: Vec<HashMap<u32, u16>> = (0..33).map(|_|{new_ip_hash()}).collect();
    {
        let path = Path::new(fname);
        let file = BufReader::new(File::open(&path).unwrap());
        for line in file.lines() {
          let l = line.unwrap();
          let parts:Vec<&str> = l.split(" ").collect();
          if parts.len() == 2 {
            let addr_parts:Vec<&str> = parts[0].split("/").collect();
            if addr_parts.len() == 2 {
              let len = addr_parts[1].parse::<usize>().unwrap();
              let addr = str_to_ipv4(addr_parts[0]);
              let nhop = parts[1].parse::<u16>().unwrap();
              hash[len].insert(addr, nhop);
            }
          }
        }
    }
    //let self = Box<FIB>
    println!("Creating FIB");
    let mut fib = box FIB{tbl24: [0u16;TBL_SIZE], tbl_long: [0u16;TBL_SIZE]};
    {
        fib.create_fib(&hash[..]);
    }
    println!("Done creating FIB");
    const WARM:i64 = 1;
    const BATCH_SIZE:u64 = 10;
    const BATCHES:u32 = 5;
    for exp in 0..BATCH_SIZE {
      benchmark(&fib, WARM, (1u64 << exp), BATCHES);
    }
}
<|endoftext|>


<commit_before>use std::marker::PhantomData;

use crate::Idx;

/// A map from arena indexes to some other type.
/// Space requirement is O(highest index).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArenaMap<IDX, V> {
    v: Vec<Option<V>>,
    _ty: PhantomData<IDX>,
}

impl<T, V> ArenaMap<Idx<T>, V> {
    /// Creates a new empty map.
    pub const fn new() -> Self {
        Self { v: Vec::new(), _ty: PhantomData }
    }

    /// Create a new empty map with specific capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self { v: Vec::with_capacity(capacity), _ty: PhantomData }
    }

    /// Inserts a value associated with a given arena index into the map.
    pub fn insert(&mut self, idx: Idx<T>, t: V) {
        let idx = Self::to_idx(idx);

        self.v.resize_with((idx + 1).max(self.v.len()), || None);
        self.v[idx] = Some(t);
    }

    /// Returns a reference to the value associated with the provided index
    /// if it is present.
    pub fn get(&self, idx: Idx<T>) -> Option<&V> {
        self.v.get(Self::to_idx(idx)).and_then(|it| it.as_ref())
    }

    /// Returns a mutable reference to the value associated with the provided index
    /// if it is present.
    pub fn get_mut(&mut self, idx: Idx<T>) -> Option<&mut V> {
        self.v.get_mut(Self::to_idx(idx)).and_then(|it| it.as_mut())
    }

    /// Returns an iterator over the values in the map.
    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.v.iter().filter_map(|o| o.as_ref())
    }

    /// Returns an iterator over mutable references to the values in the map.
    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.v.iter_mut().filter_map(|o| o.as_mut())
    }

    /// Returns an iterator over the arena indexes and values in the map.
    pub fn iter(&self) -> impl Iterator<Item = (Idx<T>, &V)> {
        self.v.iter().enumerate().filter_map(|(idx, o)| Some((Self::from_idx(idx), o.as_ref()?)))
    }

    /// Gets the given key's corresponding entry in the map for in-place manipulation.
    pub fn entry(&mut self, idx: Idx<T>) -> Entry<'_, Idx<T>, V> {
        let idx = Self::to_idx(idx);
        self.v.resize_with((idx + 1).max(self.v.len()), || None);
        match &mut self.v[idx] {
            slot @ Some(_) => Entry::Occupied(OccupiedEntry { slot, _ty: PhantomData }),
            slot @ None => Entry::Vacant(VacantEntry { slot, _ty: PhantomData }),
        }
    }

    fn to_idx(idx: Idx<T>) -> usize {
        u32::from(idx.into_raw()) as usize
    }

    fn from_idx(idx: usize) -> Idx<T> {
        Idx::from_raw((idx as u32).into())
    }
}

impl<T, V> std::ops::Index<Idx<V>> for ArenaMap<Idx<V>, T> {
    type Output = T;
    fn index(&self, idx: Idx<V>) -> &T {
        self.v[Self::to_idx(idx)].as_ref().unwrap()
    }
}

impl<T, V> std::ops::IndexMut<Idx<V>> for ArenaMap<Idx<V>, T> {
    fn index_mut(&mut self, idx: Idx<V>) -> &mut T {
        self.v[Self::to_idx(idx)].as_mut().unwrap()
    }
}

impl<T, V> Default for ArenaMap<Idx<V>, T> {
    fn default() -> Self {
        Self::new()
    }
}

/// A view into a single entry in a map, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`ArenaMap`].
///
/// [`entry`]: ArenaMap::entry
pub enum Entry<'a, IDX, V> {
    /// A vacant entry.
    Vacant(VacantEntry<'a, IDX, V>),
    /// An occupied entry.
    Occupied(OccupiedEntry<'a, IDX, V>),
}

impl<'a, IDX, V> Entry<'a, IDX, V> {
    /// Ensures a value is in the entry by inserting the default if empty, and returns a mutable reference to
    /// the value in the entry.
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Self::Vacant(ent) => ent.insert(default),
            Self::Occupied(ent) => ent.into_mut(),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty, and returns
    /// a mutable reference to the value in the entry.
    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
        match self {
            Self::Vacant(ent) => ent.insert(default()),
            Self::Occupied(ent) => ent.into_mut(),
        }
    }

    /// Provides in-place mutable access to an occupied entry before any potential inserts into the map.
    pub fn and_modify<F: FnOnce(&mut V)>(mut self, f: F) -> Self {
        if let Self::Occupied(ent) = &mut self {
            f(ent.get_mut());
        }
        self
    }
}

impl<'a, IDX, V> Entry<'a, IDX, V>
where
    V: Default,
{
    /// Ensures a value is in the entry by inserting the default value if empty, and returns a mutable reference
    /// to the value in the entry.
    pub fn or_default(self) -> &'a mut V {
        self.or_insert_with(Default::default)
    }
}

/// A view into an vacant entry in a [`ArenaMap`]. It is part of the [`Entry`] enum.
pub struct VacantEntry<'a, IDX, V> {
    slot: &'a mut Option<V>,
    _ty: PhantomData<IDX>,
}

impl<'a, IDX, V> VacantEntry<'a, IDX, V> {
    /// Sets the value of the entry with the `VacantEntry`’s key, and returns a mutable reference to it.
    pub fn insert(self, value: V) -> &'a mut V {
        self.slot.insert(value)
    }
}

/// A view into an occupied entry in a [`ArenaMap`]. It is part of the [`Entry`] enum.
pub struct OccupiedEntry<'a, IDX, V> {
    slot: &'a mut Option<V>,
    _ty: PhantomData<IDX>,
}

impl<'a, IDX, V> OccupiedEntry<'a, IDX, V> {
    /// Gets a reference to the value in the entry.
    pub fn get(&self) -> &V {
        self.slot.as_ref().expect("Occupied")
    }

    /// Gets a mutable reference to the value in the entry.
    pub fn get_mut(&mut self) -> &mut V {
        self.slot.as_mut().expect("Occupied")
    }

    /// Converts the entry into a mutable reference to its value.
    pub fn into_mut(self) -> &'a mut V {
        self.slot.as_mut().expect("Occupied")
    }

    /// Sets the value of the entry with the `OccupiedEntry`’s key, and returns the entry’s old value.
    pub fn insert(&mut self, value: V) -> V {
        self.slot.replace(value).expect("Occupied")
    }

    /// Takes the value of the entry out of the map, and returns it.
    pub fn remove(self) -> V {
        self.slot.take().expect("Occupied")
    }
}
<commit_msg>Impl more methods and traits for la_arena::ArenaMap<commit_after>use std::marker::PhantomData;

use crate::Idx;

/// A map from arena indexes to some other type.
/// Space requirement is O(highest index).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArenaMap<IDX, V> {
    v: Vec<Option<V>>,
    _ty: PhantomData<IDX>,
}

impl<T, V> ArenaMap<Idx<T>, V> {
    /// Creates a new empty map.
    pub const fn new() -> Self {
        Self { v: Vec::new(), _ty: PhantomData }
    }

    /// Create a new empty map with specific capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self { v: Vec::with_capacity(capacity), _ty: PhantomData }
    }

    /// Reserves capacity for at least additional more elements to be inserted in the map.
    pub fn reserve(&mut self, additional: usize) {
        self.v.reserve(additional);
    }

    /// Clears the map, removing all elements.
    pub fn clear(&mut self) {
        self.v.clear();
    }

    /// Shrinks the capacity of the map as much as possible.
    pub fn shrink_to_fit(&mut self) {
        let min_len = self.v.iter().rposition(|slot| slot.is_some()).map_or(0, |i| i + 1);
        self.v.truncate(min_len);
        self.v.shrink_to_fit();
    }

    /// Returns whether the map contains a value for the specified index.
    pub fn contains_idx(&self, idx: Idx<T>) -> bool {
        matches!(self.v.get(Self::to_idx(idx)), Some(Some(_)))
    }

    /// Removes an index from the map, returning the value at the index if the index was previously in the map.
    pub fn remove(&mut self, idx: Idx<T>) -> Option<V> {
        self.v.get_mut(Self::to_idx(idx))?.take()
    }

    /// Inserts a value associated with a given arena index into the map.
    pub fn insert(&mut self, idx: Idx<T>, t: V) {
        let idx = Self::to_idx(idx);

        self.v.resize_with((idx + 1).max(self.v.len()), || None);
        self.v[idx] = Some(t);
    }

    /// Returns a reference to the value associated with the provided index
    /// if it is present.
    pub fn get(&self, idx: Idx<T>) -> Option<&V> {
        self.v.get(Self::to_idx(idx)).and_then(|it| it.as_ref())
    }

    /// Returns a mutable reference to the value associated with the provided index
    /// if it is present.
    pub fn get_mut(&mut self, idx: Idx<T>) -> Option<&mut V> {
        self.v.get_mut(Self::to_idx(idx)).and_then(|it| it.as_mut())
    }

    /// Returns an iterator over the values in the map.
    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.v.iter().filter_map(|o| o.as_ref())
    }

    /// Returns an iterator over mutable references to the values in the map.
    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.v.iter_mut().filter_map(|o| o.as_mut())
    }

    /// Returns an iterator over the arena indexes and values in the map.
    pub fn iter(&self) -> impl Iterator<Item = (Idx<T>, &V)> {
        self.v.iter().enumerate().filter_map(|(idx, o)| Some((Self::from_idx(idx), o.as_ref()?)))
    }

    /// Gets the given key's corresponding entry in the map for in-place manipulation.
    pub fn entry(&mut self, idx: Idx<T>) -> Entry<'_, Idx<T>, V> {
        let idx = Self::to_idx(idx);
        self.v.resize_with((idx + 1).max(self.v.len()), || None);
        match &mut self.v[idx] {
            slot @ Some(_) => Entry::Occupied(OccupiedEntry { slot, _ty: PhantomData }),
            slot @ None => Entry::Vacant(VacantEntry { slot, _ty: PhantomData }),
        }
    }

    fn to_idx(idx: Idx<T>) -> usize {
        u32::from(idx.into_raw()) as usize
    }

    fn from_idx(idx: usize) -> Idx<T> {
        Idx::from_raw((idx as u32).into())
    }
}

impl<T, V> std::ops::Index<Idx<V>> for ArenaMap<Idx<V>, T> {
    type Output = T;
    fn index(&self, idx: Idx<V>) -> &T {
        self.v[Self::to_idx(idx)].as_ref().unwrap()
    }
}

impl<T, V> std::ops::IndexMut<Idx<V>> for ArenaMap<Idx<V>, T> {
    fn index_mut(&mut self, idx: Idx<V>) -> &mut T {
        self.v[Self::to_idx(idx)].as_mut().unwrap()
    }
}

impl<T, V> Default for ArenaMap<Idx<V>, T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T, V> Extend<(Idx<V>, T)> for ArenaMap<Idx<V>, T> {
    fn extend<I: IntoIterator<Item = (Idx<V>, T)>>(&mut self, iter: I) {
        iter.into_iter().for_each(move |(k, v)| {
            self.insert(k, v);
        });
    }
}

impl<T, V> FromIterator<(Idx<V>, T)> for ArenaMap<Idx<V>, T> {
    fn from_iter<I: IntoIterator<Item = (Idx<V>, T)>>(iter: I) -> Self {
        let mut this = Self::new();
        this.extend(iter);
        this
    }
}

/// A view into a single entry in a map, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`ArenaMap`].
///
/// [`entry`]: ArenaMap::entry
pub enum Entry<'a, IDX, V> {
    /// A vacant entry.
    Vacant(VacantEntry<'a, IDX, V>),
    /// An occupied entry.
    Occupied(OccupiedEntry<'a, IDX, V>),
}

impl<'a, IDX, V> Entry<'a, IDX, V> {
    /// Ensures a value is in the entry by inserting the default if empty, and returns a mutable reference to
    /// the value in the entry.
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Self::Vacant(ent) => ent.insert(default),
            Self::Occupied(ent) => ent.into_mut(),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty, and returns
    /// a mutable reference to the value in the entry.
    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
        match self {
            Self::Vacant(ent) => ent.insert(default()),
            Self::Occupied(ent) => ent.into_mut(),
        }
    }

    /// Provides in-place mutable access to an occupied entry before any potential inserts into the map.
    pub fn and_modify<F: FnOnce(&mut V)>(mut self, f: F) -> Self {
        if let Self::Occupied(ent) = &mut self {
            f(ent.get_mut());
        }
        self
    }
}

impl<'a, IDX, V> Entry<'a, IDX, V>
where
    V: Default,
{
    /// Ensures a value is in the entry by inserting the default value if empty, and returns a mutable reference
    /// to the value in the entry.
    pub fn or_default(self) -> &'a mut V {
        self.or_insert_with(Default::default)
    }
}

/// A view into an vacant entry in a [`ArenaMap`]. It is part of the [`Entry`] enum.
pub struct VacantEntry<'a, IDX, V> {
    slot: &'a mut Option<V>,
    _ty: PhantomData<IDX>,
}

impl<'a, IDX, V> VacantEntry<'a, IDX, V> {
    /// Sets the value of the entry with the `VacantEntry`’s key, and returns a mutable reference to it.
    pub fn insert(self, value: V) -> &'a mut V {
        self.slot.insert(value)
    }
}

/// A view into an occupied entry in a [`ArenaMap`]. It is part of the [`Entry`] enum.
pub struct OccupiedEntry<'a, IDX, V> {
    slot: &'a mut Option<V>,
    _ty: PhantomData<IDX>,
}

impl<'a, IDX, V> OccupiedEntry<'a, IDX, V> {
    /// Gets a reference to the value in the entry.
    pub fn get(&self) -> &V {
        self.slot.as_ref().expect("Occupied")
    }

    /// Gets a mutable reference to the value in the entry.
    pub fn get_mut(&mut self) -> &mut V {
        self.slot.as_mut().expect("Occupied")
    }

    /// Converts the entry into a mutable reference to its value.
    pub fn into_mut(self) -> &'a mut V {
        self.slot.as_mut().expect("Occupied")
    }

    /// Sets the value of the entry with the `OccupiedEntry`’s key, and returns the entry’s old value.
    pub fn insert(&mut self, value: V) -> V {
        self.slot.replace(value).expect("Occupied")
    }

    /// Takes the value of the entry out of the map, and returns it.
    pub fn remove(self) -> V {
        self.slot.take().expect("Occupied")
    }
}
<|endoftext|>


<commit_before><commit_msg>Commit with finished joiner.rs<commit_after>use std::str;
use std::os;
use std::io::File;

fn main() {
    let args: ~[~str] = os::args();
    if args.len() != 3 {
        println!("Usage: {:s} <inputfile>", args[0]);
    } else {
        let tempArg = &args;
        let fname = &tempArg[1];
        let fname2 = &tempArg[2];

        let path = Path::new(fname.clone());
        let msg_file = File::open(&path);

        let path2 = Path::new(fname2.clone());
        let msg_file2 = File::open(&path2);

        match (msg_file, msg_file2) {
            (Some(mut msg), Some(mut msg2)) => {
                let msg_bytes: ~[u8] = msg.read_to_end();
                let msg_bytes2: ~[u8] = msg2.read_to_end();
                join(msg_bytes, msg_bytes2);
            } ,
            (_,_) => fail!("Error opening message files: {:s} and {:s}", *fname, *fname2)
        }
    }
}

fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
    let mut ret = ~[];
    for i in range(0, a.len()) {
    ret.push(a[i] ^ b[i]);
    }
    ret
}

fn join(msg_bytes: &[u8], msg_bytes2: &[u8]) {
    let undoEncrypt = xor(msg_bytes, msg_bytes2);
    println!("{}", str::from_utf8(undoEncrypt));
}<|endoftext|>


<commit_before>use std::rc::Rc;
struct ListNode {
    val: i32,
    next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(v: i32) -> Self {
        ListNode { val: v, next: None }
    }
}

fn check_ten(this: &mut ListNode, f: &i32) {
    let mut inner_this = this;
    let mut temp: Rc<&mut Box<ListNode>>;
    let mut flag = *f;
    while let Some(t) = { inner_this } {
        t.val += flag;
        if t.val >= 10 {
            t.val = t.val - 10;
            flag = 1;
        } else {
            flag = 0
        }
        temp = Rc::new(t);
        let next = &mut t.next;
        inner_this = next;
    }
    if flag == 1 {
        temp.next = Some(Box::new(ListNode::new(1)));
    }
}

fn main() {
    //let a = ListNode::new(1);
    //let mut b = ListNode::new(9);
    //b.next = Some(Box::new(ListNode::new(2)));

    let mut c = Some(Box::new(ListNode::new(9)));
    check_ten(&mut c, &1);
}
<commit_msg>change funtion to method<commit_after>#[derive(Debug)]
struct ListNode {
    val: i32,
    next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(v: i32) -> Self {
        ListNode { val: v, next: None }
    }

    fn check_ten(&mut self, flag: i32) {
        let mut inner_flag = flag;
        self.val += flag;
        if self.val >= 10 {
            self.val -= 10;
            inner_flag = 1;
        }
        match self.next {
            Some(ref mut n) => n.check_ten(inner_flag),
            None => if inner_flag == 1 {
                self.next = Some(Box::new(ListNode::new(inner_flag)));
            },
        }
    }
}

fn main() {
    //let a = ListNode::new(1);
    //let mut b = ListNode::new(9);
    //b.next = Some(Box::new(ListNode::new(2)));

    let mut c = Box::new(ListNode::new(9));
    c.check_ten(1);
    println!("{:?}", c);
    println!("{:?}", c.next);
}
<|endoftext|>


<commit_before>extern crate rs_nes;

use rs_nes::memory::Memory;

#[test]
fn store_and_load() {
  let mut mem = Memory::new();
  let stored = 0x1234;
  mem.store(0x0, stored);
  let loaded = mem.load(0x0).unwrap();
  assert_eq!(stored, loaded);
}

<commit_msg>Add another memory test<commit_after>extern crate rs_nes;

use rs_nes::memory::Memory;

#[test]
fn store_and_load() {
  let mut mem = Memory::new();
  let stored = 0x1234;
  mem.store(0x0, stored);
  let loaded = mem.load(0x0).unwrap();
  assert_eq!(stored, loaded);
}

#[test]
fn store_and_load_errors_when_address_out_of_bounds() {
  let mut mem = Memory::new();
  match mem.store(0xffffff, 0xb) {
    Err(_) => {
      // we want an error to be thrown!
      assert!(true);
    }
    _ => {
      assert!(false);
    }
  };
}
<|endoftext|>


<commit_before>use std::collections::BTreeMap;

use toml::Value;

use error::RefErrorKind as REK;
use result::Result;

#[derive(Default)]
pub struct RefFlags {
    content_hashing:       bool,
    permission_tracking:   bool,
}

impl RefFlags {

    /// Read the RefFlags from a TOML document
    ///
    /// Assumes that the whole TOML tree is passed. So this looks up `ref.flags` to get the flags.
    /// It assumes that this is a Map with Key = <name of the setting> and Value = boolean.
    pub fn read(v: &Value) -> Result<RefFlags> {
        fn get_field(v: &Value, key: &str) -> Result<bool> {
            match v.lookup(key) {
                Some(&Value::Boolean(b)) => Ok(b),
                Some(_) => Err(REK::HeaderTypeError.into()),
                None    => Err(REK::HeaderFieldMissingError.into()),
            }
        }

        Ok(RefFlags {
            content_hashing:     try!(get_field(v, "ref.flags.content_hashing")),
            permission_tracking: try!(get_field(v, "ref.flags.permission_tracking")),
        })
    }

    /// Alias for `RefFlags::content_hashing()`
    pub fn is_often_moving(mut self, b: bool) -> RefFlags {
        self.with_content_hashing(b)
    }

    pub fn with_content_hashing(mut self, b: bool) -> RefFlags {
        self.content_hashing = b;
        self
    }

    pub fn with_permission_tracking(mut self, b: bool) -> RefFlags {
        self.permission_tracking = b;
        self
    }

    pub fn get_content_hashing(&self) -> bool {
        self.content_hashing
    }

    pub fn get_permission_tracking(&self) -> bool {
        self.permission_tracking
    }

}

impl Into<Value> for RefFlags {

    /// Build a TOML::Value from this RefFlags object.
    ///
    /// Returns a Map which should be set in `ref.flags` in the header.
    fn into(self) -> Value {
        let mut btm = BTreeMap::new();
        btm.insert(String::from("content_hashing"),     Value::Boolean(self.content_hashing));
        btm.insert(String::from("permission_tracking"), Value::Boolean(self.permission_tracking));
        return Value::Table(btm)
    }

}

<commit_msg>Impl Default for RefFlags<commit_after>use std::collections::BTreeMap;

use toml::Value;

use error::RefErrorKind as REK;
use result::Result;

pub struct RefFlags {
    content_hashing:       bool,
    permission_tracking:   bool,
}

impl RefFlags {

    /// Read the RefFlags from a TOML document
    ///
    /// Assumes that the whole TOML tree is passed. So this looks up `ref.flags` to get the flags.
    /// It assumes that this is a Map with Key = <name of the setting> and Value = boolean.
    pub fn read(v: &Value) -> Result<RefFlags> {
        fn get_field(v: &Value, key: &str) -> Result<bool> {
            match v.lookup(key) {
                Some(&Value::Boolean(b)) => Ok(b),
                Some(_) => Err(REK::HeaderTypeError.into()),
                None    => Err(REK::HeaderFieldMissingError.into()),
            }
        }

        Ok(RefFlags {
            content_hashing:     try!(get_field(v, "ref.flags.content_hashing")),
            permission_tracking: try!(get_field(v, "ref.flags.permission_tracking")),
        })
    }

    /// Alias for `RefFlags::content_hashing()`
    pub fn is_often_moving(mut self, b: bool) -> RefFlags {
        self.with_content_hashing(b)
    }

    pub fn with_content_hashing(mut self, b: bool) -> RefFlags {
        self.content_hashing = b;
        self
    }

    pub fn with_permission_tracking(mut self, b: bool) -> RefFlags {
        self.permission_tracking = b;
        self
    }

    pub fn get_content_hashing(&self) -> bool {
        self.content_hashing
    }

    pub fn get_permission_tracking(&self) -> bool {
        self.permission_tracking
    }

}

impl Into<Value> for RefFlags {

    /// Build a TOML::Value from this RefFlags object.
    ///
    /// Returns a Map which should be set in `ref.flags` in the header.
    fn into(self) -> Value {
        let mut btm = BTreeMap::new();
        btm.insert(String::from("content_hashing"),     Value::Boolean(self.content_hashing));
        btm.insert(String::from("permission_tracking"), Value::Boolean(self.permission_tracking));
        return Value::Table(btm)
    }

}

impl Default for RefFlags {

    fn default() -> RefFlags {
        RefFlags {
            content_hashing: false,
            permission_tracking: false,
        }
    }
}

<|endoftext|>


<commit_before>use std::env;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_dir).join("bindgen.rs");
    if cfg!(feature = "sqlcipher") {
        if cfg!(any(
            feature = "bundled",
            all(windows, feature = "bundled-windows")
        )) {
            println!(
                "cargo:warning={}",
                "Builds with bundled SQLCipher are not supported. Searching for SQLCipher to link against. \
                 This can lead to issues if your version of SQLCipher is not up to date!");
        }
        build_linked::main(&out_dir, &out_path)
    } else {
        // This can't be `cfg!` without always requiring our `mod build_bundled` (and
        // thus `cc`)
        #[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
        {
            build_bundled::main(&out_dir, &out_path)
        }
        #[cfg(not(any(feature = "bundled", all(windows, feature = "bundled-windows"))))]
        {
            build_linked::main(&out_dir, &out_path)
        }
    }
}

#[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
mod build_bundled {
    use cc;
    use std::env;
    use std::path::Path;

    pub fn main(out_dir: &str, out_path: &Path) {
        if cfg!(feature = "sqlcipher") {
            // This is just a sanity check, the top level `main` should ensure this.
            panic!("Builds with bundled SQLCipher are not supported");
        }

        #[cfg(feature = "buildtime_bindgen")]
        {
            use super::{bindings, HeaderLocation};
            let header = HeaderLocation::FromPath("sqlite3/sqlite3.h".to_owned());
            bindings::write_to_out_dir(header, out_path);
        }
        #[cfg(not(feature = "buildtime_bindgen"))]
        {
            use std::fs;
            fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
                .expect("Could not copy bindings to output directory");
        }

        let mut cfg = cc::Build::new();
        cfg.file("sqlite3/sqlite3.c")
            .flag("-DSQLITE_CORE")
            .flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1")
            .flag("-DSQLITE_ENABLE_API_ARMOR")
            .flag("-DSQLITE_ENABLE_COLUMN_METADATA")
            .flag("-DSQLITE_ENABLE_DBSTAT_VTAB")
            .flag("-DSQLITE_ENABLE_FTS3")
            .flag("-DSQLITE_ENABLE_FTS3_PARENTHESIS")
            .flag("-DSQLITE_ENABLE_FTS5")
            .flag("-DSQLITE_ENABLE_JSON1")
            .flag("-DSQLITE_ENABLE_LOAD_EXTENSION=1")
            .flag("-DSQLITE_ENABLE_MEMORY_MANAGEMENT")
            .flag("-DSQLITE_ENABLE_RTREE")
            .flag("-DSQLITE_ENABLE_STAT2")
            .flag("-DSQLITE_ENABLE_STAT4")
            .flag("-DSQLITE_SOUNDEX")
            .flag("-DSQLITE_THREADSAFE=1")
            .flag("-DSQLITE_USE_URI")
            .flag("-DHAVE_USLEEP=1");
        // Older versions of visual studio don't support c99 (including isnan), which
        // causes a build failure when the linker fails to find the `isnan`
        // function. `sqlite` provides its own implmentation, using the fact
        // that x != x when x is NaN.
        //
        // There may be other platforms that don't support `isnan`, they should be
        // tested for here.
        if cfg!(target_env = "msvc") {
            use cc::windows_registry::{find_vs_version, VsVers};
            let vs_has_nan = match find_vs_version() {
                Ok(ver) => ver != VsVers::Vs12,
                Err(_msg) => false,
            };
            if vs_has_nan {
                cfg.flag("-DSQLITE_HAVE_ISNAN");
            }
        } else {
            cfg.flag("-DSQLITE_HAVE_ISNAN");
        }
        if cfg!(feature = "unlock_notify") {
            cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "preupdate_hook") {
            cfg.flag("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            cfg.flag("-DSQLITE_ENABLE_SESSION");
        }

        if let Ok(limit) = env::var("SQLITE_MAX_VARIABLE_NUMBER") {
            cfg.flag(&format!("-DSQLITE_MAX_VARIABLE_NUMBER={}", limit));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_VARIABLE_NUMBER");

        if let Ok(limit) = env::var("SQLITE_MAX_EXPR_DEPTH") {
            cfg.flag(&format!("-DSQLITE_MAX_EXPR_DEPTH={}", limit));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_EXPR_DEPTH");

        cfg.compile("libsqlite3.a");

        println!("cargo:lib_dir={}", out_dir);
    }
}

fn env_prefix() -> &'static str {
    if cfg!(feature = "sqlcipher") {
        "SQLCIPHER"
    } else {
        "SQLITE3"
    }
}

pub enum HeaderLocation {
    FromEnvironment,
    Wrapper,
    FromPath(String),
}

impl From<HeaderLocation> for String {
    fn from(header: HeaderLocation) -> String {
        match header {
            HeaderLocation::FromEnvironment => {
                let prefix = env_prefix();
                let mut header = env::var(format!("{}_INCLUDE_DIR", prefix)).unwrap_or_else(|_| {
                    panic!(
                        "{}_INCLUDE_DIR must be set if {}_LIB_DIR is set",
                        prefix, prefix
                    )
                });
                header.push_str("/sqlite3.h");
                header
            }
            HeaderLocation::Wrapper => "wrapper.h".into(),
            HeaderLocation::FromPath(path) => path,
        }
    }
}

mod build_linked {
    use pkg_config;

    #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
    extern crate vcpkg;

    use super::{bindings, env_prefix, HeaderLocation};
    use std::env;
    use std::path::Path;

    pub fn main(_out_dir: &str, out_path: &Path) {
        let header = find_sqlite();
        if cfg!(any(
            feature = "bundled",
            all(windows, feature = "bundled-windows")
        )) && !cfg!(feature = "buildtime_bindgen")
        {
            // We can only get here if `bundled` and `sqlcipher` were both
            // specified (and `builtime_bindgen` was not). In order to keep
            // `rusqlite` relatively clean we hide the fact that `bundled` can
            // be ignored in some cases, and just use the bundled bindings, even
            // though the library we found might not match their version.
            // Ideally we'd perform a version check here, but doing so is rather
            // tricky, since we might not have access to executables (and
            // moreover, we might be cross compiling).
            std::fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
                .expect("Could not copy bindings to output directory");
        } else {
            bindings::write_to_out_dir(header, out_path);
        }
    }

    fn find_link_mode() -> &'static str {
        // If the user specifies SQLITE_STATIC (or SQLCIPHER_STATIC), do static
        // linking, unless it's explicitly set to 0.
        match &env::var(format!("{}_STATIC", env_prefix())) {
            Ok(v) if v != "0" => "static",
            _ => "dylib",
        }
    }
    // Prints the necessary cargo link commands and returns the path to the header.
    fn find_sqlite() -> HeaderLocation {
        let link_lib = link_lib();

        println!("cargo:rerun-if-env-changed={}_INCLUDE_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_LIB_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_STATIC", env_prefix());
        if cfg!(target_os = "windows") {
            println!("cargo:rerun-if-env-changed=PATH");
        }
        if cfg!(all(feature = "vcpkg", target_env = "msvc")) {
            println!("cargo:rerun-if-env-changed=VCPKGRS_DYNAMIC");
        }
        // Allow users to specify where to find SQLite.
        if let Ok(dir) = env::var(format!("{}_LIB_DIR", env_prefix())) {
            // Try to use pkg-config to determine link commands
            let pkgconfig_path = Path::new(&dir).join("pkgconfig");
            env::set_var("PKG_CONFIG_PATH", pkgconfig_path);
            if pkg_config::Config::new().probe(link_lib).is_err() {
                // Otherwise just emit the bare minimum link commands.
                println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
                println!("cargo:rustc-link-search={}", dir);
            }
            return HeaderLocation::FromEnvironment;
        }

        if let Some(header) = try_vcpkg() {
            return header;
        }

        // See if pkg-config can do everything for us.
        match pkg_config::Config::new()
            .print_system_libs(false)
            .probe(link_lib)
        {
            Ok(mut lib) => {
                if let Some(mut header) = lib.include_paths.pop() {
                    header.push("sqlite3.h");
                    HeaderLocation::FromPath(header.to_string_lossy().into())
                } else {
                    HeaderLocation::Wrapper
                }
            }
            Err(_) => {
                // No env var set and pkg-config couldn't help; just output the link-lib
                // request and hope that the library exists on the system paths. We used to
                // output /usr/lib explicitly, but that can introduce other linking problems;
                // see https://github.com/jgallagher/rusqlite/issues/207.
                println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
                HeaderLocation::Wrapper
            }
        }
    }

    #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
    fn try_vcpkg() -> Option<HeaderLocation> {
        // See if vcpkg can find it.
        if let Ok(mut lib) = vcpkg::Config::new().probe(link_lib()) {
            if let Some(mut header) = lib.include_paths.pop() {
                header.push("sqlite3.h");
                return Some(HeaderLocation::FromPath(header.to_string_lossy().into()));
            }
        }
        None
    }

    #[cfg(not(all(feature = "vcpkg", target_env = "msvc")))]
    fn try_vcpkg() -> Option<HeaderLocation> {
        None
    }

    fn link_lib() -> &'static str {
        if cfg!(feature = "sqlcipher") {
            "sqlcipher"
        } else {
            "sqlite3"
        }
    }
}

#[cfg(not(feature = "buildtime_bindgen"))]
mod bindings {
    use super::HeaderLocation;

    use std::fs;
    use std::path::Path;

    static PREBUILT_BINDGEN_PATHS: &'static [&'static str] = &[
        "bindgen-bindings/bindgen_3.6.8.rs",
        #[cfg(feature = "min_sqlite_version_3_6_23")]
        "bindgen-bindings/bindgen_3.6.23.rs",
        #[cfg(feature = "min_sqlite_version_3_7_7")]
        "bindgen-bindings/bindgen_3.7.7.rs",
        #[cfg(feature = "min_sqlite_version_3_7_16")]
        "bindgen-bindings/bindgen_3.7.16.rs",
    ];

    pub fn write_to_out_dir(_header: HeaderLocation, out_path: &Path) {
        let in_path = PREBUILT_BINDGEN_PATHS[PREBUILT_BINDGEN_PATHS.len() - 1];
        fs::copy(in_path, out_path).expect("Could not copy bindings to output directory");
    }
}

#[cfg(feature = "buildtime_bindgen")]
mod bindings {
    use bindgen;

    use super::HeaderLocation;
    use bindgen::callbacks::{IntKind, ParseCallbacks};

    use std::fs::OpenOptions;
    use std::io::Write;
    use std::path::Path;

    #[derive(Debug)]
    struct SqliteTypeChooser;

    impl ParseCallbacks for SqliteTypeChooser {
        fn int_macro(&self, _name: &str, value: i64) -> Option<IntKind> {
            if value >= i32::min_value() as i64 && value <= i32::max_value() as i64 {
                Some(IntKind::I32)
            } else {
                None
            }
        }
    }

    pub fn write_to_out_dir(header: HeaderLocation, out_path: &Path) {
        let header: String = header.into();
        let mut output = Vec::new();
        let mut bindings = bindgen::builder()
            .header(header.clone())
            .parse_callbacks(Box::new(SqliteTypeChooser))
            .rustfmt_bindings(true);

        if cfg!(feature = "unlock_notify") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "preupdate_hook") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_SESSION");
        }

        bindings
            .generate()
            .unwrap_or_else(|_| panic!("could not run bindgen on header {}", header))
            .write(Box::new(&mut output))
            .expect("could not write output of bindgen");
        let mut output = String::from_utf8(output).expect("bindgen output was not UTF-8?!");

        // rusqlite's functions feature ors in the SQLITE_DETERMINISTIC flag when it
        // can. This flag was added in SQLite 3.8.3, but oring it in in prior
        // versions of SQLite is harmless. We don't want to not build just
        // because this flag is missing (e.g., if we're linking against
        // SQLite 3.7.x), so append the flag manually if it isn't present in bindgen's
        // output.
        if !output.contains("pub const SQLITE_DETERMINISTIC") {
            output.push_str("\npub const SQLITE_DETERMINISTIC: i32 = 2048;\n");
        }

        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(out_path)
            .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));

        file.write_all(output.as_bytes())
            .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));
    }
}
<commit_msg>Allow crates with a direct dep on libsqlite3-sys to know if `sqlcipher` has been enabled<commit_after>use std::env;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_dir).join("bindgen.rs");
    if cfg!(feature = "sqlcipher") {
        if cfg!(any(
            feature = "bundled",
            all(windows, feature = "bundled-windows")
        )) {
            println!(
                "cargo:warning={}",
                "Builds with bundled SQLCipher are not supported. Searching for SQLCipher to link against. \
                 This can lead to issues if your version of SQLCipher is not up to date!");
        }
        build_linked::main(&out_dir, &out_path)
    } else {
        // This can't be `cfg!` without always requiring our `mod build_bundled` (and
        // thus `cc`)
        #[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
        {
            build_bundled::main(&out_dir, &out_path)
        }
        #[cfg(not(any(feature = "bundled", all(windows, feature = "bundled-windows"))))]
        {
            build_linked::main(&out_dir, &out_path)
        }
    }
}

#[cfg(any(feature = "bundled", all(windows, feature = "bundled-windows")))]
mod build_bundled {
    use cc;
    use std::env;
    use std::path::Path;

    pub fn main(out_dir: &str, out_path: &Path) {
        if cfg!(feature = "sqlcipher") {
            // This is just a sanity check, the top level `main` should ensure this.
            panic!("Builds with bundled SQLCipher are not supported");
        }

        #[cfg(feature = "buildtime_bindgen")]
        {
            use super::{bindings, HeaderLocation};
            let header = HeaderLocation::FromPath("sqlite3/sqlite3.h".to_owned());
            bindings::write_to_out_dir(header, out_path);
        }
        #[cfg(not(feature = "buildtime_bindgen"))]
        {
            use std::fs;
            fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
                .expect("Could not copy bindings to output directory");
        }

        let mut cfg = cc::Build::new();
        cfg.file("sqlite3/sqlite3.c")
            .flag("-DSQLITE_CORE")
            .flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1")
            .flag("-DSQLITE_ENABLE_API_ARMOR")
            .flag("-DSQLITE_ENABLE_COLUMN_METADATA")
            .flag("-DSQLITE_ENABLE_DBSTAT_VTAB")
            .flag("-DSQLITE_ENABLE_FTS3")
            .flag("-DSQLITE_ENABLE_FTS3_PARENTHESIS")
            .flag("-DSQLITE_ENABLE_FTS5")
            .flag("-DSQLITE_ENABLE_JSON1")
            .flag("-DSQLITE_ENABLE_LOAD_EXTENSION=1")
            .flag("-DSQLITE_ENABLE_MEMORY_MANAGEMENT")
            .flag("-DSQLITE_ENABLE_RTREE")
            .flag("-DSQLITE_ENABLE_STAT2")
            .flag("-DSQLITE_ENABLE_STAT4")
            .flag("-DSQLITE_SOUNDEX")
            .flag("-DSQLITE_THREADSAFE=1")
            .flag("-DSQLITE_USE_URI")
            .flag("-DHAVE_USLEEP=1");
        // Older versions of visual studio don't support c99 (including isnan), which
        // causes a build failure when the linker fails to find the `isnan`
        // function. `sqlite` provides its own implmentation, using the fact
        // that x != x when x is NaN.
        //
        // There may be other platforms that don't support `isnan`, they should be
        // tested for here.
        if cfg!(target_env = "msvc") {
            use cc::windows_registry::{find_vs_version, VsVers};
            let vs_has_nan = match find_vs_version() {
                Ok(ver) => ver != VsVers::Vs12,
                Err(_msg) => false,
            };
            if vs_has_nan {
                cfg.flag("-DSQLITE_HAVE_ISNAN");
            }
        } else {
            cfg.flag("-DSQLITE_HAVE_ISNAN");
        }
        if cfg!(feature = "unlock_notify") {
            cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "preupdate_hook") {
            cfg.flag("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            cfg.flag("-DSQLITE_ENABLE_SESSION");
        }

        if let Ok(limit) = env::var("SQLITE_MAX_VARIABLE_NUMBER") {
            cfg.flag(&format!("-DSQLITE_MAX_VARIABLE_NUMBER={}", limit));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_VARIABLE_NUMBER");

        if let Ok(limit) = env::var("SQLITE_MAX_EXPR_DEPTH") {
            cfg.flag(&format!("-DSQLITE_MAX_EXPR_DEPTH={}", limit));
        }
        println!("cargo:rerun-if-env-changed=SQLITE_MAX_EXPR_DEPTH");

        cfg.compile("libsqlite3.a");

        println!("cargo:lib_dir={}", out_dir);
    }
}

fn env_prefix() -> &'static str {
    if cfg!(feature = "sqlcipher") {
        "SQLCIPHER"
    } else {
        "SQLITE3"
    }
}

pub enum HeaderLocation {
    FromEnvironment,
    Wrapper,
    FromPath(String),
}

impl From<HeaderLocation> for String {
    fn from(header: HeaderLocation) -> String {
        match header {
            HeaderLocation::FromEnvironment => {
                let prefix = env_prefix();
                let mut header = env::var(format!("{}_INCLUDE_DIR", prefix)).unwrap_or_else(|_| {
                    panic!(
                        "{}_INCLUDE_DIR must be set if {}_LIB_DIR is set",
                        prefix, prefix
                    )
                });
                header.push_str("/sqlite3.h");
                header
            }
            HeaderLocation::Wrapper => "wrapper.h".into(),
            HeaderLocation::FromPath(path) => path,
        }
    }
}

mod build_linked {
    use pkg_config;

    #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
    extern crate vcpkg;

    use super::{bindings, env_prefix, HeaderLocation};
    use std::env;
    use std::path::Path;

    pub fn main(_out_dir: &str, out_path: &Path) {
        let header = find_sqlite();
        if cfg!(any(
            feature = "bundled",
            all(windows, feature = "bundled-windows")
        )) && !cfg!(feature = "buildtime_bindgen")
        {
            // We can only get here if `bundled` and `sqlcipher` were both
            // specified (and `builtime_bindgen` was not). In order to keep
            // `rusqlite` relatively clean we hide the fact that `bundled` can
            // be ignored in some cases, and just use the bundled bindings, even
            // though the library we found might not match their version.
            // Ideally we'd perform a version check here, but doing so is rather
            // tricky, since we might not have access to executables (and
            // moreover, we might be cross compiling).
            std::fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
                .expect("Could not copy bindings to output directory");
        } else {
            bindings::write_to_out_dir(header, out_path);
        }
    }

    fn find_link_mode() -> &'static str {
        // If the user specifies SQLITE_STATIC (or SQLCIPHER_STATIC), do static
        // linking, unless it's explicitly set to 0.
        match &env::var(format!("{}_STATIC", env_prefix())) {
            Ok(v) if v != "0" => "static",
            _ => "dylib",
        }
    }
    // Prints the necessary cargo link commands and returns the path to the header.
    fn find_sqlite() -> HeaderLocation {
        let link_lib = link_lib();

        println!("cargo:rerun-if-env-changed={}_INCLUDE_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_LIB_DIR", env_prefix());
        println!("cargo:rerun-if-env-changed={}_STATIC", env_prefix());
        if cfg!(target_os = "windows") {
            println!("cargo:rerun-if-env-changed=PATH");
        }
        if cfg!(all(feature = "vcpkg", target_env = "msvc")) {
            println!("cargo:rerun-if-env-changed=VCPKGRS_DYNAMIC");
        }

        // dependents can access `DEP_SQLITE3_LINK_TARGET` (`sqlite3` being the
        // `links=` value in our Cargo.toml) to get this value. This might be
        // useful if you need to ensure whatever crypto library sqlcipher relies
        // on is available, for example.
        println!("cargo:link-target={}", link_lib);

        // Allow users to specify where to find SQLite.
        if let Ok(dir) = env::var(format!("{}_LIB_DIR", env_prefix())) {
            // Try to use pkg-config to determine link commands
            let pkgconfig_path = Path::new(&dir).join("pkgconfig");
            env::set_var("PKG_CONFIG_PATH", pkgconfig_path);
            if pkg_config::Config::new().probe(link_lib).is_err() {
                // Otherwise just emit the bare minimum link commands.
                println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
                println!("cargo:rustc-link-search={}", dir);
            }
            return HeaderLocation::FromEnvironment;
        }

        if let Some(header) = try_vcpkg() {
            return header;
        }

        // See if pkg-config can do everything for us.
        match pkg_config::Config::new()
            .print_system_libs(false)
            .probe(link_lib)
        {
            Ok(mut lib) => {
                if let Some(mut header) = lib.include_paths.pop() {
                    header.push("sqlite3.h");
                    HeaderLocation::FromPath(header.to_string_lossy().into())
                } else {
                    HeaderLocation::Wrapper
                }
            }
            Err(_) => {
                // No env var set and pkg-config couldn't help; just output the link-lib
                // request and hope that the library exists on the system paths. We used to
                // output /usr/lib explicitly, but that can introduce other linking problems;
                // see https://github.com/jgallagher/rusqlite/issues/207.
                println!("cargo:rustc-link-lib={}={}", find_link_mode(), link_lib);
                HeaderLocation::Wrapper
            }
        }
    }

    #[cfg(all(feature = "vcpkg", target_env = "msvc"))]
    fn try_vcpkg() -> Option<HeaderLocation> {
        // See if vcpkg can find it.
        if let Ok(mut lib) = vcpkg::Config::new().probe(link_lib()) {
            if let Some(mut header) = lib.include_paths.pop() {
                header.push("sqlite3.h");
                return Some(HeaderLocation::FromPath(header.to_string_lossy().into()));
            }
        }
        None
    }

    #[cfg(not(all(feature = "vcpkg", target_env = "msvc")))]
    fn try_vcpkg() -> Option<HeaderLocation> {
        None
    }

    fn link_lib() -> &'static str {
        if cfg!(feature = "sqlcipher") {
            "sqlcipher"
        } else {
            "sqlite3"
        }
    }
}

#[cfg(not(feature = "buildtime_bindgen"))]
mod bindings {
    use super::HeaderLocation;

    use std::fs;
    use std::path::Path;

    static PREBUILT_BINDGEN_PATHS: &'static [&'static str] = &[
        "bindgen-bindings/bindgen_3.6.8.rs",
        #[cfg(feature = "min_sqlite_version_3_6_23")]
        "bindgen-bindings/bindgen_3.6.23.rs",
        #[cfg(feature = "min_sqlite_version_3_7_7")]
        "bindgen-bindings/bindgen_3.7.7.rs",
        #[cfg(feature = "min_sqlite_version_3_7_16")]
        "bindgen-bindings/bindgen_3.7.16.rs",
    ];

    pub fn write_to_out_dir(_header: HeaderLocation, out_path: &Path) {
        let in_path = PREBUILT_BINDGEN_PATHS[PREBUILT_BINDGEN_PATHS.len() - 1];
        fs::copy(in_path, out_path).expect("Could not copy bindings to output directory");
    }
}

#[cfg(feature = "buildtime_bindgen")]
mod bindings {
    use bindgen;

    use super::HeaderLocation;
    use bindgen::callbacks::{IntKind, ParseCallbacks};

    use std::fs::OpenOptions;
    use std::io::Write;
    use std::path::Path;

    #[derive(Debug)]
    struct SqliteTypeChooser;

    impl ParseCallbacks for SqliteTypeChooser {
        fn int_macro(&self, _name: &str, value: i64) -> Option<IntKind> {
            if value >= i32::min_value() as i64 && value <= i32::max_value() as i64 {
                Some(IntKind::I32)
            } else {
                None
            }
        }
    }

    pub fn write_to_out_dir(header: HeaderLocation, out_path: &Path) {
        let header: String = header.into();
        let mut output = Vec::new();
        let mut bindings = bindgen::builder()
            .header(header.clone())
            .parse_callbacks(Box::new(SqliteTypeChooser))
            .rustfmt_bindings(true);

        if cfg!(feature = "unlock_notify") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
        }
        if cfg!(feature = "preupdate_hook") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_PREUPDATE_HOOK");
        }
        if cfg!(feature = "session") {
            bindings = bindings.clang_arg("-DSQLITE_ENABLE_SESSION");
        }

        bindings
            .generate()
            .unwrap_or_else(|_| panic!("could not run bindgen on header {}", header))
            .write(Box::new(&mut output))
            .expect("could not write output of bindgen");
        let mut output = String::from_utf8(output).expect("bindgen output was not UTF-8?!");

        // rusqlite's functions feature ors in the SQLITE_DETERMINISTIC flag when it
        // can. This flag was added in SQLite 3.8.3, but oring it in in prior
        // versions of SQLite is harmless. We don't want to not build just
        // because this flag is missing (e.g., if we're linking against
        // SQLite 3.7.x), so append the flag manually if it isn't present in bindgen's
        // output.
        if !output.contains("pub const SQLITE_DETERMINISTIC") {
            output.push_str("\npub const SQLITE_DETERMINISTIC: i32 = 2048;\n");
        }

        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(out_path)
            .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));

        file.write_all(output.as_bytes())
            .unwrap_or_else(|_| panic!("Could not write to {:?}", out_path));
    }
}
<|endoftext|>


<commit_before><commit_msg>2019 day 05 part 2<commit_after><|endoftext|>


<commit_before>use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(ref error) if error.kind() == ErrorKind::NotFound => {
            match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => {
                    panic!("File creation failed: {:?}", e)
                }
            }
        },
        Err(error) => {
            panic!("Problem with opening file: {:?}", error)
        }
    };
}
<commit_msg>Example of using unwrap to shorten error/result handling<commit_after>use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(ref error) if error.kind() == ErrorKind::NotFound => {
            match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => {
                    panic!("File creation failed: {:?}", e)
                }
            }
        },
        Err(error) => {
            panic!("Problem with opening file: {:?}", error)
        }
    };

    let f_unwrap = File::open("hello.txt").unwrap();
    // Example of unwrap usage to shorten code (Ok(res) => res and Err(e) => panic!("...")
}
<|endoftext|>


<commit_before>use super::table::{Table, PML4Level};
use cpu::control_regs::cr3::{read, write};
pub use cpu::control_regs::cr3::*;

/// Returns the current Page Meta-Level 4 table
///
/// # Safety
/// + Reading from control registers while not in kernel mode will cause
///   a general protection fault.
#[cfg(target_arch = "x86_64")]
#[inline]
pub unsafe fn current_pml4() -> *mut Table<PML4Level> {
    read().as_mut_ptr::<Table<PML4Level>>()
}

/// Sets the current Page Meta-Level 4 Table
///
/// # Safety
/// + Control registers should generally not be modified during normal
///   operation.
#[cfg(target_arch = "x86_64")]
pub unsafe fn set_pml4(pml4: Table<PML4Level>) {
    write(pml4.frame().base_addr())
}
<commit_msg>[paging] add more safety docs to paging cr3 module<commit_after>use super::table::{Table, PML4Level};
use cpu::control_regs::cr3::{read, write};
pub use cpu::control_regs::cr3::*;

/// Returns the current Page Meta-Level 4 table
///
/// # Safety
/// + Reading from control registers while not in kernel mode will cause
///   a general protection fault.
/// + Returns a `*mut` pointer with an arbitrary lifetime.
#[cfg(target_arch = "x86_64")]
#[inline]
pub unsafe fn current_pml4() -> *mut Table<PML4Level> {
    read().as_mut_ptr::<Table<PML4Level>>()
}

/// Sets the current Page Meta-Level 4 Table
///
/// # Safety
/// + Control registers should generally not be modified during normal
///   operation.
#[cfg(target_arch = "x86_64")]
pub unsafe fn set_pml4(pml4: Table<PML4Level>) {
    write(pml4.frame().base_addr())
}
<|endoftext|>


<commit_before>/*
 * userchannel.rs
 *
 * All user and channel related functionality.
 *
 */
extern crate tokio_core;

use std::collections::HashMap;
//use tokio_core::net::TcpStream;
use std::net::TcpStream;

struct ChannelDb<'a> {
    channels: HashMap<String, ChannelDb<'a>>,
    users: HashMap<String, &'a TcpStream>,
    values: Vec<Vec<String>>
}

impl<'a> ChannelDb<'a> {
    pub fn join_channel(&'a mut self, socket: &'a TcpStream, userid: &str, channelid: &str) {
        let user_exists = self.check_user_existence(userid);

        if !user_exists {
            self.users.insert(userid.to_string(), socket);
        }

        let channel_exists = self.check_channel_existence(channelid);
        if !channel_exists {
            let mut channel = ChannelDb{ channels: HashMap::new(), users: HashMap::new(), values: Vec::new() };
            self.channels.insert(channelid.to_string(), channel);
        }
    }

    pub fn leave_channel(&'a mut self, userid: &str, channelid: &str) {
        let user_exists = self.check_user_existence(userid);
        if user_exists {
            let channel_exists = self.check_channel_existence(channelid);
            if channel_exists {
                self.channels.remove(channelid);
            }
            self.users.remove(userid);
        }
    }

    fn check_user_existence(&'a self, userid: &str) -> bool {
        let opt = self.users.get(userid);
        match opt {
            Some(db) => return true,
                None => {}
        }
        return false;
    }
    fn check_channel_existence(&'a self, channelid: &str) -> bool {
        let opt = self.channels.get(channelid);
        match opt {
            Some(db) => return true,
                None => {}
        }
        return false;
    }
}

#[cfg(test)]

mod tests {
    use super::*;

    #[test]
    fn test_join_channel() {
        let mut user_chan_db = HashMap::new();
        let channel = "Rust";
        let user = "Sampo";
        let mut ret;

        ret = join_channel(user_chan_db, user, channel);
        assert_eq!(0, ret);

        ret = join_channel(user_chan_db, user, channel);
        assert_eq!(1, ret);
    }

    fn test_leave_channel() {
        let mut user_chan_db = HashMap::new();
        let channel = "Evolve";
        let user = "Anna";
        let mut ret;

        ret = join_channel(user_chan_db, user, channel);
        assert_eq!(0, ret);

        ret = leave_channel(user_chan_db, user, channel);
        assert_eq!(0, ret);

        ret = leave_channel(user_chan_db, user, channel);
        assert_eq!(1, ret);

    }
}
<commit_msg>Unit tests for ChannelDb.<commit_after>/*
 * userchannel.rs
 *
 * All user and channel related functionality.
 *
 */
extern crate tokio_core;

use std::collections::HashMap;
//use tokio_core::net::TcpStream;
use std::net::TcpStream;

#[derive(Debug)]
struct ChannelDb<'a> {
    channels: HashMap<String, ChannelDb<'a>>,
    users: HashMap<String, &'a TcpStream>,
    values: Vec<Vec<String>>
}

impl<'a> ChannelDb<'a> {
    pub fn join_channel(mut self, socket: &'a TcpStream, userid: &str, channelid: &str) -> ChannelDb<'a> {
        let user_exists = self.check_user_existence(userid);

        if !user_exists {
            self.users.insert(userid.to_string(), socket);
        }

        let channel_exists = self.check_channel_existence(channelid);
        if !channel_exists {
            let channel = ChannelDb{ channels: HashMap::new(), users: HashMap::new(), values: Vec::new() };
            self.channels.insert(channelid.to_string(), channel);
        }
        self
    }

    pub fn leave_channel(mut self, userid: &str, channelid: &str) -> ChannelDb<'a> {
        let user_exists = self.check_user_existence(userid);
        if user_exists {
            let channel_exists = self.check_channel_existence(channelid);
            if channel_exists {
                self.channels.remove(channelid);
            }
            self.users.remove(userid);
        }
        self
    }

    pub fn check_user_existence(&'a self, userid: &str) -> bool {
        let opt = self.users.get(userid);
        match opt {
            Some(_) => return true,
            None => {}
        }
        return false;
    }

    pub fn check_channel_existence(&'a self, channelid: &str) -> bool {
        let opt = self.channels.get(channelid);
        match opt {
            Some(_) => return true,
            None => {}
        }
        return false;
    }
}

#[cfg(test)]

mod tests {
    use std::collections::HashMap;
    use std::net::TcpStream;
    use super::ChannelDb;

    #[test]
    fn test_join_channel() {
        // google should be up always
        let socket = TcpStream::connect("209.85.202.94:80").unwrap();
        {
            /* Arrange */
            let mut channel_db = ChannelDb{ channels: HashMap::new(), users: HashMap::new(), values: Vec::new() };
            let channel = "Rust";
            let user = "Sampo";
            let mut ret;

            /* Assert */
            ret = channel_db.check_user_existence(user);
            assert_eq!(false, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(false, ret);

            /* Act */
            channel_db = channel_db.join_channel(&socket, user, channel);

            /* Assert */
            ret = channel_db.check_user_existence(user);
            assert_eq!(true, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(true, ret);

            /* Negative */
            channel_db = channel_db.join_channel(&socket, user, channel);
            ret = channel_db.check_user_existence(user);
            assert_eq!(true, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(true, ret);
        }
    }

    #[test]
    fn test_leave_channel() {
        // google should be up always
        let socket = TcpStream::connect("209.85.202.94:80").unwrap();
        {
            let mut channel_db = ChannelDb{ channels: HashMap::new(), users: HashMap::new(), values: Vec::new() };
            let channel = "Mles";
            let user = "Anna";
            let mut ret;

            channel_db = channel_db.join_channel(&socket, user, channel);
            ret = channel_db.check_user_existence(user);
            assert_eq!(true, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(true, ret);

            channel_db = channel_db.leave_channel(user, channel);
            ret = channel_db.check_user_existence(user);
            assert_eq!(false, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(false, ret);

            channel_db = channel_db.leave_channel(user, channel);
            ret = channel_db.check_user_existence(user);
            assert_eq!(false, ret);
            ret = channel_db.check_channel_existence(channel);
            assert_eq!(false, ret);
        }
    }
}
<|endoftext|>