<commit_before>use types::{
    ValidatorRecord,
    ValidatorStatus,
};

use super::proof_of_possession::verify_proof_of_possession;
use super::registration::ValidatorRegistration;

/// The size of a validators deposit in GWei.
pub const DEPOSIT_GWEI: u64 = 32_000_000_000;

/// Inducts validators into a `CrystallizedState`.
pub struct ValidatorInductor<'a> {
    pub current_slot: u64,
    pub shard_count: u16,
    validators: &'a mut Vec<ValidatorRecord>,
    empty_validator_start: usize,
}

#[derive(Debug, PartialEq, Clone)]
pub enum ValidatorInductionError {
    InvalidShard,
    InvaidProofOfPossession,
}

impl<'a> ValidatorInductor<'a> {
    pub fn new(current_slot: u64, shard_count: u16, validators: &'a mut Vec<ValidatorRecord>)
        -> Self
    {
        Self {
            current_slot,
            shard_count,
            validators,
            empty_validator_start: 0,
        }
    }

    /// Attempt to induct a validator into the CrystallizedState.
    ///
    /// Returns an error if the registration is invalid, otherwise returns the index of the
    /// validator in `CrystallizedState.validators`.
    pub fn induct(&mut self, rego: &ValidatorRegistration)
        -> Result<usize, ValidatorInductionError>
    {
        let v = self.process_registration(rego)?;
        Ok(self.add_validator(v))
    }

    /// Verify a `ValidatorRegistration` and return a `ValidatorRecord` if valid.
    fn process_registration(&self, r: &ValidatorRegistration)
        -> Result<ValidatorRecord, ValidatorInductionError>
    {
        /*
         * Ensure withdrawal shard is not too high.
         */
        if r.withdrawal_shard > self.shard_count {
            return Err(ValidatorInductionError::InvalidShard)
        }

        /*
         * Prove validator has knowledge of their secret key.
         */
        if !verify_proof_of_possession(&r.proof_of_possession, &r.pubkey) {
            return Err(ValidatorInductionError::InvaidProofOfPossession)
        }

        Ok(ValidatorRecord {
            pubkey: r.pubkey.clone(),
            withdrawal_shard: r.withdrawal_shard,
            withdrawal_address: r.withdrawal_address,
            randao_commitment: r.randao_commitment,
            randao_last_change: self.current_slot,
            balance: DEPOSIT_GWEI,
            status: ValidatorStatus::PendingActivation as u8,
            exit_slot: 0,
        })
    }

    /// Returns the index of the first `ValidatorRecord` in the `CrystallizedState` where
    /// `validator.status == Withdrawn`. If no such record exists, `None` is returned.
    fn first_withdrawn_validator(&mut self)
        -> Option<usize>
    {
        for i in self.empty_validator_start..self.validators.len() {
            if self.validators[i].status == ValidatorStatus::Withdrawn as u8 {
                self.empty_validator_start = i + 1;
                return Some(i)
            }
        }
        None
    }

    /// Adds a `ValidatorRecord` to the `CrystallizedState` by replacing first validator where
    /// `validator.status == Withdraw`. If no such withdrawn validator exists, adds the new
    /// validator to the end of the list.
    fn add_validator(&mut self, v: ValidatorRecord)
        -> usize
    {
        match self.first_withdrawn_validator() {
            Some(i) => {
                self.validators[i] = v;
                i
            }
            None => {
                self.validators.push(v);
                self.validators.len() - 1
            }
        }
    }

    fn to_ref(self)
        -> &'a Vec<ValidatorRecord>
    {
        self.validators
    }
}

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

    use bls::{
        Keypair,
        Signature,
    };
    use types::{
        Address,
        Hash256,
    };
    use hashing::proof_of_possession_hash;

    /// Generate a proof of possession for some keypair.
    fn get_proof_of_possession(kp: &Keypair) -> Signature {
        let pop_message = proof_of_possession_hash(&kp.pk.as_bytes());
        Signature::new_hashed(&pop_message, &kp.sk)
    }

    /// Generate a basic working ValidatorRegistration for use in tests.
    fn get_registration() -> ValidatorRegistration {
        let kp = Keypair::random();
        ValidatorRegistration {
            pubkey: kp.pk.clone(),
            withdrawal_shard: 0,
            withdrawal_address: Address::zero(),
            randao_commitment: Hash256::zero(),
            proof_of_possession: get_proof_of_possession(&kp),
        }
    }

    /// Induct a validator using the ValidatorInductor, return the result.
    fn do_induction(validator_rego: &ValidatorRegistration,
                    validators: &mut Vec<ValidatorRecord>,
                    current_slot: u64,
                    shard_count: u16)
        -> Result<usize, ValidatorInductionError>
    {
        let mut inductor = ValidatorInductor::new(
            current_slot,
            shard_count,
            validators);
        inductor.induct(&validator_rego)
    }

    #[test]
    fn test_validator_inductor_valid_empty_validators() {
        let mut validators = vec![];

        let r = get_registration();

        let result = do_induction(&r, &mut validators, 0, 1024);

        assert_eq!(result.unwrap(), 0);
        assert_eq!(r, validators[0]);
        assert_eq!(validators.len(), 1);
    }

    #[test]
    fn test_validator_inductor_valid_all_active_validators() {
        let mut validators = vec![];
        for _ in 0..5 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Active as u8;
            validators.push(v);
        }

        let r = get_registration();

        let result = do_induction(&r, &mut validators, 0, 1024);

        assert_eq!(result.unwrap(), 5);
        assert_eq!(r, validators[5]);
        assert_eq!(validators.len(), 6);
    }

    #[test]
    fn test_validator_inductor_valid_all_second_validator_withdrawn() {
        let mut validators = vec![];
        let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
        v.status = ValidatorStatus::Active as u8;
        validators.push(v);
        for _ in 0..4 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Withdrawn as u8;
            validators.push(v);
        }

        let r = get_registration();

        let result = do_induction(&r, &mut validators, 0, 1024);

        assert_eq!(result.unwrap(), 1);
        assert_eq!(r, validators[1]);
        assert_eq!(validators.len(), 5);
    }

    #[test]
    fn test_validator_inductor_valid_all_withdrawn_validators() {
        let mut validators = vec![];
        for _ in 0..5 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Withdrawn as u8;
            validators.push(v);
        }

        /*
         * Ensure the first validator gets the 0'th slot
         */
        let r = get_registration();
        let result = do_induction(&r, &mut validators, 0, 1024);
        assert_eq!(result.unwrap(), 0);
        assert_eq!(r, validators[0]);
        assert_eq!(validators.len(), 5);

        /*
         * Ensure the second validator gets the 1'st slot
         */
        let r_two = get_registration();
        let result = do_induction(&r_two, &mut validators, 0, 1024);
        assert_eq!(result.unwrap(), 1);
        assert_eq!(r_two, validators[1]);
        assert_eq!(validators.len(), 5);
    }

    #[test]
    fn test_validator_inductor_shard_too_high() {
        let mut validators = vec![];

        let mut r = get_registration();
        r.withdrawal_shard = 1025;

        let result = do_induction(&r, &mut validators, 0, 1024);

        assert_eq!(result, Err(ValidatorInductionError::InvalidShard));
        assert_eq!(validators.len(), 0);
    }

    #[test]
    fn test_validator_inductor_shard_proof_of_possession_failure() {
        let mut validators = vec![];

        let mut r = get_registration();
        let kp = Keypair::random();
        r.proof_of_possession = get_proof_of_possession(&kp);

        let result = do_induction(&r, &mut validators, 0, 1024);

        assert_eq!(result, Err(ValidatorInductionError::InvaidProofOfPossession));
        assert_eq!(validators.len(), 0);
    }
}
<commit_msg>Change ValidatorInductor to own instead of borrow<commit_after>use types::{
    ValidatorRecord,
    ValidatorStatus,
};

use super::proof_of_possession::verify_proof_of_possession;
use super::registration::ValidatorRegistration;

/// The size of a validators deposit in GWei.
pub const DEPOSIT_GWEI: u64 = 32_000_000_000;

/// Inducts validators into a `CrystallizedState`.
pub struct ValidatorInductor {
    pub current_slot: u64,
    pub shard_count: u16,
    validators: Vec<ValidatorRecord>,
    empty_validator_start: usize,
}

#[derive(Debug, PartialEq, Clone)]
pub enum ValidatorInductionError {
    InvalidShard,
    InvaidProofOfPossession,
}

impl ValidatorInductor {
    pub fn new(current_slot: u64, shard_count: u16, validators: Vec<ValidatorRecord>)
        -> Self
    {
        Self {
            current_slot,
            shard_count,
            validators,
            empty_validator_start: 0,
        }
    }

    /// Attempt to induct a validator into the CrystallizedState.
    ///
    /// Returns an error if the registration is invalid, otherwise returns the index of the
    /// validator in `CrystallizedState.validators`.
    pub fn induct(&mut self, rego: &ValidatorRegistration)
        -> Result<usize, ValidatorInductionError>
    {
        let v = self.process_registration(rego)?;
        Ok(self.add_validator(v))
    }

