<commit_before>extern crate crossbeam;
extern crate clap;
#[macro_use] extern crate version;
#[macro_use] extern crate log;
extern crate walkdir;

extern crate libimagrt;
extern crate libimagerror;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;

use walkdir::WalkDir;
use crossbeam::*;
use clap::{Arg, AppSettings, SubCommand};

use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;

/// Returns the helptext, putting the Strings in cmds as possible
/// subcommands into it
fn help_text(cmds: Vec<String>) -> String {
    let text = format!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:

    {imagbins}

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#, imagbins = cmds.into_iter()
        .map(|cmd| format!("\t{}\n", cmd))
        .fold(String::new(), |s, c| {
            let s = s + c.as_str();
            s
        }));
    text
}

/// Returns the list of imag-* executables found in $PATH
fn get_commands() -> Vec<String> {
    let path = env::var("PATH");
    if path.is_err() {
        println!("PATH error: {:?}", path);
        exit(1);
    }
    let pathelements = path.unwrap();
    let pathelements = pathelements.split(":");

    let joinhandles : Vec<ScopedJoinHandle<Vec<String>>> = pathelements
        .map(|elem| {
            crossbeam::scope(|scope| {
                scope.spawn(|| {
                    WalkDir::new(elem)
                        .max_depth(1)
                        .into_iter()
                        .filter(|path| {
                            match path {
                                &Ok(ref p) => p.file_name()
                                    .to_str()
                                    .map_or(false, |filename| filename.starts_with("imag-")),
                                &Err(_)   => false,
                            }
                        })
                        .filter_map(|x| x.ok())
                        .filter_map(|path| {
                           path.file_name()
                               .to_str()
                               .and_then(|s| s.splitn(2, "-").nth(1).map(String::from))
                        })
                        .collect()
                })
            })
        })
        .collect();

    let mut execs = vec![];
    for joinhandle in joinhandles.into_iter() {
        let mut v = joinhandle.join();
        execs.append(&mut v);
    }

    execs
}

fn main() {
    // Initialize the Runtime and build the CLI
    let appname  = "imag";
    let version  = &version!();
    let about    = "imag - the PIM suite for the commandline";
    let commands = get_commands();
    let helptext = help_text(commands.clone());
    let app      = Runtime::get_default_cli_builder(appname, version, about)
        .settings(&[AppSettings::AllowExternalSubcommands, AppSettings::ArgRequiredElseHelp])
        .arg(Arg::with_name("version")
             .long("version")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the version of imag"))
        .arg(Arg::with_name("versions")
             .long("versions")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the versions of the imag commands"))
        .subcommand(SubCommand::with_name("help").help("Show help"))
        .help(helptext.as_str());
    let rt = Runtime::new(app)
        .unwrap_or_else(|e| {
            println!("Runtime couldn't be setup. Exiting");
            trace_error(&e);
            exit(1);
        });
    let matches = rt.cli();

    debug!("matches: {:?}", matches);

    // Begin checking for arguments

    if matches.is_present("version") {
        debug!("Showing version");
        println!("imag {}", &version!()[..]);
        exit(0);
    }

    if matches.is_present("versions") {
        debug!("Showing versions");
        let mut result = vec![];
        for command in get_commands().iter() {
            result.push(crossbeam::scope(|scope| {
                scope.spawn(|| {
                    let v = Command::new(format!("imag-{}",command)).arg("--version").output();
                    match v {
                        Ok(v) => match String::from_utf8(v.stdout) {
                            Ok(s) => format!("{} -> {}", command, s),
                            Err(e) => format!("Failed calling {} -> {:?}", command, e),
                        },
                        Err(e) => format!("Failed calling {} -> {:?}", command, e),
                    }
                })
            }))
        }

        for versionstring in result.into_iter().map(|handle| handle.join()) {
            println!("{}", versionstring);
        }
    }

    // Matches any subcommand given
    match matches.subcommand() {
        (subcommand, Some(scmd)) => {
            // Get all given arguments and further subcommands to pass to
            // the imag-<> binary
            // Providing no arguments is OK, and is therefore ignored here
            let subcommand_args : Vec<&str> = match scmd.values_of("") {
                Some(values) => values.collect(),
                None => Vec::new()
            };

            // Typos happen, so check if the given subcommand is one found in $PATH
            if !commands.clone().contains(&String::from(subcommand)) {
                println!("No such command: 'imag-{}'", subcommand);
                println!("See 'imag --help' for available subcommands");
                exit(2);
            }

            debug!("Calling 'imag-{}' with args: {:?}", subcommand, subcommand_args);

            // Create a Command, and pass it the gathered arguments
            match Command::new(format!("imag-{}", subcommand))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&subcommand_args[..])
                .spawn()
                .and_then(|mut handle| handle.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        debug!("{} exited with non-zero exit code: {:?}", subcommand, exit_status);
                        println!("{} exited with non-zero exit code", subcommand);
                        exit(exit_status.code().unwrap_or(1));
                    }
                    debug!("Successful exit!");
                },

                Err(e) => {
                    debug!("Error calling the subcommand");
                    match e.kind() {
                        ErrorKind::NotFound => {
                            // With the check above, this absolutely should not happen.
                            // Keeping it to be safe
                            println!("No such command: 'imag-{}'", subcommand);
                            println!("See 'imag --help' for available subcommands");
                            exit(2);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", subcommand);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1);
                        }
                    }
                }
            }
        },
        // Calling for example 'imag --versions' will lead here, as this option does not exit.
        // There's nothing to do in such a case
        _ => {},
    }
}
<commit_msg>Pretty output of --versions<commit_after>extern crate crossbeam;
extern crate clap;
#[macro_use] extern crate version;
#[macro_use] extern crate log;
extern crate walkdir;

extern crate libimagrt;
extern crate libimagerror;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;

use walkdir::WalkDir;
use crossbeam::*;
use clap::{Arg, AppSettings, SubCommand};

use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;

/// Returns the helptext, putting the Strings in cmds as possible
/// subcommands into it
fn help_text(cmds: Vec<String>) -> String {
    let text = format!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:

    {imagbins}

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#, imagbins = cmds.into_iter()
        .map(|cmd| format!("\t{}\n", cmd))
        .fold(String::new(), |s, c| {
            let s = s + c.as_str();
            s
        }));
    text
}

/// Returns the list of imag-* executables found in $PATH
fn get_commands() -> Vec<String> {
    let path = env::var("PATH");
    if path.is_err() {
        println!("PATH error: {:?}", path);
        exit(1);
    }
    let pathelements = path.unwrap();
    let pathelements = pathelements.split(":");

    let joinhandles : Vec<ScopedJoinHandle<Vec<String>>> = pathelements
        .map(|elem| {
            crossbeam::scope(|scope| {
                scope.spawn(|| {
                    WalkDir::new(elem)
                        .max_depth(1)
                        .into_iter()
                        .filter(|path| {
                            match path {
                                &Ok(ref p) => p.file_name()
                                    .to_str()
                                    .map_or(false, |filename| filename.starts_with("imag-")),
                                &Err(_)   => false,
                            }
                        })
                        .filter_map(|x| x.ok())
                        .filter_map(|path| {
                           path.file_name()
                               .to_str()
                               .and_then(|s| s.splitn(2, "-").nth(1).map(String::from))
                        })
                        .collect()
                })
            })
        })
        .collect();

    let mut execs = vec![];
    for joinhandle in joinhandles.into_iter() {
        let mut v = joinhandle.join();
        execs.append(&mut v);
    }

    execs
}

