<commit_before>use super::{error::TomlHelper, gobjects::GStatus, ident::Ident, parsable::Parse};
use crate::version::Version;
use log::error;
use toml::Value;

#[derive(Clone, Debug)]
pub struct Constant {
    pub ident: Ident,
    pub status: GStatus,
    pub version: Option<Version>,
    pub cfg_condition: Option<String>,
}

impl Parse for Constant {
    fn parse(toml: &Value, object_name: &str) -> Option<Constant> {
        let ident = match Ident::parse(toml, object_name, "function") {
            Some(ident) => ident,
            None => {
                error!(
                    "No 'name' or 'pattern' given for function for object {}",
                    object_name
                );
                return None;
            }
        };
        toml.check_unwanted(
            &[
                "ignore",
                "manual",
                "name",
                "version",
                "cfg_condition",
                "pattern",
            ],
            &format!("function {}", object_name),
        );

        let version = toml
            .lookup("version")
            .and_then(Value::as_str)
            .and_then(|s| s.parse().ok());
        let cfg_condition = toml
            .lookup("cfg_condition")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned);

        let status = {
            if toml
                .lookup("ignore")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                GStatus::Ignore
            } else if toml
                .lookup("manual")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                GStatus::Manual
            } else {
                GStatus::Generate
            }
        };

        Some(Constant {
            ident,
            status,
            version,
            cfg_condition,
        })
    }
}

impl AsRef<Ident> for Constant {
    fn as_ref(&self) -> &Ident {
        &self.ident
    }
}

pub type Constants = Vec<Constant>;
<commit_msg>Fix error message<commit_after>use super::{error::TomlHelper, gobjects::GStatus, ident::Ident, parsable::Parse};
use crate::version::Version;
use log::error;
use toml::Value;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Constant {
    pub ident: Ident,
    pub status: GStatus,
    pub version: Option<Version>,
    pub cfg_condition: Option<String>,
}

impl Parse for Constant {
    fn parse(toml: &Value, object_name: &str) -> Option<Constant> {
        let ident = match Ident::parse(toml, object_name, "constant") {
            Some(ident) => ident,
            None => {
                error!(
                    "No 'name' or 'pattern' given for constant for object {}",
                    object_name
                );
                return None;
            }
        };
        toml.check_unwanted(
            &[
                "ignore",
                "manual",
                "name",
                "version",
                "cfg_condition",
                "pattern",
            ],
            &format!("function {}", object_name),
        );

        let version = toml
            .lookup("version")
            .and_then(Value::as_str)
            .and_then(|s| s.parse().ok());
        let cfg_condition = toml
            .lookup("cfg_condition")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned);

        let status = {
            if toml
                .lookup("ignore")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                GStatus::Ignore
            } else if toml
                .lookup("manual")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                GStatus::Manual
            } else {
                GStatus::Generate
            }
        };

        Some(Constant {
            ident,
            status,
            version,
            cfg_condition,
        })
    }
}

impl AsRef<Ident> for Constant {
    fn as_ref(&self) -> &Ident {
        &self.ident
    }
}

pub type Constants = Vec<Constant>;
<|endoftext|>


<commit_before>vec![(
-0.455710106346205,
51.54845680184121
),
(
-0.455709712543818,
51.5485323305162
),
(
-0.455594367453926,
51.5485312620149
),
(
-0.455593479260942,
51.548536195991204
),
(
-0.455506951417257,
51.548535956295446
),
(
-0.455490372746285,
51.548535738074314
),
(
-0.455491624685765,
51.54845617423884
),
(
-0.455543538255777,
51.548456407953225
),
(
-0.455543319614012,
51.548441568066536
),
(
-0.455613238208449,
51.54844248834169
),
(
-0.455612781709629,
51.54845597052231
),
(
-0.455710106346205,
51.54845680184121
)]<commit_msg>Neater London vec<commit_after>vec![
    (-0.455710106346205, 51.548456801841212),
    (-0.455709712543818, 51.548532330516203),
    (-0.455594367453926, 51.548531262014897),
    (-0.455593479260942, 51.548536195991204),
    (-0.455506951417257, 51.548535956295446),
    (-0.455490372746285, 51.548535738074314),
    (-0.455491624685765, 51.548456174238837),
    (-0.455543538255777, 51.548456407953225),
    (-0.455543319614012, 51.548441568066536),
    (-0.455613238208449, 51.548442488341692),
    (-0.455612781709629, 51.548455970522312),
    (-0.455710106346205, 51.548456801841212)
]
<|endoftext|>


<commit_before>// Copyright 2015 Jauhien Piatlicki.
//
// 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.

// Core LLVM: Instructions hierarchy
// LLVM-C header Core.h

use std;

use libc::c_uint;

use llvm_sys::*;
use llvm_sys::prelude::*;
use llvm_sys::core::*;

use ::{LLVMRef, LLVMRefCtor};
use core::value::{Value, ValueCtor};

pub trait Instruction : Value + ValueCtor {
    fn get_parent(&self) -> LLVMBasicBlockRef {
        unsafe {
            LLVMGetInstructionParent(self.to_ref())
        }
    }

    fn get_next(&self) -> Self {
        unsafe {
            Self::from_ref(LLVMGetNextInstruction(self.to_ref()))
        }
    }

    fn get_previous(&self) -> Self {
        unsafe {
            Self::from_ref(LLVMGetPreviousInstruction(self.to_ref()))
        }
    }

    // TODO make this function safe and somehow inform compiler about
    // ref invalidation
    unsafe fn erase_from_parent(&mut self) {
        LLVMInstructionEraseFromParent(self.to_ref())
    }

    fn get_opcode(&self) -> LLVMOpcode {
        unsafe {
            LLVMGetInstructionOpcode(self.to_ref())
        }
    }
}

new_ref_type!(InstructionRef for LLVMValueRef
              implementing
              Value,
              ValueCtor,
              Instruction
              );

pub trait PHINode : Instruction {
    fn add_incoming(&self, incoming_values: &mut [LLVMValueRef], incoming_blocks: &mut [LLVMBasicBlockRef]) {
        assert!(incoming_values.len() == incoming_blocks.len());
        unsafe {
            LLVMAddIncoming(self.to_ref(),
                            incoming_values.as_mut_ptr(),
                            incoming_blocks.as_mut_ptr(),
                            incoming_values.len() as c_uint)
        }
    }

    fn count_incoming(&self) -> u32 {
        unsafe {
            LLVMCountIncoming(self.to_ref())
        }
    }

    fn get_incoming_value(&self, index: u32) -> Option<LLVMValueRef> {
        if index < self.count_incoming() {
            unsafe {
                Some(LLVMGetIncomingValue(self.to_ref(), index))
            }
        } else {
            None
        }
    }

    fn get_incoming_block(&self, index: u32) -> Option<LLVMBasicBlockRef> {
        if index < self.count_incoming() {
            unsafe {
                Some(LLVMGetIncomingBlock(self.to_ref(), index))
            }
        } else {
            None
        }
    }
}

new_ref_type!(PHINodeRef for LLVMValueRef
              implementing
              Value,
              ValueCtor,
              Instruction,
              PHINode
              );
<commit_msg>[core] fix ownership<commit_after>// Copyright 2015 Jauhien Piatlicki.
//
// 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.

// Core LLVM: Instructions hierarchy
// LLVM-C header Core.h

use std;

use libc::c_uint;

use llvm_sys::*;
use llvm_sys::prelude::*;
use llvm_sys::core::*;

use ::{LLVMRef, LLVMRefCtor};
use core::value::{Value, ValueCtor};

pub trait Instruction : Value + ValueCtor {
    fn get_parent(&self) -> LLVMBasicBlockRef {
        unsafe {
            LLVMGetInstructionParent(self.to_ref())
        }
    }

    fn get_next(&self) -> Self {
        unsafe {
            Self::from_ref(LLVMGetNextInstruction(self.to_ref()))
        }
    }

    fn get_previous(&self) -> Self {
        unsafe {
            Self::from_ref(LLVMGetPreviousInstruction(self.to_ref()))
        }
    }

    fn erase_from_parent(mut self) {
        unsafe {
            LLVMInstructionEraseFromParent(self.to_ref())
        }
    }

    fn get_opcode(&self) -> LLVMOpcode {
        unsafe {
            LLVMGetInstructionOpcode(self.to_ref())
        }
    }
}

new_ref_type!(InstructionRef for LLVMValueRef
              implementing
              Value,
              ValueCtor,
              Instruction
              );

pub trait PHINode : Instruction {
    fn add_incoming(&mut self, incoming_values: &mut [LLVMValueRef], incoming_blocks: &mut [LLVMBasicBlockRef]) {
        assert!(incoming_values.len() == incoming_blocks.len());
        unsafe {
            LLVMAddIncoming(self.to_ref(),
                            incoming_values.as_mut_ptr(),
                            incoming_blocks.as_mut_ptr(),
                            incoming_values.len() as c_uint)
        }
    }

    fn count_incoming(&self) -> u32 {
        unsafe {
            LLVMCountIncoming(self.to_ref())
        }
    }

    fn get_incoming_value(&self, index: u32) -> Option<LLVMValueRef> {
        if index < self.count_incoming() {
            unsafe {
                Some(LLVMGetIncomingValue(self.to_ref(), index))
            }
        } else {
            None
        }
    }

    fn get_incoming_block(&self, index: u32) -> Option<LLVMBasicBlockRef> {
        if index < self.count_incoming() {
            unsafe {
                Some(LLVMGetIncomingBlock(self.to_ref(), index))
            }
        } else {
            None
        }
    }
}

new_ref_type!(PHINodeRef for LLVMValueRef
              implementing
              Value,
              ValueCtor,
              Instruction,
              PHINode
              );
<|endoftext|>


<commit_before>// Chapter 1
// ------------------ print macros start ------------------
// Macros: Macros look like functions, except that their name ends with a bang !,
// but instead of generating a function call, macros are expanded into source code
// that gets compiled with the rest of the program. eg. println!
// println! -> prints statement to console in a new line

// !!!--- start uncommenting from line below ---!!!
// fn main() {
//     println!("April has {} days.", 31);
//     println!("{month} has {numberOfDays} days.",
//         month = "January",
//         numberOfDays = "31");
//     // Special formating is used here
//     // {:b} -> converts 2 to 10 (binary form)
//     println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
//     let width = 6;
//     println!("{number:>width$} {spaces} spaces and {number}", number = 1, width = width, spaces = width - 1);
//     println!("{}", format!("{:05}", 12));

//     // rounds off the number
//     let pi = 3.141592;
//     println!("Pi is roughly {:.3}", pi);
// }
// !!!--- end uncommenting from line above ---!!!
// ------------------ print macros end ------------------

// Chapter 2
// ------------------ Debugging start ------------------
// In JS we use console.log() for logging and debugging purposes.
// console.log() can be used to print pretty any type of object.
// However, in Rust this is not possible as all types which want to use
// std::fmt formatting traits require an implementation to be printable.
// The fmt::Debug trait makes this very straightforward.
// All types can derive (automatically create) the fmt::Debug implementation.
// This is not true for fmt::Display which must be manually implemented.
// Below given example shows automatic derive(Debug) implementation
// and manual Display implementation.

