<commit_before>

//NEW
#[test]
#[ignore]
/// ending with whitespace
fn test_ending_with_whitespace() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Okay if like my  spacebar  quite a bit?   "); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// shouting numbers
fn test_shouting_numbers() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "1, 2, 3 GO!"); hm}, "Whoa, chill out!");
}

//NEW
#[test]
#[ignore]
/// other whitespace
fn test_other_whitespace() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "\r\r 	"); hm}, "Fine. Be that way!");
}

//NEW
#[test]
#[ignore]
/// shouting with special characters
fn test_shouting_with_special_characters() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"); hm}, "Whoa, chill out!");
}

//NEW
#[test]
#[ignore]
/// talking forcefully
fn test_talking_forcefully() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Hi there!"); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// prattling on
fn test_prattling_on() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Wait! Hang on. Are you going to be OK?"); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// forceful question
fn test_forceful_question() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "WHAT'S GOING ON?"); hm}, "Calm down, I know what I'm doing!");
}

//NEW
#[test]
#[ignore]
/// shouting with no exclamation mark
fn test_shouting_with_no_exclamation_mark() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "I HATE THE DENTIST"); hm}, "Whoa, chill out!");
}

//NEW
#[test]
#[ignore]
/// asking gibberish
fn test_asking_gibberish() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "fffbbcbeab?"); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// question with no letters
fn test_question_with_no_letters() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "4?"); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// no letters
fn test_no_letters() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "1, 2, 3"); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// statement containing question mark
fn test_statement_containing_question_mark() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Ending with ? means a question."); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// multiple line question
fn test_multiple_line_question() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "
Does this cryogenic chamber make me look fat?
No."); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// non-question ending with whitespace
fn test_nonquestion_ending_with_whitespace() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "This is a statement ending with whitespace      "); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// shouting
fn test_shouting() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "WATCH OUT!"); hm}, "Whoa, chill out!");
}

//NEW
#[test]
#[ignore]
/// non-letters with question
fn test_nonletters_with_question() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", ":) ?"); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// stating something
fn test_stating_something() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Tom-ay-to, tom-aaaah-to."); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// shouting gibberish
fn test_shouting_gibberish() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "FCECDFCAAB"); hm}, "Whoa, chill out!");
}

//NEW
#[test]
#[ignore]
/// asking a question
fn test_asking_a_question() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "Does this cryogenic chamber make me look fat?"); hm}, "Sure.");
}

//NEW
/// Process a single test case for the property `response`
///
/// All cases for the `response` property are implemented
/// in terms of this function.
///
/// Note that you'll need to both name the expected transform which
/// the student needs to write, and name the types of the inputs and outputs.
/// While rustc _may_ be able to handle things properly given a working example,
/// students will face confusing errors if the `I` and `O` types are not concrete.
///
fn process_response_case<I, O>(input: I, expected: O) {
//  typical implementation:
//  assert_eq!(
//      student_response_func(input),
//      expected
//  )
    unimplemented!()
}

//NEW
#[test]
#[ignore]
/// asking a numeric question
fn test_asking_a_numeric_question() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "You are, what, like 15?"); hm}, "Sure.");
}

//NEW
#[test]
#[ignore]
/// silence
fn test_silence() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", ""); hm}, "Fine. Be that way!");
}

//NEW
#[test]
#[ignore]
/// starting with whitespace
fn test_starting_with_whitespace() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "         hmmmmmmm..."); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// using acronyms in regular speech
fn test_using_acronyms_in_regular_speech() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "It's OK if you don't want to go work for NASA."); hm}, "Whatever.");
}

//NEW
#[test]
#[ignore]
/// alternate silence
fn test_alternate_silence() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "										"); hm}, "Fine. Be that way!");
}

//NEW
#[test]
#[ignore]
/// prolonged silence
fn test_prolonged_silence() {
process_response_case({let mut hm = ::std::collections::HashMap::new(); hm.insert("heyBob", "          "); hm}, "Fine. Be that way!");
}

<commit_msg>Actually implement the test-cases this time<commit_after>fn process_response_case(phrase: &str, expected_response: &str) {
    assert_eq!(bob::reply(phrase), expected_response);
}

#[test]
#[ignore]
/// ending with whitespace
fn test_ending_with_whitespace() {
    process_response_case("Okay if like my  spacebar  quite a bit?   ", "Sure.");
}

#[test]
#[ignore]
/// shouting numbers
fn test_shouting_numbers() {
    process_response_case("1, 2, 3 GO!", "Whoa, chill out!");
}

#[test]
#[ignore]
/// other whitespace
fn test_other_whitespace() {
    process_response_case("\r\r 	", "Fine. Be that way!");
}

#[test]
#[ignore]
/// shouting with special characters
fn test_shouting_with_special_characters() {
    process_response_case("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!", "Whoa, chill out!");
}

#[test]
#[ignore]
/// talking forcefully
fn test_talking_forcefully() {
    process_response_case("Hi there!", "Whatever.");
}

#[test]
#[ignore]
/// prattling on
fn test_prattling_on() {
    process_response_case("Wait! Hang on. Are you going to be OK?", "Sure.");
}

#[test]
#[ignore]
/// forceful question
fn test_forceful_question() {
   process_response_case("WHAT'S GOING ON?", "Calm down, I know what I'm doing!");
}

#[test]
#[ignore]
/// shouting with no exclamation mark
fn test_shouting_with_no_exclamation_mark() {
    process_response_case("I HATE THE DENTIST", "Whoa, chill out!");
}

#[test]
#[ignore]
/// asking gibberish
fn test_asking_gibberish() {
    process_response_case("fffbbcbeab?", "Sure.");
}

#[test]
#[ignore]
/// question with no letters
fn test_question_with_no_letters() {
    process_response_case("4?", "Sure.");
}

#[test]
#[ignore]
/// no letters
fn test_no_letters() {
    process_response_case("1, 2, 3", "Whatever.");
}

#[test]
#[ignore]
/// statement containing question mark
fn test_statement_containing_question_mark() {
    process_response_case("Ending with ? means a question.", "Whatever.");
}

//NEW
#[test]
#[ignore]
/// multiple line question
fn test_multiple_line_question() {
    process_response_case("\rDoes this cryogenic chamber make me look fat?\rNo.", "Whatever.");
}

#[test]
#[ignore]
/// non-question ending with whitespace
fn test_nonquestion_ending_with_whitespace() {
    process_response_case("This is a statement ending with whitespace      ", "Whatever.");
}

#[test]
#[ignore]
/// shouting
fn test_shouting() {
    process_response_case("WATCH OUT!", "Whoa, chill out!");
}

#[test]
#[ignore]
/// non-letters with question
fn test_nonletters_with_question() {
    process_response_case(":) ?", "Sure.");
}

#[test]
#[ignore]
/// stating something
fn test_stating_something() {
    process_response_case("Tom-ay-to, tom-aaaah-to.", "Whatever.");
}

#[test]
#[ignore]
/// shouting gibberish
fn test_shouting_gibberish() {
    process_response_case("FCECDFCAAB", "Whoa, chill out!");
}

#[test]
#[ignore]
/// asking a question
fn test_asking_a_question() {
    process_response_case("Does this cryogenic chamber make me look fat?", "Sure.");
}

#[test]
#[ignore]
/// asking a numeric question
fn test_asking_a_numeric_question() {
    process_response_case("You are, what, like 15?", "Sure.");
}

#[test]
#[ignore]
/// silence
fn test_silence() {
    process_response_case("", "Fine. Be that way!");
}

#[test]
#[ignore]
/// starting with whitespace
fn test_starting_with_whitespace() {
    process_response_case("         hmmmmmmm...", "Whatever.");
}

#[test]
#[ignore]
/// using acronyms in regular speech
fn test_using_acronyms_in_regular_speech() {
    process_response_case("It's OK if you don't want to go work for NASA.", "Whatever.");
}

#[test]
#[ignore]
/// alternate silence
fn test_alternate_silence() {
    process_response_case("										", "Fine. Be that way!");
}

#[test]
#[ignore]
/// prolonged silence
fn test_prolonged_silence() {
    process_response_case("          ", "Fine. Be that way!");
}

<|endoftext|>


<commit_before>#![feature(zero_one)]
#![feature(const_fn)]
#![no_std]

#[cfg(test)]
mod tests;

use core::mem::size_of;

#[derive(Debug, Clone, Copy)]
pub struct BitField<T: Number>(T);

impl<T> BitField<T>
    where T: Number
{
    pub const fn new(value: T) -> BitField<T> {
        BitField(value)
    }

    pub fn bits(&self) -> T {
        self.0
    }

    pub fn get_bit(&self, bit: u8) -> bool {
        assert!(bit < self.length());
        self.get_range(bit..(bit + 1)) == T::one()
    }

    pub fn get_range(&self, range: Range<u8>) -> T {
        assert!(range.start < self.length());
        assert!(range.end <= self.length());
        assert!(range.start < range.end);

        // shift away high bits
        let bits = self.0 << (self.length() - range.end) >> (self.length() - range.end);

        // shift away low bits
        bits >> range.start
    }

    pub fn set_bit(&mut self, bit: u8, value: bool) -> &mut Self {
        assert!(bit < self.length());
        if value {
            self.0 |= T::one() << bit;
        } else {
            self.0 &= !(T::one() << bit);
        }
        self
    }

    pub fn set_range(&mut self, range: Range<u8>, value: T) -> &mut Self {
        assert!(range.start < self.length());
        assert!(range.end <= self.length());
        assert!(range.start < range.end);
        assert!(value << (self.length() - (range.end - range.start)) >>
                (self.length() - (range.end - range.start)) == value,
                "value too big");

        let bitmask: T = !(!T::zero() << (self.length() - range.end) >>
                           (self.length() - range.end) >>
                           range.start << range.start);

        let bits = self.0 & bitmask;
        // set bits
        self.0 = bits | (value << range.start);

        self
    }

    fn length(&self) -> u8 {
        size_of::<T>() as u8 * 8
    }
}

use core::ops::{Range, Shl, Shr, BitAnd, BitOr, BitOrAssign, BitAndAssign, Not};
use core::num::{Zero, One};
use core::fmt::Debug;

pub trait Number: Debug + Copy + Eq + Zero + One +
    Not<Output=Self> + Shl<u8, Output=Self> + Shr<u8, Output=Self> +
    BitAnd<Self, Output=Self> + BitOr<Self, Output=Self>  + BitAndAssign + BitOrAssign {}