    /// Verify a `ValidatorRegistration` and return a `ValidatorRecord` if valid.
    fn process_registration(&self, r: &ValidatorRegistration)
        -> Result<ValidatorRecord, ValidatorInductionError>
    {
        /*
         * Ensure withdrawal shard is not too high.
         */
        if r.withdrawal_shard > self.shard_count {
            return Err(ValidatorInductionError::InvalidShard)
        }

        /*
         * Prove validator has knowledge of their secret key.
         */
        if !verify_proof_of_possession(&r.proof_of_possession, &r.pubkey) {
            return Err(ValidatorInductionError::InvaidProofOfPossession)
        }

        Ok(ValidatorRecord {
            pubkey: r.pubkey.clone(),
            withdrawal_shard: r.withdrawal_shard,
            withdrawal_address: r.withdrawal_address,
            randao_commitment: r.randao_commitment,
            randao_last_change: self.current_slot,
            balance: DEPOSIT_GWEI,
            status: ValidatorStatus::PendingActivation as u8,
            exit_slot: 0,
        })
    }

    /// Returns the index of the first `ValidatorRecord` in the `CrystallizedState` where
    /// `validator.status == Withdrawn`. If no such record exists, `None` is returned.
    fn first_withdrawn_validator(&mut self)
        -> Option<usize>
    {
        for i in self.empty_validator_start..self.validators.len() {
            if self.validators[i].status == ValidatorStatus::Withdrawn as u8 {
                self.empty_validator_start = i + 1;
                return Some(i)
            }
        }
        None
    }

    /// Adds a `ValidatorRecord` to the `CrystallizedState` by replacing first validator where
    /// `validator.status == Withdraw`. If no such withdrawn validator exists, adds the new
    /// validator to the end of the list.
    fn add_validator(&mut self, v: ValidatorRecord)
        -> usize
    {
        match self.first_withdrawn_validator() {
            Some(i) => {
                self.validators[i] = v;
                i
            }
            None => {
                self.validators.push(v);
                self.validators.len() - 1
            }
        }
    }

    pub fn to_vec(self)
        -> Vec<ValidatorRecord>
    {
        self.validators
    }
}

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

    use bls::{
        Keypair,
        Signature,
    };
    use types::{
        Address,
        Hash256,
    };
    use hashing::proof_of_possession_hash;

    /// Generate a proof of possession for some keypair.
    fn get_proof_of_possession(kp: &Keypair) -> Signature {
        let pop_message = proof_of_possession_hash(&kp.pk.as_bytes());
        Signature::new_hashed(&pop_message, &kp.sk)
    }

    /// Generate a basic working ValidatorRegistration for use in tests.
    fn get_registration() -> ValidatorRegistration {
        let kp = Keypair::random();
        ValidatorRegistration {
            pubkey: kp.pk.clone(),
            withdrawal_shard: 0,
            withdrawal_address: Address::zero(),
            randao_commitment: Hash256::zero(),
            proof_of_possession: get_proof_of_possession(&kp),
        }
    }

    #[test]
    fn test_validator_inductor_valid_empty_validators() {
        let validators = vec![];

        let r = get_registration();

        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();

        assert_eq!(result.unwrap(), 0);
        assert_eq!(r, validators[0]);
        assert_eq!(validators.len(), 1);
    }

    #[test]
    fn test_validator_inductor_valid_all_active_validators() {
        let mut validators = vec![];
        for _ in 0..5 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Active as u8;
            validators.push(v);
        }

        let r = get_registration();

        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();

        assert_eq!(result.unwrap(), 5);
        assert_eq!(r, validators[5]);
        assert_eq!(validators.len(), 6);
    }

    #[test]
    fn test_validator_inductor_valid_all_second_validator_withdrawn() {
        let mut validators = vec![];
        let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
        v.status = ValidatorStatus::Active as u8;
        validators.push(v);
        for _ in 0..4 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Withdrawn as u8;
            validators.push(v);
        }

        let r = get_registration();

        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();

        assert_eq!(result.unwrap(), 1);
        assert_eq!(r, validators[1]);
        assert_eq!(validators.len(), 5);
    }

    #[test]
    fn test_validator_inductor_valid_all_withdrawn_validators() {
        let mut validators = vec![];
        for _ in 0..5 {
            let (mut v, _) = ValidatorRecord::zero_with_thread_rand_keypair();
            v.status = ValidatorStatus::Withdrawn as u8;
            validators.push(v);
        }

        /*
         * Ensure the first validator gets the 0'th slot
         */
        let r = get_registration();
        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();
        assert_eq!(result.unwrap(), 0);
        assert_eq!(r, validators[0]);
        assert_eq!(validators.len(), 5);

        /*
         * Ensure the second validator gets the 1'st slot
         */
        let r_two = get_registration();
        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();
        assert_eq!(result.unwrap(), 1);
        assert_eq!(r_two, validators[1]);
        assert_eq!(validators.len(), 5);
    }

    #[test]
    fn test_validator_inductor_shard_too_high() {
        let validators = vec![];

        let mut r = get_registration();
        r.withdrawal_shard = 1025;

        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();

        assert_eq!(result, Err(ValidatorInductionError::InvalidShard));
        assert_eq!(validators.len(), 0);
    }

    #[test]
    fn test_validator_inductor_shard_proof_of_possession_failure() {
        let validators = vec![];

        let mut r = get_registration();
        let kp = Keypair::random();
        r.proof_of_possession = get_proof_of_possession(&kp);

        let mut inductor = ValidatorInductor::new(0, 1024, validators);
        let result = inductor.induct(&r);
        let validators = inductor.to_vec();

        assert_eq!(result, Err(ValidatorInductionError::InvaidProofOfPossession));
        assert_eq!(validators.len(), 0);
    }
}
<|endoftext|>


<commit_before>use hyper;
use webdriver::command::{GetParameters, LocatorParameters};
use webdriver::common::LocatorStrategy;
use webdriver::error::{WebDriverResult, ErrorStatus, WebDriverError};
use webdriver::response::{WebDriverResponse, ValueResponse};
use std::io::Read;
use std::ops::Drop;

use rustc_serialize::json;
use rustc_serialize::json::Json;
use rustc_serialize::json::ToJson;
use rustc_serialize::base64::FromBase64Error;
use rustc_serialize::base64::FromBase64;

pub struct Webdriver<'a> {
    client: hyper::client::Client,
    host: &'a str,
    port: u32
}

pub struct WebdriverSession<'a> {
    webdriver: &'a Webdriver<'a>,
    session_id: String,
}

fn decode_response(json_str: &str) -> WebDriverResult<Json> {
    let decoded = Json::from_str(&json_str).unwrap();
    let status =
        decoded.find("status").expect("status code").as_u64().expect("numeric status code");
    let value = decoded.find("value").expect("value");
    return match status {
        0 => Ok(decoded.clone()),
        _ => {
            let message = value.find("message")
                .expect("error message")
                .as_string()
                .expect("a string message")
                .to_string();
            let kind = match status {
                7 => ErrorStatus::NoSuchElement,
                _ => ErrorStatus::UnknownError,
            };
            return Err(WebDriverError::new(kind, message));
        }
    };
}

trait DoesPost<'a> {
    fn do_post(&'a self, url: String, body: &String) -> WebDriverResult<Json> {
        debug!("Request: {:?}", body);
        let mut res = self.client()
            .post(&url)
            .body(body)
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        debug!("Buffer: {}", buffer);
        // assert_eq!(res.status, hyper::Ok);
        let decoded = decode_response(&buffer);
        debug!("Decoded: {:?}", decoded);
        return decoded;
    }

    fn client(&'a self) -> &'a hyper::client::Client;
}

impl<'a> Webdriver<'a> {
    pub fn new() -> Webdriver<'a> {
        Webdriver {
            client: hyper::client::Client::new(),
            host: "localhost",
            port: 9516
        }
    }

    pub fn url(&self, rest: &str) -> String {
        format!("http://{}:{}/session{}", self.host, self.port, rest)
    }

    pub fn make_session(&self) -> WebdriverSession {
        let mut mobile_emulation: json::Object = json::Object::new();
        mobile_emulation.insert("deviceName".to_string(), "Apple iPhone 5".to_json());
        let mut chrome_options: json::Object = json::Object::new();
        chrome_options.insert("mobileEmulation".to_string(), mobile_emulation.to_json());
        let mut desired: json::Object = json::Object::new();
        desired.insert("chromeOptions".to_string(), chrome_options.to_json());
        let mut request: json::Object = json::Object::new();
        request.insert("desiredCapabilities".to_string(), desired.to_json());
        let json_str = (&request).to_json().to_string();
        let decoded = self.do_post(self.url(""), &json_str);
        let session_id = decoded.expect("ok response")
            .find("sessionId")
            .expect("sessionId")
            .as_string()
            .expect("string session id")
            .to_string();
        WebdriverSession {
            webdriver: self,
            session_id: session_id,
        }
    }
}

impl<'a> DoesPost<'a> for Webdriver<'a> {
    fn client(&'a self) -> &'a hyper::client::Client {
        &self.client
    }
}
impl<'a> DoesPost<'a> for WebdriverSession<'a> {
    fn client(&'a self) -> &'a hyper::client::Client {
        &self.webdriver.client()
    }
}

impl <'a>Drop for WebdriverSession<'a> {
    fn drop(&mut self) {
        self.client()
            .delete(&self.url(format!("/{}", self.session_id)))
            .send()
            .unwrap();
    }
}

impl <'a>WebdriverSession<'a> {
    fn url(&self, rest: String) -> String {
        self.webdriver.url(&rest)
    }

    pub fn goto_url(&self, url: String) {
        let params = GetParameters { url: url };
        self.client()
            .post(&self.url(format!("/{}/url", self.session_id)))
            .body(&params.to_json().to_string())
            .send()
            .unwrap();
    }