// !!!--- start uncommenting from line below ---!!!
// Import (via `use`) the `fmt` module to make it available.
// use std::fmt::{self, Formatter, Display};
// #[derive(Debug)]
// struct Person<'a> {
//     name: &'a str,
//     age: u8
// }

// // Implement `Display` for `Person`.
// impl<'a> fmt::Display for Person<'a> {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         // Try `write!` to see if it errors. If it errors, return
//         // the error. Otherwise continue.
//         write!(f, "(Name is {} and Age is {})", self.name, self.age)?;
//         write!(f, "")
//     }
// }

// #[derive(Debug)]
// struct Color {
//     red: u8,
//     green: u8,
//     blue: u8,
// }

// impl Display for Color {
//     // `f` is a buffer, this method must write the formatted string into it
//     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
//         // `write!` is like `format!`, but it will write the formatted string
//         // into a buffer (the first argument)
//         write!(f, "RGB ({}, {}, {}) 0x{:02.X}{:02.X}{:02.X}",
//             self.red, self.green, self.blue, self.red, self.green, self.blue)
//     }
// }

// fn main() {
//     let name = "Peter";
//     let age = 27;
//     let peter = Person { name, age };

//     println!("Compare Person");
//     println!("Debug: Normal {:?}", peter);
//     println!("Debug: Pretty {:#?}", peter);
//     println!("Display: {}", peter);

//     for color in [
//         Color { red: 128, green: 255, blue: 90 },
//         Color { red: 0, green: 3, blue: 254 },
//         Color { red: 0, green: 0, blue: 0 },
//     ].iter() {
//         // Switch this to use {} once you've added an implementation
//         // for fmt::Display
//         println!("{:}", *color);
//     }
// }
// !!!--- end uncommenting from line above ---!!!
// ------------------ Debugging end ------------------

// Chapter 3
// ------------------ Primitives start ------------------
// Rust provides access to a wide variety of primitives.

// !!!--- start uncommenting from line below ---!!!
use std::fmt;
use std::mem;

#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);

impl fmt::Display for Matrix {
    // `f` is a buffer, this method must write the formatted string into it
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "( {} {} ) \n( {} {} )", self.0, self.1, self.2, self.3)
    }
}

fn transpose(matrix: Matrix) -> Matrix {
    Matrix(matrix.0, matrix.2, matrix.1, matrix.3)
}

// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    // A type can also be inferred from context
    let mut inferred_type = 12; // Type i64 is inferred from another line
    inferred_type = 4294967296i64;

    // A mutable variable's value can be changed.
    let mut mutable = 12; // Mutable `i32`
    mutable = 21;

    // Error! The type of a variable can't be changed.
    //mutable = true;

    // Variables can be overwritten with shadowing.
    let mutable = true;

    // Integer addition
    // We need to tell the compiler the type of the literals we use.
    println!("1 + 2 = {}", 1u32 + 2);

    // Integer subtraction
    // We need to tell the compiler the type of the literals we use.
    println!("1 - 2 = {}", 1i32 - 2);

    // Short-circuiting boolean logic
    println!("true AND false is {}", true && false);
    println!("true OR false is {}", true || false);
    println!("NOT true is {}", !true);

    // Bitwise operations
    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
    println!("1 << 5 is {}", 1u32 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);

    // Use underscores to improve readability!
    println!("One million is written as {}", 1_000_000u32);

    // A tuple with a bunch of different types
    let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);

    // Values can be extracted from the tuple using tuple indexing
    println!("long tuple first value: {}", long_tuple.0);
    println!("long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members
    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

    // Tuples are printable
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    // But long Tuples cannot be printed
    // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    // println!("too long tuple: {:?}", too_long_tuple);
    // TODO ^ Uncomment the above 2 lines to see the compiler error

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses
    println!("one element tuple: {:?}", (5u32,));
    println!("just an integer: {:?}", (5u32));

    //tuples can be destructured to create bindings
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("{:?}", matrix);
    println!("{}", matrix);
    println!("{}", transpose(matrix));

    // Fixed-size array (type signature is superfluous)
    let xs: [i32; 5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0
    println!("first element of the array: {}", xs[0]);
    println!("second element of the array: {}", xs[1]);

    // `len` returns the size of the array
    println!("array size: {}", ys.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&ys));

    // Arrays can be automatically borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(&xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(&ys[1 .. 4]);

    // Out of bound indexing causes compile error
    // println!("{}", xs[5]);
}
// !!!--- end uncommenting from line above ---!!!
// ------------------ Primitives end ------------------<commit_msg>start writing chapter 4<commit_after>// Chapter 1
// ------------------ print macros start ------------------
// Macros: Macros look like functions, except that their name ends with a bang !,
// but instead of generating a function call, macros are expanded into source code
// that gets compiled with the rest of the program. eg. println!
// println! -> prints statement to console in a new line

// !!!--- start uncommenting from line below ---!!!
// fn main() {
//     println!("April has {} days.", 31);
//     println!("{month} has {numberOfDays} days.",
//         month = "January",
//         numberOfDays = "31");
//     // Special formating is used here
//     // {:b} -> converts 2 to 10 (binary form)
//     println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
//     let width = 6;
//     println!("{number:>width$} {spaces} spaces and {number}", number = 1, width = width, spaces = width - 1);
//     println!("{}", format!("{:05}", 12));

//     // rounds off the number
//     let pi = 3.141592;
//     println!("Pi is roughly {:.3}", pi);
// }
// !!!--- end uncommenting from line above ---!!!
// ------------------ print macros end ------------------

// Chapter 2
// ------------------ Debugging start ------------------
// In JS we use console.log() for logging and debugging purposes.
// console.log() can be used to print pretty any type of object.
// However, in Rust this is not possible as all types which want to use
// std::fmt formatting traits require an implementation to be printable.
// The fmt::Debug trait makes this very straightforward.
// All types can derive (automatically create) the fmt::Debug implementation.
// This is not true for fmt::Display which must be manually implemented.
// Below given example shows automatic derive(Debug) implementation
// and manual Display implementation.

// !!!--- start uncommenting from line below ---!!!
// Import (via `use`) the `fmt` module to make it available.
// use std::fmt::{self, Formatter, Display};
// #[derive(Debug)]
// struct Person<'a> {
//     name: &'a str,
//     age: u8
// }

// // Implement `Display` for `Person`.
// impl<'a> fmt::Display for Person<'a> {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         // Try `write!` to see if it errors. If it errors, return
//         // the error. Otherwise continue.
//         write!(f, "(Name is {} and Age is {})", self.name, self.age)?;
//         write!(f, "")
//     }
// }

// #[derive(Debug)]
// struct Color {
//     red: u8,
//     green: u8,
//     blue: u8,
// }

// impl Display for Color {
//     // `f` is a buffer, this method must write the formatted string into it
//     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
//         // `write!` is like `format!`, but it will write the formatted string
//         // into a buffer (the first argument)
//         write!(f, "RGB ({}, {}, {}) 0x{:02.X}{:02.X}{:02.X}",
//             self.red, self.green, self.blue, self.red, self.green, self.blue)
//     }
// }

// fn main() {
//     let name = "Peter";
//     let age = 27;
//     let peter = Person { name, age };

//     println!("Compare Person");
//     println!("Debug: Normal {:?}", peter);
//     println!("Debug: Pretty {:#?}", peter);
//     println!("Display: {}", peter);

//     for color in [
//         Color { red: 128, green: 255, blue: 90 },
//         Color { red: 0, green: 3, blue: 254 },
//         Color { red: 0, green: 0, blue: 0 },
//     ].iter() {
//         // Switch this to use {} once you've added an implementation
//         // for fmt::Display
//         println!("{:}", *color);
//     }
// }
// !!!--- end uncommenting from line above ---!!!
// ------------------ Debugging end ------------------

// Chapter 3
// ------------------ Primitives start ------------------
// Rust provides access to a wide variety of primitives.

// !!!--- start uncommenting from line below ---!!!
// use std::fmt;
// use std::mem;

// #[derive(Debug)]
// struct Matrix(f32, f32, f32, f32);

// impl fmt::Display for Matrix {
//     // `f` is a buffer, this method must write the formatted string into it
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "( {} {} ) \n( {} {} )", self.0, self.1, self.2, self.3)
//     }
// }

// fn transpose(matrix: Matrix) -> Matrix {
//     Matrix(matrix.0, matrix.2, matrix.1, matrix.3)
// }

// // This function borrows a slice
// fn analyze_slice(slice: &[i32]) {
//     println!("first element of the slice: {}", slice[0]);
//     println!("the slice has {} elements", slice.len());
// }

// fn main() {
//     // Variables can be type annotated.
//     let logical: bool = true;

//     let a_float: f64 = 1.0;  // Regular annotation
//     let an_integer   = 5i32; // Suffix annotation

//     // Or a default will be used.
//     let default_float   = 3.0; // `f64`
//     let default_integer = 7;   // `i32`

//     // A type can also be inferred from context
//     let mut inferred_type = 12; // Type i64 is inferred from another line
//     inferred_type = 4294967296i64;

//     // A mutable variable's value can be changed.
//     let mut mutable = 12; // Mutable `i32`
//     mutable = 21;

//     // Error! The type of a variable can't be changed.
//     //mutable = true;

//     // Variables can be overwritten with shadowing.
//     let mutable = true;

//     // Integer addition
//     // We need to tell the compiler the type of the literals we use.
//     println!("1 + 2 = {}", 1u32 + 2);

//     // Integer subtraction
//     // We need to tell the compiler the type of the literals we use.
//     println!("1 - 2 = {}", 1i32 - 2);

//     // Short-circuiting boolean logic
//     println!("true AND false is {}", true && false);
//     println!("true OR false is {}", true || false);
//     println!("NOT true is {}", !true);

//     // Bitwise operations
//     println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
//     println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
//     println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
//     println!("1 << 5 is {}", 1u32 << 5);
//     println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);

//     // Use underscores to improve readability!
//     println!("One million is written as {}", 1_000_000u32);

//     // A tuple with a bunch of different types
//     let long_tuple = (1u8, 2u16, 3u32, 4u64,
//                       -1i8, -2i16, -3i32, -4i64,
//                       0.1f32, 0.2f64,
//                       'a', true);

//     // Values can be extracted from the tuple using tuple indexing
//     println!("long tuple first value: {}", long_tuple.0);
//     println!("long tuple second value: {}", long_tuple.1);

//     // Tuples can be tuple members
//     let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

//     // Tuples are printable
//     println!("tuple of tuples: {:?}", tuple_of_tuples);

//     // But long Tuples cannot be printed
//     // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
//     // println!("too long tuple: {:?}", too_long_tuple);
//     // TODO ^ Uncomment the above 2 lines to see the compiler error

//     // To create one element tuples, the comma is required to tell them apart
//     // from a literal surrounded by parentheses
//     println!("one element tuple: {:?}", (5u32,));
//     println!("just an integer: {:?}", (5u32));