impl Number for u8 {}
impl Number for u16 {}
impl Number for u32 {}
impl Number for u64 {}
impl Number for usize {}
<commit_msg>Implement own versions of Zero/One since they were deprecated<commit_after>#![feature(const_fn)]
#![no_std]

#[cfg(test)]
mod tests;

use core::mem::size_of;

#[derive(Debug, Clone, Copy)]
pub struct BitField<T: Number>(T);

impl<T> BitField<T>
    where T: Number
{
    pub const fn new(value: T) -> BitField<T> {
        BitField(value)
    }

    pub fn bits(&self) -> T {
        self.0
    }

    pub fn get_bit(&self, bit: u8) -> bool {
        assert!(bit < self.length());
        self.get_range(bit..(bit + 1)) == T::one()
    }

    pub fn get_range(&self, range: Range<u8>) -> T {
        assert!(range.start < self.length());
        assert!(range.end <= self.length());
        assert!(range.start < range.end);

        // shift away high bits
        let bits = self.0 << (self.length() - range.end) >> (self.length() - range.end);

        // shift away low bits
        bits >> range.start
    }

    pub fn set_bit(&mut self, bit: u8, value: bool) -> &mut Self {
        assert!(bit < self.length());
        if value {
            self.0 |= T::one() << bit;
        } else {
            self.0 &= !(T::one() << bit);
        }
        self
    }

    pub fn set_range(&mut self, range: Range<u8>, value: T) -> &mut Self {
        assert!(range.start < self.length());
        assert!(range.end <= self.length());
        assert!(range.start < range.end);
        assert!(value << (self.length() - (range.end - range.start)) >>
                (self.length() - (range.end - range.start)) == value,
                "value too big");

        let bitmask: T = !(!T::zero() << (self.length() - range.end) >>
                           (self.length() - range.end) >>
                           range.start << range.start);

        let bits = self.0 & bitmask;
        // set bits
        self.0 = bits | (value << range.start);

        self
    }

    fn length(&self) -> u8 {
        size_of::<T>() as u8 * 8
    }
}

use core::ops::{Range, Shl, Shr, BitAnd, BitOr, BitOrAssign, BitAndAssign, Not};
use core::fmt::Debug;

pub trait Number: Debug + Copy + Eq +
    Not<Output=Self> + Shl<u8, Output=Self> + Shr<u8, Output=Self> +
    BitAnd<Self, Output=Self> + BitOr<Self, Output=Self>  + BitAndAssign + BitOrAssign {

    fn zero() -> Self;
    fn one() -> Self;
}

macro_rules! number_impl {
    ($($t:ty)*) => ($(
        impl Number for $t {
            fn zero() -> Self { 0 }
            fn one() -> Self { 1 }
        }
    )*)
}

number_impl! { u8 u16 u32 u64 usize }
<|endoftext|>


<commit_before>//! Provides abstractions for working with bytes.
//!
//! The `bytes` crate provides an efficient byte buffer structure
//! ([`Bytes`](struct.Bytes.html)) and traits for working with buffer
//! implementations ([`Buf`], [`BufMut`]).
//!
//! [`Buf`]: trait.Buf.html
//! [`BufMut`]: trait.BufMut.html
//!
//! # `Bytes`
//!
//! `Bytes` is an efficient container for storing and operating on continguous
//! slices of memory. It is intended for use primarily in networking code, but
//! could have applications elsewhere as well.
//!
//! `Bytes` values facilitate zero-copy network programming by allowing multiple
//! `Bytes` objects to point to the same underlying memory. This is managed by
//! using a reference count to track when the memory is no longer needed and can
//! be freed.
//!
//! A `Bytes` handle can be created directly from an existing byte store (such as &[u8]
//! or Vec<u8>), but usually a `BytesMut` is used first and written to. For
//! example:
//!
//! ```rust
//! use bytes::{BytesMut, BufMut, BigEndian};
//!
//! let mut buf = BytesMut::with_capacity(1024);
//! buf.put(&b"hello world"[..]);
//! buf.put_u16::<BigEndian>(1234);
//!
//! let a = buf.take();
//! assert_eq!(a, b"hello world\x04\xD2"[..]);
//!
//! buf.put(&b"goodbye world"[..]);
//!
//! let b = buf.take();
//! assert_eq!(b, b"goodbye world"[..]);
//!
//! assert_eq!(buf.capacity(), 998);
//! ```
//!
//! In the above example, only a single buffer of 1024 is allocated. The handles
//! `a` and `b` will share the underlying buffer and maintain indices tracking
//! the view into the buffer represented by the handle.
//!
//! See the [struct docs] for more details.
//!
//! [struct docs]: struct.Bytes.html
//!
//! # `Buf`, `BufMut`
//!
//! These two traits provide read and write access to buffers. The underlying
//! storage may or may not be in contiguous memory. For example, `Bytes` is a
//! buffer that guarantees contiguous memory, but a [rope] stores the bytes in
//! disjoint chunks. `Buf` and `BufMut` maintain cursors tracking the current
//! position in the underlying byte storage. When bytes are read or written, the
//! cursor is advanced.
//!
//! [rope]: https://en.wikipedia.org/wiki/Rope_(data_structure)
//!
//! ## Relation with `Read` and `Write`
//!
//! At first glance, it may seem that `Buf` and `BufMut` overlap in
//! functionality with `std::io::Read` and `std::io::Write`. However, they
//! serve different purposes. A buffer is the value that is provided as an
//! argument to `Read::read` and `Write::write`. `Read` and `Write` may then
//! perform a syscall, which has the potential of failing. Operations on `Buf`
//! and `BufMut` are infallible.

#![deny(warnings, missing_docs, missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/bytes/0.4.8")]

extern crate byteorder;
extern crate iovec;

pub mod buf;
pub use buf::{
    Buf,
    BufMut,
    IntoBuf,
};
#[deprecated(since = "0.4.1", note = "moved to `buf` module")]
#[doc(hidden)]
pub use buf::{
    Reader,
    Writer,
    Take,
};

mod bytes;
mod debug;
pub use bytes::{Bytes, BytesMut};

#[deprecated]
pub use byteorder::{ByteOrder, BigEndian, LittleEndian};