    pub fn find_element_by_xpath(&self, xpath: String) -> WebDriverResult<WebDriverResponse> {
        let params = LocatorParameters {
            value: xpath.clone(),
            using: LocatorStrategy::XPath,
        };
        let decoded =
            self.do_post(self.url(format!("/{}/element", self.session_id)),
                         &params.to_json().to_string());
        return match decoded {
            Err(val) => Err(val),
            Ok(val) => {
                Ok(WebDriverResponse::Generic(ValueResponse::new(val.find("value")
                    .expect("has value")
                    .clone())))
            }
        };
    }

    fn get_for_element(&self, element: &ValueResponse, kind: &str) -> WebDriverResult<Json> {
        let element_id =
            element.value.find("ELEMENT").expect("ELEMENT").as_string().expect("String ELEMENT");
        let mut res = self.client()
            .get(&self.url(format!("/{}/element/{}/{}",
                          self.session_id,
                          element_id,
                          kind)))
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        debug!("Buffer: {}", buffer);
        // assert_eq!(res.status, hyper::Ok);
        let decoded = decode_response(&buffer);
        debug!("Decoded: {:?}", decoded);
        return decoded;
    }

    pub fn get_element_location(&self, element: &ValueResponse) -> WebDriverResult<Json> {
        return self.get_for_element(element, "location");
    }

    pub fn get_element_size(&self, element: &ValueResponse) -> WebDriverResult<Json> {
        return self.get_for_element(element, "size");
    }

    pub fn get_screenshot_as_png(&self) -> Result<Vec<u8>, FromBase64Error> {
        let mut res = self.client()
            .get(&self.url(format!("/{}/screenshot",
                          self.session_id)))
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        let decoded = decode_response(&buffer).expect("decoded");
        let value = decoded.find("value").expect("value").as_string().expect("string value");
        return value.clone().from_base64();
    }
}
<commit_msg>Spawn chromedriver directly<commit_after>use hyper;
use webdriver::command::{GetParameters, LocatorParameters};
use webdriver::common::LocatorStrategy;
use webdriver::error::{WebDriverResult, ErrorStatus, WebDriverError};
use webdriver::response::{WebDriverResponse, ValueResponse};
use std::io::Read;
use std::ops::Drop;

use rustc_serialize::json;
use rustc_serialize::json::{Json, ToJson};
use rustc_serialize::base64::{FromBase64Error, FromBase64};

use std::process::{Command, Child};

pub struct Webdriver<'a> {
    client: hyper::client::Client,
    host: &'a str,
    port: u32,
    process: Child,
}

pub struct WebdriverSession<'a> {
    webdriver: &'a Webdriver<'a>,
    session_id: String,
}

fn decode_response(json_str: &str) -> WebDriverResult<Json> {
    let decoded = Json::from_str(&json_str).unwrap();
    let status =
        decoded.find("status").expect("status code").as_u64().expect("numeric status code");
    let value = decoded.find("value").expect("value");
    return match status {
        0 => Ok(decoded.clone()),
        _ => {
            let message = value.find("message")
                .expect("error message")
                .as_string()
                .expect("a string message")
                .to_string();
            let kind = match status {
                7 => ErrorStatus::NoSuchElement,
                _ => ErrorStatus::UnknownError,
            };
            return Err(WebDriverError::new(kind, message));
        }
    };
}

trait DoesPost<'a> {
    fn do_post(&'a self, url: String, body: &String) -> WebDriverResult<Json> {
        debug!("Request: {:?}", body);
        let mut res = self.client()
            .post(&url)
            .body(body)
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        debug!("Buffer: {}", buffer);
        // assert_eq!(res.status, hyper::Ok);
        let decoded = decode_response(&buffer);
        debug!("Decoded: {:?}", decoded);
        return decoded;
    }

    fn client(&'a self) -> &'a hyper::client::Client;
}

impl<'a> Webdriver<'a> {
    pub fn new() -> Webdriver<'a> {
        let child = Command::new("./chromedriver")
            .arg("--port=9516")
            .spawn()
            .expect("spawned child");
        Webdriver {
            client: hyper::client::Client::new(),
            host: "localhost",
            port: 9516,
            process: child,
        }
    }

    pub fn url(&self, rest: &str) -> String {
        format!("http://{}:{}/session{}", self.host, self.port, rest)
    }

    pub fn make_session(&self) -> WebdriverSession {
        let mut mobile_emulation: json::Object = json::Object::new();
        mobile_emulation.insert("deviceName".to_string(), "Apple iPhone 5".to_json());
        let mut chrome_options: json::Object = json::Object::new();
        chrome_options.insert("mobileEmulation".to_string(), mobile_emulation.to_json());
        let mut desired: json::Object = json::Object::new();
        desired.insert("chromeOptions".to_string(), chrome_options.to_json());
        let mut request: json::Object = json::Object::new();
        request.insert("desiredCapabilities".to_string(), desired.to_json());
        let json_str = (&request).to_json().to_string();
        let decoded = self.do_post(self.url(""), &json_str);
        let session_id = decoded.expect("ok response")
            .find("sessionId")
            .expect("sessionId")
            .as_string()
            .expect("string session id")
            .to_string();
        WebdriverSession {
            webdriver: self,
            session_id: session_id,
        }
    }
}

impl<'a> Drop for Webdriver<'a> {
    fn drop(&mut self) {
        self.process.kill().unwrap();
    }
}

impl<'a> DoesPost<'a> for Webdriver<'a> {
    fn client(&'a self) -> &'a hyper::client::Client {
        &self.client
    }
}
impl<'a> DoesPost<'a> for WebdriverSession<'a> {
    fn client(&'a self) -> &'a hyper::client::Client {
        &self.webdriver.client()
    }
}

impl<'a> Drop for WebdriverSession<'a> {
    fn drop(&mut self) {
        self.client()
            .delete(&self.url(format!("/{}", self.session_id)))
            .send()
            .unwrap();
    }
}

impl<'a> WebdriverSession<'a> {
    fn url(&self, rest: String) -> String {
        self.webdriver.url(&rest)
    }

    pub fn goto_url(&self, url: String) {
        let params = GetParameters { url: url };
        self.client()
            .post(&self.url(format!("/{}/url", self.session_id)))
            .body(&params.to_json().to_string())
            .send()
            .unwrap();
    }

    pub fn find_element_by_xpath(&self, xpath: String) -> WebDriverResult<WebDriverResponse> {
        let params = LocatorParameters {
            value: xpath.clone(),
            using: LocatorStrategy::XPath,
        };
        let decoded = self.do_post(self.url(format!("/{}/element", self.session_id)),
                                   &params.to_json().to_string());
        return match decoded {
            Err(val) => Err(val),
            Ok(val) => {
                Ok(WebDriverResponse::Generic(ValueResponse::new(val.find("value")
                    .expect("has value")
                    .clone())))
            }
        };
    }

    fn get_for_element(&self, element: &ValueResponse, kind: &str) -> WebDriverResult<Json> {
        let element_id =
            element.value.find("ELEMENT").expect("ELEMENT").as_string().expect("String ELEMENT");
        let mut res = self.client()
            .get(&self.url(format!("/{}/element/{}/{}", self.session_id, element_id, kind)))
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        debug!("Buffer: {}", buffer);
        // assert_eq!(res.status, hyper::Ok);
        let decoded = decode_response(&buffer);
        debug!("Decoded: {:?}", decoded);
        return decoded;
    }

    pub fn get_element_location(&self, element: &ValueResponse) -> WebDriverResult<Json> {
        return self.get_for_element(element, "location");
    }

    pub fn get_element_size(&self, element: &ValueResponse) -> WebDriverResult<Json> {
        return self.get_for_element(element, "size");
    }

    pub fn get_screenshot_as_png(&self) -> Result<Vec<u8>, FromBase64Error> {
        let mut res = self.client()
            .get(&self.url(format!("/{}/screenshot", self.session_id)))
            .send()
            .unwrap();
        let mut buffer = String::new();
        res.read_to_string(&mut buffer).unwrap();
        let decoded = decode_response(&buffer).expect("decoded");
        let value = decoded.find("value").expect("value").as_string().expect("string value");
        return value.clone().from_base64();
    }
}
<|endoftext|>


<commit_before>use glium::{self, DisplayBuild, glutin};
use glium::backend::glutin_backend::GlutinFacade;
use super::Config;
use render::Renderer;
use event_manager::{EventManager, EventResponse};

pub fn run(config: &Config) -> Result<(), ()> {
    let context = try!(create_context(config));
    let renderer = Renderer::new(context.clone());
    let event_manager = EventManager::new(context.clone());

    loop {
        renderer.render().expect("error while rendering");

        let event_resp = event_manager.poll_events();
        if event_resp == EventResponse::Quit {
            break;
        }
    }

    Ok(())
}