fn main() {
    // Initialize the Runtime and build the CLI
    let appname  = "imag";
    let version  = &version!();
    let about    = "imag - the PIM suite for the commandline";
    let commands = get_commands();
    let helptext = help_text(commands.clone());
    let app      = Runtime::get_default_cli_builder(appname, version, about)
        .settings(&[AppSettings::AllowExternalSubcommands, AppSettings::ArgRequiredElseHelp])
        .arg(Arg::with_name("version")
             .long("version")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the version of imag"))
        .arg(Arg::with_name("versions")
             .long("versions")
             .takes_value(false)
             .required(false)
             .multiple(false)
             .help("Get the versions of the imag commands"))
        .subcommand(SubCommand::with_name("help").help("Show help"))
        .help(helptext.as_str());
    let rt = Runtime::new(app)
        .unwrap_or_else(|e| {
            println!("Runtime couldn't be setup. Exiting");
            trace_error(&e);
            exit(1);
        });
    let matches = rt.cli();

    debug!("matches: {:?}", matches);

    // Begin checking for arguments

    if matches.is_present("version") {
        debug!("Showing version");
        println!("imag {}", &version!()[..]);
        exit(0);
    }

    if matches.is_present("versions") {
        debug!("Showing versions");
        let mut result = vec![];
        for command in get_commands().iter() {
            result.push(crossbeam::scope(|scope| {
                scope.spawn(|| {
                    let v = Command::new(format!("imag-{}",command)).arg("--version").output();
                    match v {
                        Ok(v) => match String::from_utf8(v.stdout) {
                            Ok(s) => format!("{:10} -> {}", command, s),
                            Err(e) => format!("Failed calling {} -> {:?}", command, e),
                        },
                        Err(e) => format!("Failed calling {} -> {:?}", command, e),
                    }
                })
            }))
        }

        for versionstring in result.into_iter().map(|handle| handle.join()) {
            print!("{}", versionstring);
        }
    }

    // Matches any subcommand given
    match matches.subcommand() {
        (subcommand, Some(scmd)) => {
            // Get all given arguments and further subcommands to pass to
            // the imag-<> binary
            // Providing no arguments is OK, and is therefore ignored here
            let subcommand_args : Vec<&str> = match scmd.values_of("") {
                Some(values) => values.collect(),
                None => Vec::new()
            };

            // Typos happen, so check if the given subcommand is one found in $PATH
            if !commands.clone().contains(&String::from(subcommand)) {
                println!("No such command: 'imag-{}'", subcommand);
                println!("See 'imag --help' for available subcommands");
                exit(2);
            }

            debug!("Calling 'imag-{}' with args: {:?}", subcommand, subcommand_args);

            // Create a Command, and pass it the gathered arguments
            match Command::new(format!("imag-{}", subcommand))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&subcommand_args[..])
                .spawn()
                .and_then(|mut handle| handle.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        debug!("{} exited with non-zero exit code: {:?}", subcommand, exit_status);
                        println!("{} exited with non-zero exit code", subcommand);
                        exit(exit_status.code().unwrap_or(1));
                    }
                    debug!("Successful exit!");
                },

                Err(e) => {
                    debug!("Error calling the subcommand");
                    match e.kind() {
                        ErrorKind::NotFound => {
                            // With the check above, this absolutely should not happen.
                            // Keeping it to be safe
                            println!("No such command: 'imag-{}'", subcommand);
                            println!("See 'imag --help' for available subcommands");
                            exit(2);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", subcommand);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1);
                        }
                    }
                }
            }
        },
        // Calling for example 'imag --versions' will lead here, as this option does not exit.
        // There's nothing to do in such a case
        _ => {},
    }
}
<|endoftext|>


<commit_before><commit_msg>style: convert NS_STYLE_STROKE_LINECAP_* to an enum class in nsStyleConsts.h<commit_after><|endoftext|>


<commit_before><commit_msg>commands: fix from_bytes. get rid of stupid code duplication... what was i thinking when i wrote that.<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor Chunk setters+getters to use usize for indeces<commit_after><|endoftext|>


<commit_before><commit_msg>Formatting for World::touch<commit_after><|endoftext|>


<commit_before><commit_msg>WIP Add to_rule<commit_after><|endoftext|>


<commit_before><commit_msg>style<commit_after><|endoftext|>


<commit_before><commit_msg>21 - ownership and move<commit_after>// This function takes ownership of the heap allocated memory
fn destroy_box(c: Box<int>) {
    println!("destroying a box that contains {}", c);

    // `c` will be destroyed in this scope, and the memory will be freed
}

fn main() {
    // Stack allocated integer
    let x = 5u;

    // "Copy" `x` into `y`, there are no resources to move
    let y = x;

    // Both values can be independently used
    println!("x is {}, and y is {}", x, y);

    // `a` is a pointer to a heap allocated integer
    let a = box 5;

    println!("a contains: {}", a);

    // "Move" `a` into `b`
    // Here's what happens under the hood: the pointer `a` gets copied (*not*
    // the data on the heap, just its address) into `b`. Now both are pointers
    // to the *same* heap allocated data. But now, `b` *owns* the heap
    // allocated data; `b` is now in charge of freeing the memory in the heap.
    let b = a;

    // After the previous move, `a` can no longer be used
    // Error! `a` can no longer access the data, because it no longer owns the
    // heap memory
    //println!("a contains: {}", a);
    // TODO ^ Try uncommenting this line

    // "Move" `b` into the function; `b` gives up ownership of the heap data
    destroy_box(b);

    // Since the heap memory has been freed at this point, this action would
    // result in dereferencing freed memory, but it's forbidden by the compiler
    // Error! Same reason as the previous Error
    //println!("b contains: {}", b);
    // TODO ^ Try uncommenting this line
}
<|endoftext|>


<commit_before><commit_msg>ls adeheres to new ArgParser interface<commit_after><|endoftext|>


<commit_before><commit_msg>added TwitchClient, User, and Message types<commit_after>
pub struct TwitchClient {
	user: String,
	auth: String,
	default_channel: String,
	logging: bool,
}

impl TwitchClient {
	pub fn connect(&self) {
		// TODO: Connect!
	}
}
<|endoftext|>


<commit_before><commit_msg>Simplify client (closes #16)<commit_after><|endoftext|>


<commit_before><commit_msg>Add protocol module, in order to retrieve the protocol to retrieve a file<commit_after>use hyper::Url;

#[derive(Debug)]
pub enum Protocol {
    HTTP,
    HTTPS,
}

pub fn get_protocol(url: &str) -> Option<Protocol> {
    match Url::parse(url) {
        Ok(url) => match url.scheme() {
            "http" => Some(Protocol::HTTP),
            "https" => Some(Protocol::HTTPS),
            _ => None,
        },
        Err(error) => {
            warning!(&format!("Canno't extract the protocol from the URL: {}", error));
            None
        }
    }
}<|endoftext|>


<commit_before>use super::moves::Plies;
use super::pos::Position;
use super::fen;
use super::legal;
use super::make_move::make_move;
use super::mate;

#[test]
fn perf() {
    perf_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
             &[1, 20, 400, 8902, 197281, 4865609]);
}

fn perf_fen(fen_str: &str, res: &[u64]) {
    let p = fen::fen_to_position(fen_str).unwrap();
    perf_pos(&p, res);
}

fn perf_pos(p: &Position, res: &[u64]) {
    for (num_plies, expect_num_from_pos) in res.iter().enumerate() {
        assert_eq!(*expect_num_from_pos, num_from_pos(p, Plies(num_plies as u8)));
    }
}