//     //tuples can be destructured to create bindings
//     let tuple = (1, "hello", 4.5, true);

//     let (a, b, c, d) = tuple;
//     println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);

//     let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
//     println!("{:?}", matrix);
//     println!("{}", matrix);
//     println!("{}", transpose(matrix));

//     // Fixed-size array (type signature is superfluous)
//     let xs: [i32; 5] = [1, 2, 3, 4, 5];

//     // All elements can be initialized to the same value
//     let ys: [i32; 500] = [0; 500];

//     // Indexing starts at 0
//     println!("first element of the array: {}", xs[0]);
//     println!("second element of the array: {}", xs[1]);

//     // `len` returns the size of the array
//     println!("array size: {}", ys.len());

//     // Arrays are stack allocated
//     println!("array occupies {} bytes", mem::size_of_val(&ys));

//     // Arrays can be automatically borrowed as slices
//     println!("borrow the whole array as a slice");
//     analyze_slice(&xs);

//     // Slices can point to a section of an array
//     println!("borrow a section of the array as a slice");
//     analyze_slice(&ys[1 .. 4]);

//     // Out of bound indexing causes compile error
//     // println!("{}", xs[5]);
// }
// !!!--- end uncommenting from line above ---!!!
// ------------------ Primitives end ------------------

// Chapter 4
// ------------------ Custom Types start ------------------
// Rust custom data types are formed mainly through the two keywords:

// struct: define a structure
// enum: define an enumeration
// Constants can also be created via the const and static keywords.

// !!!--- start uncommenting from line below ---!!!

// !!!--- end uncommenting from line above ---!!!

// ------------------ Custom Types end --------------------<|endoftext|>


<commit_before>
use std::collections::HashMap;
use uuid::Uuid;

use graphics::*;

use event::GenericEvent;
use ai_behavior::{
    Behavior,
    State,
    Running,
};

use sprite::Sprite;

use animation::{
    Animation,
    AnimationState,
};

/// A scene is used to manage sprite's life and run animation with sprite
pub struct Scene<I: ImageSize> {
    children: Vec<Sprite<I>>,
    children_index: HashMap<Uuid, uint>,
    running: HashMap<Uuid,
        Vec<(Behavior<Animation>, State<Animation, AnimationState>, bool)>>,
}

impl<I: ImageSize> Scene<I> {
    /// Create a new scene
    pub fn new() -> Scene<I> {
        Scene {
            children: Vec::new(),
            children_index: HashMap::new(),
            running: HashMap::new(),
        }
    }

    /// Update animation's state
    pub fn event<E: GenericEvent>(&mut self, e: &E) {
        // regenerate the animations and their states
        let running = self.running.clone();
        self.running.clear();

        for (id, animations) in running.into_iter() {
            let mut new_animations = Vec::new();

            for (b, mut a, paused) in animations.into_iter() {
                if paused {
                    new_animations.push((b, a, paused));
                    continue;
                }

                let sprite = self.child_mut(id.clone()).unwrap();
                let (status, _) = a.event(e, |_, dt, animation, s| {
                    let (state, status, remain) = {
                        let start_state;
                        let state = match *s {
                            None => { start_state = animation.to_state(sprite); &start_state },
                            Some(ref state) => state,
                        };
                        state.update(sprite, dt)
                    };
                    *s = state;
                    (status, remain)
                });

                match status {
                    // the behavior is still running, add it for next update
                    Running => {
                        new_animations.push((b, a, paused));
                    },
                    _ => {},
                }
            }

            if new_animations.len() > 0 {
                self.running.insert(id, new_animations);
            }
        }
    }

    /// Render this scene
    pub fn draw<B: BackEnd<I>>(&self, c: &Context, b: &mut B) {
        for child in self.children.iter() {
            child.draw(c, b);
        }
    }

    /// Register animation with sprite
    pub fn run(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        use std::collections::hash_map::Entry::{ Vacant, Occupied };
        let animations = match self.running.entry(sprite_id) {
            Vacant(entry) => entry.set(Vec::new()),
            Occupied(entry) => entry.into_mut()
        };
        let state = State::new(animation.clone());
        animations.push((animation.clone(), state, false));
    }

    fn find(&self, sprite_id: Uuid, animation: &Behavior<Animation>) -> Option<uint> {
        let mut index = None;
        match self.running.get(&sprite_id) {
            Some(animations) => {
                for i in range(0, animations.len()) {
                    let (ref b, _, _) = animations[i];
                    if b == animation {
                        index = Some(i);
                        break;
                    }
                }
            },
            _ => {},
        }
        index
    }