// Optional Serde support
#[cfg(feature = "serde")]
#[doc(hidden)]
pub mod serde;
<commit_msg>Fix documentation (#219)<commit_after>//! Provides abstractions for working with bytes.
//!
//! The `bytes` crate provides an efficient byte buffer structure
//! ([`Bytes`](struct.Bytes.html)) and traits for working with buffer
//! implementations ([`Buf`], [`BufMut`]).
//!
//! [`Buf`]: trait.Buf.html
//! [`BufMut`]: trait.BufMut.html
//!
//! # `Bytes`
//!
//! `Bytes` is an efficient container for storing and operating on continguous
//! slices of memory. It is intended for use primarily in networking code, but
//! could have applications elsewhere as well.
//!
//! `Bytes` values facilitate zero-copy network programming by allowing multiple
//! `Bytes` objects to point to the same underlying memory. This is managed by
//! using a reference count to track when the memory is no longer needed and can
//! be freed.
//!
//! A `Bytes` handle can be created directly from an existing byte store (such as `&[u8]`
//! or `Vec<u8>`), but usually a `BytesMut` is used first and written to. For
//! example:
//!
//! ```rust
//! use bytes::{BytesMut, BufMut, BigEndian};
//!
//! let mut buf = BytesMut::with_capacity(1024);
//! buf.put(&b"hello world"[..]);
//! buf.put_u16::<BigEndian>(1234);
//!
//! let a = buf.take();
//! assert_eq!(a, b"hello world\x04\xD2"[..]);
//!
//! buf.put(&b"goodbye world"[..]);
//!
//! let b = buf.take();
//! assert_eq!(b, b"goodbye world"[..]);
//!
//! assert_eq!(buf.capacity(), 998);
//! ```
//!
//! In the above example, only a single buffer of 1024 is allocated. The handles
//! `a` and `b` will share the underlying buffer and maintain indices tracking
//! the view into the buffer represented by the handle.
//!
//! See the [struct docs] for more details.
//!
//! [struct docs]: struct.Bytes.html
//!
//! # `Buf`, `BufMut`
//!
//! These two traits provide read and write access to buffers. The underlying
//! storage may or may not be in contiguous memory. For example, `Bytes` is a
//! buffer that guarantees contiguous memory, but a [rope] stores the bytes in
//! disjoint chunks. `Buf` and `BufMut` maintain cursors tracking the current
//! position in the underlying byte storage. When bytes are read or written, the
//! cursor is advanced.
//!
//! [rope]: https://en.wikipedia.org/wiki/Rope_(data_structure)
//!
//! ## Relation with `Read` and `Write`
//!
//! At first glance, it may seem that `Buf` and `BufMut` overlap in
//! functionality with `std::io::Read` and `std::io::Write`. However, they
//! serve different purposes. A buffer is the value that is provided as an
//! argument to `Read::read` and `Write::write`. `Read` and `Write` may then
//! perform a syscall, which has the potential of failing. Operations on `Buf`
//! and `BufMut` are infallible.

#![deny(warnings, missing_docs, missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/bytes/0.4.8")]

extern crate byteorder;
extern crate iovec;

pub mod buf;
pub use buf::{
    Buf,
    BufMut,
    IntoBuf,
};
#[deprecated(since = "0.4.1", note = "moved to `buf` module")]
#[doc(hidden)]
pub use buf::{
    Reader,
    Writer,
    Take,
};

mod bytes;
mod debug;
pub use bytes::{Bytes, BytesMut};

#[deprecated]
pub use byteorder::{ByteOrder, BigEndian, LittleEndian};

// Optional Serde support
#[cfg(feature = "serde")]
#[doc(hidden)]
pub mod serde;
<|endoftext|>


<commit_before>use std::net::TcpListener;
use std::ops::Range;

/// Scan a port and return true if it's open
///
/// # Example
/// ```no_run
/// use port_scanner::scan_port;
/// println!("Port 8000 open? {}", scan_port(8000));
/// ```
pub fn scan_port(port: u16) -> bool {
    match TcpListener::bind(("127.0.0.1", port)) {
        Ok(_) => true,
        Err(_) => false,
    }
}

/// Scan specified ports and return a list of all open ports
///
/// # Example
/// ```no_run
/// use port_scanner::scan_ports;
/// for open_port in scan_ports(vec![8000, 9000, 8888]) {
///     println!("Port {} is open", open_port);
/// }
/// ```
pub fn scan_ports(ports: Vec<u16>) -> Vec<u16> {
    let mut open_ports = Vec::new();
    for port in ports {
        if scan_port(port) {
            open_ports.push(port);
        }
    }
    open_ports
}

/// Scan a port range and return a list of all open ports
///
/// # Example
/// ```no_run
/// use port_scanner::scan_ports_range;
/// for open_port in scan_ports_range(8000..9000) {
///     println!("Port {} is open", open_port);
/// }
/// ```
pub fn scan_ports_range(port_range: Range<u16>) -> Vec<u16> {
    let mut open_ports = Vec::new();
    for port in port_range {
        if scan_port(port) {
            open_ports.push(port);
        }
    }
    open_ports
}
<commit_msg>Add request for open port<commit_after>use std::net::TcpListener;
use std::ops::Range;

/// Scan a port and return true if it's open.
///
/// # Example
/// ```no_run
/// use port_scanner::scan_port;
/// println!("Port 8000 open? {}", scan_port(8000));
/// ```
pub fn scan_port(port: u16) -> bool {
    match TcpListener::bind(("0.0.0.0", port)) {
        Ok(_) => true,
        Err(_) => false,
    }
}

/// Scan specified ports and return a list of all open ports.
///
/// # Example
/// ```no_run
/// use port_scanner::scan_ports;
/// for open_port in scan_ports(vec![8000, 9000, 8888]) {
///     println!("Port {} is open", open_port);
/// }
/// ```
pub fn scan_ports(ports: Vec<u16>) -> Vec<u16> {
    let mut open_ports = Vec::new();
    for port in ports {
        if scan_port(port) {
            open_ports.push(port);
        }
    }
    open_ports
}

/// Scan a port range and return a list of all open ports.
///
/// # Example
/// ```no_run
/// use port_scanner::scan_ports_range;
/// for open_port in scan_ports_range(8000..9000) {
///     println!("Port {} is open", open_port);
/// }
/// ```
pub fn scan_ports_range(port_range: Range<u16>) -> Vec<u16> {
    let mut open_ports = Vec::new();
    for port in port_range {
        if scan_port(port) {
            open_ports.push(port);
        }
    }
    open_ports
}

/// Request to the os the next open port.
///
/// # Example
/// ```no_run
/// use port_scanner::request_open_port;
/// println!("Port {}", request_open_port().unwrap_or(0));
/// ```
pub fn request_open_port() -> Option<u16> {
    match TcpListener::bind("0.0.0.0:0") {
        Ok(a) => {
            match a.local_addr() {
                Ok(a) => Some(a.port()),
                Err(_) => None,
            }
        }
        Err(_) => None
    }
}
<|endoftext|>


<commit_before>//! Nom, eating data byte by byte
//!
//! The goal is to make a parser combinator library that is safe,
//! supports streaming (push and pull), and as much as possible zero copy.
//!
//! The code is available on [Github](https://github.com/Geal/nom)
//!
//! # Example
//!
//! ```
//! # #[macro_use] extern crate nom;
//! # use nom::{IResult,Producer,ProducerState,FileProducer};
//! # use nom::IResult::*;
//! # use std::fmt::Debug;
//! # fn main() {
//!  use std::str;
//!  fn local_print<'a,T: Debug>(input: T) -> IResult<'a, T, ()> {
//!    println!("{:?}", input);
//!    Done(input, ())
//!  }
//!  // create a data producer from a file
//!  FileProducer::new("links.txt", 20).map(|producer: FileProducer| {
//!    let mut p = producer;
//!
//!    // adapt the parsing function to the producer
//!    pusher!(push, local_print);
//!    // get started
//!    push(&mut p);
//!  });
//! # }
//! ```
//!

pub use self::util::*;
pub use self::internal::*;//{IResult, IResultClosure, GetInput, GetOutput};
pub use self::macros::*;
pub use self::producer::*;//{ProducerState,Producer,FileProducer,MemProducer};
pub use self::consumer::*;//{ConsumerState,Consumer};
pub use self::nom::*;

#[macro_use] pub mod util;
pub mod internal;
#[macro_use] pub mod macros;
#[macro_use] pub mod producer;
pub mod consumer;
#[macro_use] pub mod nom;

<commit_msg>use the omnom parser as main example<commit_after>//! Nom, eating data byte by byte
//!
//! The goal is to make a parser combinator library that is safe,
//! supports streaming (push and pull), and as much as possible zero copy.
//!
//! The code is available on [Github](https://github.com/Geal/nom)
//!
//! # Example
//!
//! ```
//! #[macro_use]
//! extern crate nom;
//!
//! use nom::{Consumer,ConsumerState,MemProducer,IResult};
//! use nom::IResult::*;
//!
//! // Parser definition
//!
//! named!( om_parser,                   tag!( "om" ) );
//! named!( nomnom_parser< &[u8], Vec<&[u8]> >, many1!( tag!( "nom" ) ) );
//! named!( end_parser,                  tag!( "kthxbye")  );
//!
//!
//! // Streaming parsing and state machine
//!
//! #[derive(PartialEq,Eq,Debug)]
//! enum State {
//!   Beginning,
//!   Middle,
//!   End,
//!   Done
//! }
//!
//! struct TestConsumer {
//!   state:   State,
//!   counter: usize
//! }
//!
//! impl Consumer for TestConsumer {
//!   fn consume(&mut self, input: &[u8]) -> ConsumerState {
//!     match self.state {
//!       State::Beginning => {
//!         match om_parser(input) {
//!           Error(_)      => ConsumerState::ConsumerError(0),
//!           Incomplete(_) => ConsumerState::Await(0, 2),
//!           Done(_,_)     => {
//!             // "om" was recognized, get to the next state
//!             self.state = State::Middle;
//!             ConsumerState::Await(2, 3)
//!           }
//!         }
//!       },
//!       State::Middle    => {
//!         match nomnom_parser(input) {
//!           Error(a)         => {
//!             // the "nom" parser failed, let's get to the next state
//!             self.state = State::End;
//!             ConsumerState::Await(0, 7)
//!           },
//!           Incomplete(_)    => ConsumerState::Await(0, 3),
//!           Done(i,noms_vec) => {
//!             // we got a few noms, let's count them and continue
//!             self.counter = self.counter + noms_vec.len();
//!             ConsumerState::Await(input.len() - i.len(), 3)
//!           }
//!         }
//!       },
//!       State::End       => {
//!         match end_parser(input) {
//!           Error(_)      => ConsumerState::ConsumerError(0),
//!           Incomplete(_) => ConsumerState::Await(0, 7),
//!           Done(_,_)     => {
//!             // we recognized the suffix, everything was parsed correctly
//!             self.state = State::Done;
//!             ConsumerState::ConsumerDone
//!           }
//!         }
//!       },
//!       State::Done      => {
//!         // this should not be called
//!         ConsumerState::ConsumerError(42)
//!       }
//!     }
//!   }
//!
//!   fn end(&mut self) {
//!     println!("we counted {} noms", self.counter);
//!   }
//! }
//!
//! fn main() {
//!   let mut p = MemProducer::new(b"omnomnomnomkthxbye", 4);
//!   let mut c = TestConsumer{state: State::Beginning, counter: 0};
//!   c.run(&mut p);
//!
//!   assert_eq!(c.counter, 3);
//!   assert_eq!(c.state, State::Done);
//! }
//! ```
//!

pub use self::util::*;
pub use self::internal::*;//{IResult, IResultClosure, GetInput, GetOutput};
pub use self::macros::*;
pub use self::producer::*;//{ProducerState,Producer,FileProducer,MemProducer};
pub use self::consumer::*;//{ConsumerState,Consumer};
pub use self::nom::*;

#[macro_use] pub mod util;
pub mod internal;
#[macro_use] pub mod macros;
#[macro_use] pub mod producer;
pub mod consumer;
#[macro_use] pub mod nom;

<|endoftext|>


<commit_before>#![allow(missing_copy_implementations)]
#![cfg_attr(test, deny(warnings))]

#[macro_use] extern crate log;

extern crate time;
extern crate conduit;
extern crate "conduit-middleware" as middleware;

use std::error::Error;

use conduit::{Request, Response};
use middleware::Middleware;

pub struct LogRequests(pub log::LogLevel);

struct LogStart(u64);

impl Middleware for LogRequests {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error+Send>> {
        req.mut_extensions().insert(LogStart(time::precise_time_ns()));
        Ok(())
    }

    fn after(&self, req: &mut Request, resp: Result<Response, Box<Error+Send>>)
             -> Result<Response, Box<Error+Send>> {
        let LogStart(start) = *req.mut_extensions().find::<LogStart>().unwrap();

        match resp {
            Ok(ref resp) => self.log_message(req, start, resp.status.0, None),
            Err(ref e) => {
                let msg: &Error = &**e;
                self.log_message(req, start, 500, Some(msg))
            }
        }
        resp
    }

}

impl LogRequests {
    fn log_message(&self, req: &mut Request, start: u64, status: u32,
                   msg: Option<&Error>) {
        let LogRequests(level) = *self;
        log!(level, "{} [{}] {:?} {} - {}ms {}{}",
             req.remote_ip(),
             time::now().rfc3339(),
             req.method(),
             req.path(),
             (time::precise_time_ns() - start) / 1000000,
             status,
             match msg {
                 None => String::new(),
                 Some(s) => format!(": {} {}", s.description(), s),
             })
    }
}

#[cfg(all(test, foo))] // FIXME: needs a thread-local logger
mod tests {
    extern crate "conduit-test" as test;

    use {LogRequests};

    use conduit::{Request, Response, Handler, Method};
    use log::{Log, LogRecord};
    use log;
    use middleware;
    use std::error::Error;
    use std::old_io::{ChanWriter, ChanReader};
    use std::sync::Mutex;
    use std::sync::mpsc::{channel, Sender};
    use std::thread::Thread;
    use std;

    struct MyWriter(Mutex<ChanWriter>);

    impl Log for MyWriter {
        fn enabled(&self, _: log::LogLevel, _: &str) -> bool { true }
        fn log(&self, record: &LogRecord) {
            let MyWriter(ref inner) = *self;
            (write!(inner.lock(), "{}", record.args)).unwrap();
        }
    }

    #[test]
    fn test_log() {
        let (sender, receiver) = channel();
        let mut reader = ChanReader::new(receiver);

        let mut builder = middleware::MiddlewareBuilder::new(handler);
        builder.add(LogRequests(log::LogLevel::Error));

        task(builder, sender);

        let result = reader.read_to_string().ok().expect("No response");
        let parts = result.as_slice().split(' ').map(|s| s.to_string()).collect::<Vec<String>>();

        assert_eq!(parts[0].as_slice(), "127.0.0.1");
        // Failing on travis?! bug in libtime?!
        // assert!(parts.get(1).as_slice().len() == "[2014-07-01T22:34:06-07:00]".len(),
        //         "bad length for {}", parts.get(1));
        assert_eq!(parts[2].as_slice(), "Get");
        assert_eq!(parts[3].as_slice(), "/foo");
    }

    fn task<H: Handler + 'static + Send>(handler: H, sender: Sender<Vec<u8>>) {
        Thread::spawn(move|| {
            log::set_logger(Box::new(MyWriter(Mutex::new(ChanWriter::new(sender)))));
            let mut request = test::MockRequest::new(Method::Get, "/foo");
            let _ = handler.call(&mut request);
        });
    }

    fn handler(_: &mut Request) -> Result<Response, Box<Error+Send>> {
        Ok(Response {
            status: (200, "OK"),
            headers: std::collections::HashMap::new(),
            body: Box::new(std::old_io::util::NullReader)
        })
    }
}
<commit_msg>Tweak logging<commit_after>#![allow(missing_copy_implementations)]
#![cfg_attr(test, deny(warnings))]