/// Creates the OpenGL context and prints useful information about the
/// success or failure of said action.
fn create_context(config: &Config) -> Result<GlutinFacade, ()> {
    // Create glium context
    // TODO: handle fullscreen
    // TODO: OpenGL version/profile
    // TODO: vsync
    let context = glutin::WindowBuilder::new()
        .with_dimensions(config.resolution.width, config.resolution.height)
        .with_title(config.window_title.clone())
        .build_glium();

    match context {
        Err(e) => {
            // TODO: print more user friendly output
            error!("OpenGL context creation failed! Detailed error:");
            error!("{}", e);

            Err(())
        }
        Ok(context) => {
            info!("OpenGL context was successfully built");

            // print some information about the aquired OpenGL context
            let glium::Version(api, major, minor) = *context.get_opengl_version();
            info!("Version of context: {} {}.{}",
                  if api == glium::Api::Gl { "OpenGL" } else { "OpenGL ES" },
                  major,
                  minor);

            let glium::Version(api, major, minor) = context.get_supported_glsl_version();
            info!("Supported GLSL version: {} {}.{}",
                  if api == glium::Api::Gl { "GLSL" } else { "GLSL ES" },
                  major,
                  minor);

            if let Some(mem) = context.get_free_video_memory() {
                let (mem, unit) = match mem {
                    _ if mem < (1 << 12) => (mem, "B"),
                    _ if mem < (1 << 22) => (mem >> 10, "KB"),
                    _ if mem < (1 << 32) => (mem >> 20, "MB"),
                    _ => (mem >> 30, "GB"),
                };
                info!("Free GPU memory (estimated): {}{}", mem, unit);
            }

            Ok(context)
        }
    }
}
<commit_msg>Fix typo in comment<commit_after>use glium::{self, DisplayBuild, glutin};
use glium::backend::glutin_backend::GlutinFacade;
use super::Config;
use render::Renderer;
use event_manager::{EventManager, EventResponse};

/// Main game function: contains the mai render loop and owns all important
/// components. This function should remain rather small, all heavy lifting
/// should be done in other functions.
pub fn run(config: &Config) -> Result<(), ()> {
    // Create OpenGL context, the renderer and the event manager
    let context = try!(create_context(config));
    let renderer = Renderer::new(context.clone());
    let event_manager = EventManager::new(context.clone());

    loop {
        try!(renderer.render());

        let event_resp = event_manager.poll_events();
        if event_resp == EventResponse::Quit {
            break;
        }
    }

    Ok(())
}

/// Creates the OpenGL context and prints useful information about the
/// success or failure of said action.
fn create_context(config: &Config) -> Result<GlutinFacade, ()> {
    // Create glium context
    // TODO: handle fullscreen
    // TODO: OpenGL version/profile
    // TODO: vsync
    let context = glutin::WindowBuilder::new()
        .with_dimensions(config.resolution.width, config.resolution.height)
        .with_title(config.window_title.clone())
        .build_glium();

    match context {
        Err(e) => {
            // TODO: print more user friendly output
            error!("OpenGL context creation failed! Detailed error:");
            error!("{}", e);

            Err(())
        }
        Ok(context) => {
            // Print some information about the acquired OpenGL context
            info!("OpenGL context was successfully built");

            let glium::Version(api, major, minor) = *context.get_opengl_version();
            info!("Version of context: {} {}.{}",
                  if api == glium::Api::Gl { "OpenGL" } else { "OpenGL ES" },
                  major,
                  minor);

            let glium::Version(api, major, minor) = context.get_supported_glsl_version();
            info!("Supported GLSL version: {} {}.{}",
                  if api == glium::Api::Gl { "GLSL" } else { "GLSL ES" },
                  major,
                  minor);

            if let Some(mem) = context.get_free_video_memory() {
                let (mem, unit) = match () {
                    _ if mem < (1 << 12) => (mem, "B"),
                    _ if mem < (1 << 22) => (mem >> 10, "KB"),
                    _ if mem < (1 << 32) => (mem >> 20, "MB"),
                    _ => (mem >> 30, "GB"),
                };
                info!("Free GPU memory (estimated): {}{}", mem, unit);
            }

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


<commit_before>use std;
use std::fmt;

use ext4::mbr;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileType {
    GZip,
    Zip,
    Tar,
    BZip2,
    Xz,
    Deb,
    MBR,
    Other,
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

fn read_octal(bytes: &[u8]) -> Option<u32> {
    let mut start = 0;
    while start < bytes.len() && b' ' == bytes[start] {
        start += 1;
    }

    let mut end = bytes.len() - 1;
    while end > start && (b' ' == bytes[end] || 0 == bytes[end]) {
        end -= 1;
    }

    if let Ok(string) = std::str::from_utf8(&bytes[start..(end+1)]) {
        if let Ok(val) = u32::from_str_radix(string, 8) {
            return Some(val);
        }
    }
    None
}

fn is_probably_tar(header: &[u8]) -> bool {
    if header.len() < 512 {
        return false;
    }

    if let Some(checksum) = read_octal(&header[148..156]) {
        let mut sum: u32 = (b' ' as u32) * 8;
        for i in 0..148 {
            sum += header[i] as u32;
        }
        for i in 156..512 {
            sum += header[i] as u32;
        }

        if checksum == sum {
            return true;
        }
    }

    return false;
}

fn is_probably_mbr(header: &[u8]) -> bool {
    if header.len() < 512 + 4 {
        return false;
    }

    if 0x55 != header[510] || 0xAA != header[511] {
        return false;
    }

    if b"EFI"[..] == header[512..515] {
        return false;
    }

    match mbr::parse_partition_table(header, 512) {
        Err(_) => false,
        Ok(table) => !table.is_empty(),
    }
}

const DEB_PREFIX: &[u8] = b"!<arch>\ndebian-binary ";

impl FileType {
    pub fn identify<'a>(header: &[u8]) -> FileType {
        if header.len() >= 20
            && 0x1f == header[0] && 0x8b == header[1] {
            FileType::GZip
        } else if header.len() >= 152
            && b'P' == header[0] && b'K' == header[1]
            && 0x03 == header[2] && 0x04 == header[3] {
            FileType::Zip
        } else if header.len() > 257 + 10
            && b'u' == header[257] && b's' == header[258]
            && b't' == header[259] && b'a' == header[260]
            && b'r' == header[261]
            && (
            (0 == header[262] && b'0' == header[263] && b'0' == header[264]) ||
                (b' ' == header[262] && b' ' == header[263] && 0 == header[264])
        ) {
            FileType::Tar
        } else if header.len() > 70
            && header[0..DEB_PREFIX.len()] == DEB_PREFIX[..]
            && header[66..70] == b"`\n2."[..] {
            FileType::Deb
        } else if header.len() > 40
            && b'B' == header[0] && b'Z' == header[1]
            && b'h' == header[2] && 0x31 == header[3]
            && 0x41 == header[4] && 0x59 == header[5]
            && 0x26 == header[6] {
            FileType::BZip2
        } else if header.len() > 6
            && 0xfd == header[0] && b'7' == header[1]
            && b'z' == header[2] && b'X' == header[3]
            && b'Z' == header[4] && 0 == header[5] {
            FileType::Xz
        } else if is_probably_tar(header) {
            FileType::Tar
        } else if is_probably_mbr(header) {
            FileType::MBR
        } else {
            FileType::Other
        }
    }
}
<commit_msg>fix misidentifying bz2<commit_after>use std;
use std::fmt;

use ext4::mbr;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileType {
    GZip,
    Zip,
    Tar,
    BZip2,
    Xz,
    Deb,
    MBR,
    Other,
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

fn read_octal(bytes: &[u8]) -> Option<u32> {
    let mut start = 0;
    while start < bytes.len() && b' ' == bytes[start] {
        start += 1;
    }

    let mut end = bytes.len() - 1;
    while end > start && (b' ' == bytes[end] || 0 == bytes[end]) {
        end -= 1;
    }

    if let Ok(string) = std::str::from_utf8(&bytes[start..(end+1)]) {
        if let Ok(val) = u32::from_str_radix(string, 8) {
            return Some(val);
        }
    }
    None
}

fn is_probably_tar(header: &[u8]) -> bool {
    if header.len() < 512 {
        return false;
    }

    if let Some(checksum) = read_octal(&header[148..156]) {
        let mut sum: u32 = (b' ' as u32) * 8;
        for i in 0..148 {
            sum += header[i] as u32;
        }
        for i in 156..512 {
            sum += header[i] as u32;
        }

        if checksum == sum {
            return true;
        }
    }

    return false;
}

fn is_probably_mbr(header: &[u8]) -> bool {
    if header.len() < 512 + 4 {
        return false;
    }

    if 0x55 != header[510] || 0xAA != header[511] {
        return false;
    }

    if b"EFI"[..] == header[512..515] {
        return false;
    }

    match mbr::parse_partition_table(header, 512) {
        Err(_) => false,
        Ok(table) => !table.is_empty(),
    }
}

const DEB_PREFIX: &[u8] = b"!<arch>\ndebian-binary ";

impl FileType {
    pub fn identify<'a>(header: &[u8]) -> FileType {
        if header.len() >= 20
            && 0x1f == header[0] && 0x8b == header[1] {
            FileType::GZip
        } else if header.len() >= 152
            && b'P' == header[0] && b'K' == header[1]
            && 0x03 == header[2] && 0x04 == header[3] {
            FileType::Zip
        } else if header.len() > 257 + 10
            && b'u' == header[257] && b's' == header[258]
            && b't' == header[259] && b'a' == header[260]
            && b'r' == header[261]
            && (
            (0 == header[262] && b'0' == header[263] && b'0' == header[264]) ||
                (b' ' == header[262] && b' ' == header[263] && 0 == header[264])
        ) {
            FileType::Tar
        } else if header.len() > 70
            && header[0..DEB_PREFIX.len()] == DEB_PREFIX[..]
            && header[66..70] == b"`\n2."[..] {
            FileType::Deb
        } else if header.len() > 40
            && b'B' == header[0] && b'Z' == header[1]
            && b'h' == header[2] // [3]: compression level
            && 0x31 == header[4] && 0x41 == header[5]
            && 0x59 == header[6] && 0x26 == header[7]
            && 0x53 == header[8] && 0x59 == header[9] {
            FileType::BZip2
        } else if header.len() > 6
            && 0xfd == header[0] && b'7' == header[1]
            && b'z' == header[2] && b'X' == header[3]
            && b'Z' == header[4] && 0 == header[5] {
            FileType::Xz
        } else if is_probably_tar(header) {
            FileType::Tar
        } else if is_probably_mbr(header) {
            FileType::MBR
        } else {
            FileType::Other
        }
    }
}
<|endoftext|>


<commit_before>extern crate portmidi as pm;

extern crate rustc_serialize;
extern crate docopt;

const USAGE: &'static str = r#"
portmidi-rs: monitor-device example

Usage:
    monitor-device <id>

Options:
    -h --help   Show this screen.

Omitting <id> will list the available devices.
"#;

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_id: i32,
}

fn print_devices(pm: &pm::PortMidi) {
    for dev in pm.devices().unwrap() {
        println!("{}", dev);
    }
}

fn main() {
    // initialize the PortMidi context.
    let context = pm::PortMidi::new().unwrap();

    // setup the command line interface
    let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {
        print_devices(&context);
        err.exit();
    });

    // get the device info for the given id
    let info = context.device(args.arg_id).unwrap();
    println!("Listening on: {}) {}", info.id(), info.name());

    // get the device's input port
    let mut in_port = context.input_port(info, 1024).unwrap();

    while let Ok(_) = in_port.poll() {
        if let Ok(Some(event)) = in_port.read_n(1024) {
            println!("{:?}", event);
            // there is no blocking receive method in PortMidi, therefore
            // we have to sleep some time to prevent a busy-wait loop
            ::std::thread::sleep_ms(20);
        }
    }
}
<commit_msg>Replace deprecated `thread::sleep_ms` with `thread::sleep`<commit_after>extern crate portmidi as pm;

extern crate rustc_serialize;
extern crate docopt;

use std::time::Duration;
use std::thread;

const USAGE: &'static str = r#"
portmidi-rs: monitor-device example

Usage:
    monitor-device <id>

Options:
    -h --help   Show this screen.

Omitting <id> will list the available devices.
"#;

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_id: i32,
}

