<commit_before>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Creates keys (signing and encryption keys) for a new Identity (owned by the caller of the library).
/// Identity's DID can be either explicitly provided, or taken as the first 16 bit of verkey.
/// Saves the Identity DID with keys in a secured Wallet, so that it can be used to sign and encrypt transactions.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// identity_json: Identity information as json. Example:
/// {
///     "did": string, (optional; if not provided then the first 16 bit of the verkey will be used as a new DID;
///                               if provided, then keys will be replaced - key rotation use case)
///     "seed": string, (optional; if not provide then a random one will be created)
///     "signer": string, (optional; if not set then ed25519 curve is used; currently only 'ed25519' value is supported for this field)
/// }
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// DID, verkey (for verification of signatire) and public_key (for decryption)
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_create_and_store_my_identity(client_id: i32, command_id: i32,
                                             identity_json: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                           did: *const c_char,
                                                           verkey: *const c_char,
                                                           pk: *const c_char)) {
    unimplemented!();
}

/// Saves their Identity for a pairwise connection in a secured Wallet, so that it can be used to verify transaction.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// identity_json: Identity information as json. Example:
///     {
///        "did": string, (required)
///        "verkey": string, (optional; if only public key for decryption is provided),
///        "pk": string (optional, if only verification key sis provided),
///     }
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// None
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_store_their_identity(client_id: i32, command_id: i32,
                                             identity_json: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}

/// Signs a message by a signing key associated with my DID. The DID with a signing key must be already created and
/// stored in a secured wallet (see wallet_create_and_store_my_identity)
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// did: signing DID
/// msg: a message to be signed
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// a signature string
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_sign_by_my_did(client_id: i32, command_id: i32,
                                             did: *const c_char,
                                             msg: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                            signature: *const c_char)) {
    unimplemented!();
}

/// Verify a signature created by a key associated with a DID.
/// If a secure wallet doesn't contain a verkey associated with the given DID, then verkey is read from the Ledger.
/// Otherwise either an existing verkey from wallet is used (see wallet_store_their_identity),
/// or it checks the Ledger (according to freshness settings set during initialization) whether verkey is still the same and updates verkey for the DID if needed.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// did: DID that signed the message
/// msg: message
/// signature: a signature to be verified
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// None
///
/// #Errors
/// VerificationError
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_verify_by_their_did(client_id: i32, command_id: i32,
                                             did: *const c_char,
                                             msg: *const c_char,
                                             signature: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}

/// Encrypts a message by a public key associated with a DID.
/// If a secure wallet doesn't contain a public key associated with the given DID, then the public key is read from the Ledger.
/// Otherwise either an existing public key from wallet is used (see wallet_store_their_identity),
/// or it checks the Ledger (according to freshness settings set during initialization) whether public key is still the same and updates public key for the DID if needed.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// did: encrypting DID
/// msg: a message to be signed
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// an encrypted message
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_encrypt_by_their_did(client_id: i32, command_id: i32,
                                             did: *const c_char,
                                             msg: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                            encrypted_msg: *const c_char)) {
    unimplemented!();
}

/// Decrypts a message encrypted by a public key associated with my DID.
/// The DID with a secret key must be already created and
/// stored in a secured wallet (see wallet_create_and_store_my_identity)
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// did: DID that signed the message
/// encrypted_msg: encrypted message
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// decrypted message
///
/// #Errors
/// VerificationError
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_decrypt_by_my_did(client_id: i32, command_id: i32,
                                             did: *const c_char,
                                             encrypted_msg: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                        decrypted_msg: *const c_char)) {
    unimplemented!();
}<commit_msg>small changes for wallet<commit_after>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Creates keys (signing and encryption keys) for a new
/// Identity (owned by the caller of the library).
/// Identity's DID can be either explicitly provided, or taken as the first 16 bit of verkey.
/// Saves the Identity DID with keys in a secured Wallet, so that it can be used to sign
/// and encrypt transactions.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// identity_json: Identity information as json. Example:
/// {
///     "did": string, (optional; if not provided then the first 16 bit of the verkey will be used
///             as a new DID; if provided, then keys will be replaced - key rotation use case)
///     "seed": string, (optional; if not provide then a random one will be created)
///     "signer": string, (optional; if not set then ed25519 curve is used;
///               currently only 'ed25519' value is supported for this field)
/// }
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// DID, verkey (for verification of signatire) and public_key (for decryption)
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_create_and_store_my_identity(client_handle: i32, command_handle: i32,
                                                   identity_json: *const c_char,
                                                   cb: extern fn(xcommand_handle: i32, err: i32,
                                                                 did: *const c_char,
                                                                 verkey: *const c_char,
                                                                 pk: *const c_char)) {
    unimplemented!();
}

/// Saves their Identity for a pairwise connection in a secured Wallet,
/// so that it can be used to verify transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// identity_json: Identity information as json. Example:
///     {
///        "did": string, (required)
///        "verkey": string, (optional; if only public key for decryption is provided),
///        "pk": string (optional, if only verification key sis provided),
///     }
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// None
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_store_their_identity(client_handle: i32, command_handle: i32,
                                           identity_json: *const c_char,
                                           cb: extern fn(xcommand_handle: i32, err: i32)) {
    unimplemented!();
}

/// Signs a message by a signing key associated with my DID. The DID with a signing key
/// must be already created and stored in a secured wallet (see wallet_create_and_store_my_identity)
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// did: signing DID
/// msg: a message to be signed
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// a signature string
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_sign_by_my_did(client_handle: i32, command_handle: i32,
                                     did: *const c_char,
                                     msg: *const c_char,
                                     cb: extern fn(xcommand_handle: i32, err: i32,
                                                   signature: *const c_char)) {
    unimplemented!();
}

/// Verify a signature created by a key associated with a DID.
/// If a secure wallet doesn't contain a verkey associated with the given DID,
/// then verkey is read from the Ledger.
/// Otherwise either an existing verkey from wallet is used (see wallet_store_their_identity),
/// or it checks the Ledger (according to freshness settings set during initialization)
/// whether verkey is still the same and updates verkey for the DID if needed.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// did: DID that signed the message
/// msg: message
/// signature: a signature to be verified
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// None
///
/// #Errors
/// VerificationError
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_verify_by_their_did(client_handle: i32, command_handle: i32,
                                          did: *const c_char,
                                          msg: *const c_char,
                                          signature: *const c_char,
                                          cb: extern fn(xcommand_handle: i32, err: i32)) {
    unimplemented!();
}

/// Encrypts a message by a public key associated with a DID.
/// If a secure wallet doesn't contain a public key associated with the given DID,
/// then the public key is read from the Ledger.
/// Otherwise either an existing public key from wallet is used (see wallet_store_their_identity),
/// or it checks the Ledger (according to freshness settings set during initialization)
/// whether public key is still the same and updates public key for the DID if needed.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// did: encrypting DID
/// msg: a message to be signed
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// an encrypted message
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_encrypt_by_their_did(client_handle: i32, command_handle: i32,
                                           did: *const c_char,
                                           msg: *const c_char,
                                           cb: extern fn(xcommand_handle: i32, err: i32,
                                                         encrypted_msg: *const c_char)) {
    unimplemented!();
}

/// Decrypts a message encrypted by a public key associated with my DID.
/// The DID with a secret key must be already created and
/// stored in a secured wallet (see wallet_create_and_store_my_identity)
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// did: DID that signed the message
/// encrypted_msg: encrypted message
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// decrypted message
///
/// #Errors
/// VerificationError
/// See `LedgerError` docs for common errors description.
pub  extern fn wallet_decrypt_by_my_did(client_handle: i32, command_handle: i32,
                                        did: *const c_char,
                                        encrypted_msg: *const c_char,
                                        cb: extern fn(xcommand_handle: i32, err: i32,
                                                      decrypted_msg: *const c_char)) {
    unimplemented!();
}<|endoftext|>