#[macro_use] extern crate log;

extern crate time;
extern crate conduit;
extern crate "conduit-middleware" as middleware;

use std::error::Error;

use conduit::{Request, Response};
use middleware::Middleware;

pub struct LogRequests(pub log::LogLevel);

struct LogStart(u64);

impl Middleware for LogRequests {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error+Send>> {
        req.mut_extensions().insert(LogStart(time::precise_time_ns()));
        Ok(())
    }

    fn after(&self, req: &mut Request, resp: Result<Response, Box<Error+Send>>)
             -> Result<Response, Box<Error+Send>> {
        let LogStart(start) = *req.mut_extensions().find::<LogStart>().unwrap();

        match resp {
            Ok(ref resp) => self.log_message(req, start, resp.status.0, None),
            Err(ref e) => {
                let msg: &Error = &**e;
                self.log_message(req, start, 500, Some(msg))
            }
        }
        resp
    }

}

impl LogRequests {
    fn log_message(&self, req: &mut Request, start: u64, status: u32,
                   msg: Option<&Error>) {
        let LogRequests(level) = *self;
        let level = if msg.is_some() {log::LogLevel::Error} else {level};
        log!(level, "{} [{}] {:?} {} - {}ms {}{}",
             req.remote_ip(),
             time::now().rfc3339(),
             req.method(),
             req.path(),
             (time::precise_time_ns() - start) / 1000000,
             status,
             match msg {
                 None => String::new(),
                 Some(s) => format!(": {} {}", s.description(), s),
             })
    }
}

#[cfg(all(test, foo))] // FIXME: needs a thread-local logger
mod tests {
    extern crate "conduit-test" as test;

    use {LogRequests};

    use conduit::{Request, Response, Handler, Method};
    use log::{Log, LogRecord};
    use log;
    use middleware;
    use std::error::Error;
    use std::old_io::{ChanWriter, ChanReader};
    use std::sync::Mutex;
    use std::sync::mpsc::{channel, Sender};
    use std::thread::Thread;
    use std;

    struct MyWriter(Mutex<ChanWriter>);

    impl Log for MyWriter {
        fn enabled(&self, _: log::LogLevel, _: &str) -> bool { true }
        fn log(&self, record: &LogRecord) {
            let MyWriter(ref inner) = *self;
            (write!(inner.lock(), "{}", record.args)).unwrap();
        }
    }

    #[test]
    fn test_log() {
        let (sender, receiver) = channel();
        let mut reader = ChanReader::new(receiver);

        let mut builder = middleware::MiddlewareBuilder::new(handler);
        builder.add(LogRequests(log::LogLevel::Error));

        task(builder, sender);

        let result = reader.read_to_string().ok().expect("No response");
        let parts = result.as_slice().split(' ').map(|s| s.to_string()).collect::<Vec<String>>();

        assert_eq!(parts[0].as_slice(), "127.0.0.1");
        // Failing on travis?! bug in libtime?!
        // assert!(parts.get(1).as_slice().len() == "[2014-07-01T22:34:06-07:00]".len(),
        //         "bad length for {}", parts.get(1));
        assert_eq!(parts[2].as_slice(), "Get");
        assert_eq!(parts[3].as_slice(), "/foo");
    }

    fn task<H: Handler + 'static + Send>(handler: H, sender: Sender<Vec<u8>>) {
        Thread::spawn(move|| {
            log::set_logger(Box::new(MyWriter(Mutex::new(ChanWriter::new(sender)))));
            let mut request = test::MockRequest::new(Method::Get, "/foo");
            let _ = handler.call(&mut request);
        });
    }

    fn handler(_: &mut Request) -> Result<Response, Box<Error+Send>> {
        Ok(Response {
            status: (200, "OK"),
            headers: std::collections::HashMap::new(),
            body: Box::new(std::old_io::util::NullReader)
        })
    }
}
<|endoftext|>


<commit_before>//! ODBC types those representation is compatible with the ODBC C API.
//!
//! This layer has not been created using automatic code generation. It is incomplete, i.e. it does
//! not contain every symbol or constant defined in the ODBC C headers. Symbols which are
//! deprecated since ODBC 3 have been left out intentionally. While some extra type safety has been
//! added by grouping some of C's `#define` constants into `enum`-types it mostly offers the same
//! power (all) and safety guarantess(none) as the wrapped C-API.
//! ODBC 4.0 is still under development by Microsoft, so these symbols are deactivated by default
//! in the cargo.toml

mod sqlreturn;
pub use self::sqlreturn::*;
mod info_type;
pub use self::info_type::*;
mod fetch_orientation;
pub use self::fetch_orientation::*;
mod attributes;
pub use self::attributes::*;
use std::os::raw::{c_void, c_short, c_ushort, c_int};

//These types can never be instantiated in Rust code.
pub enum Obj {}
pub enum Env {}
pub enum Dbc {}
pub enum Stmt {}

pub type SQLHANDLE = *mut Obj;
pub type SQLHENV = *mut Env;

/// The connection handle references storage of all information about the connection to the data
/// source, including status, transaction state, and error information.
pub type SQLHDBC = *mut Dbc;
pub type SQLHSTMT = *mut Stmt;

/// 16 Bit signed integer
pub type SQLSMALLINT = c_short;
pub type SQLUSMALLINT = c_ushort;
pub type SQLINTEGER = c_int;
pub type SQLPOINTER = *mut c_void;
pub type SQLCHAR = u8;

#[cfg(all(windows, target_pointer_width = "64"))]
pub type SQLLEN = i64;
#[cfg(not(windows))]
pub type SQLLEN = SQLINTEGER;

pub type SQLHWND = SQLPOINTER;

// flags for null-terminated string
pub const SQL_NTS: SQLSMALLINT = -3;
pub const SQL_NTSL: SQLINTEGER = -3;

/// Maximum message length
pub const SQL_MAX_MESSAGE_LENGTH: SQLSMALLINT = 512;
pub const SQL_SQLSTATE_SIZE: usize = 5;

// Special SQLGetData indicator values
pub const SQL_NULL_DATA: SQLLEN = -1;
pub const SQL_NO_TOTAL: SQLLEN = -4;

/// SQL Data Types
#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlDataType {
    SQL_UNKNOWN_TYPE = 0, // also called SQL_VARIANT_TYPE since odbc 4.0
    SQL_CHAR = 1,
    SQL_NUMERIC = 2,
    SQL_DECIMAL = 3,
    SQL_INTEGER = 4,
    SQL_SMALLINT = 5,
    SQL_FLOAT = 6,
    SQL_REAL = 7,
    SQL_DOUBLE = 8,
    SQL_DATETIME = 9,
    SQL_VARCHAR = 12,
    #[cfg(feature = "odbc_version_4")]
    SQL_UDT = 17,
    #[cfg(feature = "odbc_version_4")]
    SQL_ROW = 19,
    #[cfg(feature = "odbc_version_4")]
    SQL_ARRAY = 50,
    #[cfg(feature = "odbc_version_4")]
    SQL_MULTISET = 55,
}
pub use self::SqlDataType::*;

#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlCDataType {
    SQL_C_CHAR = 1,
}
pub use self::SqlCDataType::*;

/// Represented in C headers as SQLSMALLINT
#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum HandleType {
    SQL_HANDLE_ENV = 1,
    SQL_HANDLE_DBC = 2,
    SQL_HANDLE_STMT = 3,
    SQL_HANDLE_DESC = 4,
}
pub use self::HandleType::*;

/// Options for `SQLDriverConnect`
#[repr(u16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlDriverConnectOption {
    SQL_DRIVER_NOPROMPT = 0,
    SQL_DRIVER_COMPLETE = 1,
    SQL_DRIVER_PROMPT = 2,
    SQL_DRIVER_COMPLETE_REQUIRED = 3,
}
pub use self::SqlDriverConnectOption::*;