    /// Pause a running animation of the sprite
    pub fn pause(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            println!("found");
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, _) = animations.remove(i);
            animations.push((b, s, true));
        }
    }

    /// Resume a paused animation of the sprite
    pub fn resume(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            println!("found");
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, _) = animations.remove(i);
            animations.push((b, s, false));
        }
    }

    /// Toggle an animation of the sprite
    pub fn toggle(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, paused) = animations.remove(i);
            animations.push((b, s, !paused));
        }
    }

    /// Stop a running animation of the sprite
    pub fn stop(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            let i = index.unwrap();
            &mut self.running[sprite_id].remove(i);
        }
    }

    /// Stop all running animations of the sprite
    pub fn stop_all(&mut self, sprite_id: Uuid) {
        self.running.remove(&sprite_id);
    }

    /// Get all the running animations in the scene
    pub fn running(&self) -> uint {
        let mut total = 0;
        for (_, animations) in self.running.iter() {
            total += animations.len();
        }
        total
    }

    /// Add sprite to scene
    pub fn add_child(&mut self, sprite: Sprite<I>) -> Uuid {
        let id = sprite.id();
        self.children.push(sprite);
        self.children_index.insert(id.clone(), self.children.len() - 1);
        id
    }

    fn stop_all_including_children(&mut self, sprite: &Sprite<I>) {
        self.stop_all(sprite.id());
        for child in sprite.children().iter() {
            self.stop_all_including_children(child);
        }
    }

    /// Remove the child by `id` from the scene's children or grandchild
    /// will stop all the animations run by this child
    pub fn remove_child(&mut self, id: Uuid) -> Option<Sprite<I>> {
        let removed = match self.children_index.remove(&id) {
            Some(i) => {
                let removed = self.children.remove(i);
                // Removing a element of vector will alter the index,
                // update the mapping from uuid to index.
                for index in range(i, self.children.len()) {
                    let uuid = self.children[index].id();
                    self.children_index.insert(uuid, index);
                }
                Some(removed)
            },
            None => {
                for child in self.children.iter_mut() {
                    match child.remove_child(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        };

        if removed.is_some() {
            self.stop_all_including_children(removed.as_ref().unwrap());
        }

        removed
    }

    /// Find the child by `id` from the scene's children or grandchild
    pub fn child(&self, id: Uuid) -> Option<&Sprite<I>> {
        match self.children_index.get(&id) {
            Some(i) => { Some(&self.children[*i]) },
            None => {
                for child in self.children.iter() {
                    match child.child(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        }
    }

    /// Find the child by `id` from this sprite's children or grandchild, mutability
    pub fn child_mut(&mut self, id: Uuid) -> Option<&mut Sprite<I>> {
        match self.children_index.get(&id) {
            Some(i) => { Some(&mut self.children[*i]) },
            None => {
                for child in self.children.iter_mut() {
                    match child.child_mut(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        }
    }
}
<commit_msg>Update to new HashMap API<commit_after>
use std::collections::HashMap;
use uuid::Uuid;

use graphics::*;

use event::GenericEvent;
use ai_behavior::{
    Behavior,
    State,
    Running,
};

use sprite::Sprite;

use animation::{
    Animation,
    AnimationState,
};

/// A scene is used to manage sprite's life and run animation with sprite
pub struct Scene<I: ImageSize> {
    children: Vec<Sprite<I>>,
    children_index: HashMap<Uuid, uint>,
    running: HashMap<Uuid,
        Vec<(Behavior<Animation>, State<Animation, AnimationState>, bool)>>,
}

impl<I: ImageSize> Scene<I> {
    /// Create a new scene
    pub fn new() -> Scene<I> {
        Scene {
            children: Vec::new(),
            children_index: HashMap::new(),
            running: HashMap::new(),
        }
    }

    /// Update animation's state
    pub fn event<E: GenericEvent>(&mut self, e: &E) {
        // regenerate the animations and their states
        let running = self.running.clone();
        self.running.clear();

        for (id, animations) in running.into_iter() {
            let mut new_animations = Vec::new();

            for (b, mut a, paused) in animations.into_iter() {
                if paused {
                    new_animations.push((b, a, paused));
                    continue;
                }

                let sprite = self.child_mut(id.clone()).unwrap();
                let (status, _) = a.event(e, |_, dt, animation, s| {
                    let (state, status, remain) = {
                        let start_state;
                        let state = match *s {
                            None => { start_state = animation.to_state(sprite); &start_state },
                            Some(ref state) => state,
                        };
                        state.update(sprite, dt)
                    };
                    *s = state;
                    (status, remain)
                });

                match status {
                    // the behavior is still running, add it for next update
                    Running => {
                        new_animations.push((b, a, paused));
                    },
                    _ => {},
                }
            }

            if new_animations.len() > 0 {
                self.running.insert(id, new_animations);
            }
        }
    }

    /// Render this scene
    pub fn draw<B: BackEnd<I>>(&self, c: &Context, b: &mut B) {
        for child in self.children.iter() {
            child.draw(c, b);
        }
    }

    /// Register animation with sprite
    pub fn run(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        use std::collections::hash_map::Entry::{ Vacant, Occupied };
        let animations = match self.running.entry(&sprite_id) {
            Vacant(entry) => entry.insert(Vec::new()),
            Occupied(entry) => entry.into_mut()
        };
        let state = State::new(animation.clone());
        animations.push((animation.clone(), state, false));
    }

    fn find(&self, sprite_id: Uuid, animation: &Behavior<Animation>) -> Option<uint> {
        let mut index = None;
        match self.running.get(&sprite_id) {
            Some(animations) => {
                for i in range(0, animations.len()) {
                    let (ref b, _, _) = animations[i];
                    if b == animation {
                        index = Some(i);
                        break;
                    }
                }
            },
            _ => {},
        }
        index
    }

    /// Pause a running animation of the sprite
    pub fn pause(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            println!("found");
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, _) = animations.remove(i);
            animations.push((b, s, true));
        }
    }

    /// Resume a paused animation of the sprite
    pub fn resume(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            println!("found");
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, _) = animations.remove(i);
            animations.push((b, s, false));
        }
    }

    /// Toggle an animation of the sprite
    pub fn toggle(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            let i = index.unwrap();
            let animations = &mut self.running[sprite_id];
            let (b, s, paused) = animations.remove(i);
            animations.push((b, s, !paused));
        }
    }

    /// Stop a running animation of the sprite
    pub fn stop(&mut self, sprite_id: Uuid, animation: &Behavior<Animation>) {
        let index = self.find(sprite_id.clone(), animation);
        if index.is_some() {
            let i = index.unwrap();
            &mut self.running[sprite_id].remove(i);
        }
    }

    /// Stop all running animations of the sprite
    pub fn stop_all(&mut self, sprite_id: Uuid) {
        self.running.remove(&sprite_id);
    }

    /// Get all the running animations in the scene
    pub fn running(&self) -> uint {
        let mut total = 0;
        for (_, animations) in self.running.iter() {
            total += animations.len();
        }
        total
    }

    /// Add sprite to scene
    pub fn add_child(&mut self, sprite: Sprite<I>) -> Uuid {
        let id = sprite.id();
        self.children.push(sprite);
        self.children_index.insert(id.clone(), self.children.len() - 1);
        id
    }

    fn stop_all_including_children(&mut self, sprite: &Sprite<I>) {
        self.stop_all(sprite.id());
        for child in sprite.children().iter() {
            self.stop_all_including_children(child);
        }
    }

    /// Remove the child by `id` from the scene's children or grandchild
    /// will stop all the animations run by this child
    pub fn remove_child(&mut self, id: Uuid) -> Option<Sprite<I>> {
        let removed = match self.children_index.remove(&id) {
            Some(i) => {
                let removed = self.children.remove(i);
                // Removing a element of vector will alter the index,
                // update the mapping from uuid to index.
                for index in range(i, self.children.len()) {
                    let uuid = self.children[index].id();
                    self.children_index.insert(uuid, index);
                }
                Some(removed)
            },
            None => {
                for child in self.children.iter_mut() {
                    match child.remove_child(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        };

        if removed.is_some() {
            self.stop_all_including_children(removed.as_ref().unwrap());
        }

        removed
    }

    /// Find the child by `id` from the scene's children or grandchild
    pub fn child(&self, id: Uuid) -> Option<&Sprite<I>> {
        match self.children_index.get(&id) {
            Some(i) => { Some(&self.children[*i]) },
            None => {
                for child in self.children.iter() {
                    match child.child(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        }
    }

    /// Find the child by `id` from this sprite's children or grandchild, mutability
    pub fn child_mut(&mut self, id: Uuid) -> Option<&mut Sprite<I>> {
        match self.children_index.get(&id) {
            Some(i) => { Some(&mut self.children[*i]) },
            None => {
                for child in self.children.iter_mut() {
                    match child.child_mut(id.clone()) {
                        Some(c) => {
                            return Some(c);
                        }
                        _ => {}
                    }
                }

                None
            }
        }
    }
}
<|endoftext|>


<commit_before>use gmp::mpq::Mpq;
use std::borrow::Borrow;
use std::collections::VecDeque;
use std::vec::Vec;

struct BallotState {
    visited: bool,
    prev: usize,
    edge_flow: Box<[Mpq]>,
    sink_flow: Mpq,
    count: i32,
}

#[derive(Clone)]
struct CandidateState {
    prev: usize,
    count: i32,
}

pub fn strength<Ballot>(num_candidates: usize, ballots: &[(Ballot, Mpq)]) -> Mpq
    where Ballot: Borrow<[bool]>
{
    let candidate_ballots = &mut vec![Vec::new(); num_candidates][..];
    for (b, &(ref cs, _)) in ballots.iter().enumerate() {
        for (c, &s) in cs.borrow().iter().enumerate() {
            if s {
                candidate_ballots[c].push(b);
            }
        }
    }
    let ballot_states = &mut ballots.iter()
        .map(|&(_, ref w)| {
            BallotState {
                visited: false,
                prev: !0,
                edge_flow: vec![Mpq::zero(); num_candidates].into_boxed_slice(),
                sink_flow: w.clone(),
                count: 0,
            }
        })
        .collect::<Vec<_>>()[..];
    let candidate_states = &mut vec![CandidateState {
        prev: !0,
        count: 0,
    }; num_candidates][..];

    let mut total_flow = Mpq::zero();
    let mut queue = VecDeque::new();

    loop {
        for (b, bs) in ballot_states.iter_mut().enumerate() {
            if !bs.sink_flow.is_zero() {
                bs.visited = true;
                queue.push_back(b);
            }
        }

        let mut found = Vec::new();
        'search: loop {
            match queue.pop_front() {
                None => {
                    return total_flow;
                }
                Some(b) => {
                    let (ref cs, _) = ballots[b];
                    for (c, &s) in cs.borrow().iter().enumerate() {
                        if !s || candidate_states[c].prev != !0 {
                            continue;
                        }
                        candidate_states[c].prev = b;
                        found.push(c);
                        if found.len() == num_candidates {
                            break 'search;
                        }
                        for &b1 in &candidate_ballots[c] {
                            if ballot_states[b1].edge_flow[c].is_zero() ||
                               ballot_states[b1].visited {
                                continue;
                            }
                            ballot_states[b1].visited = true;
                            ballot_states[b1].prev = c;
                            queue.push_back(b1);
                        }
                    }
                }
            }
        }

        let mut sunk = 0;
        for &c in found.iter().rev() {
            let b = candidate_states[c].prev;
            let count = candidate_states[c].count + 1;
            ballot_states[b].count += count;
            let c1 = ballot_states[b].prev;
            if c1 == !0 {
                sunk += count;
            } else {
                candidate_states[c1].count += count;
            }
        }
        debug_assert_eq!(sunk, num_candidates as i32);

        let flow = found.iter()
            .map(|&c| {
                let b = candidate_states[c].prev;
                let c1 = ballot_states[b].prev;
                (if c1 == !0 {
                    &ballot_states[b].sink_flow
                } else {
                    &ballot_states[b].edge_flow[c1]
                } / Mpq::from(ballot_states[b].count as i64))
            })
            .min()
            .unwrap();
        debug_assert!(!flow.is_zero());
        total_flow = total_flow + &flow;

        for c in found {
            let b = candidate_states[c].prev;
            let c1 = ballot_states[b].prev;
            ballot_states[b].edge_flow[c] = &ballot_states[b].edge_flow[c] +
                                            &flow * Mpq::from(candidate_states[c].count as i64 + 1);
            if ballot_states[b].count != 0 {
                let edge_flow = if c1 == !0 {
                    &mut ballot_states[b].sink_flow
                } else {
                    &mut ballot_states[b].edge_flow[c1]
                };
                *edge_flow = &*edge_flow - &flow * Mpq::from(ballot_states[b].count as i64);
                ballot_states[b].count = 0;
            }

            candidate_states[c].prev = !0;
            candidate_states[c].count = 0;
        }

        for bs in &mut *ballot_states {
            bs.visited = false;
            bs.prev = !0;
            debug_assert_eq!(bs.count, 0);
        }
        queue.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::strength;
    use gmp::mpq::Mpq;

    const Q: fn(i64) -> Mpq = Mpq::from;

    #[test]
    fn test_strength_1() {
        // Wikipedia
        let ballots: &[(&[bool], Mpq)] = &[(&[true, false], Q(12)),
                                           (&[false, true], Q(0)),
                                           (&[true, true], Q(51)),
                                           (&[false, false], Q(27))];
        assert_eq!(strength(2, ballots), Q(63) / Q(2));
    }

    #[test]
    fn test_strength_2() {
        // Wikipedia
        let ballots: &[(&[bool], Mpq)] =
            &[(&[true, false], Q(38)), (&[false, true], Q(27)), (&[true, true], Q(12))];
        assert_eq!(strength(2, ballots), Q(77) / Q(2));
    }

    #[test]
    fn test_strength_3() {
        // Schulze’s calcul02.pdf
        let ballots: &[(&[bool], Mpq)] =
            &[(&[true, true, true, true], Q(36_597383) / Q(1_000000)),
              (&[true, true, true, false], Q(5_481150) / Q(1_000000)),
              (&[true, true, false, true], Q(13_279131) / Q(1_000000)),
              (&[true, true, false, false], Q(4_859413) / Q(1_000000)),
              (&[true, false, true, true], Q(35_425375) / Q(1_000000)),
              (&[true, false, true, false], Q(5_490934) / Q(1_000000)),
              (&[true, false, false, true], Q(22_855333) / Q(1_000000)),
              (&[true, false, false, false], Q(19_835570) / Q(1_000000)),
              (&[false, true, true, true], Q(22_928716) / Q(1_000000)),
              (&[false, true, true, false], Q(5_538309) / Q(1_000000)),
              (&[false, true, false, true], Q(13_130227) / Q(1_000000)),
              (&[false, true, false, false], Q(6_056291) / Q(1_000000)),
              (&[false, false, true, true], Q(23_992772) / Q(1_000000)),
              (&[false, false, true, false], Q(16_699207) / Q(1_000000)),
              (&[false, false, false, true], Q(98_165759) / Q(1_000000)),
              (&[false, false, false, false], Q(129_664430) / Q(1_000000))];
        assert_eq!(strength(4, ballots), Q(77_389937) / Q(1_000000));
    }
}
<commit_msg>vote_management: Rename num_candidates to num_seats<commit_after>use gmp::mpq::Mpq;
use std::borrow::Borrow;
use std::collections::VecDeque;
use std::vec::Vec;

struct BallotState {
    visited: bool,
    prev: usize,
    edge_flow: Box<[Mpq]>,
    sink_flow: Mpq,
    count: i32,
}

#[derive(Clone)]
struct CandidateState {
    prev: usize,
    count: i32,
}

pub fn strength<Ballot>(num_seats: usize, ballots: &[(Ballot, Mpq)]) -> Mpq
    where Ballot: Borrow<[bool]>
{
    let candidate_ballots = &mut vec![Vec::new(); num_seats][..];
    for (b, &(ref cs, _)) in ballots.iter().enumerate() {
        for (c, &s) in cs.borrow().iter().enumerate() {
            if s {
                candidate_ballots[c].push(b);
            }
        }
    }
    let ballot_states = &mut ballots.iter()
        .map(|&(_, ref w)| {
            BallotState {
                visited: false,
                prev: !0,
                edge_flow: vec![Mpq::zero(); num_seats].into_boxed_slice(),
                sink_flow: w.clone(),
                count: 0,
            }
        })
        .collect::<Vec<_>>()[..];
    let candidate_states = &mut vec![CandidateState {
        prev: !0,
        count: 0,
    }; num_seats][..];

    let mut total_flow = Mpq::zero();
    let mut queue = VecDeque::new();

    loop {
        for (b, bs) in ballot_states.iter_mut().enumerate() {
            if !bs.sink_flow.is_zero() {
                bs.visited = true;
                queue.push_back(b);
            }
        }

        let mut found = Vec::new();
        'search: loop {
            match queue.pop_front() {
                None => {
                    return total_flow;
                }
                Some(b) => {
                    let (ref cs, _) = ballots[b];
                    for (c, &s) in cs.borrow().iter().enumerate() {
                        if !s || candidate_states[c].prev != !0 {
                            continue;
                        }
                        candidate_states[c].prev = b;
                        found.push(c);
                        if found.len() == num_seats {
                            break 'search;
                        }
                        for &b1 in &candidate_ballots[c] {
                            if ballot_states[b1].edge_flow[c].is_zero() ||
                               ballot_states[b1].visited {
                                continue;
                            }
                            ballot_states[b1].visited = true;
                            ballot_states[b1].prev = c;
                            queue.push_back(b1);
                        }
                    }
                }
            }
        }

        let mut sunk = 0;
        for &c in found.iter().rev() {
            let b = candidate_states[c].prev;
            let count = candidate_states[c].count + 1;
            ballot_states[b].count += count;
            let c1 = ballot_states[b].prev;
            if c1 == !0 {
                sunk += count;
            } else {
                candidate_states[c1].count += count;
            }
        }
        debug_assert_eq!(sunk, num_seats as i32);

        let flow = found.iter()
            .map(|&c| {
                let b = candidate_states[c].prev;
                let c1 = ballot_states[b].prev;
                (if c1 == !0 {
                    &ballot_states[b].sink_flow
                } else {
                    &ballot_states[b].edge_flow[c1]
                } / Mpq::from(ballot_states[b].count as i64))
            })
            .min()
            .unwrap();
        debug_assert!(!flow.is_zero());
        total_flow = total_flow + &flow;

        for c in found {
            let b = candidate_states[c].prev;
            let c1 = ballot_states[b].prev;
            ballot_states[b].edge_flow[c] = &ballot_states[b].edge_flow[c] +
                                            &flow * Mpq::from(candidate_states[c].count as i64 + 1);
            if ballot_states[b].count != 0 {
                let edge_flow = if c1 == !0 {
                    &mut ballot_states[b].sink_flow
                } else {
                    &mut ballot_states[b].edge_flow[c1]
                };
                *edge_flow = &*edge_flow - &flow * Mpq::from(ballot_states[b].count as i64);
                ballot_states[b].count = 0;
            }

            candidate_states[c].prev = !0;
            candidate_states[c].count = 0;
        }

        for bs in &mut *ballot_states {
            bs.visited = false;
            bs.prev = !0;
            debug_assert_eq!(bs.count, 0);
        }
        queue.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::strength;
    use gmp::mpq::Mpq;

    const Q: fn(i64) -> Mpq = Mpq::from;

    #[test]
    fn test_strength_1() {
        // Wikipedia
        let ballots: &[(&[bool], Mpq)] = &[(&[true, false], Q(12)),
                                           (&[false, true], Q(0)),
                                           (&[true, true], Q(51)),
                                           (&[false, false], Q(27))];
        assert_eq!(strength(2, ballots), Q(63) / Q(2));
    }

    #[test]
    fn test_strength_2() {
        // Wikipedia
        let ballots: &[(&[bool], Mpq)] =
            &[(&[true, false], Q(38)), (&[false, true], Q(27)), (&[true, true], Q(12))];
        assert_eq!(strength(2, ballots), Q(77) / Q(2));
    }

    #[test]
    fn test_strength_3() {
        // Schulze’s calcul02.pdf
        let ballots: &[(&[bool], Mpq)] =
            &[(&[true, true, true, true], Q(36_597383) / Q(1_000000)),
              (&[true, true, true, false], Q(5_481150) / Q(1_000000)),
              (&[true, true, false, true], Q(13_279131) / Q(1_000000)),
              (&[true, true, false, false], Q(4_859413) / Q(1_000000)),
              (&[true, false, true, true], Q(35_425375) / Q(1_000000)),
              (&[true, false, true, false], Q(5_490934) / Q(1_000000)),
              (&[true, false, false, true], Q(22_855333) / Q(1_000000)),
              (&[true, false, false, false], Q(19_835570) / Q(1_000000)),
              (&[false, true, true, true], Q(22_928716) / Q(1_000000)),
              (&[false, true, true, false], Q(5_538309) / Q(1_000000)),
              (&[false, true, false, true], Q(13_130227) / Q(1_000000)),
              (&[false, true, false, false], Q(6_056291) / Q(1_000000)),
              (&[false, false, true, true], Q(23_992772) / Q(1_000000)),
              (&[false, false, true, false], Q(16_699207) / Q(1_000000)),
              (&[false, false, false, true], Q(98_165759) / Q(1_000000)),
              (&[false, false, false, false], Q(129_664430) / Q(1_000000))];
        assert_eq!(strength(4, ballots), Q(77_389937) / Q(1_000000));
    }
}
<|endoftext|>


<commit_before>use libc;
use platform;
use std::ptr;
use std::os::{errno, page_size, MemoryMap, MapReadable, MapWritable,
              MapNonStandardFlags};

const STACK_FLAGS: libc::c_int = libc::MAP_STACK
                               | libc::MAP_PRIVATE
                               | libc::MAP_ANON;

pub enum Stack {
  Native {
    sp_limit: *const u8
  },
  Managed {
    buf: MemoryMap,
    valgrind_id: libc::c_uint
  }
}

impl Stack {
  pub fn new(size: uint) -> Stack {
    let buf = match MemoryMap::new(size, &[MapReadable, MapWritable,
                                   MapNonStandardFlags(STACK_FLAGS)]) {
      Ok(map) => map,
      Err(e) => panic!("mmap for stack of size {} failed: {}", size, e)
    };

    if !protect_last_page(&buf) {
      panic!("Could not memory-protect guard page. stack={}, errno={}",
             buf.data(), errno());
    }

    let valgrind_id = unsafe {
      platform::stack_register(buf.data().offset(buf.len() as int) as *const _,
                               buf.data() as *const _)
    };

    let stk = Stack::Managed {
      buf: buf,
      valgrind_id: valgrind_id
    };

    stk
  }

  pub unsafe fn native(limit: *const u8) -> Stack {
    Stack::Native {
      sp_limit: limit
    }
  }

  pub fn top(&self) -> *const u8 {
    unsafe {
      match *self {
        Stack::Native { .. } => ptr::null(),
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(buf.len() as int) as *const _
        }
      }
    }
  }

  pub fn limit(&self) -> *const u8 {
    unsafe {
      match *self {
        Stack::Native { sp_limit, .. } => sp_limit,
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(page_size() as int) as *const _
        }
      }
    }
  }
}

fn protect_last_page(stack: &MemoryMap) -> bool {
  unsafe {
    let last_page = stack.data() as *mut libc::c_void;
    libc::mprotect(last_page, page_size() as libc::size_t,
                   libc::PROT_NONE) != -1
  }
}

impl Drop for Stack {
  fn drop(&mut self) {
    match *self {
      Stack::Native { .. } => {},
      Stack::Managed { valgrind_id, .. } => unsafe {
        platform::stack_deregister(valgrind_id);
      }
    }
  }
}
<commit_msg>top of stack is mutable<commit_after>use libc;
use platform;
use std::ptr;
use std::os::{errno, page_size, MemoryMap, MapReadable, MapWritable,
              MapNonStandardFlags};

const STACK_FLAGS: libc::c_int = libc::MAP_STACK
                               | libc::MAP_PRIVATE
                               | libc::MAP_ANON;

pub enum Stack {
  Native {
    sp_limit: *const u8
  },
  Managed {
    buf: MemoryMap,
    valgrind_id: libc::c_uint
  }
}

impl Stack {
  pub fn new(size: uint) -> Stack {
    let buf = match MemoryMap::new(size, &[MapReadable, MapWritable,
                                   MapNonStandardFlags(STACK_FLAGS)]) {
      Ok(map) => map,
      Err(e) => panic!("mmap for stack of size {} failed: {}", size, e)
    };

    if !protect_last_page(&buf) {
      panic!("Could not memory-protect guard page. stack={}, errno={}",
             buf.data(), errno());
    }

    let valgrind_id = unsafe {
      platform::stack_register(buf.data().offset(buf.len() as int) as *const _,
                               buf.data() as *const _)
    };

    let stk = Stack::Managed {
      buf: buf,
      valgrind_id: valgrind_id
    };

    stk
  }

  pub unsafe fn native(limit: *const u8) -> Stack {
    Stack::Native {
      sp_limit: limit
    }
  }

  pub fn top(&self) -> *mut u8 {
    unsafe {
      match *self {
        Stack::Native { .. } => ptr::null_mut(),
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(buf.len() as int)
        }
      }
    }
  }

  pub fn limit(&self) -> *const u8 {
    unsafe {
      match *self {
        Stack::Native { sp_limit, .. } => sp_limit,
        Stack::Managed { ref buf, .. } => {
          buf.data().offset(page_size() as int) as *const _
        }
      }
    }
  }
}

fn protect_last_page(stack: &MemoryMap) -> bool {
  unsafe {
    let last_page = stack.data() as *mut libc::c_void;
    libc::mprotect(last_page, page_size() as libc::size_t,
                   libc::PROT_NONE) != -1
  }
}

impl Drop for Stack {
  fn drop(&mut self) {
    match *self {
      Stack::Native { .. } => {},
      Stack::Managed { valgrind_id, .. } => unsafe {
        platform::stack_deregister(valgrind_id);
      }
    }
  }
}
<|endoftext|>


<commit_before>use std::default::Default;
use std::hash::Hash;
use std::ops::Deref;
use std::ops::DerefMut;
use std::option;

use crate::Message;

/// Wrapper around `Option<Box<T>>`, convenient newtype.
///
/// # Examples
///
/// ```no_run
/// # use protobuf::MessageField;
/// # use std::ops::Add;
/// # struct Address {
/// # }
/// # struct Customer {
/// #     address: MessageField<Address>,
/// # }
/// # impl Customer {
/// #     fn new() -> Customer { unimplemented!() }
/// # }
/// #
/// #
/// # fn make_address() -> Address { unimplemented!() }
/// let mut customer = Customer::new();
///
/// // field of type `SingularPtrField` can be initialized like this
/// customer.address = MessageField::some(make_address());
/// // or using `Option` and `Into`
/// customer.address = Some(make_address()).into();
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct MessageField<T>(pub Option<Box<T>>);

impl<T> MessageField<T> {
    /// Construct `SingularPtrField` from given object.
    #[inline]
    pub fn some(value: T) -> MessageField<T> {
        MessageField(Some(Box::new(value)))
    }

    /// Construct an empty `SingularPtrField`.
    #[inline]
    pub const fn none() -> MessageField<T> {
        MessageField(None)
    }

    /// Construct `SingularPtrField` from optional.
    #[inline]
    pub fn from_option(option: Option<T>) -> MessageField<T> {
        match option {
            Some(x) => MessageField::some(x),
            None => MessageField::none(),
        }
    }

    /// True iff this object contains data.
    #[inline]
    pub fn is_some(&self) -> bool {
        self.0.is_some()
    }

    /// True iff this object contains no data.
    #[inline]
    pub fn is_none(&self) -> bool {
        self.0.is_none()
    }

    /// Convert into `Option<T>`.
    #[inline]
    pub fn into_option(self) -> Option<T> {
        self.0.map(|v| *v)
    }

    /// View data as reference option.
    #[inline]
    pub fn as_ref(&self) -> Option<&T> {
        self.0.as_ref().map(|v| &**v)
    }

    /// View data as mutable reference option.
    #[inline]
    pub fn as_mut(&mut self) -> Option<&mut T> {
        self.0.as_mut().map(|v| &mut **v)
    }

    /// Get data as reference.
    /// Panics if empty.
    #[inline]
    pub fn get_ref(&self) -> &T {
        self.as_ref().unwrap()
    }

    /// Get data as mutable reference.
    /// Panics if empty.
    #[inline]
    pub fn get_mut_ref(&mut self) -> &mut T {
        self.as_mut().unwrap()
    }

    /// Take the data.
    /// Panics if empty
    #[inline]
    pub fn unwrap(self) -> T {
        *self.0.unwrap()
    }

    /// Take the data or return supplied default element if empty.
    #[inline]
    pub fn unwrap_or(self, def: T) -> T {
        self.0.map(|v| *v).unwrap_or(def)
    }

    /// Take the data or return supplied default element if empty.
    #[inline]
    pub fn unwrap_or_else<F>(self, f: F) -> T
    where
        F: FnOnce() -> T,
    {
        self.0.map(|v| *v).unwrap_or_else(f)
    }

    /// Apply given function to contained data to construct another `SingularPtrField`.
    /// Returns empty `SingularPtrField` if this object is empty.
    #[inline]
    pub fn map<U, F>(self, f: F) -> MessageField<U>
    where
        F: FnOnce(T) -> U,
    {
        MessageField::from_option(self.into_option().map(f))
    }

    /// View data as iterator.
    #[inline]
    pub fn iter(&self) -> option::IntoIter<&T> {
        self.as_ref().into_iter()
    }

    /// View data as mutable iterator.
    #[inline]
    pub fn mut_iter(&mut self) -> option::IntoIter<&mut T> {
        self.as_mut().into_iter()
    }

    /// Take data as option, leaving this object empty.
    #[inline]
    pub fn take(&mut self) -> Option<T> {
        self.0.take().map(|v| *v)
    }

    /// Clear this object, but do not call destructor of underlying data.
    #[inline]
    pub fn clear(&mut self) {
        self.0 = None;
    }
}

impl<T: Default> MessageField<T> {
    /// Get contained data, consume self. Return default value for type if this is empty.
    #[inline]
    pub fn unwrap_or_default(self) -> T {
        *self.0.unwrap_or_default()
    }

    /// Set object to `Some(T::default())`.
    // TODO: inline
    #[inline]
    pub fn set_default(&mut self) -> &mut T {
        *self = MessageField::some(Default::default());
        self.as_mut().unwrap()
    }
}

impl<M: Message + Default> MessageField<M> {
    /// Get a reference to contained value or a default instance.
    pub fn get_or_default(&self) -> &M {
        self.as_ref().unwrap_or_else(|| M::default_instance())
    }

    /// Get a mutable reference to contained value, initialize if not initialized yet.
    pub fn mut_or_default(&mut self) -> &mut M {
        if self.is_none() {
            *self = MessageField::some(Default::default());
        }
        self.get_mut_ref()
    }
}

/// Get a reference to contained value or a default instance if the field is not initialized.
impl<M: Message + Default> Deref for MessageField<M> {
    type Target = M;

    fn deref(&self) -> &Self::Target {
        self.get_or_default()
    }
}

/// Get a mutable reference to the message **and** initialize the message if not initialized yet.
///
/// Note that part about initializing is not conventional.
/// Generally `DerefMut` is not supposed to modify the state.
impl<M: Message + Default> DerefMut for MessageField<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.mut_or_default()
    }
}

impl<T> Default for MessageField<T> {
    #[inline]
    fn default() -> MessageField<T> {
        MessageField::none()
    }
}

impl<T> From<Option<T>> for MessageField<T> {
    fn from(o: Option<T>) -> Self {
        MessageField::from_option(o)
    }
}

impl<'a, T> IntoIterator for &'a MessageField<T> {
    type Item = &'a T;
    type IntoIter = option::IntoIter<&'a T>;

    fn into_iter(self) -> option::IntoIter<&'a T> {
        self.iter()
    }
}
<commit_msg>From<Option<Box<T>> for MessageField<T><commit_after>use std::default::Default;
use std::hash::Hash;
use std::ops::Deref;
use std::ops::DerefMut;
use std::option;

use crate::Message;

/// Wrapper around `Option<Box<T>>`, convenient newtype.
///
/// # Examples
///
/// ```no_run
/// # use protobuf::MessageField;
/// # use std::ops::Add;
/// # struct Address {
/// # }
/// # struct Customer {
/// #     address: MessageField<Address>,
/// # }
/// # impl Customer {
/// #     fn new() -> Customer { unimplemented!() }
/// # }
/// #
/// #
/// # fn make_address() -> Address { unimplemented!() }
/// let mut customer = Customer::new();
///
/// // field of type `SingularPtrField` can be initialized like this
/// customer.address = MessageField::some(make_address());
/// // or using `Option` and `Into`
/// customer.address = Some(make_address()).into();
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct MessageField<T>(pub Option<Box<T>>);

impl<T> MessageField<T> {
    /// Construct `SingularPtrField` from given object.
    #[inline]
    pub fn some(value: T) -> MessageField<T> {
        MessageField(Some(Box::new(value)))
    }

    /// Construct an empty `SingularPtrField`.
    #[inline]
    pub const fn none() -> MessageField<T> {
        MessageField(None)
    }

    /// Construct `SingularPtrField` from optional.
    #[inline]
    pub fn from_option(option: Option<T>) -> MessageField<T> {
        match option {
            Some(x) => MessageField::some(x),
            None => MessageField::none(),
        }
    }

    /// True iff this object contains data.
    #[inline]
    pub fn is_some(&self) -> bool {
        self.0.is_some()
    }

    /// True iff this object contains no data.
    #[inline]
    pub fn is_none(&self) -> bool {
        self.0.is_none()
    }

    /// Convert into `Option<T>`.
    #[inline]
    pub fn into_option(self) -> Option<T> {
        self.0.map(|v| *v)
    }

    /// View data as reference option.
    #[inline]
    pub fn as_ref(&self) -> Option<&T> {
        self.0.as_ref().map(|v| &**v)
    }

    /// View data as mutable reference option.
    #[inline]
    pub fn as_mut(&mut self) -> Option<&mut T> {
        self.0.as_mut().map(|v| &mut **v)
    }

    /// Get data as reference.
    /// Panics if empty.
    #[inline]
    pub fn get_ref(&self) -> &T {
        self.as_ref().unwrap()
    }

    /// Get data as mutable reference.
    /// Panics if empty.
    #[inline]
    pub fn get_mut_ref(&mut self) -> &mut T {
        self.as_mut().unwrap()
    }

    /// Take the data.
    /// Panics if empty
    #[inline]
    pub fn unwrap(self) -> T {
        *self.0.unwrap()
    }

    /// Take the data or return supplied default element if empty.
    #[inline]
    pub fn unwrap_or(self, def: T) -> T {
        self.0.map(|v| *v).unwrap_or(def)
    }

    /// Take the data or return supplied default element if empty.
    #[inline]
    pub fn unwrap_or_else<F>(self, f: F) -> T
    where
        F: FnOnce() -> T,
    {
        self.0.map(|v| *v).unwrap_or_else(f)
    }

    /// Apply given function to contained data to construct another `SingularPtrField`.
    /// Returns empty `SingularPtrField` if this object is empty.
    #[inline]
    pub fn map<U, F>(self, f: F) -> MessageField<U>
    where
        F: FnOnce(T) -> U,
    {
        MessageField::from_option(self.into_option().map(f))
    }

    /// View data as iterator.
    #[inline]
    pub fn iter(&self) -> option::IntoIter<&T> {
        self.as_ref().into_iter()
    }

    /// View data as mutable iterator.
    #[inline]
    pub fn mut_iter(&mut self) -> option::IntoIter<&mut T> {
        self.as_mut().into_iter()
    }

    /// Take data as option, leaving this object empty.
    #[inline]
    pub fn take(&mut self) -> Option<T> {
        self.0.take().map(|v| *v)
    }

    /// Clear this object, but do not call destructor of underlying data.
    #[inline]
    pub fn clear(&mut self) {
        self.0 = None;
    }
}

impl<T: Default> MessageField<T> {
    /// Get contained data, consume self. Return default value for type if this is empty.
    #[inline]
    pub fn unwrap_or_default(self) -> T {
        *self.0.unwrap_or_default()
    }

    /// Set object to `Some(T::default())`.
    // TODO: inline
    #[inline]
    pub fn set_default(&mut self) -> &mut T {
        *self = MessageField::some(Default::default());
        self.as_mut().unwrap()
    }
}

impl<M: Message + Default> MessageField<M> {
    /// Get a reference to contained value or a default instance.
    pub fn get_or_default(&self) -> &M {
        self.as_ref().unwrap_or_else(|| M::default_instance())
    }

    /// Get a mutable reference to contained value, initialize if not initialized yet.
    pub fn mut_or_default(&mut self) -> &mut M {
        if self.is_none() {
            *self = MessageField::some(Default::default());
        }
        self.get_mut_ref()
    }
}

/// Get a reference to contained value or a default instance if the field is not initialized.
impl<M: Message + Default> Deref for MessageField<M> {
    type Target = M;

    fn deref(&self) -> &Self::Target {
        self.get_or_default()
    }
}

/// Get a mutable reference to the message **and** initialize the message if not initialized yet.
///
/// Note that part about initializing is not conventional.
/// Generally `DerefMut` is not supposed to modify the state.
impl<M: Message + Default> DerefMut for MessageField<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.mut_or_default()
    }
}

impl<T> Default for MessageField<T> {
    #[inline]
    fn default() -> MessageField<T> {
        MessageField::none()
    }
}

impl<T> From<Option<T>> for MessageField<T> {
    fn from(o: Option<T>) -> Self {
        MessageField::from_option(o)
    }
}

impl<T> From<Option<Box<T>>> for MessageField<T> {
    fn from(o: Option<Box<T>>) -> Self {
        MessageField(o)
    }
}

impl<'a, T> IntoIterator for &'a MessageField<T> {
    type Item = &'a T;
    type IntoIter = option::IntoIter<&'a T>;

    fn into_iter(self) -> option::IntoIter<&'a T> {
        self.iter()
    }
}
<|endoftext|>