fn num_from_pos(p: &Position, plies: Plies) -> u64 {
    if plies == Plies(0) {
        return 1;
    }
    if !mate::has_legal_moves(p.clone()) {
        return 0;
    }
    let next_plies = match plies {
        Plies(val) => Plies(val-1),
    };
    let mut ans = 0;
    for m in legal::receive_legal(p.clone()).iter() {
        let new_pos = make_move(p.clone(), &m);
        ans += num_from_pos(&new_pos, next_plies);
    }
    ans
}
<commit_msg>Decrease test position.<commit_after>use super::moves::Plies;
use super::pos::Position;
use super::fen;
use super::legal;
use super::make_move::make_move;
use super::mate;

#[test]
fn perf() {
    //perf_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
    //         &[1, 20, 400, 8902, 197281, 4865609]);
    perf_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
             &[1, 20, 400, 8902]);
}

fn perf_fen(fen_str: &str, res: &[u64]) {
    let p = fen::fen_to_position(fen_str).unwrap();
    perf_pos(&p, res);
}

fn perf_pos(p: &Position, res: &[u64]) {
    for (num_plies, expect_num_from_pos) in res.iter().enumerate() {
        assert_eq!(*expect_num_from_pos, num_from_pos(p, Plies(num_plies as u8)));
    }
}

fn num_from_pos(p: &Position, plies: Plies) -> u64 {
    if plies == Plies(0) {
        return 1;
    }
    if !mate::has_legal_moves(p.clone()) {
        return 0;
    }
    let next_plies = match plies {
        Plies(val) => Plies(val-1),
    };
    let mut ans = 0;
    for m in legal::receive_legal(p.clone()).iter() {
        let new_pos = make_move(p.clone(), &m);
        ans += num_from_pos(&new_pos, next_plies);
    }
    ans
}
<|endoftext|>


<commit_before><commit_msg>Add flag removal setter<commit_after><|endoftext|>


<commit_before><commit_msg>Change packer::pack's `entries`'s 0th item from String to &str<commit_after><|endoftext|>


<commit_before><commit_msg>do correction after all checks<commit_after><|endoftext|>


<commit_before><commit_msg>fix: clap_app! should be gated by unstable, not nightly feature<commit_after><|endoftext|>


<commit_before>use runtime::Runtime;
use error::ImagError;
use error::ImagErrorBase;

pub struct ModuleError {
    base: ImagErrorBase,
    module_name: String,
}

impl ModuleError {

    pub fn short<T: Module>(module : &T, short : String) -> ModuleError {
        ModuleError::new(module, short, "".to_string())
    }

    pub fn new<T: Module>(module : &T, short : String, long : String) -> ModuleError {
        ModuleError {
            base: ImagErrorBase {
                shortdesc: short,
                longdesc: long,
            },
            module_name: module.name(),
        }
    }

}

impl<'a> ImagError<'a> for ModuleError {
    fn print(&self, rt: &Runtime) {
        if self.base.longdesc.is_empty() {
            let s = format!("{}: {}\n\n{}\n\n",
                            self.module_name,
                            self.base.shortdesc,
                            self.base.longdesc);
            rt.print(&s)
        } else {
            let s = format!("{}: {}\n",
                            self.module_name,
                            self.base.shortdesc);
            rt.print(&s)
        }
    }

    fn print_short(&self, rt : &Runtime) {
        let s = format!("{}: {}\n", self.module_name, self.base.shortdesc);
        rt.print(&s)
    }

    fn print_long(&self, rt : &Runtime) {
        let s = format!("{}: {}\n\n{}\n\n",
                        self.module_name,
                        self.base.shortdesc,
                        self.base.longdesc);
        rt.print(&s)
    }
}

pub trait Module {

    fn new() -> Self;
    fn load(&self, &rt : Runtime) -> Self;
    fn name(&self) -> String;

    fn execute(&self, &rt : Runtime) -> Option<ModuleError>;

}
<commit_msg>Revert "Add: impl ImagError for ModuleError"<commit_after>use runtime::Runtime;
use error::ImagErrorBase;

pub struct ModuleError {
    base: ImagErrorBase,
    module_name: String,
}

impl ModuleError {

    pub fn short<T: Module>(module : &T, short : String) -> ModuleError {
        ModuleError::new(module, short, "".to_string())
    }

    pub fn new<T: Module>(module : &T, short : String, long : String) -> ModuleError {
        ModuleError {
            base: ImagErrorBase {
                shortdesc: short,
                longdesc: long,
            },
            module_name: module.name(),
        }
    }

}

pub trait Module {

    fn new() -> Self;
    fn load(&self, &rt : Runtime) -> Self;
    fn name(&self) -> String;

    fn execute(&self, &rt : Runtime) -> Option<ModuleError>;

}
<|endoftext|>


<commit_before><commit_msg>No need to tokenize incoming path. Router performance is acceptable now.<commit_after><|endoftext|>


<commit_before><commit_msg>remove unused dependencies<commit_after><|endoftext|>


<commit_before><commit_msg>Implement `IndexMut` for `Vector<T>` (#38)<commit_after><|endoftext|>


<commit_before><commit_msg> Adds Rust solution for #008<commit_after><|endoftext|>


<commit_before><commit_msg>Finished #1 - Safer Count with RWArc<commit_after><|endoftext|>


<commit_before><commit_msg>7 done<commit_after><|endoftext|>


<commit_before><commit_msg>Add test of missing unsafe on extern Rust sig<commit_after>#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn f(x: i32);
    }
}

unsafe fn f(_x: i32) {}

fn main() {}
<|endoftext|>


<commit_before>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

/// MRU - Most Recently Used cache
struct Mru {
    // TODO: keep track of use counts. So mru_map becomes (use_count: u64, Vec<u8>)
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    size: usize, // Max mru cache size in bytes
    used: usize, // Used bytes in mru cache
}

impl Mru {
    pub fn new() -> Self {
        Mru {
            map: BTreeMap::new(),
            queue: VecDeque::new(),
            size: 10,
            used: 0,
        }
    }
}

/// MFU - Most Frequently Used cache
struct Mfu {
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    // TODO: Keep track of minimum frequency and corresponding DVA
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    size: usize, // Max mfu cache size in bytes
    used: usize, // Used bytes in mfu cache
}

impl Mfu {
    pub fn new() -> Self {
        Mfu {
            map: BTreeMap::new(),
            size: 10,
            used: 0,
        }
    }
}

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    // MRU
    // TODO: keep track of use counts. So mru_map becomes (use_count: u64, Vec<u8>)
    mru_map: BTreeMap<DVAddr, Vec<u8>>, // Most recently used cache
    mru_queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    mru_size: usize, // Max mru cache size in blocks
    mru_used: usize, // Number of used blocks in mru cache

    // MFU
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    // TODO: Keep track of minimum frequency and corresponding DVA
    mfu_map: BTreeMap<DVAddr, Vec<u8>>, // Most frequently used cache
    mfu_size: usize, // Max mfu cache size in blocks
    mfu_used: usize, // Number of used bytes in mfu cache
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru_map: BTreeMap::new(),
            mru_queue: VecDeque::new(),
            mru_size: 1000,
            mru_used: 0,

            mfu_map: BTreeMap::new(),
            mfu_size: 1000,
            mfu_used: 0,
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru_map.get(dva) {
            // TODO: Keep track of MRU DVA use count. If it gets used a second time, move the block into
            // the MFU cache.

            // Block is cached
            return Ok(block.clone());
        }
        if let Some(block) = self.mfu_map.get(dva) {
            // TODO: keep track of DVA use count
            // Block is cached
            return Ok(block.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);

        // Blocks start in MRU cache
        self.mru_cache_block(dva, block)
    }

    fn mru_cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String>{
        // If necessary, make room for the block in the cache
        while self.mru_used + (dva.asize() as usize) > self.mru_size {
            let last_dva =
                match self.mru_queue.pop_back()
                {
                    Some(dva) => dva,
                    None => return Err("No more ARC MRU items to free".to_string()),
                };
            self.mru_map.remove(&last_dva);
            self.mru_used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.mru_used += dva.asize() as usize;
        self.mru_map.insert(*dva, block);
        self.mru_queue.push_front(*dva);
        Ok(self.mru_map.get(dva).unwrap().clone())
    }

    // TODO: mfu_cache_block. Remove the DVA with the lowest frequency
}
<commit_msg>Reorganized code with the `Mru` and `Mfu` types<commit_after>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