#[cfg_attr(windows, link(name="odbc32"))]
#[cfg_attr(not(windows), link(name="odbc"))]
extern "C" {
    /// Allocates an environment, connection, statement, or descriptor handle.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLAllocHandle(handle_type: HandleType,
                          input_handle: SQLHANDLE,
                          output_Handle: *mut SQLHANDLE)
                          -> SQLRETURN;

    /// Frees resources associated with a specific environment, connection, statement, or
    /// descriptor handle.
    ///
    /// If `SQL_ERRQR` is returned the handle is still valid.
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLFreeHandle(handle_type: HandleType, handle: SQLHANDLE) -> SQLRETURN;

    /// Sets attributes that govern aspects of environments
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLSetEnvAttr(environment_handle: SQLHENV,
                         attribute: EnvironmentAttribute,
                         value: SQLPOINTER,
                         string_length: SQLINTEGER)
                         -> SQLRETURN;

    /// Closes the connection associated with a specific connection handle.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLDisconnect(connection_handle: SQLHDBC) -> SQLRETURN;

    pub fn SQLGetDiagRec(handle_type: HandleType,
                         handle: SQLHANDLE,
                         RecNumber: SQLSMALLINT,
                         state: *mut SQLCHAR,
                         native_error_ptr: *mut SQLINTEGER,
                         message_text: *mut SQLCHAR,
                         buffer_length: SQLSMALLINT,
                         text_length_ptr: *mut SQLSMALLINT)
                         -> SQLRETURN;

    pub fn SQLExecDirect(statement_handle: SQLHSTMT,
                         statement_text: *const SQLCHAR,
                         text_length: SQLINTEGER)
                         -> SQLRETURN;

    pub fn SQLNumResultCols(statement_handle: SQLHSTMT,
                            column_count_ptr: *mut SQLSMALLINT)
                            -> SQLRETURN;

    // Can be used since odbc version 3.8 to stream results
    pub fn SQLGetData(statement_handle: SQLHSTMT,
                      col_or_param_num: SQLUSMALLINT,
                      target_type: SqlCDataType,
                      target_value_ptr: SQLPOINTER,
                      buffer_length: SQLLEN,
                      str_len_or_ind_ptr: *mut SQLLEN)
                      -> SQLRETURN;

    pub fn SQLFetch(statement_handle: SQLHSTMT) -> SQLRETURN;

    /// Returns general information about the driver and data source associated with a connection
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLGetInfo(connection_handle: SQLHDBC,
                      info_type: InfoType,
                      info_value_ptr: SQLPOINTER,
                      buffer_length: SQLSMALLINT,
                      string_length_ptr: *mut SQLSMALLINT)
                      -> SQLRETURN;

    /// SQLConnect establishes connections to a driver and a data source.
    ///
    /// The connection handle references storage of all information about the connection to the
    /// data source, including status, transaction state, and error information.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or
    /// `SQL_STILL_EXECUTING`
    pub fn SQLConnect(connection_handle: SQLHDBC,
                      server_name: *const SQLCHAR,
                      name_length_1: SQLSMALLINT,
                      user_name: *const SQLCHAR,
                      name_length_2: SQLSMALLINT,
                      authentication: *const SQLCHAR,
                      name_length_3: SQLSMALLINT)
                      -> SQLRETURN;

    /// Returns the list of table, catalog, or schema names, and table types, stored in a specific
    /// data source. The driver returns the information as a result set
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or
    /// `SQL_STILL_EXECUTING`
    pub fn SQLTables(statement_handle: SQLHSTMT,
                     catalog_name: *const SQLCHAR,
                     name_length_1: SQLSMALLINT,
                     schema_name: *const SQLCHAR,
                     name_length_2: SQLSMALLINT,
                     table_name: *const SQLCHAR,
                     name_length_3: SQLSMALLINT,
                     TableType: *const SQLCHAR,
                     name_length_4: SQLSMALLINT)
                     -> SQLRETURN;

    /// Returns information about a data source. This function is implemented only by the Driver
    /// Manager.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or `SQL_NO_DATA`
    pub fn SQLDataSources(environment_handle: SQLHENV,
                          direction: FetchOrientation,
                          server_name: *mut SQLCHAR,
                          buffer_length_1: SQLSMALLINT,
                          name_length_1: *mut SQLSMALLINT,
                          description: *mut SQLCHAR,
                          buffer_length_2: SQLSMALLINT,
                          name_length_2: *mut SQLSMALLINT)
                          -> SQLRETURN;

    /// An alternative to `SQLConnect`. It supports data sources that require more connection
    /// information than the three arguments in `SQLConnect`, dialog boxes to prompt the user for
    /// all connection information, and data sources that are not defined in the system information
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, `SQL_NO_DATA`,
    /// or `SQL_STILL_EXECUTING`
    pub fn SQLDriverConnect(connection_handle: SQLHDBC,
                            window_handle: SQLHWND,
                            in_connection_string: *const SQLCHAR,
                            string_length_1: SQLSMALLINT,
                            out_connection_string: *mut SQLCHAR,
                            buffer_length: SQLSMALLINT,
                            string_length_2: *mut SQLSMALLINT,
                            DriverCompletion: SqlDriverConnectOption)
                            -> SQLRETURN;

    /// Lists driver descriptions and driver attribute keywords. This function is implemented only
    /// by the Driver Manager.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or `SQL_NO_DATA`
    pub fn SQLDrivers(henv: SQLHENV,
                      direction: FetchOrientation,
                      driver_desc: *mut SQLCHAR,
                      driver_desc_max: SQLSMALLINT,
                      out_driver_desc: *mut SQLSMALLINT,
                      driver_attributes: *mut SQLCHAR,
                      drvr_attr_max: SQLSMALLINT,
                      out_drvr_attr: *mut SQLSMALLINT)
                      -> SQLRETURN;
}
<commit_msg>add SQLCloseCursor<commit_after>//! ODBC types those representation is compatible with the ODBC C API.
//!
//! This layer has not been created using automatic code generation. It is incomplete, i.e. it does
//! not contain every symbol or constant defined in the ODBC C headers. Symbols which are
//! deprecated since ODBC 3 have been left out intentionally. While some extra type safety has been
//! added by grouping some of C's `#define` constants into `enum`-types it mostly offers the same
//! power (all) and safety guarantess(none) as the wrapped C-API.
//! ODBC 4.0 is still under development by Microsoft, so these symbols are deactivated by default
//! in the cargo.toml

mod sqlreturn;
pub use self::sqlreturn::*;
mod info_type;
pub use self::info_type::*;
mod fetch_orientation;
pub use self::fetch_orientation::*;
mod attributes;
pub use self::attributes::*;
use std::os::raw::{c_void, c_short, c_ushort, c_int};

//These types can never be instantiated in Rust code.
pub enum Obj {}
pub enum Env {}
pub enum Dbc {}
pub enum Stmt {}

pub type SQLHANDLE = *mut Obj;
pub type SQLHENV = *mut Env;

/// The connection handle references storage of all information about the connection to the data
/// source, including status, transaction state, and error information.
pub type SQLHDBC = *mut Dbc;
pub type SQLHSTMT = *mut Stmt;

/// 16 Bit signed integer
pub type SQLSMALLINT = c_short;
pub type SQLUSMALLINT = c_ushort;
pub type SQLINTEGER = c_int;
pub type SQLPOINTER = *mut c_void;
pub type SQLCHAR = u8;

#[cfg(all(windows, target_pointer_width = "64"))]
pub type SQLLEN = i64;
#[cfg(not(windows))]
pub type SQLLEN = SQLINTEGER;

pub type SQLHWND = SQLPOINTER;

// flags for null-terminated string
pub const SQL_NTS: SQLSMALLINT = -3;
pub const SQL_NTSL: SQLINTEGER = -3;

/// Maximum message length
pub const SQL_MAX_MESSAGE_LENGTH: SQLSMALLINT = 512;
pub const SQL_SQLSTATE_SIZE: usize = 5;

// Special SQLGetData indicator values
pub const SQL_NULL_DATA: SQLLEN = -1;
pub const SQL_NO_TOTAL: SQLLEN = -4;

/// SQL Data Types
#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlDataType {
    SQL_UNKNOWN_TYPE = 0, // also called SQL_VARIANT_TYPE since odbc 4.0
    SQL_CHAR = 1,
    SQL_NUMERIC = 2,
    SQL_DECIMAL = 3,
    SQL_INTEGER = 4,
    SQL_SMALLINT = 5,
    SQL_FLOAT = 6,
    SQL_REAL = 7,
    SQL_DOUBLE = 8,
    SQL_DATETIME = 9,
    SQL_VARCHAR = 12,
    #[cfg(feature = "odbc_version_4")]
    SQL_UDT = 17,
    #[cfg(feature = "odbc_version_4")]
    SQL_ROW = 19,
    #[cfg(feature = "odbc_version_4")]
    SQL_ARRAY = 50,
    #[cfg(feature = "odbc_version_4")]
    SQL_MULTISET = 55,
}
pub use self::SqlDataType::*;

#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlCDataType {
    SQL_C_CHAR = 1,
}
pub use self::SqlCDataType::*;

/// Represented in C headers as SQLSMALLINT
#[repr(i16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum HandleType {
    SQL_HANDLE_ENV = 1,
    SQL_HANDLE_DBC = 2,
    SQL_HANDLE_STMT = 3,
    SQL_HANDLE_DESC = 4,
}
pub use self::HandleType::*;

/// Options for `SQLDriverConnect`
#[repr(u16)]
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlDriverConnectOption {
    SQL_DRIVER_NOPROMPT = 0,
    SQL_DRIVER_COMPLETE = 1,
    SQL_DRIVER_PROMPT = 2,
    SQL_DRIVER_COMPLETE_REQUIRED = 3,
}
pub use self::SqlDriverConnectOption::*;