<commit_before>pub use self::keys::Keys;
pub use self::mouse::Mouse;
pub use self::window::Window;

/// Tracked state related to the focused window.
pub mod window {
    use window;

    /// State of the window in focus.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct Window {
        /// ID of the window currently in focus.
        pub id: Option<window::Id>,
        /// The width of the focused window agnostic of DPI.
        ///
        /// This is equal to the pixel width divided by the hidpi_factor.
        pub width: f64,
        /// The height of the focused window agnostic of DPI.
        ///
        /// This is equal to the pixel height divided by the hidpi_factor.
        pub height: f64,
        /// The high "dots-per-inch" multiplier that describes the density of the screens pixels.
        pub hidpi_factor: f64,
    }

    impl Window {
        /// Initialise the window state.
        pub fn new() -> Self {
            Window {
                id: None,
                width: 0.0,
                height: 0.0,
                hidpi_factor: 1.0,
            }
        }
    }
}

/// Tracked state related to the keyboard.
pub mod keys {
    use event::{Key, ModifiersState};
    use std::collections::HashSet;
    use std::ops::Deref;

    /// The state of the keyboard.
    #[derive(Clone, Debug, Default)]
    pub struct Keys {
        /// The state of the modifier keys as last indicated by winit.
        pub mods: ModifiersState,
        /// The state of all keys as tracked via the nannou App event handling.
        pub down: Down,
    }