/// MRU - Most Recently Used cache
struct Mru {
    // TODO: keep track of use counts. So mru_map becomes (use_count: u64, Vec<u8>)
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    size: usize, // Max mru cache size in bytes
    used: usize, // Used bytes in mru cache
}

impl Mru {
    pub fn new() -> Self {
        Mru {
            map: BTreeMap::new(),
            queue: VecDeque::new(),
            size: 1000,
            used: 0,
        }
    }

    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
        // If necessary, make room for the block in the cache
        while self.used + block.len() > self.size {
            let last_dva = match self.queue.pop_back() {
                Some(dva) => dva,
                None => return Err("No more ARC MRU items to free".to_string()),
            };
            self.map.remove(&last_dva);
            self.used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.used += block.len();
        self.map.insert(*dva, (1337, block));
        self.queue.push_front(*dva);
        Ok(self.map.get(dva).unwrap().1.clone())
    }
}

/// MFU - Most Frequently Used cache
struct Mfu {
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    // TODO: Keep track of minimum frequency and corresponding DVA
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    size: usize, // Max mfu cache size in bytes
    used: usize, // Used bytes in mfu cache
}

impl Mfu {
    pub fn new() -> Self {
        Mfu {
            map: BTreeMap::new(),
            size: 1000,
            used: 0,
        }
    }

    // TODO: cache_block. Remove the DVA with the lowest frequency
    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
    }
}

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    mru: Mru,
    mfu: Mfu,
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru: Mru::new(),
            mfu: Mfu::new(),
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru.map.get(dva) {
            // TODO: Keep track of MRU DVA use count. If it gets used a second time, move the block into
            // the MFU cache.

            // Block is cached
            return Ok(block.1.clone());
        }
        if let Some(block) = self.mfu.map.get(dva) {
            // TODO: keep track of DVA use count
            // Block is cached
            return Ok(block.1.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);

        // Blocks start in MRU cache
        self.mru.cache_block(dva, block)
    }
}
<|endoftext|>


<commit_before>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct Editor {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
    /// Number of repeation entered
    pub n: u16,
}

impl Editor {

    /// Execute a instruction n times
    pub fn exec(&mut self, n: u16, cmd: char) {

        match cmd {

        }
    }

    /// Feed a char to the editor (as input)
    fn feed(&mut self, c: char) {
        match self.cursors[self.current_cursor as usize].mode {
            Mode::Primitive(_) => {
                self.exec(0, c);
            },
            Mode::Command(_) => {
                self.n = match c {
                    '0' if self.n != 0 => self.n * 10,
                    '1'           => self.n * 10 + 1,
                    '2'           => self.n * 10 + 2,
                    '3'           => self.n * 10 + 3,
                    '4'           => self.n * 10 + 4,
                    '5'           => self.n * 10 + 5,
                    '6'           => self.n * 10 + 6,
                    '7'           => self.n * 10 + 7,
                    '8'           => self.n * 10 + 8,
                    '9'           => self.n * 10 + 9,
                    _             => {
                        self.exec(if self.n == 0 { 1 } else { self.n }, c);
                        self.n
                    }
                }

            }
        }
    }

    /// Insert text
    fn insert(&mut self, c: char) {

    }