#[cfg_attr(windows, link(name="odbc32"))]
#[cfg_attr(not(windows), link(name="odbc"))]
extern "C" {
    /// Allocates an environment, connection, statement, or descriptor handle.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLAllocHandle(handle_type: HandleType,
                          input_handle: SQLHANDLE,
                          output_Handle: *mut SQLHANDLE)
                          -> SQLRETURN;

    /// Frees resources associated with a specific environment, connection, statement, or
    /// descriptor handle.
    ///
    /// If `SQL_ERRQR` is returned the handle is still valid.
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLFreeHandle(handle_type: HandleType, handle: SQLHANDLE) -> SQLRETURN;

    /// Sets attributes that govern aspects of environments
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLSetEnvAttr(environment_handle: SQLHENV,
                         attribute: EnvironmentAttribute,
                         value: SQLPOINTER,
                         string_length: SQLINTEGER)
                         -> SQLRETURN;

    /// Closes the connection associated with a specific connection handle.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLDisconnect(connection_handle: SQLHDBC) -> SQLRETURN;

    pub fn SQLGetDiagRec(handle_type: HandleType,
                         handle: SQLHANDLE,
                         RecNumber: SQLSMALLINT,
                         state: *mut SQLCHAR,
                         native_error_ptr: *mut SQLINTEGER,
                         message_text: *mut SQLCHAR,
                         buffer_length: SQLSMALLINT,
                         text_length_ptr: *mut SQLSMALLINT)
                         -> SQLRETURN;

    pub fn SQLExecDirect(statement_handle: SQLHSTMT,
                         statement_text: *const SQLCHAR,
                         text_length: SQLINTEGER)
                         -> SQLRETURN;

    pub fn SQLNumResultCols(statement_handle: SQLHSTMT,
                            column_count_ptr: *mut SQLSMALLINT)
                            -> SQLRETURN;

    // Can be used since odbc version 3.8 to stream results
    pub fn SQLGetData(statement_handle: SQLHSTMT,
                      col_or_param_num: SQLUSMALLINT,
                      target_type: SqlCDataType,
                      target_value_ptr: SQLPOINTER,
                      buffer_length: SQLLEN,
                      str_len_or_ind_ptr: *mut SQLLEN)
                      -> SQLRETURN;

    /// SQLFetch fetches the next rowset of data from the result set and returns data for all bound
    /// columns.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, `SQL_NO_DATA` or
    /// `SQL_STILL_EXECUTING`
    pub fn SQLFetch(statement_handle: SQLHSTMT) -> SQLRETURN;

    /// Returns general information about the driver and data source associated with a connection
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, or `SQL_INVALID_HANDLE`
    pub fn SQLGetInfo(connection_handle: SQLHDBC,
                      info_type: InfoType,
                      info_value_ptr: SQLPOINTER,
                      buffer_length: SQLSMALLINT,
                      string_length_ptr: *mut SQLSMALLINT)
                      -> SQLRETURN;

    /// SQLConnect establishes connections to a driver and a data source.
    ///
    /// The connection handle references storage of all information about the connection to the
    /// data source, including status, transaction state, and error information.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or
    /// `SQL_STILL_EXECUTING`
    pub fn SQLConnect(connection_handle: SQLHDBC,
                      server_name: *const SQLCHAR,
                      name_length_1: SQLSMALLINT,
                      user_name: *const SQLCHAR,
                      name_length_2: SQLSMALLINT,
                      authentication: *const SQLCHAR,
                      name_length_3: SQLSMALLINT)
                      -> SQLRETURN;

    /// Returns the list of table, catalog, or schema names, and table types, stored in a specific
    /// data source. The driver returns the information as a result set
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or
    /// `SQL_STILL_EXECUTING`
    pub fn SQLTables(statement_handle: SQLHSTMT,
                     catalog_name: *const SQLCHAR,
                     name_length_1: SQLSMALLINT,
                     schema_name: *const SQLCHAR,
                     name_length_2: SQLSMALLINT,
                     table_name: *const SQLCHAR,
                     name_length_3: SQLSMALLINT,
                     TableType: *const SQLCHAR,
                     name_length_4: SQLSMALLINT)
                     -> SQLRETURN;

    /// Returns information about a data source. This function is implemented only by the Driver
    /// Manager.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or `SQL_NO_DATA`
    pub fn SQLDataSources(environment_handle: SQLHENV,
                          direction: FetchOrientation,
                          server_name: *mut SQLCHAR,
                          buffer_length_1: SQLSMALLINT,
                          name_length_1: *mut SQLSMALLINT,
                          description: *mut SQLCHAR,
                          buffer_length_2: SQLSMALLINT,
                          name_length_2: *mut SQLSMALLINT)
                          -> SQLRETURN;

    /// An alternative to `SQLConnect`. It supports data sources that require more connection
    /// information than the three arguments in `SQLConnect`, dialog boxes to prompt the user for
    /// all connection information, and data sources that are not defined in the system information
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, `SQL_NO_DATA`,
    /// or `SQL_STILL_EXECUTING`
    pub fn SQLDriverConnect(connection_handle: SQLHDBC,
                            window_handle: SQLHWND,
                            in_connection_string: *const SQLCHAR,
                            string_length_1: SQLSMALLINT,
                            out_connection_string: *mut SQLCHAR,
                            buffer_length: SQLSMALLINT,
                            string_length_2: *mut SQLSMALLINT,
                            DriverCompletion: SqlDriverConnectOption)
                            -> SQLRETURN;

    /// Lists driver descriptions and driver attribute keywords. This function is implemented only
    /// by the Driver Manager.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR`, `SQL_INVALID_HANDLE`, or `SQL_NO_DATA`
    pub fn SQLDrivers(henv: SQLHENV,
                      direction: FetchOrientation,
                      driver_desc: *mut SQLCHAR,
                      driver_desc_max: SQLSMALLINT,
                      out_driver_desc: *mut SQLSMALLINT,
                      driver_attributes: *mut SQLCHAR,
                      drvr_attr_max: SQLSMALLINT,
                      out_drvr_attr: *mut SQLSMALLINT)
                      -> SQLRETURN;

    /// Closes a cursor that has been opened on a statement and discards pending results.
    ///
    /// # Returns
    /// `SQL_SUCCESS`, `SQL_SUCCESS_WITH_INFO`, `SQL_ERROR` or `SQL_INVALID_HANDLE`
    pub fn SQLCloseCursor(hstmt: SQLHSTMT) -> SQLRETURN;
}
<|endoftext|>


<commit_before>#![crate_id = "logger"]
#![license = "MIT"]

//! Request logging middleware for Iron

extern crate iron;
extern crate time;

use iron::{Ingot, Alloy, Request, Response};
use iron::ingot::{Status, Continue};

use time::precise_time_ns;

use std::io::stdio::println;

#[deriving(Clone)]
pub struct Logger {
    entry_time: u64
}

impl Logger {
    pub fn new() -> Logger {
        Logger { entry_time: 0u64 }
    }
}

enum Color {
    Red,
    Yellow,
    Green,
    Blue
}

fn colorize(string: String, color: Color) -> String {
    let color_str = match color {
        Red => "\x1B[31m",
        Yellow => "\x1B[33m",
        Green => "\x1B[32m",
        Blue => "\x1B[34m"
    };
    color_str.to_string().append(string.as_slice()).append("\x1B[39m")
}

impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for Logger {
    fn enter(&mut self, _req: &mut Rq, _res: &mut Rs, _alloy: &mut Alloy) -> Status {
        self.entry_time = precise_time_ns();
        Continue
    }
    fn exit(&mut self, req: &mut Rq, res: &mut Rs, _al: &mut Alloy) -> Status {
        let status = res.status();
        let status_color = match status.code() {
            _n @ 200..299 => Green, // Success
            _n @ 300..399 => Yellow, // Redirection
            _n @ 400..599 => Red, // Error
            _ => Blue // Information
        };
        let response_time_ms = (precise_time_ns() - self.entry_time) as f64 / 1000000.0;

        let mut output = String::new();
        output.push_str(format!("\x1B[1m{}\x1B[0m {} \x1B[1m->\x1B[0m ",
                                req.method(), req.uri()).as_slice());
        output.push_str(colorize(format!("{}", status), status_color).as_slice());
        output.push_str(format!(" ({} ms)", response_time_ms).as_slice());
        println(output.as_slice());

        Continue
    }
}
<commit_msg>(doc) Documented public fields.<commit_after>#![crate_id = "logger"]
#![license = "MIT"]

//! Request logging middleware for Iron

extern crate iron;
extern crate time;

use iron::{Ingot, Alloy, Request, Response};
use iron::ingot::{Status, Continue};

use time::precise_time_ns;

use std::io::stdio::println;

/// `Ingot` for logging request and response info to the terminal.
/// `Logger` logs the request method, request URI, response status, and response
/// time in the format:
/// ```
/// {method} {uri} -> {status} ({response_time} ms)
/// ```
#[deriving(Clone)]
pub struct Logger {
    entry_time: u64
}

impl Logger {
    /// Create a new `Logger`.
    pub fn new() -> Logger {
        Logger { entry_time: 0u64 }
    }
}

enum Color {
    Red,
    Yellow,
    Green,
    Blue
}

fn colorize(string: String, color: Color) -> String {
    let color_str = match color {
        Red => "\x1B[31m",
        Yellow => "\x1B[33m",
        Green => "\x1B[32m",
        Blue => "\x1B[34m"
    };
    color_str.to_string().append(string.as_slice()).append("\x1B[39m")
}

impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for Logger {
    fn enter(&mut self, _req: &mut Rq, _res: &mut Rs, _alloy: &mut Alloy) -> Status {
        self.entry_time = precise_time_ns();
        Continue
    }
    fn exit(&mut self, req: &mut Rq, res: &mut Rs, _al: &mut Alloy) -> Status {
        let status = res.status();
        let status_color = match status.code() {
            _n @ 200..299 => Green, // Success
            _n @ 300..399 => Yellow, // Redirection
            _n @ 400..599 => Red, // Error
            _ => Blue // Information
        };
        let response_time_ms = (precise_time_ns() - self.entry_time) as f64 / 1000000.0;

        let mut output = String::new();
        output.push_str(format!("\x1B[1m{}\x1B[0m {} \x1B[1m->\x1B[0m ",
                                req.method(), req.uri()).as_slice());
        output.push_str(colorize(format!("{}", status), status_color).as_slice());
        output.push_str(format!(" ({} ms)", response_time_ms).as_slice());
        println(output.as_slice());

        Continue
    }
}
<|endoftext|>


<commit_before>//! [Problem 103](https://projecteuler.net/problem=103) solver.

#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

#![feature(slice_patterns)]

#[macro_use(problem)]
extern crate common;

use std::cmp::Ordering;
use std::collections::BinaryHeap;

/// Special sum set
#[derive(Debug)]
struct SSS {
    avg: f64,
    nums: Vec<u32>,
    sums: Vec<u32>,
}

impl PartialEq for SSS {
    fn eq(&self, other: &SSS) -> bool {
        self.avg == other.avg
    }
}
impl Eq for SSS {}

impl PartialOrd for SSS {
    fn partial_cmp(&self, other: &SSS) -> Option<Ordering> {
        self.avg.partial_cmp(&other.avg).map(|x| x.reverse())
    }
}