fn print_devices(pm: &pm::PortMidi) {
    for dev in pm.devices().unwrap() {
        println!("{}", dev);
    }
}

fn main() {
    // initialize the PortMidi context.
    let context = pm::PortMidi::new().unwrap();

    // setup the command line interface
    let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {
        print_devices(&context);
        err.exit();
    });

    // get the device info for the given id
    let info = context.device(args.arg_id).unwrap();
    println!("Listening on: {}) {}", info.id(), info.name());

    // get the device's input port
    let mut in_port = context.input_port(info, 1024).unwrap();

    while let Ok(_) = in_port.poll() {
        if let Ok(Some(event)) = in_port.read_n(1024) {
            println!("{:?}", event);
            // there is no blocking receive method in PortMidi, therefore
            // we have to sleep some time to prevent a busy-wait loop
            thread::sleep(Duration::new(0,50))
        }
    }
}
<|endoftext|>


<commit_before>extern crate portmidi as pm;

extern crate rustc_serialize;
extern crate docopt;

use std::time::Duration;
use std::thread;

const USAGE: &'static str = r#"
portmidi-rs: monitor-device example

Usage:
    monitor-device <device-id>

Options:
    -h --help   Show this screen.

Omitting <device-id> will list the available devices.
"#;

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_device_id: i32,
}

fn print_devices(pm: &pm::PortMidi) {
    for dev in pm.devices().unwrap() {
        println!("{}", dev);
    }
}

fn main() {
    // initialize the PortMidi context.
    let context = pm::PortMidi::new().unwrap();

    // setup the command line interface
    let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {
        print_devices(&context);
        err.exit();
    });

    // get the device info for the given id
    let info = context.device(args.arg_device_id).unwrap();
    println!("Listening on: {}) {}", info.id(), info.name());

    // get the device's input port
    let in_port = context.input_port(info, 1024).unwrap();

    while let Ok(_) = in_port.poll() {
        if let Ok(Some(event)) = in_port.read_n(1024) {
            println!("{:?}", event);
            // there is no blocking receive method in PortMidi, therefore
            // we have to sleep some time to prevent a busy-wait loop
            thread::sleep(Duration::new(0,50))
        }
    }
}
<commit_msg>Increase timeout duration to 10ms<commit_after>extern crate portmidi as pm;

extern crate rustc_serialize;
extern crate docopt;

use std::time::Duration;
use std::thread;

const USAGE: &'static str = r#"
portmidi-rs: monitor-device example

Usage:
    monitor-device <device-id>

Options:
    -h --help   Show this screen.

Omitting <device-id> will list the available devices.
"#;

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_device_id: i32,
}

fn print_devices(pm: &pm::PortMidi) {
    for dev in pm.devices().unwrap() {
        println!("{}", dev);
    }
}

fn main() {
    // initialize the PortMidi context.
    let context = pm::PortMidi::new().unwrap();
    let timeout = Duration::from_millis(10);

    // setup the command line interface
    let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {
        print_devices(&context);
        err.exit();
    });

    // get the device info for the given id
    let info = context.device(args.arg_device_id).unwrap();
    println!("Listening on: {}) {}", info.id(), info.name());

    // get the device's input port
    let in_port = context.input_port(info, 1024).unwrap();

    while let Ok(_) = in_port.poll() {
        if let Ok(Some(event)) = in_port.read_n(1024) {
            println!("{:?}", event);
            // there is no blocking receive method in PortMidi, therefore
            // we have to sleep some time to prevent a busy-wait loop
            thread::sleep(timeout)
        }
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate wlroots;

use std::cell::RefCell;
use std::rc::Rc;
use wlroots::{AxisEvent, ButtonEvent, Compositor, CompositorBuilder, Cursor, InputManagerHandler,
              KeyEvent, KeyboardHandler, MotionEvent, OutputBuilder, OutputBuilderResult,
              OutputHandler, OutputLayout, OutputManagerHandler, PointerHandler, XCursorTheme};
use wlroots::types::{KeyboardHandle, OutputHandle, PointerHandle};
use wlroots::wlroots_sys::gl;
use wlroots::wlroots_sys::wlr_button_state::WLR_BUTTON_RELEASED;
use wlroots::xkbcommon::xkb::keysyms::KEY_Escape;

struct State {
    color: [f32; 4],
    default_color: [f32; 4],
    cursor: Cursor
}

impl State {
    fn new(cursor: Cursor) -> Self {
        State {
            color: [0.25, 0.25, 0.25, 1.0],
            default_color: [0.25, 0.25, 0.25, 1.0],
            cursor
        }
    }
}

compositor_data!(State);

struct OutputManager;

struct Output;

struct InputManager;

struct Pointer;

struct ExKeyboardHandler;

impl OutputManagerHandler for OutputManager {
    fn output_added<'output>(&mut self,
                             compositor: &mut Compositor,
                             builder: OutputBuilder<'output>)
                             -> Option<OutputBuilderResult<'output>> {
        let mut result = builder.build_best_mode(Output);
        let state: &mut State = compositor.into();
        let cursor = &mut state.cursor;
        // TODO use output config if present instead of auto
        {
            let layout = cursor
                .output_layout()
                .as_ref()
                .expect("Could not get output layout");
            result.output.add_layout_auto(layout.clone());
            let xcursor = cursor.xcursor().expect("XCursor was not set!");
            let image = &xcursor.images()[0];
            if result.output.set_cursor(image).is_err() {
                wlr_log!(L_DEBUG, "Failed to set hardware cursor");
                return None;
            }
        }
        let (x, y) = cursor.coords();
        // https://en.wikipedia.org/wiki/Mouse_warping
        cursor.warp(None, x, y);
        Some(result)
    }
}

impl KeyboardHandler for ExKeyboardHandler {
    fn on_key(&mut self,
              compositor: &mut Compositor,
              _: &mut KeyboardHandle,
              key_event: &mut KeyEvent) {
        for key in key_event.input_keys() {
            if key == KEY_Escape {
                compositor.terminate()
            }
        }
    }
}

impl PointerHandler for Pointer {
    fn on_motion(&mut self,
                 compositor: &mut Compositor,
                 _: &mut PointerHandle,
                 event: &MotionEvent) {
        let state: &mut State = compositor.into();
        let (delta_x, delta_y) = event.delta();
        state.cursor.move_to(&event.device(), delta_x, delta_y);
    }

    fn on_button(&mut self,
                 compositor: &mut Compositor,
                 _: &mut PointerHandle,
                 event: &ButtonEvent) {
        let state: &mut State = compositor.into();
        if event.state() == WLR_BUTTON_RELEASED {
            state.color = state.default_color;
        } else {
            state.color = [0.25, 0.25, 0.25, 1.0];
            state.color[event.button() as usize % 3] = 1.0;
        }
    }

    fn on_axis(&mut self, compositor: &mut Compositor, _: &mut PointerHandle, event: &AxisEvent) {
        let state: &mut State = compositor.into();
        for color_byte in &mut state.default_color[..3] {
            *color_byte += if event.delta() > 0.0 { -0.05 } else { 0.05 };
            if *color_byte > 1.0 {
                *color_byte = 1.0
            }
            if *color_byte < 0.0 {
                *color_byte = 0.0
            }
        }
        state.color = state.default_color.clone()
    }
}