    /// Create new default state editor
    fn new() -> Editor {
        Editor {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
            n: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,

<commit_msg>More refactoring<commit_after>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

#[derive(Clone)]
/// An instruction
pub Inst(i16, char)

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct Editor<I: Iterator<Item = char>> {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
    /// Number of repeation entered
    pub n: u16,
    /// The input iterator
    pub iter: I,
}

impl Editor {

    /// Execute a instruction
    pub fn exec(&mut self, inst: Inst) {

    }

    /// Feed a char to the editor (as input)
    pub fn feed(&mut self, c: char) {
        match self.cursors[self.current_cursor as usize].mode {
            Mode::Primitive(_) => {
                self.exec(Inst(0, c));
            },
            Mode::Command(_) => {
                self.n = match c {
                    '0' if self.n != 0 => self.n * 10,
                    '1'                => self.n * 10 + 1,
                    '2'                => self.n * 10 + 2,
                    '3'                => self.n * 10 + 3,
                    '4'                => self.n * 10 + 4,
                    '5'                => self.n * 10 + 5,
                    '6'                => self.n * 10 + 6,
                    '7'                => self.n * 10 + 7,
                    '8'                => self.n * 10 + 8,
                    '9'                => self.n * 10 + 9,
                    _                  => {
                        self.exec(Inst(if self.n == 0 { 1 } else { self.n },
                                       c));
                        self.n
                    },
                }

            }
        }
    }

    /// Initialize the editor
    pub fn init(&mut self) {
        for c in self.iter {
            self.feed(c);
        }
    }

    /// Insert text
    pub fn insert(&mut self, c: char) {

    }

    /// Create new default state editor
    pub fn new() -> Editor {
        Editor {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
            n: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Inst>,
}
<|endoftext|>


<commit_before><commit_msg>Invalid source code formating Fixed<commit_after><|endoftext|>


<commit_before><commit_msg>Create automata.rs<commit_after>// Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )

//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------

/*#[derive(Debug)]
enum STATE {
    S0,
    S1,
    S2,
}*/

pub mod even_zeros_dfa {

const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";

fn assert_state(state:&'static str,desired:&'static str) -> bool {
    state == desired
}

#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
    let mut state = S0;
    // initializing the dfa to the start state with any symbol
    if s.len() > 0 {state=S1;} else {return false;}
    for i in s.chars() {
        if i=='1' && assert_state(&state,S1)
        {state = S1;}
        else if i=='0' && assert_state(&state,S1)
        {state = S2;}
        else if i=='0' && assert_state(&state,S2)
        {state = S1;}
        else if i=='1' && assert_state(&state,S2)
        {state = S2;}
    }

    // automatic boolean return from match arm
    assert_state(&state,S1)
}

pub fn init_fsm(st:&String) {
     if dfa(st) {println!("Language accepted by the dfa");}
     else {println!("Language not recognized");}
}

#[test]
fn test_dfa() {
    let string = "100".to_string();
    if dfa(&string) {
        println!("Language accepted by the dfa");
    }else {
        println!("Language not recognized");
    }
}

}
<|endoftext|>


<commit_before><commit_msg>add sample<commit_after>extern crate sea_canal;

use sea_canal::analyzer::{Analyze, Analyzer};

fn main() {
    let s = &[1, 4, 3, 6, 5];
    println!("{:?}", s);
    let analyzer = Analyzer::from_seq(s);

    for seq in analyzer.analyze_n(2) {
        println!("{}", seq);
    }

    let s = &[1, 2, 4, 8];
    println!("\n{:?}", s);
    let analyzer = Analyzer::from_seq(s);

    for seq in analyzer.analyze_n(1) {
        println!("{}", seq);
    }

    let s = &[1, 10, 19, 28];
    println!("\n{:?}", s);
    let analyzer = Analyzer::from_seq(s);

    for seq in analyzer.analyze_n(1) {
        println!("{}", seq);
    }
}
<|endoftext|>


<commit_before>#![feature(globs)]
#![feature(macro_rules)]
#![feature(phase)]
#![feature(slicing_syntax)]
#![feature(tuple_indexing)]

#[phase(plugin, link)]
extern crate gl;
extern crate math;
extern crate base;

extern crate libc;
#[phase(plugin, link)]
extern crate log;

pub use render::Renderer;
pub use render::RenderStep;
pub use shader::Shader;
pub use shader::ShaderLoader;
pub use shader::Uniform;
pub use texture::Texture;
pub use vbo::BufferBuilder;
pub use vbo::VertexBuffer;

mod render;
mod shader;
mod texture;
mod vbo;
<commit_msg>tuple_indexing is no longer gated!<commit_after>#![feature(globs, macro_rules, phase, slicing_syntax)]

#[phase(plugin, link)]
extern crate gl;
extern crate math;
extern crate base;

extern crate libc;
#[phase(plugin, link)]
extern crate log;

pub use render::Renderer;
pub use render::RenderStep;
pub use shader::Shader;
pub use shader::ShaderLoader;
pub use shader::Uniform;
pub use texture::Texture;
pub use vbo::BufferBuilder;
pub use vbo::VertexBuffer;

mod render;
mod shader;
mod texture;
mod vbo;
<|endoftext|>


<commit_before><commit_msg>Change a lot.<commit_after><|endoftext|>


<commit_before><commit_msg>Adds Rust Problem 551 in progress<commit_after>/// Problem 551
/// Let a0, a1, a2, ... be an integer sequence defined by:
///
///     a_0 = 1;
///     for n ≥ 1, a_n is the sum of the digits of all preceding terms.
///
/// The sequence starts with 1, 1, 2, 4, 8, 16, 23, 28, 38, 49, ...
/// You are given a_10^6 = 31054319.
///
///  a_10^1 = 62
///  a_10^2 = 1205
///  a_10^3 = 16577
///  a_10^4 = 213677
///  a_10^5 = 2609882
///  a_10^6 = 31054319
///  a_10^7 = 355356611
///  a_10^8 = 4047602471
///  a_10^9 = 45063267434
/// a_10^10 = 500834734271
///
/// Find a_10^15.
fn main() {
    // In essence, the next term is the current term plus the sum of the
    // current term's digits. a_7 = 28, sum of digits = 10, a_8 = 38.
    let mut i: u64 = 1;
    let mut a: u64 = 1;
    // let mut i: u64 = 1000000;
    // let mut a: u64 = 31054319;
    let mut c: u64 = 0;
    let mut pow: u64 = 10;
    loop {
        // if c > 25 {
        //     break
        // }
        // if i == 1000000 {
        // if i == 1000000000000000 {
        if i % pow == 0 {
            println!("a_{} = {}", i, a);
            pow *= 10;
            // break
        }
        // Take sum of digits of current term
        let mut b = a;
        let mut s = b%10;
        while b > 0 {
            b /= 10;
            s += b%10;
        }
        // Increment term
        a += s;
        i += 1;
        c += 1;
    }
}<|endoftext|>


<commit_before><commit_msg>Formatting + remove dead handler code<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![feature(append)]
#![feature(arc_unique)]
#![feature(as_slice)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(drain)]
#![feature(hashmap_hasher)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(owned_ascii_ext)]
#![feature(plugin)]
#![feature(rc_unique)]
#![feature(slice_chars)]
#![feature(str_utf16)]
#![feature(unicode)]
#![feature(vec_push_all)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc="The script crate contains all matters DOM."]

#![plugin(string_cache_plugin)]
#![plugin(plugins)]

#[macro_use]
extern crate log;

#[macro_use] extern crate bitflags;
extern crate core;
extern crate devtools_traits;
extern crate cssparser;
extern crate euclid;
extern crate html5ever;
extern crate encoding;
extern crate fnv;
extern crate hyper;
extern crate ipc_channel;
extern crate js;
extern crate layout_traits;
extern crate libc;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate serde;
extern crate time;
extern crate canvas;
extern crate canvas_traits;
extern crate rand;
#[macro_use]
extern crate profile_traits;
extern crate script_traits;
extern crate selectors;
extern crate smallvec;
extern crate util;
extern crate websocket;
#[macro_use]
extern crate style;
extern crate unicase;
extern crate url;
extern crate uuid;
extern crate string_cache;
extern crate offscreen_gl_context;
extern crate tendril;

pub mod cors;
pub mod document_loader;

#[macro_use]
pub mod dom;

pub mod parse;

pub mod layout_interface;
mod network_listener;
pub mod page;
pub mod script_task;
mod timers;
pub mod textinput;
pub mod clipboard_provider;
mod devtools;
mod horribly_inefficient_timers;
mod webdriver_handlers;

#[allow(unsafe_code)]
pub fn init() {
    unsafe {
        assert_eq!(js::jsapi::JS_Init(), 1);
    }
}
<commit_msg>Auto merge of #6707 - pcwalton:more-fds, r=larsbergstrom<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![feature(append)]
#![feature(arc_unique)]
#![feature(as_slice)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(drain)]
#![feature(hashmap_hasher)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(owned_ascii_ext)]
#![feature(plugin)]
#![feature(rc_unique)]
#![feature(slice_chars)]
#![feature(str_utf16)]
#![feature(unicode)]
#![feature(vec_push_all)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc="The script crate contains all matters DOM."]

#![plugin(string_cache_plugin)]
#![plugin(plugins)]

#[macro_use]
extern crate log;

#[macro_use] extern crate bitflags;
extern crate core;
extern crate devtools_traits;
extern crate cssparser;
extern crate euclid;
extern crate html5ever;
extern crate encoding;
extern crate fnv;
extern crate hyper;
extern crate ipc_channel;
extern crate js;
extern crate layout_traits;
extern crate libc;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate rustc_serialize;
extern crate rustc_unicode;
extern crate serde;
extern crate time;
extern crate canvas;
extern crate canvas_traits;
extern crate rand;
#[macro_use]
extern crate profile_traits;
extern crate script_traits;
extern crate selectors;
extern crate smallvec;
extern crate util;
extern crate websocket;
#[macro_use]
extern crate style;
extern crate unicase;
extern crate url;
extern crate uuid;
extern crate string_cache;
extern crate offscreen_gl_context;
extern crate tendril;

pub mod cors;
pub mod document_loader;

#[macro_use]
pub mod dom;

pub mod parse;

pub mod layout_interface;
mod network_listener;
pub mod page;
pub mod script_task;
mod timers;
pub mod textinput;
pub mod clipboard_provider;
mod devtools;
mod horribly_inefficient_timers;
mod webdriver_handlers;

#[cfg(any(target_os="linux", target_os="android"))]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
    use std::mem;
    const RLIMIT_NOFILE: libc::c_int = 7;

    // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
    // of iframes.
    unsafe {
        let mut rlim = mem::uninitialized();
        assert!(libc::getrlimit(RLIMIT_NOFILE, &mut rlim) == 0);
        rlim.rlim_cur = rlim.rlim_max;
        assert!(libc::setrlimit(RLIMIT_NOFILE, &mut rlim) == 0);
    }
}

#[cfg(not(any(target_os="linux", target_os="android")))]
fn perform_platform_specific_initialization() {}

#[allow(unsafe_code)]
pub fn init() {
    unsafe {
        assert_eq!(js::jsapi::JS_Init(), 1);
    }

    perform_platform_specific_initialization();
}

<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>Fix typo: WithField is WithFields<commit_after><|endoftext|>


<commit_before><commit_msg>Init from a func return value<commit_after><|endoftext|>


<commit_before><commit_msg>Added very basic example of bindings working<commit_after>extern crate celix;

fn main() {
    println!("{}", celix::CELIX_SUCCESS);
}
<|endoftext|>


<commit_before><commit_msg>More doc!<commit_after><|endoftext|>


<commit_before><commit_msg>Use Vec::from_raw_parts<commit_after><|endoftext|>


<commit_before><commit_msg>added unary scope<commit_after>use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;

use progress::count_map::CountMap;
use progress::notificator::Notificator;
use progress::{Timestamp, Scope, Antichain};
use communication::channels::Data;
use communication::exchange::ExchangeReceiver;
use communication::channels::{OutputPort, ObserverHelper};

pub struct UnaryScopeHandle<T: Timestamp, D1: Data, D2: Data> {
    pub input:          ExchangeReceiver<T, D1>,
    pub output:         ObserverHelper<OutputPort<T, D2>>,
    pub notificator:    Notificator<T>,
}

pub struct UnaryScope<T: Timestamp, D1: Data, D2: Data, L: FnMut(&mut UnaryScopeHandle<T, D1, D2>)> {
    handle:         UnaryScopeHandle<T, D1, D2>,
    logic:          L,
}

impl<T: Timestamp, D1: Data, D2: Data, L: FnMut(&mut UnaryScopeHandle<T, D1, D2>)> UnaryScope<T, D1, D2, L> {
    pub fn new(receiver: ExchangeReceiver<T, D1>, targets: OutputPort<T, D2>, logic: L) -> UnaryScope<T, D1, D2, L> {
        UnaryScope {
            handle: UnaryScopeHandle {
                input: receiver,
                output: ObserverHelper::new(targets.clone(), Rc::new(RefCell::new(CountMap::new()))),
                notificator: Default::default(),
            },
            logic: logic,
        }
    }
}

impl<T: Timestamp, D1: Data, D2: Data, L: FnMut(&mut UnaryScopeHandle<T, D1, D2>)> Scope<T> for UnaryScope<T, D1, D2, L> {
    fn inputs(&self) -> u64 { 1 }
    fn outputs(&self) -> u64 { 1 }

    fn set_external_summary(&mut self, _summaries: Vec<Vec<Antichain<T::Summary>>>, frontier: &mut Vec<CountMap<T>>) -> () {
        self.handle.notificator.update_frontier_from_cm(&mut frontier[0]);
        frontier[0].clear();
    }

    fn push_external_progress(&mut self, external: &mut Vec<CountMap<T>>) -> () {
        // println!("unary.pep: {:?}", external);
        self.handle.notificator.update_frontier_from_cm(&mut external[0]);
        external[0].clear();
    }

    fn pull_internal_progress(&mut self, internal: &mut Vec<CountMap<T>>,
                                         consumed: &mut Vec<CountMap<T>>,
                                         produced: &mut Vec<CountMap<T>>) -> bool
    {
        (self.logic)(&mut self.handle);

        // extract what we know about progress from the input and output adapters.
        self.handle.input.pull_progress(&mut consumed[0]);
        self.handle.output.pull_progress(&mut produced[0]);
        self.handle.notificator.pull_progress(&mut internal[0]);

        return false;   // no unannounced internal work
    }

    fn name(&self) -> String { format!("Unary") }
    fn notify_me(&self) -> bool { true }
}
<|endoftext|>


<commit_before>use std::path::Path;
use sdl2::{self};
use sdl2_image::{self, LoadTexture, INIT_PNG, INIT_JPG};
use sdl2::event::Event;
use sdl2::keycode::KeyCode;

pub fn main(png: &Path) {

    let mut context = sdl2::init().video().unwrap();
    sdl2_image::init(INIT_PNG | INIT_JPG);
    let window = context.window("rust-sdl2 demo: Video", 800, 600)
      .position_centered()
      .opengl()
      .build()
      .unwrap();

    let mut renderer = window.renderer().accelerated().build().unwrap();
    let mut texture = renderer.load_texture(png).unwrap();

    // Draws and shows the loaded texture.
    let mut drawer = renderer.drawer();
    drawer.copy(&mut texture, None, None);
    drawer.present();

    'mainloop: loop {
        for event in context.event_pump().poll_iter() {
            match event {
                Event::Quit{..} |
                Event::KeyDown {keycode: KeyCode::Escape, ..} =>
                    break 'mainloop,
                _ => {}
            }
        }
    }

    sdl2_image::quit();
}
<commit_msg>fix 'use'<commit_after>use std::path::Path;
use sdl2;
use sdl2_image::{self, LoadTexture, INIT_PNG, INIT_JPG};
use sdl2::event::Event;
use sdl2::keycode::KeyCode;

pub fn main(png: &Path) {

    let mut context = sdl2::init().video().unwrap();
    sdl2_image::init(INIT_PNG | INIT_JPG);
    let window = context.window("rust-sdl2 demo: Video", 800, 600)
      .position_centered()
      .opengl()
      .build()
      .unwrap();

    let mut renderer = window.renderer().accelerated().build().unwrap();
    let mut texture = renderer.load_texture(png).unwrap();

    // Draws and shows the loaded texture.
    let mut drawer = renderer.drawer();
    drawer.copy(&mut texture, None, None);
    drawer.present();

    'mainloop: loop {
        for event in context.event_pump().poll_iter() {
            match event {
                Event::Quit{..} |
                Event::KeyDown {keycode: KeyCode::Escape, ..} =>
                    break 'mainloop,
                _ => {}
            }
        }
    }

    sdl2_image::quit();
}
<|endoftext|>


<commit_before><commit_msg>Add make_exp method to GroupCurve25519<commit_after><|endoftext|>


<commit_before><commit_msg>Started work on number_dialer module<commit_after>
use std::from_str::FromStr;
use opengl_graphics::Gl;
use piston::{
    RenderArgs,
};
use color::Color;
use point::Point;
use rectangle;
use rectangle::RectangleState;
use widget::{
    Widget,
    NumberDialer,
};
use ui_context::{
    UIID,
    UIContext,
};
use mouse_state::{
    MouseState,
    Up,
    Down,
};
use label;
use label::{
    FontSize,
    IsLabel,
    NoLabel,
    Label,
};
use utils::clamp;

widget_state!(NumberDialerState, NumberDialerState {
    Normal -> 0,
    Highlighted -> 1,
    Clicked -> 2
})

impl NumberDialerState {
    /// Return the associated Rectangle state.
    fn as_rectangle_state(&self) -> RectangleState {
        match self {
            &Normal => rectangle::Normal,
            &Highlighted => rectangle::Highlighted,
            &Clicked => rectangle::Clicked,
        }
    }
}

/// Draw the number_dialer. When successfully pressed,
/// or if the value is changed, the given `callback`
/// function will be called.
pub fn draw<T: Num + Copy + Primitive + FromPrimitive + ToPrimitive + ToString + FromStr>
    (args: &RenderArgs,
     gl: &mut Gl,
     uic: &mut UIContext,
     ui_id: UIID,
     pos: Point<f64>,
     font_size: FontSize,
     color: Color,
     label: IsLabel,
     value: T,
     min: T,
     max: T,
     precision: u8,
     callback: |T|) {
    let val = clamp(value, min, max);
    let state = get_state(uic, ui_id);
    let mouse = uic.get_mouse_state();
    let string = create_string(&label, val, precision);
    //println!("{}", string.as_slice());

    // TODO
    // determine rect dimensions.
    // draw rect.
    // draw string.
    // if being interacted with, determine which glyph captures the mouse.
    // determine new value by comparing previous state with new state.
}

/// Create the string to be drawn from the given values
/// and precision. Combine this with the label string if
/// one is given.
fn create_string<T: ToString>(label: &IsLabel, val: T, precision: u8) -> String {
    let label_string = match *label {
        NoLabel => String::new(),
        Label(ref text, _, _) => text.to_string().append(": "),
    };
    let mut val_string = val.to_string();
    match (val_string.as_slice().chars().position(|ch| ch == '.'), precision) {
        (None, 0u8) => label_string.append(val_string.as_slice()),
        (None, _) => {
            val_string.push_char('.');
            val_string.grow(precision as uint, '0');
            label_string.append(val_string.as_slice())
        },
        (Some(idx), 0u8) => {
            val_string.truncate(idx);
            label_string.append(val_string.as_slice())
        },
        (Some(idx), _) => {
            let (len, desired_len) = (val_string.len(), idx + precision as uint + 1u);
            match len.cmp(&desired_len) {
                Greater => val_string.truncate(desired_len),
                Equal => (),
                Less => val_string.grow(desired_len - len, '0'),
            }
            label_string.append(val_string.as_slice())
        },
    }
}

/// Return a default Widget variant.
fn default() -> Widget { NumberDialer(Normal) }

/// Get a reference to the widget associated with the given UIID.
fn get_widget(uic: &mut UIContext, ui_id: UIID) -> &mut Widget {
    uic.get_widget(ui_id, default())
}

/// Get the current SliderState for the widget.
fn get_state(uic: &mut UIContext, ui_id: UIID) -> NumberDialerState {
    match *get_widget(uic, ui_id) {
        NumberDialer(state) => state,
        _ => fail!("The Widget variant returned by UIContext is different to the requested."),
    }
}

/// Set the state for the widget in the UIContext.
fn set_state(uic: &mut UIContext, ui_id: UIID, new_state: NumberDialerState) {
    match *get_widget(uic, ui_id) {
        NumberDialer(ref mut state) => { *state = new_state; },
        _ => fail!("The Widget variant returned by UIContext is different to the requested."),
    }
}

<|endoftext|>


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

// Ruby -> Toml translation primitives

use std::collections::BTreeMap;

use ruru::{Object, AnyObject, Class, RString, Fixnum, Float, Symbol, Hash, Array, VM};
use ruru::types::ValueType;
use toml::Value;

pub trait AsToml : Sized {
    fn as_toml(&self) -> Value;
}

pub trait IntoToml : AsToml {
    fn into_toml(self) -> Value {
        self.as_toml()
    }
}
impl<T: AsToml> IntoToml for T { }

impl AsToml for AnyObject {