impl Ord for SSS {
    fn cmp(&self, other: &SSS) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl SSS {
    #[cfg(test)]
    fn new() -> SSS {
        SSS {
            avg: 0.0,
            nums: vec![],
            sums: vec![0],
        }
    }

    fn new_with_pair(a: u32, b: u32) -> SSS {
        assert!(a < b);
        SSS {
            avg: ((a + b) as f64) / 2.0,
            nums: vec![a, b],
            sums: vec![0, a, b, a + b],
        }
    }

    fn append_num(&self, n: u32) -> Option<SSS> {
        let mut i = 0;
        let mut j = 0;
        let len = self.sums.len();
        let mut sums = Vec::with_capacity(len * 2);

        while i < len {
            assert!(j <= i);

            match self.sums[i].cmp(&(self.sums[j] + n)) {
                Ordering::Equal => {
                    return None;
                }
                Ordering::Less => {
                    sums.push(self.sums[i]);
                    i += 1;
                }
                Ordering::Greater => {
                    sums.push(self.sums[j] + n);
                    j += 1;
                }
            }
        }
        while j < len {
            sums.push(self.sums[j] + n);
            j += 1;
        }

        let avg = (self.avg * (len as f64) + n as f64) / ((len as f64) + 1.0);
        let mut nums = self.nums.clone();
        nums.push(n);

        Some(SSS {
            avg: avg,
            nums: nums,
            sums: sums,
        })
    }

    fn max_addable(&self) -> u32 {
        // 6: [a, b, c, d, e, f] => (a + b + c + d) - (e + f) - 1
        // 5: [a, b, c, d, e]    => (a + b + c)     - e       - 1
        // 4: [a, b, c, d]       => (a + b + c)     - d       - 1
        // 3: [a, b, c]          => (a + b)                   - 1
        // 2: [a, b]             => (a + b)                   - 1
        let len = self.nums.len();
        let add = self.nums[..len / 2 + 1].iter().fold(0, |a, &b| a + b);
        let sub = self.nums[(len + 1) / 2 + 1..].iter().fold(0, |a, &b| a + b);
        add - sub - 1
    }

    fn each_next<F: FnMut(SSS)>(&self, mut f: F) {
        if let [a, b] = self.nums.as_ref() {
            f(SSS::new_with_pair(a, b + 1));
            if a == b - 1 {
                f(SSS::new_with_pair(a + 1, b + 1));
            }
        }

        for n in (*self.nums.last().unwrap())..(self.max_addable() + 1) {
            if let Some(sss) = self.append_num(n) {
                f(sss)
            }
        }
    }
}

struct SSSIterator {
    heap: BinaryHeap<SSS>,
}

impl SSSIterator {
    fn new() -> SSSIterator {
        let mut heap = BinaryHeap::new();
        heap.push(SSS::new_with_pair(1, 2));
        SSSIterator { heap: heap }
    }
}

impl Iterator for SSSIterator {
    type Item = SSS;

    fn next(&mut self) -> Option<SSS> {
        self.heap.pop().map(|sss| {
            sss.each_next(|next| self.heap.push(next));
            sss
        })
    }
}

fn solve() -> String {
    let sss = SSSIterator::new().find(|sss| sss.nums.len() == 7).unwrap();
    sss.nums.iter().map(|&n| n.to_string()).collect::<Vec<_>>().concat()
}

problem!("20313839404245", solve);

#[cfg(test)]
mod tests {
    use super::SSS;
    #[test]
    fn append_num() {
        let mut sss = SSS::new();
        assert!(sss.nums.is_empty());
        sss = sss.append_num(1).unwrap();
        assert_eq!(vec![1], sss.nums);
        sss = sss.append_num(2).unwrap();
        assert_eq!(vec![1, 2], sss.nums);
        assert_eq!(None, sss.append_num(3));
        sss = sss.append_num(4).unwrap();
        assert_eq!(vec![1, 2, 4], sss.nums);
    }
}
<commit_msg>update to rustc 1.11.0-nightly (7d2f75a95 2016-06-09)<commit_after>//! [Problem 103](https://projecteuler.net/problem=103) solver.

#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

#[macro_use(problem)]
extern crate common;

use std::cmp::Ordering;
use std::collections::BinaryHeap;

/// Special sum set
#[derive(Debug)]
struct SSS {
    avg: f64,
    nums: Vec<u32>,
    sums: Vec<u32>,
}

impl PartialEq for SSS {
    fn eq(&self, other: &SSS) -> bool {
        self.avg == other.avg
    }
}
impl Eq for SSS {}

impl PartialOrd for SSS {
    fn partial_cmp(&self, other: &SSS) -> Option<Ordering> {
        self.avg.partial_cmp(&other.avg).map(|x| x.reverse())
    }
}

impl Ord for SSS {
    fn cmp(&self, other: &SSS) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl SSS {
    #[cfg(test)]
    fn new() -> SSS {
        SSS {
            avg: 0.0,
            nums: vec![],
            sums: vec![0],
        }
    }

    fn new_with_pair(a: u32, b: u32) -> SSS {
        assert!(a < b);
        SSS {
            avg: ((a + b) as f64) / 2.0,
            nums: vec![a, b],
            sums: vec![0, a, b, a + b],
        }
    }

    fn append_num(&self, n: u32) -> Option<SSS> {
        let mut i = 0;
        let mut j = 0;
        let len = self.sums.len();
        let mut sums = Vec::with_capacity(len * 2);

        while i < len {
            assert!(j <= i);

            match self.sums[i].cmp(&(self.sums[j] + n)) {
                Ordering::Equal => {
                    return None;
                }
                Ordering::Less => {
                    sums.push(self.sums[i]);
                    i += 1;
                }
                Ordering::Greater => {
                    sums.push(self.sums[j] + n);
                    j += 1;
                }
            }
        }
        while j < len {
            sums.push(self.sums[j] + n);
            j += 1;
        }

        let avg = (self.avg * (len as f64) + n as f64) / ((len as f64) + 1.0);
        let mut nums = self.nums.clone();
        nums.push(n);

        Some(SSS {
            avg: avg,
            nums: nums,
            sums: sums,
        })
    }

    fn max_addable(&self) -> u32 {
        // 6: [a, b, c, d, e, f] => (a + b + c + d) - (e + f) - 1
        // 5: [a, b, c, d, e]    => (a + b + c)     - e       - 1
        // 4: [a, b, c, d]       => (a + b + c)     - d       - 1
        // 3: [a, b, c]          => (a + b)                   - 1
        // 2: [a, b]             => (a + b)                   - 1
        let len = self.nums.len();
        let add = self.nums[..len / 2 + 1].iter().fold(0, |a, &b| a + b);
        let sub = self.nums[(len + 1) / 2 + 1..].iter().fold(0, |a, &b| a + b);
        add - sub - 1
    }

    fn each_next<F: FnMut(SSS)>(&self, mut f: F) {
        if self.nums.len() == 2 {
            let a = self.nums[0];
            let b = self.nums[1];
            f(SSS::new_with_pair(a, b + 1));
            if a == b - 1 {
                f(SSS::new_with_pair(a + 1, b + 1));
            }
        }

        for n in (*self.nums.last().unwrap())..(self.max_addable() + 1) {
            if let Some(sss) = self.append_num(n) {
                f(sss)
            }
        }
    }
}

struct SSSIterator {
    heap: BinaryHeap<SSS>,
}

impl SSSIterator {
    fn new() -> SSSIterator {
        let mut heap = BinaryHeap::new();
        heap.push(SSS::new_with_pair(1, 2));
        SSSIterator { heap: heap }
    }
}

impl Iterator for SSSIterator {
    type Item = SSS;

    fn next(&mut self) -> Option<SSS> {
        self.heap.pop().map(|sss| {
            sss.each_next(|next| self.heap.push(next));
            sss
        })
    }
}

fn solve() -> String {
    let sss = SSSIterator::new().find(|sss| sss.nums.len() == 7).unwrap();
    sss.nums.iter().map(|&n| n.to_string()).collect::<Vec<_>>().concat()
}

problem!("20313839404245", solve);

#[cfg(test)]
mod tests {
    use super::SSS;
    #[test]
    fn append_num() {
        let mut sss = SSS::new();
        assert!(sss.nums.is_empty());
        sss = sss.append_num(1).unwrap();
        assert_eq!(vec![1], sss.nums);
        sss = sss.append_num(2).unwrap();
        assert_eq!(vec![1, 2], sss.nums);
        assert_eq!(None, sss.append_num(3));
        sss = sss.append_num(4).unwrap();
        assert_eq!(vec![1, 2, 4], sss.nums);
    }
}
<|endoftext|>


<commit_before>#![feature(specialization)]
#![feature(trace_macros)]
#![feature(log_syntax)]

extern crate num;
extern crate rand;
extern crate rutorch;
#[macro_use]
extern crate modparse_derive;
#[macro_use]
extern crate derive_builder;

#[macro_use]
pub mod macros;

pub mod nn;
pub mod autograd;
pub mod optim;
pub mod utils;
pub mod tensor;
pub mod storage;
use std::rc::Rc;
use std::cell::{RefCell, RefMut};

// Mutable reference counted T
pub type RcMut<T> = Rc<RefCell<T>>;
// Nullable mutable reference counted T
pub type OptRcMut<T> = Option<RcMut<T>>;
/// Array index type
pub type Ix = usize;
/// Array index type (signed)
pub type Ixs = isize;

#[allow(non_snake_case)]
pub fn RcMutNew<T>(arg: T) -> RcMut<T> {
    Rc::new(RefCell::new(arg))
}

#[cfg(test)]
mod tests {

    #[test]
    fn it_works() {}
}
<commit_msg>add itertools<commit_after>#![feature(specialization)]
#![feature(trace_macros)]
#![feature(log_syntax)]

extern crate num;
extern crate rand;
extern crate rutorch;
#[macro_use]
extern crate modparse_derive;
#[macro_use]
extern crate derive_builder;

extern crate itertools;

#[macro_use]
pub mod macros;

pub mod nn;
pub mod autograd;
pub mod optim;
pub mod utils;
pub mod tensor;
pub mod storage;
use std::rc::Rc;
use std::cell::RefCell;

// Mutable reference counted T
pub type RcMut<T> = Rc<RefCell<T>>;
// Nullable mutable reference counted T
pub type OptRcMut<T> = Option<RcMut<T>>;
pub type Ix = usize;
/// Array index type (signed)
pub type Ixs = isize;

#[allow(non_snake_case)]
pub fn RcMutNew<T>(arg: T) -> RcMut<T> {
    Rc::new(RefCell::new(arg))
}

#[cfg(test)]
mod tests {