impl OutputHandler for Output {
    fn output_frame(&mut self, compositor: &mut Compositor, output: &mut OutputHandle) {
        let state: &mut State = compositor.into();
        output.make_current();
        unsafe {
            gl::ClearColor(state.color[0], state.color[1], state.color[2], 1.0);
            gl::Clear(gl::COLOR_BUFFER_BIT);
        }
        output.swap_buffers();
    }
}

impl InputManagerHandler for InputManager {
    fn pointer_added(&mut self,
                     _: &mut Compositor,
                     _: &mut PointerHandle)
                     -> Option<Box<PointerHandler>> {
        Some(Box::new(Pointer))
    }

    fn keyboard_added(&mut self,
                      _: &mut Compositor,
                      _: &mut KeyboardHandle)
                      -> Option<Box<KeyboardHandler>> {
        Some(Box::new(ExKeyboardHandler))
    }
}

fn main() {
    let mut cursor = Cursor::new().expect("Could not create cursor");
    let xcursor_theme = XCursorTheme::load_theme(None, 16).expect("Could not load theme");
    let xcursor = xcursor_theme
        .get_cursor("left_ptr".into())
        .expect("Could not load cursor from theme");
    let layout = Rc::new(RefCell::new(OutputLayout::new()));
    cursor.set_xcursor(Some(xcursor));

    cursor.attach_output_layout(layout);
    let compositor = CompositorBuilder::new().build_auto(State::new(cursor),
                                                         Box::new(InputManager),
                                                         Box::new(OutputManager));
    compositor.run();
}
<commit_msg>Fixed warnings<commit_after>#[macro_use]
extern crate wlroots;

use std::cell::RefCell;
use std::rc::Rc;
use wlroots::{AxisEvent, ButtonEvent, Compositor, CompositorBuilder, Cursor, InputManagerHandler,
              KeyEvent, KeyboardHandler, MotionEvent, OutputBuilder, OutputBuilderResult,
              OutputHandler, OutputLayout, OutputManagerHandler, PointerHandler, XCursorTheme};
use wlroots::types::{KeyboardHandle, OutputHandle, PointerHandle};
use wlroots::wlroots_sys::gl;
use wlroots::wlroots_sys::wlr_button_state::WLR_BUTTON_RELEASED;
use wlroots::xkbcommon::xkb::keysyms::KEY_Escape;

struct State {
    color: [f32; 4],
    default_color: [f32; 4],
    cursor: Cursor
}

impl State {
    fn new(cursor: Cursor) -> Self {
        State {
            color: [0.25, 0.25, 0.25, 1.0],
            default_color: [0.25, 0.25, 0.25, 1.0],
            cursor
        }
    }
}

compositor_data!(State);

struct OutputManager;

struct Output;

struct InputManager;

struct Pointer;

struct ExKeyboardHandler;

impl OutputManagerHandler for OutputManager {
    fn output_added<'output>(&mut self,
                             compositor: &mut Compositor,
                             builder: OutputBuilder<'output>)
                             -> Option<OutputBuilderResult<'output>> {
        let result = builder.build_best_mode(Output);
        let state: &mut State = compositor.into();
        let cursor = &mut state.cursor;
        // TODO use output config if present instead of auto
        {
            let layout = cursor
                .output_layout()
                .as_ref()
                .expect("Could not get output layout");
            result.output.add_layout_auto(layout.clone());
            let xcursor = cursor.xcursor().expect("XCursor was not set!");
            let image = &xcursor.images()[0];
            if result.output.set_cursor(image).is_err() {
                wlr_log!(L_DEBUG, "Failed to set hardware cursor");
                return None;
            }
        }
        let (x, y) = cursor.coords();
        // https://en.wikipedia.org/wiki/Mouse_warping
        cursor.warp(None, x, y);
        Some(result)
    }
}

impl KeyboardHandler for ExKeyboardHandler {
    fn on_key(&mut self,
              compositor: &mut Compositor,
              _: &mut KeyboardHandle,
              key_event: &mut KeyEvent) {
        for key in key_event.input_keys() {
            if key == KEY_Escape {
                compositor.terminate()
            }
        }
    }
}

impl PointerHandler for Pointer {
    fn on_motion(&mut self,
                 compositor: &mut Compositor,
                 _: &mut PointerHandle,
                 event: &MotionEvent) {
        let state: &mut State = compositor.into();
        let (delta_x, delta_y) = event.delta();
        state.cursor.move_to(&event.device(), delta_x, delta_y);
    }

    fn on_button(&mut self,
                 compositor: &mut Compositor,
                 _: &mut PointerHandle,
                 event: &ButtonEvent) {
        let state: &mut State = compositor.into();
        if event.state() == WLR_BUTTON_RELEASED {
            state.color = state.default_color;
        } else {
            state.color = [0.25, 0.25, 0.25, 1.0];
            state.color[event.button() as usize % 3] = 1.0;
        }
    }

    fn on_axis(&mut self, compositor: &mut Compositor, _: &mut PointerHandle, event: &AxisEvent) {
        let state: &mut State = compositor.into();
        for color_byte in &mut state.default_color[..3] {
            *color_byte += if event.delta() > 0.0 { -0.05 } else { 0.05 };
            if *color_byte > 1.0 {
                *color_byte = 1.0
            }
            if *color_byte < 0.0 {
                *color_byte = 0.0
            }
        }
        state.color = state.default_color.clone()
    }
}

impl OutputHandler for Output {
    fn output_frame(&mut self, compositor: &mut Compositor, output: &mut OutputHandle) {
        let state: &mut State = compositor.into();
        output.make_current();
        unsafe {
            gl::ClearColor(state.color[0], state.color[1], state.color[2], 1.0);
            gl::Clear(gl::COLOR_BUFFER_BIT);
        }
        output.swap_buffers();
    }
}

impl InputManagerHandler for InputManager {
    fn pointer_added(&mut self,
                     _: &mut Compositor,
                     _: &mut PointerHandle)
                     -> Option<Box<PointerHandler>> {
        Some(Box::new(Pointer))
    }

    fn keyboard_added(&mut self,
                      _: &mut Compositor,
                      _: &mut KeyboardHandle)
                      -> Option<Box<KeyboardHandler>> {
        Some(Box::new(ExKeyboardHandler))
    }
}

fn main() {
    let mut cursor = Cursor::new().expect("Could not create cursor");
    let xcursor_theme = XCursorTheme::load_theme(None, 16).expect("Could not load theme");
    let xcursor = xcursor_theme
        .get_cursor("left_ptr".into())
        .expect("Could not load cursor from theme");
    let layout = Rc::new(RefCell::new(OutputLayout::new()));
    cursor.set_xcursor(Some(xcursor));

    cursor.attach_output_layout(layout);
    let compositor = CompositorBuilder::new().build_auto(State::new(cursor),
                                                         Box::new(InputManager),
                                                         Box::new(OutputManager));
    compositor.run();
}
<|endoftext|>


<commit_before>#![feature(test, plugin)]
#![plugin(clippy)]
#![deny(clippy, clippy_pedantic)]

extern crate compiletest_rs as compiletest;
extern crate test;

use std::env::{var, set_var};
use std::path::PathBuf;
use test::TestPaths;

#[test]
fn dogfood() {
    // don't run dogfood on travis, cargo-clippy already runs clippy on itself
    if let Ok(travis) = var("TRAVIS") {
        if travis == "true" {
            return;
        }
    }

    let mut config = compiletest::default_config();

    let cfg_mode = "run-fail".parse().expect("Invalid mode");
    let mut s = String::new();
    s.push_str(" -L target/debug/");
    s.push_str(" -L target/debug/deps");
    s.push_str(" -Zextra-plugins=clippy -Ltarget_recur/debug -Dclippy_pedantic -Dclippy -Dclippy_internal");
    config.target_rustcflags = Some(s);
    if let Ok(name) = var("TESTNAME") {
        config.filter = Some(name.to_owned())
    }

    config.mode = cfg_mode;
    config.verbose = true;

    let files = ["src/main.rs", "src/lib.rs", "clippy_lints/src/lib.rs"];

    for file in &files {
        let paths = TestPaths {
            base: PathBuf::new(),
            file: PathBuf::from(file),
            relative_dir: PathBuf::new(),
        };

        set_var("CLIPPY_DOGFOOD", "tastes like chicken");

        compiletest::runtest::run(config.clone(), &paths);
    }
}
<commit_msg>Forbid default warnings in dogfood<commit_after>#![feature(test, plugin)]
#![plugin(clippy)]
#![deny(clippy, clippy_pedantic)]

extern crate compiletest_rs as compiletest;
extern crate test;

use std::env::{var, set_var};
use std::path::PathBuf;
use test::TestPaths;