    fn as_toml(&self) -> Value {
        match self.value().ty() {
             ValueType::None => {
                 Value::Boolean(false)
             },
             ValueType::Object => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Class => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Module => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Float =>
                        Value::Float(self.try_convert_to::<Float>().unwrap().to_f64()),
             ValueType::RString =>
                        Value::String(self.try_convert_to::<RString>().unwrap().to_string()),
             ValueType::Regexp => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Array => {
                let vals = self
                    .try_convert_to::<Array>()
                    .unwrap()
                    .into_iter()
                    .map(|v| v.as_toml())
                    .collect::<Vec<Value>>();

                Value::Array(vals)
             },
             ValueType::Hash => {
                let mut btm = BTreeMap::new();
                self.try_convert_to::<Hash>()
                    .unwrap()
                    .each(|key, value| {
                        let key = match key.as_toml() {
                            Value::String(s) => s,
                            _ => {
                                let rte = Class::from_existing("TypeError");
                                VM::raise(rte, "Can only have String or Symbol as Key for TOML maps");
                                String::new()
                            }
                        };
                        let value = value.as_toml();
                        btm.insert(key, value);
                    });
                Value::Table(btm)
             },
             ValueType::Struct => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Bignum => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::File => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Data => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Match => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Complex => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Rational => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Nil => Value::Boolean(false),
             ValueType::True => Value::Boolean(true),
             ValueType::False => Value::Boolean(false),
             ValueType::Symbol => Value::String(self.try_convert_to::<Symbol>().unwrap().to_string()),
             ValueType::Fixnum => Value::Integer(self.try_convert_to::<Fixnum>().unwrap().to_i64()),
             ValueType::Undef => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Node => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::IClass => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Zombie => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Mask => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
        }
    }

}

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

// Ruby -> Toml translation primitives

use std::collections::BTreeMap;

use ruru::{Object, AnyObject, Class, RString, Fixnum, Float, Symbol, Hash, Array, VM};
use ruru::types::ValueType;
use toml::Value;

pub trait AsToml : Sized {
    fn as_toml(&self) -> Value;
}

pub trait IntoToml : AsToml {
    fn into_toml(self) -> Value {
        self.as_toml()
    }
}
impl<T: AsToml> IntoToml for T { }

impl AsToml for AnyObject {