    /// The set of keys that are currently pressed.
    #[derive(Clone, Debug, Default)]
    pub struct Down {
        pub(crate) keys: HashSet<Key>,
    }

    impl Deref for Down {
        type Target = HashSet<Key>;
        fn deref(&self) -> &Self::Target {
            &self.keys
        }
    }
}

/// Tracked state related to the mouse.
pub mod mouse {
    use math::Point2;
    use std;
    use window;

    #[doc(inline)]
    pub use event::MouseButton as Button;

    /// The max total number of buttons on a mouse.
    pub const NUM_BUTTONS: usize = 9;

    /// The state of the `Mouse` at a single moment in time.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct Mouse {
        /// The ID of the last window currently in focus.
        pub window: Option<window::Id>,
        /// *x* position relative to the middle of `window`.
        pub x: f64,
        /// *y* position relative to the middle of `window`.
        pub y: f64,
        /// A map describing the state of each mouse button.
        pub buttons: ButtonMap,
    }

    /// Whether the button is up or down.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub enum ButtonPosition {
        /// The button is up (i.e. pressed).
        Up,
        /// The button is down and was originally pressed down at the given `Point2`.
        Down(Point2<f64>),
    }

    /// Stores the state of all mouse buttons.
    ///
    /// If the mouse button is down, it stores the position of the mouse when the button was pressed
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct ButtonMap {
        buttons: [ButtonPosition; NUM_BUTTONS],
    }

    /// An iterator yielding all pressed buttons.
    #[derive(Clone)]
    pub struct PressedButtons<'a> {
        buttons: std::iter::Enumerate<std::slice::Iter<'a, ButtonPosition>>,
    }

    impl Mouse {
        /// Construct a new default `Mouse`.
        pub fn new() -> Self {
            Mouse {
                window: None,
                buttons: ButtonMap::new(),
                x: 0.0,
                y: 0.0,
            }
        }

        /// The position of the mouse relative to the middle of the window in focus..
        pub fn position(&self) -> Point2<f64> {
            Point2 { x: self.x, y: self.y }
        }
    }

    impl ButtonPosition {
        /// If the mouse button is down, return a new one with position relative to the given `xy`.
        pub fn relative_to(self, xy: Point2<f64>) -> Self {
            match self {
                ButtonPosition::Down(pos) => {
                    let rel_p = pos - xy;
                    ButtonPosition::Down(Point2 { x: rel_p.x, y: rel_p.y })
                }
                button_pos => button_pos,
            }
        }

        /// Is the `ButtonPosition` down.
        pub fn is_down(&self) -> bool {
            match *self {
                ButtonPosition::Down(_) => true,
                _ => false,
            }
        }

        /// Is the `ButtonPosition` up.
        pub fn is_up(&self) -> bool {
            match *self {
                ButtonPosition::Up => true,
                _ => false,
            }
        }

        /// Returns the position at which the button was pressed.
        pub fn if_down(&self) -> Option<Point2<f64>> {
            match *self {
                ButtonPosition::Down(xy) => Some((xy)),
                _ => None,
            }
        }
    }

    impl ButtonMap {
        /// Returns a new button map with all states set to `None`
        pub fn new() -> Self {
            ButtonMap { buttons: [ButtonPosition::Up; NUM_BUTTONS] }
        }

        /// Returns a copy of the ButtonMap relative to the given `Point`
        pub fn relative_to(self, xy: Point2<f64>) -> Self {
            self.buttons.iter().enumerate().fold(
                ButtonMap::new(),
                |mut map,
                 (idx, button_pos)| {
                    map.buttons[idx] = button_pos.relative_to(xy);
                    map
                },
            )
        }

        /// The state of the left mouse button.
        pub fn left(&self) -> &ButtonPosition {
            &self[Button::Left]
        }

        /// The state of the middle mouse button.
        pub fn middle(&self) -> &ButtonPosition {
            &self[Button::Middle]
        }

        /// The state of the right mouse button.
        pub fn right(&self) -> &ButtonPosition {
            &self[Button::Right]
        }

        /// Sets the `Button` in the `Down` position.
        pub fn press(&mut self, button: Button, xy: Point2<f64>) {
            self.buttons[button_to_idx(button)] = ButtonPosition::Down(xy);
        }

        /// Set's the `Button` in the `Up` position.
        pub fn release(&mut self, button: Button) {
            self.buttons[button_to_idx(button)] = ButtonPosition::Up;
        }

        /// An iterator yielding all pressed mouse buttons along with the location at which they
        /// were originally pressed.
        pub fn pressed(&self) -> PressedButtons {
            PressedButtons { buttons: self.buttons.iter().enumerate() }
        }
    }

    impl std::ops::Index<Button> for ButtonMap {
        type Output = ButtonPosition;
        fn index(&self, button: Button) -> &Self::Output {
            &self.buttons[button_to_idx(button)]
        }
    }

    impl<'a> Iterator for PressedButtons<'a> {
        type Item = (Button, Point2<f64>);
        fn next(&mut self) -> Option<Self::Item> {
            while let Some((idx, button_pos)) = self.buttons.next() {
                if let ButtonPosition::Down(xy) = *button_pos {
                    return Some((idx_to_button(idx), xy));
                }
            }
            None
        }
    }

    fn idx_to_button(i: usize) -> Button {
        match i {
            n @ 0...5 => Button::Other(n as u8),
            6 => Button::Left,
            7 => Button::Right,
            8 => Button::Middle,
            _ => Button::Other(std::u8::MAX),
        }
    }

    fn button_to_idx(button: Button) -> usize {
        match button {
            Button::Other(n) => n as usize,
            Button::Left => 6,
            Button::Right => 7,
            Button::Middle => 8,
        }
    }
}
<commit_msg>Add method for retrieving window size as a Vector2<commit_after>pub use self::keys::Keys;
pub use self::mouse::Mouse;
pub use self::window::Window;