<commit_before><commit_msg>Add servo example<commit_after>extern crate firmata;

use firmata::*;
use std::thread;

fn main() {
    let mut b = firmata::Board::new("/dev/ttyACM0");

    let pin = 3;

    println!("firmware version {}", b.firmware_version);
    println!("firmware name {}", b.firmware_name);
    println!("protocol version {}", b.protocol_version);

    b.set_pin_mode(pin, firmata::SERVO);

    loop {
        for value in 0..180{
            b.analog_write(pin, value);
            println!("{}", value);
            thread::sleep_ms(10);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix parsing of cylinder in CHS addresses<commit_after><|endoftext|>


<commit_before><commit_msg>Delete junk<commit_after><|endoftext|>


<commit_before><commit_msg>Offset is Measurable<commit_after><|endoftext|>


<commit_before><commit_msg>Add extension trait for iterator over Result<Entry><commit_after><|endoftext|>


<commit_before><commit_msg>Add flex_direction_test<commit_after>#[macro_use]
extern crate yoga;

use yoga::{Direction, FlexDirection, Node, Point, Undefined};
use yoga::FlexStyle::*;

#[test]
fn test_flex_direction_column_no_height() {
	let mut root = Node::new();

	style!(root,
		Width(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Height(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Height(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Height(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(30.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(10.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(20.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(30.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(10.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(20.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);
}

#[test]
fn test_flex_direction_row_no_width() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Width(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Width(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(30.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(10.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(20.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(30.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(20.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(10.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);
}

#[test]
fn test_flex_direction_column() {
	let mut root = Node::new();

	style!(root,
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Height(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Height(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Height(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(10.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(20.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(10.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(20.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);
}

#[test]
fn test_flex_direction_row() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Width(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Width(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(10.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(20.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(90.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(80.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(70.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);
}

#[test]
fn test_flex_direction_column_reverse() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::ColumnReverse),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Height(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Height(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Height(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(90.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(80.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(70.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(90.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(10.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(80.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(10.0, child_1_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(70.0, child_2_layout.top);
	assert_eq!(100.0, child_2_layout.width);
	assert_eq!(10.0, child_2_layout.height);
}

#[test]
fn test_flex_direction_row_reverse() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::RowReverse),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		Width(10 pt)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Width(10 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		Width(10 pt)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(90.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(80.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(70.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(10.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(10.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(10.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	assert_eq!(20.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(10.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);
}
<|endoftext|>


<commit_before><commit_msg>Refactor(syncfile): switch to use io::Error<commit_after><|endoftext|>


<commit_before><commit_msg>add an example TCP proxy<commit_after>#![allow(unused_variables,unused_must_use)]
#[macro_use] extern crate sozu_lib as sozu;
extern crate sozu_command_lib as sozu_command;
extern crate time;

use std::thread;
use std::io::stdout;
use sozu::network;
use sozu_command::messages;
use sozu_command::channel::Channel;
use sozu::logging::{Logger,LoggerBackend};

fn main() {
  /*
  if env::var("RUST_LOG").is_ok() {
   Logger::init("EXAMPLE".to_string(), &env::var("RUST_LOG").expect("could not get the RUST_LOG env var"), LoggerBackend::Stdout(stdout()));
  } else {
   Logger::init("EXAMPLE".to_string(), "info", LoggerBackend::Stdout(stdout()));
  }
  */
 Logger::init("EXAMPLE".to_string(), "debug", LoggerBackend::Stdout(stdout()));

  info!("starting up");

  let (mut command, channel) = Channel::generate(1000, 10000).expect("should create a channel");

  let jg = thread::spawn(move || {
    let max_listeners = 500;
    let max_buffers   = 500;
    let buffer_size   = 16384;
    Logger::init("TCP".to_string(), "debug", LoggerBackend::Stdout(stdout()));
    network::tcp::start(max_listeners, max_buffers, buffer_size, channel);
  });

  let tcp_front = messages::TcpFront {
    app_id:      String::from("test"),
    ip_address:  String::from("127.0.0.1"),
    port:        8080,
  };
  let tcp_instance = messages::Instance {
    app_id:      String::from("test"),
    instance_id: String::from("test-0"),
    ip_address:  String::from("127.0.0.1"),
    port:        1026,
  };

  command.write_message(&messages::OrderMessage {
    id:    String::from("ID_ABCD"),
    order: messages::Order::AddTcpFront(tcp_front)
  });

  command.write_message(&messages::OrderMessage {
    id:    String::from("ID_EFGH"),
    order: messages::Order::AddInstance(tcp_instance)
  });

  info!("TCP -> {:?}", command.read_message());
  info!("TCP -> {:?}", command.read_message());

  let _ = jg.join();
  info!("good bye");
}

<|endoftext|>


<commit_before><commit_msg>Add test: Kakuro.<commit_after>//! Kakuro.
//!
//! https://en.wikipedia.org/wiki/Kakuro

extern crate puzzle_solver;

use puzzle_solver::{LinExpr,Puzzle,Solution,Val,VarToken};

const SIZE: usize = 7;
const X: Val = 0;
type Board = [[Val; SIZE]; SIZE];
type KakuroVars = Vec<Vec<Option<VarToken>>>;

enum Rule {
    H{ total: Val, y: usize, x1: usize, x2: usize },
    V{ total: Val, x: usize, y1: usize, y2: usize },
}

fn make_kakuro(board: &[Rule]) -> (Puzzle, KakuroVars) {
    let mut sys = Puzzle::new();
    let mut vars = vec![vec![None; SIZE]; SIZE];

    for rule in board.iter() {
        let (total, x1, y1, x2, y2) = match rule {
            &Rule::H{total, y, x1, x2} => (total, x1, y, x2, y),
            &Rule::V{total, x, y1, y2} => (total, x, y1, x, y2),
        };

        let mut vec = Vec::new();
        for y in y1..(y2 + 1) {
            for x in x1..(x2 + 1) {
                let var = vars[y][x].unwrap_or_else(|| {
                    let var = sys.new_var_with_candidates(&[1,2,3,4,5,6,7,8,9]);
                    vars[y][x] = Some(var);
                    var
                });

                vec.push(var);
            }
        }

        sys.all_different(&vec);
        sys.equals(total, vec.iter().fold(LinExpr::from(0), |sum, &var| sum + var));
    }

    (sys, vars)
}

fn print_kakuro(dict: &Solution, vars: &KakuroVars) {
    for y in 0..SIZE {
        for x in 0..SIZE {
            if let Some(var) = vars[y][x] {
                print!(" {}", dict[var]);
            } else {
                print!(" .");
            }
        }
        println!();
    }
}

fn verify_kakuro(dict: &Solution, vars: &KakuroVars, expected: &Board) {
    for y in 0..SIZE {
        for x in 0..SIZE {
            let val = vars[y][x].map_or(X, |var| dict[var]);
            assert_eq!(val, expected[y][x]);
        }
    }
}

#[test]
fn kakuro_wikipedia() {
    let puzzle = [
        Rule::H{ total:16, y:0, x1:0, x2:1 }, Rule::H{ total:24, y:0, x1:4, x2:6},
        Rule::H{ total:17, y:1, x1:0, x2:1 }, Rule::H{ total:29, y:1, x1:3, x2:6},
        Rule::H{ total:35, y:2, x1:0, x2:4 },
        Rule::H{ total: 7, y:3, x1:1, x2:2 }, Rule::H{ total: 8, y:3, x1:4, x2:5},
        Rule::H{ total:16, y:4, x1:2, x2:6 },
        Rule::H{ total:21, y:5, x1:0, x2:3 }, Rule::H{ total: 5, y:5, x1:5, x2:6},
        Rule::H{ total: 6, y:6, x1:0, x2:2 }, Rule::H{ total: 3, y:6, x1:5, x2:6},

        Rule::V{ total:23, x:0, y1:0, y2:2 }, Rule::V{ total:11, x:0, y1:5, y2:6},
        Rule::V{ total:30, x:1, y1:0, y2:3 }, Rule::V{ total:10, x:1, y1:5, y2:6},
        Rule::V{ total:15, x:2, y1:2, y2:6 },
        Rule::V{ total:17, x:3, y1:1, y2:2 }, Rule::V{ total: 7, x:3, y1:4, y2:5},
        Rule::V{ total:27, x:4, y1:0, y2:4 },
        Rule::V{ total:12, x:5, y1:0, y2:1 }, Rule::V{ total:12, x:5, y1:3, y2:6},
        Rule::V{ total:16, x:6, y1:0, y2:1 }, Rule::V{ total: 7, x:6, y1:4, y2:6},
    ];

    let expected = [
        [ 9, 7, X, X, 8, 7, 9 ],
        [ 8, 9, X, 8, 9, 5, 7 ],
        [ 6, 8, 5, 9, 7, X, X ],
        [ X, 6, 1, X, 2, 6, X ],
        [ X, X, 4, 6, 1, 3, 2 ],
        [ 8, 9, 3, 1, X, 1, 4 ],
        [ 3, 1, 2, X, X, 2, 1 ] ];

    let (mut sys, vars) = make_kakuro(&puzzle);
    let dict = sys.solve_any().expect("solution");
    print_kakuro(&dict, &vars);
    verify_kakuro(&dict, &vars, &expected);
    println!("kakuro_wikipedia: {} guesses", sys.num_guesses());
}
<|endoftext|>


<commit_before><commit_msg>quat: TDD<commit_after><|endoftext|>


<commit_before><commit_msg>update print messages<commit_after><|endoftext|>


<commit_before><commit_msg>Add Tabs widget<commit_after>use unicode_width::UnicodeWidthStr;

use widgets::{Block, Widget};
use buffer::Buffer;
use layout::Rect;
use style::Color;
use symbols::line;

pub struct Tabs<'a> {
    block: Option<Block<'a>>,
    titles: &'a [&'a str],
    selected: usize,
    highlight_color: Color,
    color: Color,
}

impl<'a> Default for Tabs<'a> {
    fn default() -> Tabs<'a> {
        Tabs {
            block: None,
            titles: &[],
            selected: 0,
            highlight_color: Color::Reset,
            color: Color::Reset,
        }
    }
}

impl<'a> Tabs<'a> {
    pub fn block(&mut self, block: Block<'a>) -> &mut Tabs<'a> {
        self.block = Some(block);
        self
    }

    pub fn titles(&mut self, titles: &'a [&'a str]) -> &mut Tabs<'a> {
        self.titles = titles;
        self
    }

    pub fn select(&mut self, selected: usize) -> &mut Tabs<'a> {
        self.selected = selected;
        self
    }

    pub fn color(&mut self, color: Color) -> &mut Tabs<'a> {
        self.color = color;
        self
    }

    pub fn highlight_color(&mut self, color: Color) -> &mut Tabs<'a> {
        self.highlight_color = color;
        self
    }
}

impl<'a> Widget for Tabs<'a> {
    fn buffer(&self, area: &Rect, buf: &mut Buffer) {
        let tabs_area = match self.block {
            Some(b) => {
                b.buffer(area, buf);
                b.inner(area)
            }
            None => *area,
        };
        if tabs_area.height < 1 {
            return;
        }

        let mut x = tabs_area.left();
        for (title, color) in self.titles.iter().enumerate().map(|(i, t)| if i == self.selected {
            (t, self.highlight_color)
        } else {
            (t, self.color)
        }) {
            x += 1;
            if x > tabs_area.right() {
                break;
            } else {
                buf.set_string(x, tabs_area.top(), title, color, Color::Reset);
                x += title.width() as u16 + 1;
                if x > tabs_area.right() {
                    break;
                } else {
                    buf.set_cell(x,
                                 tabs_area.top(),
                                 line::VERTICAL,
                                 Color::Reset,
                                 Color::Reset);
                    x += 1;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Adding in windows backend<commit_after>use std::rc::Rc;
use std::cell::RefCell;
use std::sync::atomic::{AtomicU32, Ordering};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use futures::channel::mpsc;
use futures::stream::Stream;
use std::future::Future;
use dominator::clone;
use uuid::Uuid;
use js_sys::{Array, Promise};
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen::{JsCast, intern};
use wasm_bindgen::prelude::*;
use tab_organizer::{Listener, deserialize, serialize, object, array};
use web_extension::browser;

#[derive(Debug)]
struct Mapping<A> {
    keys: HashMap<i32, Id>,
    values: HashMap<Id, A>,
}

impl<A> Mapping<A> {
    fn new() -> Self {
        Self {
            keys: HashMap::new(),
            values: HashMap::new(),
        }
    }

    fn has_key(&self, key: i32) -> bool {
        self.keys.contains_key(&key)
    }

    fn get_key(&self, key: i32) -> Option<Id> {
        self.keys.get(&key).map(|x| *x)
    }

    fn get_mut(&mut self, key: i32) -> Option<(Id, &mut A)> {
        let id = self.get_key(key)?;
        Some((id, self.values.get_mut(&id).unwrap()))
    }

    fn get_or_insert<F>(&mut self, key: i32, id: Id, set: F) -> &mut A where F: FnOnce() -> A {
        let entry = self.values.entry(id);

        match entry {
            Entry::Vacant(_) => {
                self.keys.insert(key, id).unwrap_none();
            },
            Entry::Occupied(_) => {
                assert_eq!(*self.keys.get(&key).unwrap(), id);
            },
        }

        entry.or_insert_with(set)
    }

    fn remove(&mut self, key: i32) -> Option<(Id, A)> {
        let id = self.keys.remove(&key)?;
        let value = self.values.remove(&id).unwrap();
        Some((id, value))
    }

    fn move_key(&mut self, old_key: i32, new_key: i32) -> Option<&mut A> {
        if let Some(id) = self.keys.remove(&old_key) {
            self.keys.insert(new_key, id).unwrap_none();
            Some(self.values.get_mut(&id).unwrap())

        } else {
            None
        }
    }
}

impl<A> Mapping<A> where A: std::fmt::Debug {
    fn insert(&mut self, key: i32, id: Id, value: A) {
        self.keys.insert(key, id).unwrap_none();
        self.values.insert(id, value).unwrap_none();
    }
}

fn get_uuid(fut: Promise) -> impl Future<Output = Result<Option<Uuid>, JsValue>> {
    async move {
        let id = JsFuture::from(fut).await?;

        // TODO better implementation of this ?
        if id.is_undefined() {
            Ok(None)

        } else {
            Ok(Some(deserialize(&id)))
        }
    }
}

fn set_uuid(fut: Promise) -> impl Future<Output = Result<(), JsValue>> {
    async move {
        let value = JsFuture::from(fut).await?;

        assert!(value.is_undefined());

        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id(u32);

impl Id {
    fn new() -> Self {
        static COUNTER: AtomicU32 = AtomicU32::new(0);

        // TODO more efficient ordering ?
        Id(COUNTER.fetch_add(1, Ordering::SeqCst))
    }
}

#[derive(Debug)]
pub struct TabAudio {
    pub playing: bool,
    pub muted: bool,
}

impl TabAudio {
    fn new(browser_tab: &web_extension::Tab) -> Self {
        Self {
            playing: browser_tab.audible().unwrap_or(false),
            muted: browser_tab.muted_info().muted(),
        }
    }
}

#[derive(Debug)]
pub enum TabStatus {
    New,
    Loading,
    Complete,
}

impl TabStatus {
    fn new(browser_tab: &web_extension::Tab) -> Self {
        match browser_tab.status().as_deref() {
            None => Self::New,
            Some("loading") => Self::Loading,
            Some("complete") => Self::Complete,
            Some(status) => panic!("Unknown tab status: {}", status),
        }
    }
}

#[derive(Debug)]
pub struct TabState {
    pub id: Id,
    pub focused: bool,
    pub pinned: bool,
    pub has_attention: bool,
    pub audio: TabAudio,
    pub status: TabStatus,
    pub favicon_url: Option<String>,
    pub title: Option<String>,
    pub url: Option<String>,
}

impl TabState {
    fn new(id: Id, browser_tab: &web_extension::Tab) -> Self {
        Self {
            id,
            focused: browser_tab.active(),
            pinned: browser_tab.pinned(),
            has_attention: browser_tab.attention().unwrap_or(false),
            audio: TabAudio::new(browser_tab),
            status: TabStatus::new(browser_tab),
            favicon_url: browser_tab.fav_icon_url(),
            title: browser_tab.title(),
            url: browser_tab.url(),
        }
    }
}

#[derive(Debug)]
pub struct WindowState {
    pub id: Id,
    pub focused: bool,
    pub tabs: Vec<TabState>,
}

impl WindowState {
    fn new(id: Id, tabs: Vec<TabState>, browser_window: &web_extension::Window) -> Self {
        Self {
            id,
            focused: browser_window.focused(),
            tabs
        }
    }
}

#[derive(Debug)]
struct TabDetached {
    index: u32,
    window_id: Id,
}

#[derive(Debug)]
pub struct Tab {
    tab_id: i32,
    window_id: i32,
    detached: Option<TabDetached>,
}

impl Tab {
    pub fn get_uuid(&self) -> impl Future<Output = Result<Option<Uuid>, JsValue>> {
        get_uuid(browser.sessions().get_tab_value(self.tab_id, intern("id")))
    }

    pub fn set_uuid(&self, uuid: Uuid) -> impl Future<Output = Result<(), JsValue>> {
        set_uuid(browser.sessions().set_tab_value(self.tab_id, intern("id"), &serialize(&uuid)))
    }

    /*fn to_tab(&self, window: &Window) -> Tab {
        Tab {
            // TODO figure out a way to avoid this clone
            serialized: self.serialized.clone(),
            focused: window.is_tab_focused(self.uuid),
            playing_audio: self.playing_audio,
        }
    }*/
}

#[derive(Debug)]
pub struct Window {
    window_id: i32,
}

impl Window {
    pub fn get_uuid(&self) -> impl Future<Output = Result<Option<Uuid>, JsValue>> {
        get_uuid(browser.sessions().get_window_value(self.window_id, intern("id")))
    }

    pub fn set_uuid(&self, uuid: Uuid) -> impl Future<Output = Result<(), JsValue>> {
        set_uuid(browser.sessions().set_window_value(self.window_id, intern("id"), &serialize(&uuid)))
    }

    /*pub fn is_tab_focused(&self, tab_id: i32) -> bool {
        match self.focused_tab {
            Some(id) => id == tab_id,
            None => false,
        }
    }

    pub fn set_focused(&mut self, new_id: i32) -> Option<Option<i32>> {
        let old_id = self.focused_tab;

        if let Some(old_id) = old_id {
            if old_id == new_id {
                return None;
            }
        }

        self.focused_tab = Some(new_id);

        return Some(old_id);
    }

    pub fn unfocus_tab(&mut self, tab_id: i32) {
        if let Some(old_id) = self.focused_tab {
            if old_id == tab_id {
                self.focused_tab = None;
            }
        }
    }

    pub fn detach_tab(&mut self, tab_id: i32, index: usize) {
        assert_eq!(self.tabs.remove(index), tab_id);

        self.unfocus_tab(tab_id);
    }*/
}

/*let fut = get_window_id(window_id);

                    spawn(clone!(state => async move {
                        if let Some(id) = fut.await? {
                            Some(id)

                        } else {
                            if state.borrow().windows.contains(window_id) {
                                let id = generate_uuid();
                                set_window_id(window_id, id).await?;
                                Some(id)

                            // Window was removed
                            } else {
                                None
                            }
                        }
                    }));*/

#[derive(Debug)]
struct BrowserState {
    tabs: Mapping<Tab>,
    windows: Mapping<Window>,
}

impl BrowserState {
    fn new_tab(&mut self, browser_tab: &web_extension::Tab) -> TabState {
        let id = Id::new();
        let tab_id = browser_tab.id().unwrap();
        let window_id = browser_tab.window_id();

        self.tabs.insert(tab_id, id, Tab { tab_id, window_id, detached: None });

        TabState::new(id, browser_tab)
    }

    fn new_window(&mut self, browser_window: &web_extension::Window) -> WindowState {
        let id = Id::new();
        let window_id = browser_window.id().unwrap();

        let tabs = browser_window.tabs().map(|array| {
            array.iter().map(|tab| {
                let tab: web_extension::Tab = tab.unchecked_into();
                self.new_tab(&tab)
            }).collect()
        }).unwrap_or_else(|| vec![]);

        self.windows.insert(window_id, id, Window { window_id });

        WindowState::new(id, tabs, browser_window)
    }

    fn create_or_update_tab(&mut self, browser_tab: &web_extension::Tab) -> Option<BrowserChange> {
        let window_id = browser_tab.window_id();

        // If the tab is in a normal window
        if self.windows.has_key(window_id) {
            let tab_id = browser_tab.id().unwrap();

            if let Some(id) = self.tabs.get_key(tab_id) {
                Some(BrowserChange::TabUpdated { tab: TabState::new(id, &browser_tab) })

            } else {
                Some(BrowserChange::TabCreated { tab: self.new_tab(&browser_tab) })
            }

        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct Browser {
    state: Rc<RefCell<BrowserState>>,
}

impl Browser {
    pub fn new() -> Self {
        Self {
            state: Rc::new(RefCell::new(BrowserState {
                tabs: Mapping::new(),
                windows: Mapping::new(),
            })),
        }
    }

    pub fn current(&self) -> impl Future<Output = Result<Vec<WindowState>, JsValue>> {
        // TODO should this be inside the async ?
        let fut = JsFuture::from(browser.windows().get_all(&object! {
            "populate": true,
            "windowTypes": array![ intern("normal") ],
        }));

        let state = self.state.clone();

        async move {
            let windows = fut.await?;

            let mut state = state.borrow_mut();

            Ok(windows
                .unchecked_into::<Array>()
                .iter()
                .map(|window| {
                    let window: web_extension::Window = window.unchecked_into();
                    state.new_window(&window)
                })
                .collect())
        }
    }

    pub fn changes(&self) -> impl Stream<Item = BrowserChange> {
        let (sender, receiver) = mpsc::unbounded();

        let state = self.state.clone();

        BrowserChanges {
            _window_created: Listener::new(browser.windows().on_created(), Closure::new(clone!(sender, state => move |window: web_extension::Window| {
                if window.type_().map(|x| x == "normal").unwrap_or(false) {
                    let window = state.borrow_mut().new_window(&window);

                    sender.unbounded_send(
                        BrowserChange::WindowCreated { window }
                    ).unwrap();
                }
            }))),

            _window_removed: Listener::new(browser.windows().on_removed(), Closure::new(clone!(sender, state => move |window_id: i32| {
                let id = state.borrow_mut().windows.remove(window_id);

                if let Some((window_id, _)) = id {
                    sender.unbounded_send(
                        BrowserChange::WindowRemoved { window_id }
                    ).unwrap();
                }
            }))),

            _window_focused: Listener::new(browser.windows().on_focus_changed(), Closure::new(clone!(sender, state => move |window_id: i32| {
                let window_id = if window_id == browser.windows().window_id_none() {
                    None

                } else {
                    state.borrow().windows.get_key(window_id)
                };

                sender.unbounded_send(
                    BrowserChange::WindowFocused { window_id }
                ).unwrap();
            }))),

            _tab_created: Listener::new(browser.tabs().on_created(), Closure::new(clone!(sender, state => move |tab: web_extension::Tab| {
                let message = state.borrow_mut().create_or_update_tab(&tab);

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            }))),

            _tab_updated: Listener::new(browser.tabs().on_updated(), Closure::new(clone!(sender, state => move |_tab_id: i32, _change_info: JsValue, tab: web_extension::Tab| {
                let message = state.borrow_mut().create_or_update_tab(&tab);

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            }))),

            _tab_replaced: Listener::new(browser.tabs().on_replaced(), Closure::new(clone!(state => move |new_tab_id: i32, old_tab_id: i32| {
                if let Some(tab) = state.borrow_mut().tabs.move_key(old_tab_id, new_tab_id) {
                    tab.tab_id = new_tab_id;
                }
            }))),

            _tab_focused: Listener::new(browser.tabs().on_activated(), Closure::new(clone!(sender, state => move |active_info: web_extension::TabActiveInfo| {
                let message = {
                    let state = state.borrow();

                    if let Some(window_id) = state.windows.get_key(active_info.window_id()) {
                        let old_tab_id = active_info.previous_tab_id().map(|tab_id| state.tabs.get_key(tab_id).unwrap());
                        let new_tab_id = state.tabs.get_key(active_info.tab_id()).unwrap();
                        Some(BrowserChange::TabFocused { old_tab_id, new_tab_id, window_id })

                    } else {
                        None
                    }
                };

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            }))),

            _tab_detached: Listener::new(browser.tabs().on_detached(), Closure::new(clone!(state => move |tab_id: i32, detach_info: web_extension::TabDetachInfo| {
                let state: &mut BrowserState = &mut state.borrow_mut();

                if let Some((_, tab)) = state.tabs.get_mut(tab_id) {
                    let window_id = state.windows.get_key(detach_info.old_window_id()).unwrap();

                    tab.detached = Some(TabDetached {
                        window_id,
                        index: detach_info.old_position(),
                    });
                }
            }))),

            _tab_attached: Listener::new(browser.tabs().on_attached(), Closure::new(clone!(sender, state => move |tab_id: i32, attach_info: web_extension::TabAttachInfo| {
                let message = {
                    let mut state = state.borrow_mut();

                    if let Some((tab_id, tab)) = state.tabs.get_mut(tab_id) {
                        let detached = tab.detached.take().unwrap();

                        let new_window_id = state.windows.get_key(attach_info.new_window_id()).unwrap();

                        Some(BrowserChange::TabAttached {
                            tab_id,

                            old_window_id: detached.window_id,
                            old_index: detached.index,

                            new_window_id,
                            new_index: attach_info.new_position(),
                        })

                    } else {
                        None
                    }
                };

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            }))),

            _tab_moved: Listener::new(browser.tabs().on_moved(), Closure::new(clone!(sender, state => move |tab_id: i32, move_info: web_extension::TabMoveInfo| {
                let message = {
                    let state = state.borrow();

                    if let Some(tab_id) = state.tabs.get_key(tab_id) {
                        let window_id = state.windows.get_key(move_info.window_id()).unwrap();

                        Some(BrowserChange::TabMoved {
                            tab_id,
                            window_id,
                            old_index: move_info.from_index(),
                            new_index: move_info.to_index(),
                        })

                    } else {
                        None
                    }
                };

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            }))),

            _tab_removed: Listener::new(browser.tabs().on_removed(), Closure::new(move |tab_id: i32, remove_info: web_extension::TabRemoveInfo| {
                let message = {
                    let mut state = state.borrow_mut();

                    if let Some((tab_id, _)) = state.tabs.remove(tab_id) {
                        let window_id = state.windows.get_key(remove_info.window_id()).unwrap();

                        Some(BrowserChange::TabRemoved {
                            tab_id,
                            window_id,
                            is_window_closing: remove_info.is_window_closing(),
                        })

                    } else {
                        None
                    }
                };

                if let Some(message) = message {
                    sender.unbounded_send(message).unwrap();
                }
            })),

            receiver,
        }
    }
}

#[derive(Debug)]
pub enum BrowserChange {
    WindowCreated {
        window: WindowState,
    },
    WindowRemoved {
        window_id: Id,
    },
    WindowFocused {
        window_id: Option<Id>,
    },
    TabCreated {
        tab: TabState,
    },
    TabFocused {
        old_tab_id: Option<Id>,
        new_tab_id: Id,
        window_id: Id,
    },
    TabAttached {
        tab_id: Id,

        old_window_id: Id,
        old_index: u32,

        new_window_id: Id,
        new_index: u32,
    },
    TabMoved {
        tab_id: Id,
        window_id: Id,
        old_index: u32,
        new_index: u32,
    },
    TabUpdated {
        tab: TabState,
    },
    TabRemoved {
        tab_id: Id,
        window_id: Id,
        is_window_closing: bool,
    },
}

struct BrowserChanges {
    _window_created: Listener<dyn FnMut(web_extension::Window)>,
    _window_removed: Listener<dyn FnMut(i32)>,
    _window_focused: Listener<dyn FnMut(i32)>,
    _tab_created: Listener<dyn FnMut(web_extension::Tab)>,
    _tab_focused: Listener<dyn FnMut(web_extension::TabActiveInfo)>,
    _tab_detached: Listener<dyn FnMut(i32, web_extension::TabDetachInfo)>,
    _tab_replaced: Listener<dyn FnMut(i32, i32)>,
    _tab_attached: Listener<dyn FnMut(i32, web_extension::TabAttachInfo)>,
    _tab_moved: Listener<dyn FnMut(i32, web_extension::TabMoveInfo)>,
    _tab_updated: Listener<dyn FnMut(i32, JsValue, web_extension::Tab)>,
    _tab_removed: Listener<dyn FnMut(i32, web_extension::TabRemoveInfo)>,
    receiver: mpsc::UnboundedReceiver<BrowserChange>,
}

impl Stream for BrowserChanges {
    type Item = BrowserChange;

    #[inline]
    fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context) -> std::task::Poll<Option<Self::Item>> {
        std::pin::Pin::new(&mut self.receiver).poll_next(cx)
    }
}
<|endoftext|>


<commit_before><commit_msg>change update cycle to update in doc<commit_after><|endoftext|>


<commit_before><commit_msg>Account for border-radius in hit-testing<commit_after><|endoftext|>


<commit_before><commit_msg>add space<commit_after><|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// Simple Prometheus support. Still a work in progress.
// The goal here is to develop a prometheus client that
// is fully designed for prometheus with the minimal
// dependencies and overhead.
//
// We currently provide no abstraction around collecting metrics.
// This Reporter eventually needs to handle the multiplexing and
// organization of metrics.

extern crate iron;
extern crate router;
extern crate persistent;
extern crate protobuf; // depend on rust-protobuf runtime
extern crate lru_cache;
extern crate time;

pub mod promo_proto;
use router::Router;
use iron::typemap::Key;
use iron::prelude::*;
use iron::status;
use lru_cache::LruCache;
use protobuf::Message;
use std::sync::{Arc, RwLock};
use std::thread;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;

// http handler storage
#[derive(Copy, Clone)]
struct HandlerStorage;

// refer to https://prometheus.io/docs/instrumenting/exposition_formats/
const CONTENT_TYPE: &'static str = "application/vnd.google.protobuf; \
                                    proto=io.prometheus.client.MetricFamily;
                                    encoding=delimited";

impl Key for HandlerStorage {
    type Value = Arc<RwLock<LruCache<u64, promo_proto::MetricFamily>>>;
}

fn families_to_u8(metric_families: Vec<(&u64, &promo_proto::MetricFamily)>) -> Vec<u8> {
    let mut buf = Vec::new();
    for (_, family) in metric_families {
        family.write_length_delimited_to_writer(&mut buf).unwrap();
    }
    buf
}

fn handler(req: &mut Request) -> IronResult<Response> {
    match req.get::<persistent::Read<HandlerStorage>>() {
        Ok(ts_and_metrics) => {
            // TODO catch unwrap
            let serialized: Vec<u8> =
                families_to_u8((*ts_and_metrics).read().unwrap().iter().collect());
            // TODO lifecycle out the metrics we sent up
            Ok(Response::with((CONTENT_TYPE, status::Ok, serialized)))
        }
        Err(_) => Ok(Response::with((status::InternalServerError, "ERROR"))),
    }
}

// TODO perhaps we autodiscover the host and port
pub struct PrometheusReporter {
    cache: Arc<RwLock<LruCache<u64, promo_proto::MetricFamily>>>
}

impl PrometheusReporter {
    pub fn new(host_and_port: &'static str) -> Self {
        let reporter = PrometheusReporter {
            // TODO make it configurable
            cache: Arc::new(RwLock::new(LruCache::new(86400)))
        };
        let mut router = Router::new();
        router.get("/metrics", handler);
        let mut chain = Chain::new(router);
        chain.link_before(persistent::Read::<HandlerStorage>::one(reporter.cache.clone()));
        // TODO get rid of the unwrap

        thread::spawn(move ||{
            match Iron::new(chain).http(host_and_port) {
                Ok(_) => {}
                Err(x) => panic!("Unable to start prometheus reporter {}",x),
            }
        });
        reporter
    }
    // TODO require start before add
    pub fn add(&mut self, metric_families: Vec<promo_proto::MetricFamily>) -> Result<i64, String> {

        match self.cache.write() {
            Ok(mut cache) => {
                let mut counter = 0;
                for metric_family in metric_families {

                    let mut hasher = DefaultHasher::new();
                    metric_family.get_name().hash(&mut hasher);
                    cache.insert(hasher.finish(), metric_family);
                    counter = counter + 1;
                }
                Ok(counter)
            }
            Err(y) => Err(format!("Unable to add {}", y)),
        }
    }

    pub fn remove(&mut self, metrics_to_remove: Vec<String>) -> Result<i64, String> {
        let mut hasher = DefaultHasher::new();
        match self.cache.write() {
            Ok(mut cache) => {
                let mut counter = 0;
                for metric_name_to_remove in metrics_to_remove {

                    let mut hasher = DefaultHasher::new();
                    metric_name_to_remove.hash(&mut hasher);
                    cache.remove(&hasher.finish());
                    counter = counter + 1;
                }
                Ok(counter)
            }
            Err(y) => Err(format!("Unable to remove {}", y)),
        }
    }
}

#[cfg(test)]
mod test {

    extern crate hyper;
    extern crate lru_cache;
    use std::thread;
    use std::time::Duration;
    use protobuf::repeated::RepeatedField;
    use std::io::Read;
    use super::*;

    fn a_metric_family() -> promo_proto::MetricFamily {
        let mut family = promo_proto::MetricFamily::new();
        family.set_name("MetricFamily".to_string());
        family.set_help("Help".to_string());
        family.set_field_type(promo_proto::MetricType::GAUGE);

        let mut metric = promo_proto::Metric::new();
        metric.set_timestamp_ms(a_ts());
        metric.set_gauge(a_gauge());
        metric.set_label(a_label_pair());
        family.set_metric(RepeatedField::from_vec(vec![metric]));

        family
    }

    fn a_label_pair() -> RepeatedField<promo_proto::LabelPair> {
        let mut label_pair = promo_proto::LabelPair::new();
        // The name and value alas are the names of the
        // protobuf fields in the pair in prometheus protobuf spec
        // Thes undescriptive names are part of the protocol alas.
        label_pair.set_name("name".to_string());
        label_pair.set_value("value".to_string());
        RepeatedField::from_vec(vec![label_pair])
    }

    fn a_gauge() -> promo_proto::Gauge {
        let mut gauge = promo_proto::Gauge::new();
        gauge.set_value(0.1);
        gauge
    }

    fn a_ts() -> i64 {
        0
    }

    #[test]
    fn add_some_stats_and_slurp_them_with_http() {
        let mut reporter = PrometheusReporter::new("0.0.0.0:8080");
        thread::sleep(Duration::from_millis(1024));
        reporter.add(vec![a_metric_family()]);
        let client = hyper::client::Client::new();
        let mut res = client.get("http://127.0.0.1:8080/metrics").send().unwrap();
        assert_eq!(res.status, hyper::Ok);
        let mut buffer = Vec::new();
        let size_of_buffer = res.read_to_end(&mut buffer).unwrap();
        println!("{:?} size:{} ", buffer, size_of_buffer);
        assert_eq!(size_of_buffer, 53);
    }
}
<commit_msg>Fixing count of removal and Adding test for removing<commit_after>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// Simple Prometheus support. Still a work in progress.
// The goal here is to develop a prometheus client that
// is fully designed for prometheus with the minimal
// dependencies and overhead.
//
// We currently provide no abstraction around collecting metrics.
// This Reporter eventually needs to handle the multiplexing and
// organization of metrics.

extern crate iron;
extern crate router;
extern crate persistent;
extern crate protobuf; // depend on rust-protobuf runtime
extern crate lru_cache;
extern crate time;

pub mod promo_proto;
use router::Router;
use iron::typemap::Key;
use iron::prelude::*;
use iron::status;
use lru_cache::LruCache;
use protobuf::Message;
use std::sync::{Arc, RwLock};
use std::thread;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;

// http handler storage
#[derive(Copy, Clone)]
struct HandlerStorage;

// refer to https://prometheus.io/docs/instrumenting/exposition_formats/
const CONTENT_TYPE: &'static str = "application/vnd.google.protobuf; \
                                    proto=io.prometheus.client.MetricFamily;
                                    encoding=delimited";

impl Key for HandlerStorage {
    type Value = Arc<RwLock<LruCache<u64, promo_proto::MetricFamily>>>;
}

fn families_to_u8(metric_families: Vec<(&u64, &promo_proto::MetricFamily)>) -> Vec<u8> {
    let mut buf = Vec::new();
    for (_, family) in metric_families {
        family.write_length_delimited_to_writer(&mut buf).unwrap();
    }
    buf
}

fn handler(req: &mut Request) -> IronResult<Response> {
    match req.get::<persistent::Read<HandlerStorage>>() {
        Ok(ts_and_metrics) => {
            // TODO catch unwrap
            let serialized: Vec<u8> =
                families_to_u8((*ts_and_metrics).read().unwrap().iter().collect());
            // TODO lifecycle out the metrics we sent up
            Ok(Response::with((CONTENT_TYPE, status::Ok, serialized)))
        }
        Err(_) => Ok(Response::with((status::InternalServerError, "ERROR"))),
    }
}

// TODO perhaps we autodiscover the host and port
pub struct PrometheusReporter {
    cache: Arc<RwLock<LruCache<u64, promo_proto::MetricFamily>>>
}

impl PrometheusReporter {
    pub fn new(host_and_port: &'static str) -> Self {
        let reporter = PrometheusReporter {
            // TODO make it configurable
            cache: Arc::new(RwLock::new(LruCache::new(86400)))
        };
        let mut router = Router::new();
        router.get("/metrics", handler);
        let mut chain = Chain::new(router);
        chain.link_before(persistent::Read::<HandlerStorage>::one(reporter.cache.clone()));
        // TODO get rid of the unwrap

        thread::spawn(move ||{
            match Iron::new(chain).http(host_and_port) {
                Ok(_) => {}
                Err(x) => panic!("Unable to start prometheus reporter {}",x),
            }
        });
        reporter
    }
    // TODO require start before add
    pub fn add(&mut self, metric_families: Vec<promo_proto::MetricFamily>) -> Result<i64, String> {

        match self.cache.write() {
            Ok(mut cache) => {
                let mut counter = 0;
                for metric_family in metric_families {

                    let mut hasher = DefaultHasher::new();
                    metric_family.get_name().hash(&mut hasher);
                    cache.insert(hasher.finish(), metric_family);
                    counter = counter + 1;
                }
                Ok(counter)
            }
            Err(y) => Err(format!("Unable to add {}", y)),
        }
    }

    pub fn remove(&mut self, metrics_to_remove: Vec<String>) -> Result<i64, String> {
        let mut hasher = DefaultHasher::new();
        match self.cache.write() {
            Ok(mut cache) => {
                let mut counter = 0;
                for metric_name_to_remove in metrics_to_remove {

                    let mut hasher = DefaultHasher::new();
                    metric_name_to_remove.hash(&mut hasher);
                    if let Some(_) = cache.remove(&hasher.finish()) {
                        counter = counter + 1;
                    }
                }
                Ok(counter)
            }
            Err(y) => Err(format!("Unable to remove {}", y)),
        }
    }
}

#[cfg(test)]
mod test {

    extern crate hyper;
    extern crate lru_cache;
    use std::thread;
    use std::time::Duration;
    use protobuf::repeated::RepeatedField;
    use std::io::Read;
    use super::*;

    fn a_metric_family_name() -> String {
       "MetricFamily".to_string()
    }

    fn a_metric_family() -> promo_proto::MetricFamily {
        let mut family = promo_proto::MetricFamily::new();
        family.set_name(a_metric_family_name());
        family.set_help("Help".to_string());
        family.set_field_type(promo_proto::MetricType::GAUGE);

        let mut metric = promo_proto::Metric::new();
        metric.set_timestamp_ms(a_ts());
        metric.set_gauge(a_gauge());
        metric.set_label(a_label_pair());
        family.set_metric(RepeatedField::from_vec(vec![metric]));

        family
    }

    fn a_label_pair() -> RepeatedField<promo_proto::LabelPair> {
        let mut label_pair = promo_proto::LabelPair::new();
        // The name and value alas are the names of the
        // protobuf fields in the pair in prometheus protobuf spec
        // Thes undescriptive names are part of the protocol alas.
        label_pair.set_name("name".to_string());
        label_pair.set_value("value".to_string());
        RepeatedField::from_vec(vec![label_pair])
    }

    fn a_gauge() -> promo_proto::Gauge {
        let mut gauge = promo_proto::Gauge::new();
        gauge.set_value(0.1);
        gauge
    }

    fn a_ts() -> i64 {
        0
    }

    #[test]
    fn add_some_stats_and_slurp_them_with_http() {
        let mut reporter = PrometheusReporter::new("0.0.0.0:8080");
        thread::sleep(Duration::from_millis(1024));
        reporter.add(vec![a_metric_family()]);
        let client = hyper::client::Client::new();
        let mut res = client.get("http://127.0.0.1:8080/metrics").send().unwrap();
        assert_eq!(res.status, hyper::Ok);
        let mut buffer = Vec::new();
        let size_of_buffer = res.read_to_end(&mut buffer).unwrap();
        println!("{:?} size:{} ", buffer, size_of_buffer);
        assert_eq!(size_of_buffer, 53);
    }

    #[test]
    fn add_and_remove_metric() {
        let mut reporter = PrometheusReporter::new("0.0.0.0:8081");
        thread::sleep(Duration::from_millis(1024));
        reporter.add(vec![a_metric_family()]);
        if let Ok(number_removed) = reporter.remove(vec![a_metric_family_name()]) {
           assert_eq!(number_removed, 1);
        }
        if let Ok(number_removed) = reporter.remove(vec![a_metric_family_name()]) {
           assert_eq!(number_removed, 0);
        }
    }

}
<|endoftext|>


<commit_before>use std::num::SignedInt;
use std::iter::range_step_inclusive;

#[derive(FromPrimitive, Debug)]
pub enum FilterType {
    NoFilter = 0,
    Sub = 1,
    Up = 2,
    Avg = 3,
    Paeth = 4
}

fn filter_paeth(a: u8, b: u8, c: u8) -> u8 {
    let ia = a as i16;
    let ib = b as i16;
    let ic = c as i16;

    let p = ia + ib - ic;

    let pa = (p - ia).abs();
    let pb = (p - ib).abs();
    let pc = (p - ic).abs();

    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

pub fn unfilter(filter: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len = current.len();

    match filter {
        FilterType::NoFilter => (),
        FilterType::Sub => {
            for i in (bpp..len) {
                current[i] += current[i - bpp];
            }
        }
        FilterType::Up => {
            for i in (0..len) {
                current[i] += previous[i];
            }
        }
        FilterType::Avg => {
            for i in (0..bpp) {
                current[i] += previous[i] / 2;
            }

            for i in (bpp..len) {
                current[i] += ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth => {
            for i in (0..bpp) {
                current[i] += filter_paeth(0, previous[i], 0);
            }

            for i in (bpp..len) {
                current[i] += filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}

pub fn filter(method: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len  = current.len();

    match method {
        FilterType::NoFilter => (),
        FilterType::Sub      => {
            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - current[i - bpp];
            }
        }
        FilterType::Up       => {
            for i in (0..len) {
                current[i] = current[i] - previous[i];
            }
        }
        FilterType::Avg  => {
            for i in (0..bpp) {
                current[i] = current[i] - previous[i] / 2;
            }

            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth    => {
            for i in (0..bpp) {
                current[i] = current[i] - filter_paeth(0, previous[i], 0);
            }

            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}
<commit_msg>Fix regressions in PNG filter<commit_after>use std::num::SignedInt;

#[derive(FromPrimitive, Debug)]
pub enum FilterType {
    NoFilter = 0,
    Sub = 1,
    Up = 2,
    Avg = 3,
    Paeth = 4
}

fn filter_paeth(a: u8, b: u8, c: u8) -> u8 {
    let ia = a as i16;
    let ib = b as i16;
    let ic = c as i16;

    let p = ia + ib - ic;

    let pa = (p - ia).abs();
    let pb = (p - ib).abs();
    let pc = (p - ic).abs();

    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

pub fn unfilter(filter: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len = current.len();

    match filter {
        FilterType::NoFilter => (),
        FilterType::Sub => {
            for i in (bpp..len) {
                current[i] += current[i - bpp];
            }
        }
        FilterType::Up => {
            for i in (0..len) {
                current[i] += previous[i];
            }
        }
        FilterType::Avg => {
            for i in (0..bpp) {
                current[i] += previous[i] / 2;
            }

            for i in (bpp..len) {
                current[i] += ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth => {
            for i in (0..bpp) {
                current[i] += filter_paeth(0, previous[i], 0);
            }

            for i in (bpp..len) {
                current[i] += filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}

pub fn filter(method: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len  = current.len();

    match method {
        FilterType::NoFilter => (),
        FilterType::Sub      => {
            for i in (bpp..len).rev() {
                current[i] = current[i] - current[i - bpp];
            }
        }
        FilterType::Up       => {
            for i in (0..len) {
                current[i] = current[i] - previous[i];
            }
        }
        FilterType::Avg  => {
            for i in (bpp..len) {
                current[i] = current[i] - ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }

            for i in (0..bpp) {
                current[i] = current[i] - previous[i] / 2;
            }
        }
        FilterType::Paeth    => {
            for i in (bpp..len) {
                current[i] = current[i] - filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }

            for i in (0..bpp) {
                current[i] = current[i] - filter_paeth(0, previous[i], 0);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add rust code for luhn<commit_after>pub fn is_valid(id: &str) -> bool {
    // check the length
    if id.len() < 2 {
        return false;
    }

    let mut index: u32 = 0;
    let mut number: Vec<u32> = Vec::new();

    for c in id.chars().rev() {
        if c.is_whitespace() {
            continue;
        }

        let mut v: u32;

        match c.to_digit(10) {
            Some(d) => v = d,
            None => return false,
        }

        if index % 2 != 0 {
            v *= 2;

            if v > 9 {
                v -= 9;
            }

        }

        index += 1;

        number.push(v);
    }

    if number.len() == 1 {
        return false;
    }

    let r: u32 = number.iter().sum();

    (r % 10) == 0
}
<|endoftext|>


<commit_before><commit_msg>Have empty cells for non-stops.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix off by one error<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Colored Prompt<commit_after><|endoftext|>


<commit_before><commit_msg>data bag item support<commit_after>use api_client::{ApiClient, Error};
use serde_json;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::io::{Cursor, Read, ErrorKind};
use utils::decode_list;

chef_json_type!(DataBagItemJsonClass, "Chef::DataBagItem");
chef_json_type!(DataBagItemChefType, "data_bag_item");

#[derive(Debug,Clone,Serialize,Deserialize,Default)]
pub struct DataBagItem {
    id: Option<String>,
    #[serde(default)]
    data_bag: Option<String>,
    #[serde(default)]
    chef_type: DataBagItemChefType,
    #[serde(default)]
    json_class: DataBagItemJsonClass,
    #[serde(default)]
    pub raw_data: HashMap<String, Value>,
}

impl Read for DataBagItem {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Ok(data_bag_item) = serde_json::to_vec(self) {
            let mut data_bag_item = Cursor::new(data_bag_item.as_ref() as &[u8]);
            Read::read(&mut data_bag_item, buf)
        } else {
            Err(io::Error::new(ErrorKind::InvalidData,
                               "Failed to convert data_bag_item to JSON"))
        }
    }
}

impl DataBagItem {
    pub fn new<N, D>(id: N, data_bag: D) -> DataBagItem
        where N: Into<String>,
              D: Into<String>
    {
        DataBagItem {
            id: Some(id.into()),
            data_bag: Some(data_bag.into()),
            ..Default::default()
        }
    }

    pub fn fetch<N, D>(client: &ApiClient, data_bag: D, id: N) -> Result<DataBagItem, Error>
        where N: Into<String>,
              D: Into<String>
    {
        let org = &client.config.organization_path();
        let path = format!("{}/data/{}/{}", org, data_bag.into(), id.into());
        client.get(path.as_ref()).and_then(|r| r.from_json::<DataBagItem>())
    }

    pub fn id(&self) -> String {
        self.raw_data.get("id").unwrap().as_string().unwrap().to_owned()
    }

    pub fn save(&self, client: &ApiClient) -> Result<DataBagItem, Error> {
        let id = &self.id();
        let data_bag = &self.data_bag.clone().unwrap();
        let org = &client.config.organization_path();
        let path = format!("{}/data/{}/{}", org, data_bag, id);
        client.put(path.as_ref(), self).and_then(|r| r.from_json::<DataBagItem>())
    }

    pub fn delete(&self, client: &ApiClient) -> Result<DataBagItem, Error> {
        let id = &self.id();
        let data_bag = &self.data_bag.clone().unwrap();
        let org = &client.config.organization_path();
        let path = format!("{}/data/{}/{}", org, data_bag, id);
        client.delete(path.as_ref()).and_then(|r| r.from_json::<DataBagItem>())
    }

    pub fn from_json<R>(r: R) -> Result<DataBagItem, Error>
        where R: Read
    {
        serde_json::from_reader::<R, DataBagItem>(r).map_err(|e| Error::Json(e))
    }
}

pub fn delete_data_bag_item<D, N>(client: &ApiClient,
                                  data_bag: D,
                                  id: N)
                                  -> Result<DataBagItem, Error>
    where D: Into<String>,
          N: Into<String>
{
    let org = &client.config.organization_path();
    let path = format!("{}/data/{}/{}", org, data_bag.into(), id.into());
    client.delete(path.as_ref()).and_then(|r| r.from_json::<DataBagItem>())
}

#[derive(Debug)]
pub struct DataBagItemList {
    count: usize,
    data_bag: String,
    data_bag_items: Vec<String>,
    client: ApiClient,
}

impl DataBagItemList {
    pub fn new<D: Into<String>>(client: &ApiClient, data_bag: D) -> DataBagItemList {
        let org = &client.config.organization_path();
        let db = data_bag.into();
        let path = format!("{}/data/{}", org, &db);
        client.get(path.as_ref())
              .and_then(|r| decode_list(r))
              .and_then(|list| {
                  Ok(DataBagItemList {
                      data_bag: db,
                      data_bag_items: list,
                      count: 0,
                      client: client.clone(),
                  })
              })
              .unwrap()
    }
}

impl Iterator for DataBagItemList {
    type Item = Result<DataBagItem, Error>;

    fn count(self) -> usize {
        self.data_bag_items.len()
    }

    fn next(&mut self) -> Option<Result<DataBagItem, Error>> {
        if self.count < self.data_bag_items.len() {
            let ref name = self.data_bag_items[self.count];
            self.count += 1;
            Some(DataBagItem::fetch(&self.client, self.data_bag.clone(), name.as_ref()))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::DataBagItem;
    use std::fs::File;

    #[test]
    fn test_data_bag_item_from_file() {
        let fh = File::open("fixtures/data_bag_item.json").unwrap();
        let data_bag_item = DataBagItem::from_json(fh).unwrap();
        assert_eq!(data_bag_item.name.unwrap(), "test")
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #370 - kbknapp:issue-368, r=kbknapp<commit_after><|endoftext|>