    fn as_toml(&self) -> Value {
        match self.value().ty() {
             ValueType::None => {
                 Value::Boolean(false)
             },
             ValueType::Object => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Class => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Module => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Float => self.try_convert_to::<Float>().unwrap().as_toml(),
             ValueType::RString => self.try_convert_to::<RString>().unwrap().as_toml(),
             ValueType::Regexp => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Array => self.try_convert_to::<Array>().unwrap().as_toml(),
             ValueType::Hash  => self.try_convert_to::<Hash>().unwrap().as_toml(),
             ValueType::Struct => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Bignum => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::File => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Data => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Match => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Complex => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Rational => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Nil => Value::Boolean(false),
             ValueType::True => Value::Boolean(true),
             ValueType::False => Value::Boolean(false),
             ValueType::Symbol => self.try_convert_to::<Symbol>().unwrap().as_toml(),
             ValueType::Fixnum => self.try_convert_to::<Fixnum>().unwrap().as_toml(),
             ValueType::Undef => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Node => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::IClass => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Zombie => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
             ValueType::Mask => {
                 let rte = Class::from_existing("TypeError");
                 VM::raise(rte, "Cannot translate type '' to fit into TOML");
                 Value::Boolean(false)
             },
        }
    }

}

impl AsToml for Hash {

    fn as_toml(&self) -> Value {
        let mut btm = BTreeMap::new();
        self.try_convert_to::<Hash>()
            .unwrap()
            .each(|key, value| {
                let key = match key.as_toml() {
                    Value::String(s) => s,
                    _ => {
                        let rte = Class::from_existing("TypeError");
                        VM::raise(rte, "Can only have String or Symbol as Key for TOML maps");
                        String::new()
                    }
                };
                let value = value.as_toml();
                btm.insert(key, value);
            });
        Value::Table(btm)
    }

}

impl AsToml for Array {

    fn as_toml(&self) -> Value {
        let vals = self
            .try_convert_to::<Array>()
            .unwrap()
            .into_iter()
            .map(|v| v.as_toml())
            .collect::<Vec<Value>>();

        Value::Array(vals)
    }

}

impl AsToml for RString {

    fn as_toml(&self) -> Value {
        Value::String(self.try_convert_to::<RString>().unwrap().to_string())
    }

}

impl AsToml for Float {

    fn as_toml(&self) -> Value {
        Value::Float(self.try_convert_to::<Float>().unwrap().to_f64())
    }

}

impl AsToml for Symbol {

    fn as_toml(&self) -> Value {
        Value::String(self.try_convert_to::<Symbol>().unwrap().to_string())
    }

}

impl AsToml for Fixnum {

    fn as_toml(&self) -> Value {
        Value::Integer(self.try_convert_to::<Fixnum>().unwrap().to_i64())
    }

}

<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::activation::Activatable;
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast};
use dom::bindings::codegen::InheritTypes::{MouseEventCast, NodeCast};
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::document::{Document, DocumentHelpers};
use dom::domtokenlist::DOMTokenList;
use dom::element::{Element, AttributeHandlers, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;

use num::ToPrimitive;
use std::default::Default;
use string_cache::Atom;
use util::str::DOMString;

#[dom_struct]
pub struct HTMLAnchorElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableHeap<JS<DOMTokenList>>,
}