/// Tracked state related to the focused window.
pub mod window {
    use window;
    use math::Vector2;

    /// State of the window in focus.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct Window {
        /// ID of the window currently in focus.
        pub id: Option<window::Id>,
        /// The width of the focused window agnostic of DPI.
        ///
        /// This is equal to the pixel width divided by the hidpi_factor.
        pub width: f64,
        /// The height of the focused window agnostic of DPI.
        ///
        /// This is equal to the pixel height divided by the hidpi_factor.
        pub height: f64,
        /// The high "dots-per-inch" multiplier that describes the density of the screens pixels.
        pub hidpi_factor: f64,
    }

    impl Window {
        /// Initialise the window state.
        pub fn new() -> Self {
            Window {
                id: None,
                width: 0.0,
                height: 0.0,
                hidpi_factor: 1.0,
            }
        }

        /// Return the `width` and `height` as a `Vector2`.
        pub fn size(&self) -> Vector2<f64> {
            Vector2 { x: self.width, y: self.height }
        }
    }
}

/// Tracked state related to the keyboard.
pub mod keys {
    use event::{Key, ModifiersState};
    use std::collections::HashSet;
    use std::ops::Deref;

    /// The state of the keyboard.
    #[derive(Clone, Debug, Default)]
    pub struct Keys {
        /// The state of the modifier keys as last indicated by winit.
        pub mods: ModifiersState,
        /// The state of all keys as tracked via the nannou App event handling.
        pub down: Down,
    }

    /// The set of keys that are currently pressed.
    #[derive(Clone, Debug, Default)]
    pub struct Down {
        pub(crate) keys: HashSet<Key>,
    }

    impl Deref for Down {
        type Target = HashSet<Key>;
        fn deref(&self) -> &Self::Target {
            &self.keys
        }
    }
}

/// Tracked state related to the mouse.
pub mod mouse {
    use math::Point2;
    use std;
    use window;

    #[doc(inline)]
    pub use event::MouseButton as Button;

    /// The max total number of buttons on a mouse.
    pub const NUM_BUTTONS: usize = 9;

    /// The state of the `Mouse` at a single moment in time.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct Mouse {
        /// The ID of the last window currently in focus.
        pub window: Option<window::Id>,
        /// *x* position relative to the middle of `window`.
        pub x: f64,
        /// *y* position relative to the middle of `window`.
        pub y: f64,
        /// A map describing the state of each mouse button.
        pub buttons: ButtonMap,
    }

    /// Whether the button is up or down.
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub enum ButtonPosition {
        /// The button is up (i.e. pressed).
        Up,
        /// The button is down and was originally pressed down at the given `Point2`.
        Down(Point2<f64>),
    }

    /// Stores the state of all mouse buttons.
    ///
    /// If the mouse button is down, it stores the position of the mouse when the button was pressed
    #[derive(Copy, Clone, Debug, PartialEq)]
    pub struct ButtonMap {
        buttons: [ButtonPosition; NUM_BUTTONS],
    }

    /// An iterator yielding all pressed buttons.
    #[derive(Clone)]
    pub struct PressedButtons<'a> {
        buttons: std::iter::Enumerate<std::slice::Iter<'a, ButtonPosition>>,
    }

    impl Mouse {
        /// Construct a new default `Mouse`.
        pub fn new() -> Self {
            Mouse {
                window: None,
                buttons: ButtonMap::new(),
                x: 0.0,
                y: 0.0,
            }
        }

        /// The position of the mouse relative to the middle of the window in focus..
        pub fn position(&self) -> Point2<f64> {
            Point2 { x: self.x, y: self.y }
        }
    }

    impl ButtonPosition {
        /// If the mouse button is down, return a new one with position relative to the given `xy`.
        pub fn relative_to(self, xy: Point2<f64>) -> Self {
            match self {
                ButtonPosition::Down(pos) => {
                    let rel_p = pos - xy;
                    ButtonPosition::Down(Point2 { x: rel_p.x, y: rel_p.y })
                }
                button_pos => button_pos,
            }
        }

        /// Is the `ButtonPosition` down.
        pub fn is_down(&self) -> bool {
            match *self {
                ButtonPosition::Down(_) => true,
                _ => false,
            }
        }

        /// Is the `ButtonPosition` up.
        pub fn is_up(&self) -> bool {
            match *self {
                ButtonPosition::Up => true,
                _ => false,
            }
        }

        /// Returns the position at which the button was pressed.
        pub fn if_down(&self) -> Option<Point2<f64>> {
            match *self {
                ButtonPosition::Down(xy) => Some((xy)),
                _ => None,
            }
        }
    }

    impl ButtonMap {
        /// Returns a new button map with all states set to `None`
        pub fn new() -> Self {
            ButtonMap { buttons: [ButtonPosition::Up; NUM_BUTTONS] }
        }

        /// Returns a copy of the ButtonMap relative to the given `Point`
        pub fn relative_to(self, xy: Point2<f64>) -> Self {
            self.buttons.iter().enumerate().fold(
                ButtonMap::new(),
                |mut map,
                 (idx, button_pos)| {
                    map.buttons[idx] = button_pos.relative_to(xy);
                    map
                },
            )
        }

        /// The state of the left mouse button.
        pub fn left(&self) -> &ButtonPosition {
            &self[Button::Left]
        }

        /// The state of the middle mouse button.
        pub fn middle(&self) -> &ButtonPosition {
            &self[Button::Middle]
        }

        /// The state of the right mouse button.
        pub fn right(&self) -> &ButtonPosition {
            &self[Button::Right]
        }

        /// Sets the `Button` in the `Down` position.
        pub fn press(&mut self, button: Button, xy: Point2<f64>) {
            self.buttons[button_to_idx(button)] = ButtonPosition::Down(xy);
        }

        /// Set's the `Button` in the `Up` position.
        pub fn release(&mut self, button: Button) {
            self.buttons[button_to_idx(button)] = ButtonPosition::Up;
        }

        /// An iterator yielding all pressed mouse buttons along with the location at which they
        /// were originally pressed.
        pub fn pressed(&self) -> PressedButtons {
            PressedButtons { buttons: self.buttons.iter().enumerate() }
        }
    }

    impl std::ops::Index<Button> for ButtonMap {
        type Output = ButtonPosition;
        fn index(&self, button: Button) -> &Self::Output {
            &self.buttons[button_to_idx(button)]
        }
    }

    impl<'a> Iterator for PressedButtons<'a> {
        type Item = (Button, Point2<f64>);
        fn next(&mut self) -> Option<Self::Item> {
            while let Some((idx, button_pos)) = self.buttons.next() {
                if let ButtonPosition::Down(xy) = *button_pos {
                    return Some((idx_to_button(idx), xy));
                }
            }
            None
        }
    }

    fn idx_to_button(i: usize) -> Button {
        match i {
            n @ 0...5 => Button::Other(n as u8),
            6 => Button::Left,
            7 => Button::Right,
            8 => Button::Middle,
            _ => Button::Other(std::u8::MAX),
        }
    }

    fn button_to_idx(button: Button) -> usize {
        match button {
            Button::Other(n) => n as usize,
            Button::Left => 6,
            Button::Right => 7,
            Button::Middle => 8,
        }
    }
}
<|endoftext|>