    #[test]
    fn it_works() {}
}
<|endoftext|>


<commit_before>#![feature(plugin_registrar)]

extern crate rustc;
extern crate syntax;

use std::io::Command;
use std::str;

use rustc::plugin::Registry;
use syntax::ast;
use syntax::abi;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, DummyResult, MacItem};
use syntax::ext::base::MacResult;
use syntax::ext::build::AstBuilder;
use syntax::parse::parser::Parser;
use syntax::parse::token;
use syntax::parse::token::{special_idents, InternedString};
use syntax::print::pprust;

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_macro("link_config", expand_link_config);
}

fn expand_link_config(ecx: &mut ExtCtxt, span: Span,
                      tts: &[ast::TokenTree]) -> Box<MacResult> {
    let mut parser = ecx.new_parser_from_tts(tts);
    let (pkg, sp) = match parse_string(ecx, &mut parser) {
        Some(s) => s,
        None => return DummyResult::any(span),
    };
    if !parser.eat(&token::EOF) {
        ecx.span_err(parser.span, "only one string literal allowed");
        return DummyResult::any(span);
    }

    let out = match Command::new("pkg-config").arg(pkg.as_slice())
                                              .arg("--libs").output() {
        Ok(out) => out,
        Err(e) => {
            ecx.span_err(sp, format!("could not run pkg-config: {}", e).as_slice());
            return DummyResult::any(sp)
        }
    };
    let stdout = str::from_utf8(out.output.as_slice()).unwrap();
    let stderr = str::from_utf8(out.error.as_slice()).unwrap();
    if !out.status.success() {
        ecx.span_err(sp, format!("pkg-config did not exit successfully: {}\n\
                                  --- stdout\n{}\n--- stderr\n{}",
                                 out.status, stdout, stderr).as_slice());
        return DummyResult::any(sp)
    }

    let mut libs = Vec::new();
    let mut locs = Vec::new();
    for arg in stdout.split(' ').filter(|l| !l.is_empty()) {
        if arg.starts_with("-l") {
            libs.push(arg.slice_from(2));
        } else if arg.starts_with("-L") {
            locs.push(arg.slice_from(2));
        }
    }

    let mut attrs = libs.iter().map(|l| {
        // Build #[link(name = <l>)]
        let l = token::intern_and_get_ident(*l);
        let name = ecx.meta_name_value(sp, InternedString::new("name"),
                                       ast::LitStr(l, ast::CookedStr));
        let list = ecx.meta_list(sp, InternedString::new("link"), vec![name]);
        ecx.attribute(sp, list)
    }).chain(locs.iter().map(|l| {
        let l = token::intern_and_get_ident(format!("-L{}", l).as_slice());
        let args = ecx.meta_name_value(sp, InternedString::new("link_args"),
                                       ast::LitStr(l, ast::CookedStr));
        ecx.attribute(sp, args)
    }));

    let block = ecx.item(sp, special_idents::invalid, attrs.collect(),
                         ast::ItemForeignMod(ast::ForeignMod {
        abi: abi::C,
        view_items: Vec::new(),
        items: Vec::new(),
    }));

    return MacItem::new(block)
}

fn parse_string(ecx: &mut ExtCtxt,
                parser: &mut Parser) -> Option<(String, Span)> {
    let entry = ecx.expand_expr(parser.parse_expr());
    match entry.node {
        ast::ExprLit(lit) => {
            match lit.node {
                ast::LitStr(ref s, _) => return Some((s.to_str(), entry.span)),
                _ => {}
            }
        }
        _ => {}
    }
    ecx.span_err(entry.span, format!(
        "expected string literal but got `{}`",
        pprust::expr_to_str(entry)).as_slice());
    None
}
<commit_msg>static/dynamic configs<commit_after>#![feature(plugin_registrar)]

extern crate rustc;
extern crate syntax;

use std::gc::Gc;
use std::io::Command;
use std::os;
use std::str;

use rustc::plugin::Registry;
use syntax::abi;
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, DummyResult, MacroDef};
use syntax::ext::base::MacResult;
use syntax::ext::build::AstBuilder;
use syntax::parse::parser::Parser;
use syntax::parse::token;
use syntax::parse::token::{special_idents, InternedString};
use syntax::print::pprust;
use syntax::util::small_vector::SmallVector;

struct LibInfo {
    lib: String,
    statik: bool,
    deps: Vec<(String, bool)>, // (name, static)
    locs: Vec<String>,
}

struct MacItems {
    items: Vec<Gc<ast::Item>>,
}

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_macro("link_config", expand_link_config);
}

fn expand_link_config(ecx: &mut ExtCtxt, span: Span,
                      tts: &[ast::TokenTree]) -> Box<MacResult> {
    let mut parser = ecx.new_parser_from_tts(tts);
    let (pkg, sp) = match parse_string(ecx, &mut parser) {
        Some(s) => s,
        None => return DummyResult::any(span),
    };
    if !parser.eat(&token::EOF) {
        ecx.span_err(parser.span, "only one string literal allowed");
        return DummyResult::any(span);
    }

    let dyn = match system_pkgconfig(ecx, sp, pkg.as_slice(), false) {
        Some(info) => info,
        None => return DummyResult::any(span),
    };
    let statik = match system_pkgconfig(ecx, sp, pkg.as_slice(), true) {
        Some(info) => info,
        None => return DummyResult::any(span),
    };

    let dyn = block(ecx, sp, &dyn);
    let statik = block(ecx, sp, &statik);

    box MacItems { items: vec![dyn, statik] } as Box<MacResult>
}

fn system_pkgconfig(ecx: &mut ExtCtxt, sp: Span, pkg: &str,
                    statik: bool) -> Option<LibInfo> {

    let mut env = os::env();
    env.push(("PKG_CONFIG_ALLOW_SYSTEM_LIBS".to_string(), "1".to_string()));

    let mut cmd = Command::new("pkg-config");
    cmd.arg(pkg).arg("--libs").env(env.as_slice());
    if statik {
        cmd.arg("--static");
    }
    let out = match cmd.output() {
        Ok(out) => out,
        Err(e) => {
            ecx.span_err(sp, format!("could not run pkg-config: {}", e).as_slice());
            return None
        }
    };
    let stdout = str::from_utf8(out.output.as_slice()).unwrap();
    let stderr = str::from_utf8(out.error.as_slice()).unwrap();
    if !out.status.success() {
        let mut msg = format!("pkg-config did not exit successfully: {}",
                              out.status);
        if stdout.len() > 0 {
            msg.push_str("\n--- stdout\n");
            msg.push_str(stdout);
        }
        if stderr.len() > 0 {
            msg.push_str("\n--- stderr\n");
            msg.push_str(stderr);
        }
        ecx.span_err(sp, msg.as_slice());
        return None
    }

    let mut libs = Vec::new();
    let mut locs = Vec::new();
    for arg in stdout.split(' ').filter(|l| !l.is_empty()) {
        if arg.starts_with("-l") {
            libs.push(arg.slice_from(2));
        } else if arg.starts_with("-L") {
            locs.push(arg.slice_from(2).to_string());
        }
    }

    let libs = libs.move_iter().map(|lib| {
        (lib.to_string(), statik && locs.iter().any(|l| {
            let base = Path::new(l.as_slice());
            base.join(format!("lib{}.a", lib)).exists() ||
                base.join(format!("{}.lib", lib)).exists() ||
                base.join(format!("lib{}.lib", lib)).exists()
        }))
    }).collect();
    Some(LibInfo {
        lib: pkg.to_string(),
        deps: libs,
        locs: locs,
        statik: statik,
    })
}

fn block(ecx: &mut ExtCtxt, sp: Span, info: &LibInfo) -> Gc<ast::Item> {
    let lib = token::intern_and_get_ident(info.lib.as_slice());
    let cfg = ecx.meta_name_value(sp, InternedString::new("statik"),
                                  ast::LitStr(lib, ast::CookedStr));
    let cfg = ecx.meta_list(sp, InternedString::new("cfg"), vec![if info.statik {
        cfg
    } else {
        ecx.meta_list(sp, InternedString::new("not"), vec![cfg])
    }]);

    let attrs = vec![ecx.attribute(sp, cfg)].move_iter();
    let attrs = attrs.chain(info.deps.iter().map(|&(ref l, statik)| {
        // Build #[link(name = <l>)]
        let l = token::intern_and_get_ident(l.as_slice());
        let mut items = Vec::new();
        items.push(ecx.meta_name_value(sp, InternedString::new("name"),
                                       ast::LitStr(l, ast::CookedStr)));
        if statik {
            let l = InternedString::new("static");
            items.push(ecx.meta_name_value(sp, InternedString::new("kind"),
                                           ast::LitStr(l, ast::CookedStr)));
        }
        let list = ecx.meta_list(sp, InternedString::new("link"), items);
        ecx.attribute(sp, list)
    }));
    let attrs = attrs.chain(info.locs.iter().map(|l| {
        let l = token::intern_and_get_ident(format!("-L{}", l).as_slice());
        let args = ecx.meta_name_value(sp, InternedString::new("link_args"),
                                       ast::LitStr(l, ast::CookedStr));
        ecx.attribute(sp, args)
    }));
    let mut attrs = attrs.map(|attr| {
        attr::mark_used(&attr);
        attr
    });

    ecx.item(sp, special_idents::invalid, attrs.collect(),
             ast::ItemForeignMod(ast::ForeignMod {
        abi: abi::C,
        view_items: Vec::new(),
        items: Vec::new(),
    }))
}

fn parse_string(ecx: &mut ExtCtxt,
                parser: &mut Parser) -> Option<(String, Span)> {
    let entry = ecx.expand_expr(parser.parse_expr());
    match entry.node {
        ast::ExprLit(lit) => {
            match lit.node {
                ast::LitStr(ref s, _) => return Some((s.to_str(), entry.span)),
                _ => {}
            }
        }
        _ => {}
    }
    ecx.span_err(entry.span, format!(
        "expected string literal but got `{}`",
        pprust::expr_to_str(entry)).as_slice());
    None
}

impl MacResult for MacItems {
    fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
        Some(self.items.iter().map(|a| a.clone()).collect())
    }
    fn make_stmt(&self) -> Option<Gc<ast::Stmt>> { None }
    fn make_def(&self) -> Option<MacroDef> { None }
    fn make_expr(&self) -> Option<Gc<ast::Expr>> { None }
    fn make_pat(&self) -> Option<Gc<ast::Pat>> { None }
}
<|endoftext|>