impl HTMLAnchorElementDerived for EventTarget {
    fn is_htmlanchorelement(&self) -> bool {
        *self.type_id() ==
            EventTargetTypeId::Node(
                NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)))
    }
}

impl HTMLAnchorElement {
    fn new_inherited(localName: DOMString,
                     prefix: Option<DOMString>,
                     document: &Document) -> HTMLAnchorElement {
        HTMLAnchorElement {
            htmlelement:
                HTMLElement::new_inherited(HTMLElementTypeId::HTMLAnchorElement, localName, prefix, document),
            rel_list: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString,
               prefix: Option<DOMString>,
               document: &Document) -> Root<HTMLAnchorElement> {
        let element = HTMLAnchorElement::new_inherited(localName, prefix, document);
        Node::reflect_node(box element, document, HTMLAnchorElementBinding::Wrap)
    }
}

impl<'a> VirtualMethods for &'a HTMLAnchorElement {
    fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
        let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
        Some(htmlelement as &VirtualMethods)
    }

    fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
        match name {
            &atom!("rel") => AttrValue::from_serialized_tokenlist(value),
            _ => self.super_type().unwrap().parse_plain_attribute(name, value),
        }
    }
}

impl<'a> HTMLAnchorElementMethods for &'a HTMLAnchorElement {
    fn Text(self) -> DOMString {
        let node = NodeCast::from_ref(self);
        node.GetTextContent().unwrap()
    }

    fn SetText(self, value: DOMString) {
        let node = NodeCast::from_ref(self);
        node.SetTextContent(Some(value))
    }

    fn RelList(self) -> Root<DOMTokenList> {
        self.rel_list.or_init(|| {
            DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel"))
        })
    }
}

impl<'a> Activatable for &'a HTMLAnchorElement {
    fn as_element<'b>(&'b self) -> &'b Element {
        ElementCast::from_ref(*self)
    }

    fn is_instance_activatable(&self) -> bool {
        true
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn pre_click_activation(&self) {
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
    fn canceled_activation(&self) {
    }

    //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour
    fn activation_behavior(&self, event: &Event, target: &EventTarget) {
        //Step 1. If the node document is not fully active, abort.
        let doc = document_from_node(*self);
        if !doc.r().is_fully_active() {
            return;
        }
        //TODO: Step 2. Check if browsing context is specified and act accordingly.
        //Step 3. Handle <img ismap/>.
        let element = ElementCast::from_ref(*self);
        let mouse_event = MouseEventCast::to_ref(event).unwrap();
        let mut ismap_suffix = None;
        if let Some(element) = ElementCast::to_ref(target) {
            if target.is_htmlimageelement() && element.has_attribute(&atom!("ismap")) {

                let target_node = NodeCast::to_ref(target).unwrap();
                let rect = window_from_node(target_node).r().content_box_query(
                    target_node.to_trusted_node_address());
                ismap_suffix = Some(
                    format!("?{},{}", mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
                                      mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px())
                )
            }
        }

        //TODO: Step 4. Download the link is `download` attribute is set.

        let attr = element.get_attribute(&ns!(""), &atom!("href"));
        match attr {
            Some(ref href) => {
                let value = href.r().Value() + ismap_suffix.as_ref().map(|s| &**s).unwrap_or("");
                debug!("clicked on link to {}", value);
                doc.r().load_anchor_href(value);
            }
            None => ()
        }
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) {
    }
}
<commit_msg>Remove an avoidable null-check from HTMLAnchorElement::activation_behavior.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::activation::Activatable;
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding;
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast};
use dom::bindings::codegen::InheritTypes::{MouseEventCast, NodeCast};
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::document::{Document, DocumentHelpers};
use dom::domtokenlist::DOMTokenList;
use dom::element::{Element, AttributeHandlers, ElementTypeId};
use dom::event::Event;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;

use num::ToPrimitive;
use std::default::Default;
use string_cache::Atom;
use util::str::DOMString;

#[dom_struct]
pub struct HTMLAnchorElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableHeap<JS<DOMTokenList>>,
}

impl HTMLAnchorElementDerived for EventTarget {
    fn is_htmlanchorelement(&self) -> bool {
        *self.type_id() ==
            EventTargetTypeId::Node(
                NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)))
    }
}

impl HTMLAnchorElement {
    fn new_inherited(localName: DOMString,
                     prefix: Option<DOMString>,
                     document: &Document) -> HTMLAnchorElement {
        HTMLAnchorElement {
            htmlelement:
                HTMLElement::new_inherited(HTMLElementTypeId::HTMLAnchorElement, localName, prefix, document),
            rel_list: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString,
               prefix: Option<DOMString>,
               document: &Document) -> Root<HTMLAnchorElement> {
        let element = HTMLAnchorElement::new_inherited(localName, prefix, document);
        Node::reflect_node(box element, document, HTMLAnchorElementBinding::Wrap)
    }
}

impl<'a> VirtualMethods for &'a HTMLAnchorElement {
    fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
        let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
        Some(htmlelement as &VirtualMethods)
    }

    fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
        match name {
            &atom!("rel") => AttrValue::from_serialized_tokenlist(value),
            _ => self.super_type().unwrap().parse_plain_attribute(name, value),
        }
    }
}

impl<'a> HTMLAnchorElementMethods for &'a HTMLAnchorElement {
    fn Text(self) -> DOMString {
        let node = NodeCast::from_ref(self);
        node.GetTextContent().unwrap()
    }

    fn SetText(self, value: DOMString) {
        let node = NodeCast::from_ref(self);
        node.SetTextContent(Some(value))
    }

    fn RelList(self) -> Root<DOMTokenList> {
        self.rel_list.or_init(|| {
            DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel"))
        })
    }
}

impl<'a> Activatable for &'a HTMLAnchorElement {
    fn as_element<'b>(&'b self) -> &'b Element {
        ElementCast::from_ref(*self)
    }

    fn is_instance_activatable(&self) -> bool {
        true
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn pre_click_activation(&self) {
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
    fn canceled_activation(&self) {
    }

    //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour
    fn activation_behavior(&self, event: &Event, target: &EventTarget) {
        //Step 1. If the node document is not fully active, abort.
        let doc = document_from_node(*self);
        if !doc.r().is_fully_active() {
            return;
        }
        //TODO: Step 2. Check if browsing context is specified and act accordingly.
        //Step 3. Handle <img ismap/>.
        let element = ElementCast::from_ref(*self);
        let mouse_event = MouseEventCast::to_ref(event).unwrap();
        let mut ismap_suffix = None;
        if let Some(element) = ElementCast::to_ref(target) {
            if target.is_htmlimageelement() && element.has_attribute(&atom!("ismap")) {

                let target_node = NodeCast::from_ref(element);
                let rect = window_from_node(target_node).r().content_box_query(
                    target_node.to_trusted_node_address());
                ismap_suffix = Some(
                    format!("?{},{}", mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
                                      mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px())
                )
            }
        }

        //TODO: Step 4. Download the link is `download` attribute is set.

        let attr = element.get_attribute(&ns!(""), &atom!("href"));
        match attr {
            Some(ref href) => {
                let value = href.r().Value() + ismap_suffix.as_ref().map(|s| &**s).unwrap_or("");
                debug!("clicked on link to {}", value);
                doc.r().load_anchor_href(value);
            }
            None => ()
        }
    }

    //TODO:https://html.spec.whatwg.org/multipage/#the-a-element
    fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) {
    }
}
<|endoftext|>


<commit_before><commit_msg>Improves report display<commit_after><|endoftext|>