#[test]
fn dogfood() {
    // don't run dogfood on travis, cargo-clippy already runs clippy on itself
    if let Ok(travis) = var("TRAVIS") {
        if travis == "true" {
            return;
        }
    }

    let mut config = compiletest::default_config();

    let cfg_mode = "run-fail".parse().expect("Invalid mode");
    let mut s = String::new();
    s.push_str(" -L target/debug/");
    s.push_str(" -L target/debug/deps");
    s.push_str(" -Zextra-plugins=clippy -Ltarget_recur/debug -Dwarnings -Dclippy_pedantic -Dclippy -Dclippy_internal");
    config.target_rustcflags = Some(s);
    if let Ok(name) = var("TESTNAME") {
        config.filter = Some(name.to_owned())
    }

    config.mode = cfg_mode;
    config.verbose = true;

    let files = ["src/main.rs", "src/lib.rs", "clippy_lints/src/lib.rs"];

    for file in &files {
        let paths = TestPaths {
            base: PathBuf::new(),
            file: PathBuf::from(file),
            relative_dir: PathBuf::new(),
        };

        set_var("CLIPPY_DOGFOOD", "tastes like chicken");

        compiletest::runtest::run(config.clone(), &paths);
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
extern crate typenum;
extern crate odds;

extern crate rex;

mod util;

use std::path::Path;
use std::iter;
use std::io::{Write, Cursor, Seek, SeekFrom};

use odds::vec::VecExt;

use rex::frontend::{Event, KeyPress};

use util::mock_filesystem::{DefMockFilesystem, MockFilesystem};

#[test]
fn test_edit_overwrite() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result_cursor = Cursor::new(v.clone());

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Overwrite with some junk data in the begining
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    // Overwrite some junk in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    assert_eq!(edit.get_position(), 55);
    result_cursor.seek(SeekFrom::Start(50)).unwrap();
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    // Overwrite it in the end (where it should append)
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result_cursor.seek(SeekFrom::End(0)).unwrap();
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    let result = result_cursor.into_inner();
    edit.save(Path::new("test_copy_paste"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_copy_paste").iter());
}

#[test]
fn test_edit_insert() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result = v.clone();

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Insert with some junk data in the begining
    frontend.run_keys(&mut edit, vec![KeyPress::Insert]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result.splice(..0, vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    // Insert some junk in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    assert_eq!(edit.get_position(), 55);
    result.splice(50..50, vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    // Insert it in the end (where it should append)
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    let len = result.len();
    result.splice(len.., vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    edit.save(Path::new("test_edit_insert"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_edit_insert").iter());
}

#[test]
fn test_edit_delete_and_bksp() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result = v.clone();

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Delete some chars in the begining (where the bksp key should be a no-op)
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    assert_eq!(edit.get_position(), 0);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), 0);
    result.splice(0..2, vec![]);

    // Delete some chars in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), 50);
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    assert_eq!(edit.get_position(), 48);
    result.splice(48..52, vec![]);

    // Delete in the end (where the delete key should be a no-op)
    let mut len = result.len();
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), len as isize);
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    result.splice((len-2).., vec![]);
    len = result.len();
    assert_eq!(edit.get_position(), len as isize);

    edit.save(Path::new("test_edit_delete_and_bksp"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_edit_delete_and_bksp").iter());
}
<commit_msg>Improve editing test case to test more edge cases<commit_after>#[macro_use]
extern crate lazy_static;
extern crate typenum;
extern crate odds;

extern crate rex;

mod util;

use std::path::Path;
use std::iter;
use std::io::{Write, Cursor, Seek, SeekFrom};

use odds::vec::VecExt;

use rex::frontend::{Event, KeyPress};

use util::mock_filesystem::{DefMockFilesystem, MockFilesystem};

#[test]
fn test_edit_overwrite() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result_cursor = Cursor::new(v.clone());

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Overwrite with some junk data in the begining
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    // Overwrite some junk in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    assert_eq!(edit.get_position(), 55);
    result_cursor.seek(SeekFrom::Start(50)).unwrap();
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    // Overwrite it in the end (where it should append)
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result_cursor.seek(SeekFrom::End(0)).unwrap();
    result_cursor.write(&vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]).unwrap();

    let result = result_cursor.into_inner();
    edit.save(Path::new("test_copy_paste"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_copy_paste").iter());
}

#[test]
fn test_edit_insert() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result = v.clone();

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Insert with some junk data in the begining
    frontend.run_keys(&mut edit, vec![KeyPress::Insert]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    result.splice(..0, vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    // Insert some junk in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    assert_eq!(edit.get_position(), 55);
    result.splice(50..50, vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    // Insert it in the end (where it should append)
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_str(&mut edit, "AABBCCDDEE");
    let len = result.len();
    result.splice(len.., vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);

    edit.save(Path::new("test_edit_insert"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_edit_insert").iter());
}

#[test]
fn test_edit_delete_and_bksp() {
    let v : Vec<u8> = (0..0xff).into_iter().collect();
    let mut result = v.clone();

    let (mut edit, mut frontend) = util::simple_init_with_vec(v);

    // Delete some chars in the begining (where the bksp key should be a no-op)
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    assert_eq!(edit.get_position(), 0);
    // And actually delete some chars
    frontend.run_keys(&mut edit, vec![KeyPress::Right, KeyPress:: Right, KeyPress::Right, KeyPress:: Right,
        KeyPress::Backspace, KeyPress::Backspace]);
    assert_eq!(edit.get_position(), 0);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), 0);
    result.splice(0..4, vec![]);

    // Delete some chars in the middle
    frontend.run_keys(&mut edit, vec![KeyPress::Shortcut('g')]);
    frontend.run_str(&mut edit, "50");
    frontend.run_keys(&mut edit, vec![KeyPress::Enter]);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), 50);
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    assert_eq!(edit.get_position(), 48);
    result.splice(48..52, vec![]);

    // Delete in the end (where the delete key should be a no-op)
    let mut len = result.len();
    frontend.run_keys(&mut edit, vec![KeyPress::PageDown, KeyPress::PageDown, KeyPress::PageDown]);
    frontend.run_keys(&mut edit, vec![KeyPress::Delete, KeyPress::Delete]);
    assert_eq!(edit.get_position(), len as isize);
    // And actually delete some chars
    frontend.run_keys(&mut edit, vec![KeyPress::Left, KeyPress::Left, KeyPress::Left, KeyPress::Left,
        KeyPress::Delete, KeyPress::Delete]);
    frontend.run_keys(&mut edit, vec![KeyPress::Backspace, KeyPress::Backspace]);
    result.splice((len-4).., vec![]);
    len = result.len();
    assert_eq!(edit.get_position(), len as isize);

    println!("result = {:?}", result);

    edit.save(Path::new("test_edit_delete_and_bksp"));
    util::assert_iter_eq(result.iter(), DefMockFilesystem::get_inner("test_edit_delete_and_bksp").iter());
}
<|endoftext|>


<commit_before>extern crate toml;

use toml::{Parser};

fn run(toml: &str) {
    let mut p = Parser::new(toml);
    let table = p.parse();
    assert!(table.is_none());
    assert!(p.errors.len() > 0);
}

macro_rules! test( ($name:ident, $toml:expr) => (
    #[test]
    fn $name() { run($toml); }
) );

test!(array_mixed_types_arrays_and_ints,
      include_str!("invalid/array-mixed-types-arrays-and-ints.toml"));
test!(array_mixed_types_ints_and_floats,
      include_str!("invalid/array-mixed-types-ints-and-floats.toml"));
test!(array_mixed_types_strings_and_ints,
      include_str!("invalid/array-mixed-types-strings-and-ints.toml"));
test!(datetime_malformed_no_leads,
      include_str!("invalid/datetime-malformed-no-leads.toml"));
test!(datetime_malformed_no_secs,
      include_str!("invalid/datetime-malformed-no-secs.toml"));
test!(datetime_malformed_no_t,
      include_str!("invalid/datetime-malformed-no-t.toml"));
test!(datetime_malformed_no_z,
      include_str!("invalid/datetime-malformed-no-z.toml"));
test!(datetime_malformed_with_milli,
      include_str!("invalid/datetime-malformed-with-milli.toml"));
test!(duplicate_keys,
      include_str!("invalid/duplicate-keys.toml"));
test!(duplicate_key_table,
      include_str!("invalid/duplicate-key-table.toml"));
test!(duplicate_tables,
      include_str!("invalid/duplicate-tables.toml"));
test!(empty_implicit_table,
      include_str!("invalid/empty-implicit-table.toml"));
test!(empty_table,
      include_str!("invalid/empty-table.toml"));
test!(float_no_leading_zero,
      include_str!("invalid/float-no-leading-zero.toml"));
test!(float_no_trailing_digits,
      include_str!("invalid/float-no-trailing-digits.toml"));
test!(key_two_equals,
      include_str!("invalid/key-two-equals.toml"));
test!(string_bad_byte_escape,
      include_str!("invalid/string-bad-byte-escape.toml"));
test!(string_bad_escape,
      include_str!("invalid/string-bad-escape.toml"));
test!(string_byte_escapes,
      include_str!("invalid/string-byte-escapes.toml"));
test!(string_no_close,
      include_str!("invalid/string-no-close.toml"));
test!(table_array_implicit,
      include_str!("invalid/table-array-implicit.toml"));
test!(table_array_malformed_bracket,
      include_str!("invalid/table-array-malformed-bracket.toml"));
test!(table_array_malformed_empty,
      include_str!("invalid/table-array-malformed-empty.toml"));
test!(table_nested_brackets_close,
      include_str!("invalid/table-nested-brackets-close.toml"));
test!(table_nested_brackets_open,
      include_str!("invalid/table-nested-brackets-open.toml"));
test!(text_after_array_entries,
      include_str!("invalid/text-after-array-entries.toml"));
test!(text_after_integer,
      include_str!("invalid/text-after-integer.toml"));
test!(text_after_string,
      include_str!("invalid/text-after-string.toml"));
test!(text_after_table,
      include_str!("invalid/text-after-table.toml"));
test!(text_before_array_separator,
      include_str!("invalid/text-before-array-separator.toml"));
test!(text_in_array,
      include_str!("invalid/text-in-array.toml"));
<commit_msg>Add a very simple test for Parser::to_linecol.<commit_after>extern crate toml;

use toml::{Parser};

fn run(toml: &str) {
    let mut p = Parser::new(toml);
    let table = p.parse();
    assert!(table.is_none());
    assert!(p.errors.len() > 0);

    // test Parser::to_linecol with the generated error offsets
    for error in &p.errors {
      p.to_linecol(error.lo);
      p.to_linecol(error.hi);
    }
}

macro_rules! test( ($name:ident, $toml:expr) => (
    #[test]
    fn $name() { run($toml); }
) );

test!(array_mixed_types_arrays_and_ints,
      include_str!("invalid/array-mixed-types-arrays-and-ints.toml"));
test!(array_mixed_types_ints_and_floats,
      include_str!("invalid/array-mixed-types-ints-and-floats.toml"));
test!(array_mixed_types_strings_and_ints,
      include_str!("invalid/array-mixed-types-strings-and-ints.toml"));
test!(datetime_malformed_no_leads,
      include_str!("invalid/datetime-malformed-no-leads.toml"));
test!(datetime_malformed_no_secs,
      include_str!("invalid/datetime-malformed-no-secs.toml"));
test!(datetime_malformed_no_t,
      include_str!("invalid/datetime-malformed-no-t.toml"));
test!(datetime_malformed_no_z,
      include_str!("invalid/datetime-malformed-no-z.toml"));
test!(datetime_malformed_with_milli,
      include_str!("invalid/datetime-malformed-with-milli.toml"));
test!(duplicate_keys,
      include_str!("invalid/duplicate-keys.toml"));
test!(duplicate_key_table,
      include_str!("invalid/duplicate-key-table.toml"));
test!(duplicate_tables,
      include_str!("invalid/duplicate-tables.toml"));
test!(empty_implicit_table,
      include_str!("invalid/empty-implicit-table.toml"));
test!(empty_table,
      include_str!("invalid/empty-table.toml"));
test!(float_no_leading_zero,
      include_str!("invalid/float-no-leading-zero.toml"));
test!(float_no_trailing_digits,
      include_str!("invalid/float-no-trailing-digits.toml"));
test!(key_two_equals,
      include_str!("invalid/key-two-equals.toml"));
test!(string_bad_byte_escape,
      include_str!("invalid/string-bad-byte-escape.toml"));
test!(string_bad_escape,
      include_str!("invalid/string-bad-escape.toml"));
test!(string_byte_escapes,
      include_str!("invalid/string-byte-escapes.toml"));
test!(string_no_close,
      include_str!("invalid/string-no-close.toml"));
test!(table_array_implicit,
      include_str!("invalid/table-array-implicit.toml"));
test!(table_array_malformed_bracket,
      include_str!("invalid/table-array-malformed-bracket.toml"));
test!(table_array_malformed_empty,
      include_str!("invalid/table-array-malformed-empty.toml"));
test!(table_nested_brackets_close,
      include_str!("invalid/table-nested-brackets-close.toml"));
test!(table_nested_brackets_open,
      include_str!("invalid/table-nested-brackets-open.toml"));
test!(text_after_array_entries,
      include_str!("invalid/text-after-array-entries.toml"));
test!(text_after_integer,
      include_str!("invalid/text-after-integer.toml"));
test!(text_after_string,
      include_str!("invalid/text-after-string.toml"));
test!(text_after_table,
      include_str!("invalid/text-after-table.toml"));
test!(text_before_array_separator,
      include_str!("invalid/text-before-array-separator.toml"));
test!(text_in_array,
      include_str!("invalid/text-in-array.toml"));
<|endoftext|>


<commit_before>extern crate json_pointer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quickcheck;
extern crate regex;

use json_pointer::JsonPointer;
use quickcheck::TestResult;
use regex::Regex;

quickcheck! {

/// Essentially, `unparse(parse("..."))` should be a no-op when not in URI
/// Fragment Identifier Representation.
fn faithful_parse(s: String) -> TestResult {
    if s.chars().next() == Some('#') {
        TestResult::discard()
    } else {
        match s.parse::<JsonPointer<_, _>>() {
            Ok(ptr) => if s == ptr.to_string() {
            TestResult::passed()
            } else {
                TestResult::failed()
            },
            Err(_) => TestResult::discard(),
        }
    }
}

/// Ensuring that parsing succeeds for all strings that match the regex for
/// JSON pointers.
fn parses_all_valid(s: String) -> bool {
    lazy_static! {
        static ref JSON_POINTER_REGEX: Regex = Regex::new("^(/([^/~]|~[01])*)*$").unwrap();
    }

    let matches_regex = JSON_POINTER_REGEX.is_match(&s);
    let parses = s.parse::<JsonPointer<_, _>>().is_ok();

    (matches_regex == parses)
}

}
<commit_msg>Adds URI fragments to parses_all_valid regexes.<commit_after>extern crate json_pointer;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quickcheck;
extern crate regex;

use json_pointer::JsonPointer;
use quickcheck::TestResult;
use regex::Regex;

quickcheck! {

/// Essentially, `unparse(parse("..."))` should be a no-op when not in URI
/// Fragment Identifier Representation.
fn faithful_parse(s: String) -> TestResult {
    if s.chars().next() == Some('#') {
        TestResult::discard()
    } else {
        match s.parse::<JsonPointer<_, _>>() {
            Ok(ptr) => if s == ptr.to_string() {
            TestResult::passed()
            } else {
                TestResult::failed()
            },
            Err(_) => TestResult::discard(),
        }
    }
}

/// Ensuring that parsing succeeds for all strings that match the regex for
/// JSON pointers.
fn parses_all_valid(s: String) -> bool {
    lazy_static! {
        static ref JSON_POINTER_REGEX: Regex = Regex::new("^(/([^/~]|~[01])*)*$").unwrap();
        static ref URI_FRAGMENT_REGEX: Regex = Regex::new("^#(/([^/~%]|~[01]|%[0-9a-fA-F]{2})*)*$").unwrap();
    }

    let matches_regex = JSON_POINTER_REGEX.is_match(&s) || URI_FRAGMENT_REGEX.is_match(&s);
    let parses = s.parse::<JsonPointer<_, _>>().is_ok();

    (matches_regex == parses)
}

}
<|endoftext|>


<commit_before>//
// Sysinfo
//
// Copyright (c) 2018 Guillaume Gomez
//

extern crate sysinfo;

#[cfg(not(windows))]
use sysinfo::ProcessExt;
use sysinfo::SystemExt;

#[test]
fn test_process() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.get_processes().len(), 0);
    s.refresh_processes();
    assert!(s.get_processes().len() != 0);
    #[cfg(not(windows))]
    assert!(s
        .get_processes()
        .values()
        .any(|p| p.exe().to_str().unwrap_or_else(|| "").len() != 0));
}

#[test]
fn test_process_refresh() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.get_processes().len(), 0);
    s.refresh_process(sysinfo::get_current_pid().expect("failed to get current pid"));
    assert_eq!(
        s.get_process(sysinfo::get_current_pid().expect("failed to get current pid"))
            .is_some(),
        true
    );
}

#[test]
#[cfg(windows)]
fn test_get_cmd_line() {}

#[test]
#[cfg(not(windows))]
fn test_get_cmd_line() {
    let p = std::process::Command::new("timeout")
        .arg("3")
        .arg("ping")
        .arg("localhost")
        .spawn()
        .unwrap();
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    let process = s.get_process(p.id() as sysinfo::Pid).unwrap();
    assert_eq!(process.cmd(), &["timeout", "3", "ping", "localhost"]);
}
<commit_msg>Test get_cmd_line for windows<commit_after>//
// Sysinfo
//
// Copyright (c) 2018 Guillaume Gomez
//

extern crate sysinfo;

use sysinfo::ProcessExt;
use sysinfo::SystemExt;

#[test]
fn test_process() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.get_processes().len(), 0);
    s.refresh_processes();
    assert!(s.get_processes().len() != 0);
    #[cfg(not(windows))]
    assert!(s
        .get_processes()
        .values()
        .any(|p| p.exe().to_str().unwrap_or_else(|| "").len() != 0));
}

#[test]
fn test_process_refresh() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.get_processes().len(), 0);
    s.refresh_process(sysinfo::get_current_pid().expect("failed to get current pid"));
    assert_eq!(
        s.get_process(sysinfo::get_current_pid().expect("failed to get current pid"))
            .is_some(),
        true
    );
}

#[test]
#[cfg(windows)]
fn test_get_cmd_line() {
    let p = std::process::Command::new("ping")
        .arg("localhost")
        .arg("-n")
        .arg("2")
        .spawn()
        .unwrap();
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    let process = s.get_process(p.id() as sysinfo::Pid).unwrap();
    assert_eq!(process.cmd(), &["ping", "localhost", "-n", "2"]);
}

#[test]
#[cfg(not(windows))]
fn test_get_cmd_line() {
    let p = std::process::Command::new("timeout")
        .arg("3")
        .arg("ping")
        .arg("localhost")
        .spawn()
        .unwrap();
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    let process = s.get_process(p.id() as sysinfo::Pid).unwrap();
    assert_eq!(process.cmd(), &["timeout", "3", "ping", "localhost"]);
}
<|endoftext|>