<commit_before>use std::ops;
use std::io::{self, Write};
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

use chunk_vec::{Chunk, CHUNK_MB};
use config::Config;
use solve::Node;

use tabwriter::TabWriter;
use time::{Duration, PreciseTime};

static CHUNK_ALLOC_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
static CHUNK_DEALLOC_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

static PAIR_APPLY_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
static PAIR_APPLY_SUCCESS_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

pub fn chunk_allocated() {
    CHUNK_ALLOC_COUNT.fetch_add(1, Ordering::AcqRel);
}

pub fn chunk_deallocated() {
    CHUNK_DEALLOC_COUNT.fetch_add(1, Ordering::AcqRel);
}

pub fn pairs_applied(cnt: usize) {
    PAIR_APPLY_COUNT.fetch_add(cnt, Ordering::AcqRel);
}

pub fn pairs_successfully_applied(cnt: usize) {
    PAIR_APPLY_SUCCESS_COUNT.fetch_add(cnt, Ordering::AcqRel);
}

pub struct IterStats {
    timings: Vec<Duration>,
    iter_cnt: u32,
}

impl IterStats {
    pub fn new() -> IterStats {
        IterStats {
            timings: vec![],
            iter_cnt: 0,
        }
    }

    pub fn iter<F: FnOnce()>(&mut self, f: F) {
        let start = PreciseTime::now();
        self.iter_cnt += 1;

        println!("Now starting iteration {}", self.iter_cnt);

        f();

        let stop = PreciseTime::now();

        self.timings.push(start.to(stop));
    }

    fn iter_duration(&self) -> Duration {
        self.timings.iter().cloned().fold(Duration::zero(), ops::Add::add)
    }
}

macro_rules! stat {
    ($t:expr, $l:expr) => ((writeln!($t, "{}", $l).unwrap()));
    ($t:expr, $l:expr, $v:expr) => ((writeln!($t, "{}:\t{}", $l, $v).unwrap()));
    ($t:expr, $l:expr, $v:expr, $fmt:tt) => ((writeln!($t, concat!("{}:\t", $fmt), $l, $v).unwrap()));
}

macro_rules! stats {
    ($(($($tt:tt)*))*) => {{
        let stdout = io::stdout();
        let mut t = TabWriter::new(stdout.lock());

        $(
            stat!(t, $($tt)*);
        )*

        t.flush().unwrap();
    }}
}

pub fn print(_config: &Config, iter_cnt: usize, _chunks: &[Chunk<Node>], stats: IterStats) {
    let iter_duration = stats.iter_duration();

    stats! {
        ("")
        ("-- Statistics --")
        ("chunk size", CHUNK_MB, "{:5} MB")
        ("chunks allocated", CHUNK_ALLOC_COUNT.load(Ordering::Acquire), "{:5}")
        ("chunks deallocated", CHUNK_DEALLOC_COUNT.load(Ordering::Acquire), "{:5}")
        ("chunks total memory", CHUNK_MB as f64 * CHUNK_ALLOC_COUNT.load(Ordering::Acquire) as f64 / 1024f64, "{:5.1} GB")

        ("chunks in current working set", _chunks.len(), "{:5}")
        ("pairs applied", pretty_high_str(PAIR_APPLY_COUNT.load(Ordering::Acquire) as f64))
        ("pairs applied successfully", pretty_high_str(PAIR_APPLY_SUCCESS_COUNT.load(Ordering::Acquire) as f64))

        ("number of iterations", iter_cnt, "{:5}")
        ("total iteration time", iter_duration.num_milliseconds() as f64 / 1000f64, "{:5.1} seconds")
        ("operations", pretty_high_str(PAIR_APPLY_COUNT.load(Ordering::Acquire) as f64 / iter_duration.num_milliseconds() as f64), "{} ops/ms")
    }
}

fn pretty_high_str(f: f64) -> String {
    let (f, suffix) = pretty_high(f);
    format!("{:5.1}{}", f, suffix)
}

fn pretty_high(mut f: f64) -> (f64, &'static str) {
    for suffix in &["", " thousand", " million", " billion", " trillion"] {
        if f < 1000.0 { return (f, suffix) }
        f /= 1000.0;
    }

    return (f, "e15");
}
<commit_msg>limit status message rate<commit_after>use std::ops;
use std::io::{self, Write};
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

use chunk_vec::{Chunk, CHUNK_MB};
use config::Config;
use solve::Node;

use tabwriter::TabWriter;
use time::{Duration, PreciseTime};

const PRINT_INTERVAL: i64 = 1; // seconds

static CHUNK_ALLOC_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
static CHUNK_DEALLOC_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

static PAIR_APPLY_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
static PAIR_APPLY_SUCCESS_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

pub fn chunk_allocated() {
    CHUNK_ALLOC_COUNT.fetch_add(1, Ordering::AcqRel);
}

pub fn chunk_deallocated() {
    CHUNK_DEALLOC_COUNT.fetch_add(1, Ordering::AcqRel);
}

pub fn pairs_applied(cnt: usize) {
    PAIR_APPLY_COUNT.fetch_add(cnt, Ordering::AcqRel);
}

pub fn pairs_successfully_applied(cnt: usize) {
    PAIR_APPLY_SUCCESS_COUNT.fetch_add(cnt, Ordering::AcqRel);
}

pub struct IterStats {
    timings: Vec<Duration>,
    iter_cnt: u32,
    last_print: PreciseTime,
}

impl IterStats {
    pub fn new() -> IterStats {
        IterStats {
            timings: vec![],
            iter_cnt: 0,
            last_print: PreciseTime::now(),
        }
    }

    pub fn iter<F: FnOnce()>(&mut self, f: F) {
        let start = PreciseTime::now();
        self.iter_cnt += 1;

        if self.last_print.to(start) >= Duration::seconds(PRINT_INTERVAL) {
            println!("Now starting iteration {}", self.iter_cnt);
            self.last_print = start;
        }

        f();

        let stop = PreciseTime::now();

        self.timings.push(start.to(stop));
    }

    fn iter_duration(&self) -> Duration {
        self.timings.iter().cloned().fold(Duration::zero(), ops::Add::add)
    }
}

macro_rules! stat {
    ($t:expr, $l:expr) => ((writeln!($t, "{}", $l).unwrap()));
    ($t:expr, $l:expr, $v:expr) => ((writeln!($t, "{}:\t{}", $l, $v).unwrap()));
    ($t:expr, $l:expr, $v:expr, $fmt:tt) => ((writeln!($t, concat!("{}:\t", $fmt), $l, $v).unwrap()));
}

macro_rules! stats {
    ($(($($tt:tt)*))*) => {{
        let stdout = io::stdout();
        let mut t = TabWriter::new(stdout.lock());

        $(
            stat!(t, $($tt)*);
        )*

        t.flush().unwrap();
    }}
}

pub fn print(_config: &Config, iter_cnt: usize, _chunks: &[Chunk<Node>], stats: IterStats) {
    let iter_duration = stats.iter_duration();

    stats! {
        ("")
        ("-- Statistics --")
        ("chunk size", CHUNK_MB, "{:5} MB")
        ("chunks allocated", CHUNK_ALLOC_COUNT.load(Ordering::Acquire), "{:5}")
        ("chunks deallocated", CHUNK_DEALLOC_COUNT.load(Ordering::Acquire), "{:5}")
        ("chunks total memory", CHUNK_MB as f64 * CHUNK_ALLOC_COUNT.load(Ordering::Acquire) as f64 / 1024f64, "{:5.1} GB")

        ("chunks in current working set", _chunks.len(), "{:5}")
        ("pairs applied", pretty_high_str(PAIR_APPLY_COUNT.load(Ordering::Acquire) as f64))
        ("pairs applied successfully", pretty_high_str(PAIR_APPLY_SUCCESS_COUNT.load(Ordering::Acquire) as f64))

        ("number of iterations", iter_cnt, "{:5}")
        ("total iteration time", iter_duration.num_milliseconds() as f64 / 1000f64, "{:5.1} seconds")
        ("operations", pretty_high_str(PAIR_APPLY_COUNT.load(Ordering::Acquire) as f64 / iter_duration.num_milliseconds() as f64), "{} ops/ms")
    }
}

fn pretty_high_str(f: f64) -> String {
    let (f, suffix) = pretty_high(f);
    format!("{:5.1}{}", f, suffix)
}

fn pretty_high(mut f: f64) -> (f64, &'static str) {
    for suffix in &["", " thousand", " million", " billion", " trillion"] {
        if f < 1000.0 { return (f, suffix) }
        f /= 1000.0;
    }

    return (f, "e15");
}
<|endoftext|>