<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
//
// Original implementation taken from rust-memchr
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch

use cmp;
use mem;

const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;

// use truncation
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usize;

/// Return `true` if `x` contains any zero byte.
///
/// From *Matters Computational*, J. Arndt
///
/// "The idea is to subtract one from each of the bytes and then look for
/// bytes where the borrow propagated all the way to the most significant
/// bit."
#[inline]
fn contains_zero_byte(x: usize) -> bool {
    x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
}

#[cfg(target_pointer_width = "16")]
#[inline]
fn repeat_byte(b: u8) -> usize {
    (b as usize) << 8 | b as usize
}

#[cfg(not(target_pointer_width = "16"))]
#[inline]
fn repeat_byte(b: u8) -> usize {
    (b as usize) * (::usize::MAX / 255)
}

/// Return the first index matching the byte `x` in `text`.
pub fn memchr(x: u8, text: &[u8]) -> Option<usize> {
    // Scan for a single byte value by reading two `usize` words at a time.
    //
    // Split `text` in three parts
    // - unaligned initial part, before the first word aligned address in text
    // - body, scan by 2 words at a time
    // - the last remaining part, < 2 word size
    let len = text.len();
    let ptr = text.as_ptr();
    let usize_bytes = mem::size_of::<usize>();

    // search up to an aligned boundary
    let mut offset = ptr.align_offset(usize_bytes);
    if offset > 0 {
        offset = cmp::min(offset, len);
        if let Some(index) = text[..offset].iter().position(|elt| *elt == x) {
            return Some(index);
        }
    }

    // search the body of the text
    let repeated_x = repeat_byte(x);

    if len >= 2 * usize_bytes {
        while offset <= len - 2 * usize_bytes {
            unsafe {
                let u = *(ptr.offset(offset as isize) as *const usize);
                let v = *(ptr.offset((offset + usize_bytes) as isize) as *const usize);

                // break if there is a matching byte
                let zu = contains_zero_byte(u ^ repeated_x);
                let zv = contains_zero_byte(v ^ repeated_x);
                if zu || zv {
                    break;
                }
            }
            offset += usize_bytes * 2;
        }
    }

    // find the byte after the point the body loop stopped
    text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i)
}

/// Return the last index matching the byte `x` in `text`.
pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
    // Scan for a single byte value by reading two `usize` words at a time.
    //
    // Split `text` in three parts
    // - unaligned tail, after the last word aligned address in text
    // - body, scan by 2 words at a time
    // - the first remaining bytes, < 2 word size
    let len = text.len();
    let ptr = text.as_ptr();
    let usize_bytes = mem::size_of::<usize>();

    let mut offset = {
        // We call this just to obtain the length of the suffix
        let (_, _, suffix) = unsafe { text.align_to::<usize>() };
        len - suffix.len()
    };
    if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) {
        return Some(offset + index);
    }

    // search the body of the text
    let repeated_x = repeat_byte(x);

    while offset >= 2 * usize_bytes {
        unsafe {
            let u = *(ptr.offset(offset as isize - 2 * usize_bytes as isize) as *const usize);
            let v = *(ptr.offset(offset as isize - usize_bytes as isize) as *const usize);

            // break if there is a matching byte
            let zu = contains_zero_byte(u ^ repeated_x);
            let zv = contains_zero_byte(v ^ repeated_x);
            if zu || zv {
                break;
            }
        }
        offset -= 2 * usize_bytes;
    }

    // find the byte before the point the body loop stopped
    text[..offset].iter().rposition(|elt| *elt == x)
}
<commit_msg>Rollup merge of #52854 - RalfJung:memrchr, r=Kimundi<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
//
// Original implementation taken from rust-memchr
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch

use cmp;
use mem;

const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;

// use truncation
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usize;

/// Return `true` if `x` contains any zero byte.
///
/// From *Matters Computational*, J. Arndt
///
/// "The idea is to subtract one from each of the bytes and then look for
/// bytes where the borrow propagated all the way to the most significant
/// bit."
#[inline]
fn contains_zero_byte(x: usize) -> bool {
    x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
}

#[cfg(target_pointer_width = "16")]
#[inline]
fn repeat_byte(b: u8) -> usize {
    (b as usize) << 8 | b as usize
}

#[cfg(not(target_pointer_width = "16"))]
#[inline]
fn repeat_byte(b: u8) -> usize {
    (b as usize) * (::usize::MAX / 255)
}

/// Return the first index matching the byte `x` in `text`.
pub fn memchr(x: u8, text: &[u8]) -> Option<usize> {
    // Scan for a single byte value by reading two `usize` words at a time.
    //
    // Split `text` in three parts
    // - unaligned initial part, before the first word aligned address in text
    // - body, scan by 2 words at a time
    // - the last remaining part, < 2 word size
    let len = text.len();
    let ptr = text.as_ptr();
    let usize_bytes = mem::size_of::<usize>();

    // search up to an aligned boundary
    let mut offset = ptr.align_offset(usize_bytes);
    if offset > 0 {
        offset = cmp::min(offset, len);
        if let Some(index) = text[..offset].iter().position(|elt| *elt == x) {
            return Some(index);
        }
    }

    // search the body of the text
    let repeated_x = repeat_byte(x);

    if len >= 2 * usize_bytes {
        while offset <= len - 2 * usize_bytes {
            unsafe {
                let u = *(ptr.offset(offset as isize) as *const usize);
                let v = *(ptr.offset((offset + usize_bytes) as isize) as *const usize);

                // break if there is a matching byte
                let zu = contains_zero_byte(u ^ repeated_x);
                let zv = contains_zero_byte(v ^ repeated_x);
                if zu || zv {
                    break;
                }
            }
            offset += usize_bytes * 2;
        }
    }

    // find the byte after the point the body loop stopped
    text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i)
}

/// Return the last index matching the byte `x` in `text`.
pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
    // Scan for a single byte value by reading two `usize` words at a time.
    //
    // Split `text` in three parts
    // - unaligned tail, after the last word aligned address in text
    // - body, scan by 2 words at a time
    // - the first remaining bytes, < 2 word size
    let len = text.len();
    let ptr = text.as_ptr();
    type Chunk = usize;

    let (min_aligned_offset, max_aligned_offset) = {
        // We call this just to obtain the length of the prefix and suffix.
        // In the middle we always process two chunks at once.
        let (prefix, _, suffix) = unsafe { text.align_to::<(Chunk, Chunk)>() };
        (prefix.len(), len - suffix.len())
    };

    let mut offset = max_aligned_offset;
    if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) {
        return Some(offset + index);
    }

    // search the body of the text, make sure we don't cross min_aligned_offset.
    // offset is always aligned, so just testing `>` is sufficient and avoids possible
    // overflow.
    let repeated_x = repeat_byte(x);
    let chunk_bytes = mem::size_of::<Chunk>();

    while offset > min_aligned_offset {
        unsafe {
            let u = *(ptr.offset(offset as isize - 2 * chunk_bytes as isize) as *const Chunk);
            let v = *(ptr.offset(offset as isize - chunk_bytes as isize) as *const Chunk);

            // break if there is a matching byte
            let zu = contains_zero_byte(u ^ repeated_x);
            let zv = contains_zero_byte(v ^ repeated_x);
            if zu || zv {
                break;
            }
        }
        offset -= 2 * chunk_bytes;
    }

    // find the byte before the point the body loop stopped
    text[..offset].iter().rposition(|elt| *elt == x)
}
<|endoftext|>


<commit_before><commit_msg>refactor(filtering): scan using next<commit_after><|endoftext|>


<commit_before>#[macro_use]
extern crate futures_io;
extern crate futures_mio;
extern crate futures_tls;
extern crate net2;
#[macro_use]
extern crate futures;
extern crate httparse;
extern crate time;
#[macro_use]
extern crate log;

use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread;

use futures::Future;
use futures::stream::Stream;
use futures_io::{TaskIo, Ready, IoFuture};
use futures_mio::{Loop, LoopHandle, TcpStream, TcpListener};
use futures_tls::ServerContext;

mod request;
pub use self::request::{Request, RequestHeaders};

mod response;
pub use self::response::Response;

mod io2;
pub use io2::{Parse, Serialize};
use io2::{ParseStream, StreamWriter};

mod date;

pub trait Service<Req, Resp>: Send + Sync + 'static
    where Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut: Future<Item = Resp>;

    fn process(&self, req: Req) -> Self::Fut;
}

impl<Req, Resp, Fut, F> Service<Req, Resp> for F
    where F: Fn(Req) -> Fut + Send + Sync + 'static,
          Fut: Future<Item = Resp>,
          Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut = Fut;

    fn process(&self, req: Req) -> Fut {
        (self)(req)
    }
}

pub struct Server {
    addr: SocketAddr,
    workers: u32,
    tls: Option<Box<Fn() -> io::Result<ServerContext> + Send + Sync>>,
}

struct ServerData<S> {
    service: S,
    tls: Option<Box<Fn() -> io::Result<ServerContext> + Send + Sync>>,
}

impl Server {
    pub fn new(addr: &SocketAddr) -> Server {
        Server {
            addr: *addr,
            workers: 1,
            tls: None,
        }
    }

    pub fn workers(&mut self, workers: u32) -> &mut Server {
        if cfg!(unix) {
            self.workers = workers;
        }
        self
    }

    pub fn tls<F>(&mut self, tls: F) -> &mut Server
        where F: Fn() -> io::Result<ServerContext> + Send + Sync + 'static,
    {
        self.tls = Some(Box::new(tls));
        self
    }

    pub fn serve<Req, Resp, S>(&mut self, s: S) -> io::Result<()>
        where Req: Parse,
              Resp: Serialize,
              S: Service<Req, Resp>,
              <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>, // TODO: simplify this?
    {
        let data = Arc::new(ServerData {
            service: s,
            tls: self.tls.take(),
        });

        let threads = (0..self.workers - 1).map(|i| {
            let (addr, workers) = (self.addr, self.workers);
            let data = data.clone();
            thread::Builder::new().name(format!("worker{}", i)).spawn(move || {
                let mut lp = Loop::new().unwrap();
                let listener = listener(&addr, workers, lp.handle());
                lp.run(listener.and_then(move |l| {
                    l.incoming().for_each(move |(stream, _)| {
                        handle(stream, data.clone());
                        Ok(()) // TODO: error handling
                    })
                }))
            }).unwrap()
        }).collect::<Vec<_>>();

        let mut lp = Loop::new().unwrap();
        let listener = listener(&self.addr, self.workers, lp.handle());
        lp.run(listener.and_then(move |l| {
            l.incoming().for_each(move |(stream, _)| {
                handle(stream, data.clone());
                Ok(()) // TODO: error handling
            })
        })).unwrap();

        for thread in threads {
            thread.join().unwrap().unwrap();
        }

        Ok(())
    }
}

fn listener(addr: &SocketAddr,
            workers: u32,
            handle: LoopHandle) -> Box<IoFuture<TcpListener>> {
    let listener = (|| {
        let listener = try!(net2::TcpBuilder::new_v4());
        try!(configure_tcp(workers, &listener));
        try!(listener.reuse_address(true));
        try!(listener.bind(addr));
        listener.listen(1024)
    })();

    match listener {
        Ok(l) => TcpListener::from_listener(l, addr, handle),
        Err(e) => futures::failed(e).boxed()
    }
}

#[cfg(unix)]
fn configure_tcp(workers: u32, tcp: &net2::TcpBuilder) -> io::Result<()> {
    use net2::unix::*;

    if workers > 1 {
        try!(tcp.reuse_port(true));
    }

    Ok(())
}

#[cfg(windows)]
fn configure_tcp(workers: u32, _tcp: &net2::TcpBuilder) -> io::Result<()> {
    Ok(())
}

trait IoStream: Read + Write + Stream<Item=Ready, Error=io::Error> {}

impl<T: ?Sized> IoStream for T
    where T: Read + Write + Stream<Item=Ready, Error=io::Error>
{}

fn handle<Req, Resp, S>(stream: TcpStream, data: Arc<ServerData<S>>)
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>,
{
    let io = match data.tls {
        Some(ref tls) => {
            tls().unwrap().handshake(stream).map(|b| {
                Box::new(b) as
                    Box<IoStream<Item=Ready, Error=io::Error>>
            }).boxed()
        }
        None => {
            let stream = Box::new(stream) as
                    Box<IoStream<Item=Ready, Error=io::Error>>;
            futures::finished(stream).boxed()
        }
    };
    let io = io.and_then(|io| TaskIo::new(io)).map_err(From::from).and_then(|io| {
        let (reader, writer) = io.split();

        let input = ParseStream::new(reader).map_err(From::from);
        let responses = input.and_then(move |req| data.service.process(req));
        StreamWriter::new(writer, responses)
    });

    // Crucially use `.forget()` here instead of returning the future, allows
    // processing multiple separate connections concurrently.
    io.forget();
}
<commit_msg>Remove extraneous allocations in minihttp<commit_after>#[macro_use]
extern crate futures_io;
extern crate futures_mio;
extern crate futures_tls;
extern crate net2;
#[macro_use]
extern crate futures;
extern crate httparse;
extern crate time;
#[macro_use]
extern crate log;

use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread;

use futures::{Future, Task, Poll};
use futures::stream::Stream;
use futures_io::{TaskIo, Ready, IoFuture};
use futures_mio::{Loop, LoopHandle, TcpStream, TcpListener};
use futures_tls::{ServerContext, TlsStream};

mod request;
pub use self::request::{Request, RequestHeaders};

mod response;
pub use self::response::Response;

mod io2;
pub use io2::{Parse, Serialize};
use io2::{ParseStream, StreamWriter};

mod date;

pub trait Service<Req, Resp>: Send + Sync + 'static
    where Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut: Future<Item = Resp>;

    fn process(&self, req: Req) -> Self::Fut;
}

impl<Req, Resp, Fut, F> Service<Req, Resp> for F
    where F: Fn(Req) -> Fut + Send + Sync + 'static,
          Fut: Future<Item = Resp>,
          Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut = Fut;

    fn process(&self, req: Req) -> Fut {
        (self)(req)
    }
}

pub struct Server {
    addr: SocketAddr,
    workers: u32,
    tls: Option<Box<Fn() -> io::Result<ServerContext> + Send + Sync>>,
}

struct ServerData<S> {
    service: S,
    tls: Option<Box<Fn() -> io::Result<ServerContext> + Send + Sync>>,
}

impl Server {
    pub fn new(addr: &SocketAddr) -> Server {
        Server {
            addr: *addr,
            workers: 1,
            tls: None,
        }
    }

    pub fn workers(&mut self, workers: u32) -> &mut Server {
        if cfg!(unix) {
            self.workers = workers;
        }
        self
    }

    pub fn tls<F>(&mut self, tls: F) -> &mut Server
        where F: Fn() -> io::Result<ServerContext> + Send + Sync + 'static,
    {
        self.tls = Some(Box::new(tls));
        self
    }

    pub fn serve<Req, Resp, S>(&mut self, s: S) -> io::Result<()>
        where Req: Parse,
              Resp: Serialize,
              S: Service<Req, Resp>,
              <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>, // TODO: simplify this?
    {
        let data = Arc::new(ServerData {
            service: s,
            tls: self.tls.take(),
        });

        let threads = (0..self.workers - 1).map(|i| {
            let (addr, workers) = (self.addr, self.workers);
            let data = data.clone();
            thread::Builder::new().name(format!("worker{}", i)).spawn(move || {
                let mut lp = Loop::new().unwrap();
                let listener = listener(&addr, workers, lp.handle());
                lp.run(listener.and_then(move |l| {
                    l.incoming().for_each(move |(stream, _)| {
                        handle(stream, data.clone());
                        Ok(()) // TODO: error handling
                    })
                }))
            }).unwrap()
        }).collect::<Vec<_>>();

        let mut lp = Loop::new().unwrap();
        let listener = listener(&self.addr, self.workers, lp.handle());
        lp.run(listener.and_then(move |l| {
            l.incoming().for_each(move |(stream, _)| {
                handle(stream, data.clone());
                Ok(()) // TODO: error handling
            })
        })).unwrap();

        for thread in threads {
            thread.join().unwrap().unwrap();
        }

        Ok(())
    }
}

fn listener(addr: &SocketAddr,
            workers: u32,
            handle: LoopHandle) -> Box<IoFuture<TcpListener>> {
    let listener = (|| {
        let listener = try!(net2::TcpBuilder::new_v4());
        try!(configure_tcp(workers, &listener));
        try!(listener.reuse_address(true));
        try!(listener.bind(addr));
        listener.listen(1024)
    })();

    match listener {
        Ok(l) => TcpListener::from_listener(l, addr, handle),
        Err(e) => futures::failed(e).boxed()
    }
}

#[cfg(unix)]
fn configure_tcp(workers: u32, tcp: &net2::TcpBuilder) -> io::Result<()> {
    use net2::unix::*;

    if workers > 1 {
        try!(tcp.reuse_port(true));
    }

    Ok(())
}

#[cfg(windows)]
fn configure_tcp(workers: u32, _tcp: &net2::TcpBuilder) -> io::Result<()> {
    Ok(())
}

trait IoStream: Read + Write + Stream<Item=Ready, Error=io::Error> {}

impl<T: ?Sized> IoStream for T
    where T: Read + Write + Stream<Item=Ready, Error=io::Error>
{}

fn handle<Req, Resp, S>(stream: TcpStream, data: Arc<ServerData<S>>)
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>,
{
    let io = match data.tls {
        Some(ref tls) => {
            Either::A(tls().unwrap().handshake(stream).map(|b| {
                MaybeTls::Tls(b)
            }))
        }
        None => {
            let stream = MaybeTls::NotTls(stream);
            Either::B(futures::finished(stream))
        }
    };
    let io = io.and_then(|io| TaskIo::new(io)).map_err(From::from).and_then(|io| {
        let (reader, writer) = io.split();

        let input = ParseStream::new(reader).map_err(From::from);
        let responses = input.and_then(move |req| data.service.process(req));
        StreamWriter::new(writer, responses)
    });

    // Crucially use `.forget()` here instead of returning the future, allows
    // processing multiple separate connections concurrently.
    io.forget();
}

/// Temporary adapter for a read/write stream which is either TLS or not.
enum MaybeTls<S> {
    Tls(TlsStream<S>),
    NotTls(S),
}

impl<S> Stream for MaybeTls<S>
    where S: Read + Write + Stream<Item = Ready, Error = io::Error>
{
    type Item = Ready;
    type Error = io::Error;

    fn poll(&mut self, task: &mut Task) -> Poll<Option<Ready>, io::Error> {
        match *self {
            MaybeTls::Tls(ref mut s) => s.poll(task),
            MaybeTls::NotTls(ref mut s) => s.poll(task),
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        match *self {
            MaybeTls::Tls(ref mut s) => s.schedule(task),
            MaybeTls::NotTls(ref mut s) => s.schedule(task),
        }
    }
}

impl<S> Read for MaybeTls<S>
    where S: Read + Write + Stream<Item = Ready, Error = io::Error>
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            MaybeTls::Tls(ref mut s) => s.read(buf),
            MaybeTls::NotTls(ref mut s) => s.read(buf),
        }
    }
}

impl<S> Write for MaybeTls<S>
    where S: Read + Write + Stream<Item = Ready, Error = io::Error>
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match *self {
            MaybeTls::Tls(ref mut s) => s.write(buf),
            MaybeTls::NotTls(ref mut s) => s.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match *self {
            MaybeTls::Tls(ref mut s) => s.flush(),
            MaybeTls::NotTls(ref mut s) => s.flush(),
        }
    }
}

/// Temporary adapter for a concrete type that resolves to one of two futures
enum Either<A, B> {
    A(A),
    B(B),
}

impl<A, B> Future for Either<A, B>
    where A: Future,
          B: Future<Item = A::Item, Error = A::Error>,
{
    type Item = A::Item;
    type Error = A::Error;

    fn poll(&mut self, task: &mut Task) -> Poll<A::Item, A::Error> {
        match *self {
            Either::A(ref mut s) => s.poll(task),
            Either::B(ref mut s) => s.poll(task),
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        match *self {
            Either::A(ref mut s) => s.schedule(task),
            Either::B(ref mut s) => s.schedule(task),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>adds example of reading and writing to a port<commit_after>extern crate serial;
extern crate time;

use std::env;
use std::io;

use time::Duration;

use std::io::prelude::*;
use serial::prelude::*;

fn main() {
    for arg in env::args_os().skip(1) {
        println!("opening port: {:?}", arg);
        let mut port = serial::open(&arg).unwrap();

        interact(&mut port).unwrap();
    }
}

fn interact<T: SerialPort>(port: &mut T) -> io::Result<()> {
    try!(port.configure(|settings| {
        settings.set_baud_rate(serial::Baud9600);
        settings.set_char_size(serial::Bits8);
        settings.set_parity(serial::ParityNone);
        settings.set_stop_bits(serial::Stop1);
        settings.set_flow_control(serial::FlowNone);
    }));

    port.set_timeout(Duration::milliseconds(1000));

    let mut buf: Vec<u8> = (0..255).collect();

    println!("writing bytes");
    try!(port.write(&buf[..]));

    println!("reading bytes");
    try!(port.read(&mut buf[..]));

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add the commandline options example from the README to examples<commit_after>extern crate getopts;
extern crate knob;

use getopts::optopt;
use knob::Settings;

fn main() {
    let mut settings = Settings::new();
    settings.opt(optopt("p", "port", "the port to bind to", "4000"));
    settings.opt(optopt("e", "environment", "the environment to run in", ""));
    let errors = settings.load_os_args();
    if errors.is_some() {
        println!("{}", settings.usage("Try one of these:"));
    }
}
<|endoftext|>


<commit_before><commit_msg>add create_tweet example<commit_after>mod common;

use egg_mode::media::{media_types, upload_media, MediaCategory};
use egg_mode::tweet::DraftTweet;

use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt)]
struct Args {
    /// Text of the tweet
    text: String,
    /// Optionally attach media to tweet
    #[structopt(long, parse(from_os_str))]
    media: Option<PathBuf>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::from_args();
    let config = common::Config::load().await;

    let mut tweet = DraftTweet::new(args.text.clone());

    if let Some(path) = args.media {
        println!("Uploading media from '{}'", path.display());
        let bytes = std::fs::read(path)?;
        let typ = media_types::image_jpg();
        let cat = MediaCategory::Image;
        let handle = upload_media(&bytes, &typ, &cat, &config.token).await?;
        tweet.add_media(handle.id);
    }

    tweet.send(&config.token).await?;

    println!("Sent tweet: '{}'", args.text);

    Ok(())
}
<|endoftext|>


<commit_before>use regex::Regex;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;

use super::file::{FileHeaderSpec, FileHeaderData};

pub struct ParserError {
    summary: String,
    parsertext: String,
    index: i32,
    explanation: Option<String>,
}

impl ParserError {
    pub fn new(sum: &'static str, text: String, idx: i32, expl: &'static str) -> ParserError {
        ParserError {
            summary: String::from(sum),
            parsertext: text,
            index: idx,
            explanation: Some(String::from(expl)),
        }
    }

    pub fn short(sum: &'static str, text: String, idx: i32) -> ParserError {
        ParserError {
            summary: String::from(sum),
            parsertext: text,
            index: idx,
            explanation: None
        }
    }
}

impl Error for ParserError {

    fn description(&self) -> &str {
        &self.summary[..]
    }

    fn cause(&self) -> Option<&Error> {
        None
    }

}

impl Debug for ParserError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "ParserError: {}\n\n", self.summary);

        if let Some(ref e) = self.explanation {
            write!(fmt, "{}\n\n", e);
        }

        write!(fmt, "On position {}\nin\n{}", self.index, self.parsertext);
        Ok(())
    }

}

impl Display for ParserError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "ParserError: {}", self.summary);

        if let Some(ref e) = self.explanation {
            write!(fmt, "\n\n{}", e);
        }

        Ok(())
    }

}

pub trait FileHeaderParser<'a> : Sized {
    fn new(spec: &'a FileHeaderSpec) -> Self;
    fn read(&self, string: Option<String>) -> Result<FileHeaderData, ParserError>;
    fn write(&self, data: &FileHeaderData) -> Result<String, ParserError>;
}

type TextTpl = (Option<String>, Option<String>);

pub struct Parser<HP>
{
    headerp : HP,
}

impl<'a, HP> Parser<HP> where
    HP: FileHeaderParser<'a>,
{

    fn new(headerp: HP) -> Parser<HP> {
        Parser {
            headerp: headerp,
        }
    }

    pub fn read(&self, s: String) -> Result<(FileHeaderData, String), ParserError>
    {
        let divided = self.divide_text(&s);

        if divided.is_err() {
            return Err(divided.err().unwrap());
        }

        let (header, data) = divided.ok().unwrap();

        let h_parseres = try!(self.headerp.read(header));

        Ok((h_parseres, data.unwrap_or(String::new())))
    }

    pub fn write(&self, tpl : (FileHeaderData, String)) -> Result<String, ParserError>
    {
        let (header, data) = tpl;
        let h_text = try!(self.headerp.write(&header));

        Ok(h_text + &data[..])
    }

    fn divide_text(&self, text: &String) -> Result<TextTpl, ParserError> {
        let re = Regex::new(r"(?m)^\-\-\-$\n(.*)^\-\-\-$\n(.*)").unwrap();

        let captures = re.captures(&text[..]).unwrap_or(
            return Err(ParserError::new("Cannot run regex on text",
                                        text.clone(), 0,
                                        "Cannot run regex on text to divide it into header and content."))
        );

        if captures.len() != 2 {
            return Err(ParserError::new("Unexpected Regex output",
                                        text.clone(), 0,
                                        "The regex to divide text into header and content had an unexpected output."))
        }

        let header  = captures.at(0).map(|s| String::from(s));
        let content = captures.at(1).map(|s| String::from(s));
        Ok((header, content))
    }

}

<commit_msg>Add debugging output in storage parser code<commit_after>use regex::Regex;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;

use super::file::{FileHeaderSpec, FileHeaderData};

pub struct ParserError {
    summary: String,
    parsertext: String,
    index: i32,
    explanation: Option<String>,
}

impl ParserError {
    pub fn new(sum: &'static str, text: String, idx: i32, expl: &'static str) -> ParserError {
        ParserError {
            summary: String::from(sum),
            parsertext: text,
            index: idx,
            explanation: Some(String::from(expl)),
        }
    }

    pub fn short(sum: &'static str, text: String, idx: i32) -> ParserError {
        ParserError {
            summary: String::from(sum),
            parsertext: text,
            index: idx,
            explanation: None
        }
    }
}

impl Error for ParserError {

    fn description(&self) -> &str {
        &self.summary[..]
    }

    fn cause(&self) -> Option<&Error> {
        None
    }

}

impl Debug for ParserError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "ParserError: {}\n\n", self.summary);

        if let Some(ref e) = self.explanation {
            write!(fmt, "{}\n\n", e);
        }

        write!(fmt, "On position {}\nin\n{}", self.index, self.parsertext);
        Ok(())
    }

}

impl Display for ParserError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "ParserError: {}", self.summary);

        if let Some(ref e) = self.explanation {
            write!(fmt, "\n\n{}", e);
        }

        Ok(())
    }

}

pub trait FileHeaderParser<'a> : Sized {
    fn new(spec: &'a FileHeaderSpec) -> Self;
    fn read(&self, string: Option<String>) -> Result<FileHeaderData, ParserError>;
    fn write(&self, data: &FileHeaderData) -> Result<String, ParserError>;
}

type TextTpl = (Option<String>, Option<String>);

pub struct Parser<HP>
{
    headerp : HP,
}

impl<'a, HP> Parser<HP> where
    HP: FileHeaderParser<'a>,
{

    fn new(headerp: HP) -> Parser<HP> {
        Parser {
            headerp: headerp,
        }
    }

    pub fn read(&self, s: String) -> Result<(FileHeaderData, String), ParserError>
    {
        debug!("Reading into internal datastructure: '{}'", s);
        let divided = self.divide_text(&s);

        if divided.is_err() {
            debug!("Error reading into internal datastructure");
            return Err(divided.err().unwrap());
        }

        let (header, data) = divided.ok().unwrap();
        debug!("Header = '{:?}'", header);
        debug!("Data   = '{:?}'", data);

        let h_parseres = try!(self.headerp.read(header));
        debug!("Success parsing header");

        Ok((h_parseres, data.unwrap_or(String::new())))
    }

    pub fn write(&self, tpl : (FileHeaderData, String)) -> Result<String, ParserError>
    {
        debug!("Parsing internal datastructure to String");
        let (header, data) = tpl;
        let h_text = try!(self.headerp.write(&header));
        debug!("Success translating header");

        Ok(h_text + &data[..])
    }

    fn divide_text(&self, text: &String) -> Result<TextTpl, ParserError> {
        debug!("Splitting: '{}'", text);
        let re = Regex::new(r"(?m)^\-\-\-$\n(.*)^\-\-\-$\n(.*)").unwrap();

        let captures = re.captures(&text[..]).unwrap_or(
            return Err(ParserError::new("Cannot run regex on text",
                                        text.clone(), 0,
                                        "Cannot run regex on text to divide it into header and content."))
        );

        if captures.len() != 2 {
            return Err(ParserError::new("Unexpected Regex output",
                                        text.clone(), 0,
                                        "The regex to divide text into header and content had an unexpected output."))
        }

        let header  = captures.at(0).map(|s| String::from(s));
        let content = captures.at(1).map(|s| String::from(s));

        debug!("Splitted, Header = '{:?}'", header);
        debug!("Splitted, Data   = '{:?}'", content);
        Ok((header, content))
    }

}

<|endoftext|>


<commit_before><commit_msg>Add a test for unsized tuple impls.<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

#![feature(unsized_tuple_coercion)]

use std::collections::HashSet;

fn main() {
    let x : &(i32, i32, [i32]) = &(0, 1, [2, 3]);
    let y : &(i32, i32, [i32]) = &(0, 1, [2, 3, 4]);
    let mut a = [y, x];
    a.sort();
    assert_eq!(a, [x, y]);

    assert_eq!(&format!("{:?}", a), "[(0, 1, [2, 3]), (0, 1, [2, 3, 4])]");

    let mut h = HashSet::new();
    h.insert(x);
    h.insert(y);
    assert!(h.contains(x));
    assert!(h.contains(y));
}
<|endoftext|>


<commit_before><commit_msg>`Sized` syntax changed<commit_after><|endoftext|>


<commit_before><commit_msg>Implement a trait that get an HTTP response given an URL and headers<commit_after>use hyper::client::Client;
use hyper::client::response::Response;
use hyper::error::Error;
use hyper::header::Headers;
use hyper::method::Method;

/// Trait that represents some methods to send a specific request
pub trait GetResponse {
    /// Given a specific URL, get the response from the target server
    fn get_http_response(url: &str) -> Result<Response, Error>;
    /// Given a specific URL and an header, get the response from the target server
    fn get_http_response_using_headers(url: &str, header: Headers) -> Result<Response, Error>;
}

impl GetResponse for Client {
    fn get_http_response(url: &str) -> Result<Response, Error> {
        Client::new().request(Method::Get, url).send()
    }
    fn get_http_response_using_headers(url: &str,
                                       custom_header: Headers)
                                       -> Result<Response, Error> {
        Client::new().request(Method::Get, url).headers(custom_header).send()
    }
}<|endoftext|>


<commit_before><commit_msg>iter addrs<commit_after><|endoftext|>


<commit_before><commit_msg>Add function to delete a reference header entry<commit_after><|endoftext|>


<commit_before><commit_msg>Percent-encode fragments based on https://github.com/whatwg/url/pull/169<commit_after><|endoftext|>


<commit_before>use http::server::{Request, ResponseWriter};
use regex::Regex;
use collections::hashmap::HashMap;
use request;

/// A Route is the basic data structure that stores both the path
/// and the handler that gets executed for the route.
/// The path can contain variable pattern such as `user/:userid/invoices`
struct Route {
    pub path: String,
    pub handler: fn(request: request::Request, response: &mut ResponseWriter),
    pub variables: HashMap<String, uint>,
    matcher: Regex
}

impl Clone for Route {
    fn clone(&self) -> Route {
        Route {
            path: self.path.clone(),
            handler: self.handler,
            matcher: self.matcher.clone(),
            variables: self.variables.clone()
        }
    }
}

/// A RouteResult is what the router returns when `match_route` is called.
/// It contains the matched `route` and also a `params` property holding
/// a HashMap with the keys being the variable names and the value being the
/// evaluated string
struct RouteResult<'a> {
    pub route: &'a Route,
    pub params: HashMap<String, String>
}

/// The PathUtils collects some small helper methods that operate on the path
struct PathUtils;

static REGEX_VAR_SEQ: Regex            = regex!(r":([a-zA-Z0-9_-]*)");
static VARIABLE_SEQUENCE:&'static str  = "(.[a-zA-Z0-9_-]*)";
static REGEX_START:&'static str        = "^";
static REGEX_END:&'static str          = "$";

impl PathUtils {
    fn create_regex (route_path: &str) -> Regex {

        let result = REGEX_START.to_string()
                                .append(REGEX_VAR_SEQ.replace_all(route_path, VARIABLE_SEQUENCE).as_slice())
                                .append(REGEX_END);

        match Regex::new(result.as_slice()) {
            Ok(re) => re,
            Err(err) => fail!("{}", err)
        }
    }

    fn get_variable_info (route_path: &str) -> HashMap<String, uint> {

        // this is very imperative. Let's improve on that.
        let mut map = HashMap::new();
        let mut i = 0;
        for matched in REGEX_VAR_SEQ.captures_iter(route_path) {
            //std::io::stdout().write_line(matched.at(0));
            map.insert(matched.at(1).to_string(), i);
            i = i + 1;
        }

        map
    }
}

/// The Router's job is it to hold routes and to resolve them later against
/// concrete URLs

#[deriving(Clone)]
pub struct Router{
    pub routes: Vec<Route>,
}

impl Router {
    pub fn new () -> Router {
        Router {
            routes: Vec::new()
        }
    }

    pub fn add_route (&mut self, path: String, handler: fn(request: request::Request, response: &mut ResponseWriter)) -> () {
        let matcher = PathUtils::create_regex(path.as_slice());
        let variable_infos = PathUtils::get_variable_info(path.as_slice());
        let route = Route {
            path: path,
            matcher: matcher,
            handler: handler,
            variables: variable_infos
        };
        self.routes.push(route);
    }

    pub fn match_route<'a>(&'a self, path: String) -> Option<RouteResult<'a>> {
        let route = self.routes.iter().find(|item| item.matcher.is_match(path.as_slice()));

        // can we improve on all this nested stuff? Is this the intended way to handle it?
        match route {
            Some(r) => {
                match r.matcher.captures(path.as_slice()) {
                    Some(captures) => {
                        let mut map = HashMap::new();
                        for (name, pos) in r.variables.iter() {
                            map.insert(name.to_string(), captures.at(pos + 1).to_string());
                        }

                        Some(RouteResult {
                            route: r,
                            params: map
                        })
                    },
                    None => Some(RouteResult{
                        route: r,
                        params: HashMap::new()
                    })
                }
            },
            None => None
        }
    }
}

#[test]
fn creates_map_with_var_variable_infos () {
    let map = PathUtils::get_variable_info("foo/:uid/bar/:groupid");

    assert_eq!(map.len(), 2);
    assert_eq!(map.get(&"uid".to_string()), &0);
    assert_eq!(map.get(&"groupid".to_string()), &1);
}

#[test]
fn creates_regex_with_captures () {
    let regex = PathUtils::create_regex("foo/:uid/bar/:groupid");
    assert_eq!(regex.is_match("foo/4711/bar/5490"), true);

    let caps = regex.captures("foo/4711/bar/5490").unwrap();

    assert_eq!(caps.at(1), "4711");
    assert_eq!(caps.at(2), "5490");
    assert_eq!(regex.is_match("foo/"), false);
}

#[test]
fn can_match_var_routes () {
    let route_store = &mut Router::new();

    fn handler (request: request::Request, response: &mut ResponseWriter) -> () {
        response.write("hello from foo".as_bytes());
    };

    route_store.add_route("/foo/:userid".to_string(), handler);
    route_store.add_route("/bar".to_string(), handler);

    let route_result = route_store.match_route("/foo/4711".to_string()).unwrap();
    let route = route_result.route;

    assert_eq!(route_result.params.get(&"userid".to_string()), &"4711".to_string());

    //assert the route has identified the variable
    assert_eq!(route.variables.len(), 1);
    assert_eq!(route.variables.get(&"userid".to_string()), &0);

    let route_result = route_store.match_route("/bar/4711".to_string());

    let result = match route_result {
        Some(res) => true,
        None => false
    };

    assert_eq!(result, false);

    let route_result = route_store.match_route("/foo".to_string());

    let result = match route_result{
        Some(res) => true,
        None => false
    };

    assert_eq!(result, false);
}<commit_msg>refactor(router.rs): make it more functional<commit_after>use http::server::{Request, ResponseWriter};
use regex::Regex;
use collections::hashmap::HashMap;
use request;

/// A Route is the basic data structure that stores both the path
/// and the handler that gets executed for the route.
/// The path can contain variable pattern such as `user/:userid/invoices`
struct Route {
    pub path: String,
    pub handler: fn(request: request::Request, response: &mut ResponseWriter),
    pub variables: HashMap<String, uint>,
    matcher: Regex
}

impl Clone for Route {
    fn clone(&self) -> Route {
        Route {
            path: self.path.clone(),
            handler: self.handler,
            matcher: self.matcher.clone(),
            variables: self.variables.clone()
        }
    }
}

/// A RouteResult is what the router returns when `match_route` is called.
/// It contains the matched `route` and also a `params` property holding
/// a HashMap with the keys being the variable names and the value being the
/// evaluated string
struct RouteResult<'a> {
    pub route: &'a Route,
    pub params: HashMap<String, String>
}

/// The PathUtils collects some small helper methods that operate on the path
struct PathUtils;

static REGEX_VAR_SEQ: Regex            = regex!(r":([a-zA-Z0-9_-]*)");
static VARIABLE_SEQUENCE:&'static str  = "(.[a-zA-Z0-9_-]*)";
static REGEX_START:&'static str        = "^";
static REGEX_END:&'static str          = "$";

impl PathUtils {
    fn create_regex (route_path: &str) -> Regex {

        let result = REGEX_START.to_string()
                                .append(REGEX_VAR_SEQ.replace_all(route_path, VARIABLE_SEQUENCE).as_slice())
                                .append(REGEX_END);

        match Regex::new(result.as_slice()) {
            Ok(re) => re,
            Err(err) => fail!("{}", err)
        }
    }

    fn get_variable_info (route_path: &str) -> HashMap<String, uint> {
        REGEX_VAR_SEQ.captures_iter(route_path)
             .enumerate()
             .map(|(i, matched)| (matched.at(1).to_string(), i))
             .collect()
    }
}

/// The Router's job is it to hold routes and to resolve them later against
/// concrete URLs

#[deriving(Clone)]
pub struct Router{
    pub routes: Vec<Route>,
}

impl Router {
    pub fn new () -> Router {
        Router {
            routes: Vec::new()
        }
    }

    pub fn add_route (&mut self, path: String, handler: fn(request: request::Request, response: &mut ResponseWriter)) -> () {
        let matcher = PathUtils::create_regex(path.as_slice());
        let variable_infos = PathUtils::get_variable_info(path.as_slice());
        let route = Route {
            path: path,
            matcher: matcher,
            handler: handler,
            variables: variable_infos
        };
        self.routes.push(route);
    }

    pub fn match_route<'a>(&'a self, path: String) -> Option<RouteResult<'a>> {
        let route = self.routes.iter().find(|item| item.matcher.is_match(path.as_slice()));

        // can we improve on all this nested stuff? Is this the intended way to handle it?
        match route {
            Some(r) => {
                match r.matcher.captures(path.as_slice()) {
                    Some(captures) => {
                        let mut map = HashMap::new();
                        for (name, pos) in r.variables.iter() {
                            map.insert(name.to_string(), captures.at(pos + 1).to_string());
                        }

                        Some(RouteResult {
                            route: r,
                            params: map
                        })
                    },
                    None => Some(RouteResult{
                        route: r,
                        params: HashMap::new()
                    })
                }
            },
            None => None
        }
    }
}

#[test]
fn creates_map_with_var_variable_infos () {
    let map = PathUtils::get_variable_info("foo/:uid/bar/:groupid");

    assert_eq!(map.len(), 2);
    assert_eq!(map.get(&"uid".to_string()), &0);
    assert_eq!(map.get(&"groupid".to_string()), &1);
}

#[test]
fn creates_regex_with_captures () {
    let regex = PathUtils::create_regex("foo/:uid/bar/:groupid");
    assert_eq!(regex.is_match("foo/4711/bar/5490"), true);

    let caps = regex.captures("foo/4711/bar/5490").unwrap();

    assert_eq!(caps.at(1), "4711");
    assert_eq!(caps.at(2), "5490");
    assert_eq!(regex.is_match("foo/"), false);
}

#[test]
fn can_match_var_routes () {
    let route_store = &mut Router::new();

    fn handler (request: request::Request, response: &mut ResponseWriter) -> () {
        response.write("hello from foo".as_bytes());
    };

    route_store.add_route("/foo/:userid".to_string(), handler);
    route_store.add_route("/bar".to_string(), handler);

    let route_result = route_store.match_route("/foo/4711".to_string()).unwrap();
    let route = route_result.route;

    assert_eq!(route_result.params.get(&"userid".to_string()), &"4711".to_string());

    //assert the route has identified the variable
    assert_eq!(route.variables.len(), 1);
    assert_eq!(route.variables.get(&"userid".to_string()), &0);

    let route_result = route_store.match_route("/bar/4711".to_string());

    let result = match route_result {
        Some(res) => true,
        None => false
    };

    assert_eq!(result, false);

    let route_result = route_store.match_route("/foo".to_string());

    let result = match route_result{
        Some(res) => true,
        None => false
    };

    assert_eq!(result, false);
}<|endoftext|>


<commit_before><commit_msg>Factor password check into impl User.<commit_after><|endoftext|>


<commit_before>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
//! Set and unset common attributes on LLVM values.

use std::ffi::{CStr, CString};

use rustc::hir::{self, CodegenFnAttrFlags};
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::session::Session;
use rustc::session::config::Sanitizer;
use rustc::ty::TyCtxt;
use rustc::ty::query::Providers;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::PanicStrategy;

use attributes;
use llvm::{self, Attribute, ValueRef};
use llvm::AttributePlace::Function;
use llvm_util;
pub use syntax::attr::{self, InlineAttr};
use context::CodegenCx;

/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
    use self::InlineAttr::*;
    match inline {
        Hint   => Attribute::InlineHint.apply_llfn(Function, val),
        Always => Attribute::AlwaysInline.apply_llfn(Function, val),
        Never  => Attribute::NoInline.apply_llfn(Function, val),
        None   => {
            Attribute::InlineHint.unapply_llfn(Function, val);
            Attribute::AlwaysInline.unapply_llfn(Function, val);
            Attribute::NoInline.unapply_llfn(Function, val);
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
    Attribute::UWTable.toggle_llfn(Function, val, emit);
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
pub fn unwind(val: ValueRef, can_unwind: bool) {
    Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
}

/// Tell LLVM whether it should optimize function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
    Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
}

/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
#[inline]
pub fn naked(val: ValueRef, is_naked: bool) {
    Attribute::Naked.toggle_llfn(Function, val, is_naked);
}

pub fn set_frame_pointer_elimination(cx: &CodegenCx, llfn: ValueRef) {
    if cx.sess().must_not_eliminate_frame_pointers() {
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
            cstr("no-frame-pointer-elim\0"), cstr("true\0"));
    }
}

pub fn set_probestack(cx: &CodegenCx, llfn: ValueRef) {
    // Only use stack probes if the target specification indicates that we
    // should be using stack probes
    if !cx.sess().target.target.options.stack_probes {
        return
    }

    // Currently stack probes seem somewhat incompatible with the address
    // sanitizer. With asan we're already protected from stack overflow anyway
    // so we don't really need stack probes regardless.
    match cx.sess().opts.debugging_opts.sanitizer {
        Some(Sanitizer::Address) => return,
        _ => {}
    }

    // probestack doesn't play nice either with pgo-gen.
    if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
        return;
    }

    // Flag our internal `__rust_probestack` function as the stack probe symbol.
    // This is defined in the `compiler-builtins` crate for each architecture.
    llvm::AddFunctionAttrStringValue(
        llfn, llvm::AttributePlace::Function,
        cstr("probe-stack\0"), cstr("__rust_probestack\0"));
}

pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
    const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
        "crt-static",
    ];

    let cmdline = sess.opts.cg.target_feature.split(',')
        .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
    sess.target.target.options.features.split(',')
        .chain(cmdline)
        .filter(|l| !l.is_empty())
}

/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(cx: &CodegenCx, llfn: ValueRef, id: DefId) {
    let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(id);

    inline(llfn, codegen_fn_attrs.inline);

    set_frame_pointer_elimination(cx, llfn);
    set_probestack(cx, llfn);

    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
        Attribute::Cold.apply_llfn(Function, llfn);
    }
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
        naked(llfn, true);
    }
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
        Attribute::NoAlias.apply_llfn(
            llvm::AttributePlace::ReturnValue, llfn);
    }

    let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
        Some(true)
    } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
        Some(false)

    // Perhaps questionable, but we assume that anything defined
    // *in Rust code* may unwind. Foreign items like `extern "C" {
    // fn foo(); }` are assumed not to unwind **unless** they have
    // a `#[unwind]` attribute.
    } else if !cx.tcx.is_foreign_item(id) {
        Some(true)
    } else {
        None
    };

    match can_unwind {
        Some(false) => attributes::unwind(llfn, false),
        Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
            attributes::unwind(llfn, true);
        }
        Some(true) | None => {}
    }

    let features = llvm_target_features(cx.tcx.sess)
        .map(|s| s.to_string())
        .chain(
            codegen_fn_attrs.target_features
                .iter()
                .map(|f| {
                    let feature = &*f.as_str();
                    format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
                })
        )
        .collect::<Vec<String>>()
        .join(",");

    if !features.is_empty() {
        let val = CString::new(features).unwrap();
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
            cstr("target-features\0"), &val);
    }

    // Note that currently the `wasm-import-module` doesn't do anything, but
    // eventually LLVM 7 should read this and ferry the appropriate import
    // module to the output file.
    if cx.tcx.sess.target.target.arch == "wasm32" {
        if let Some(module) = wasm_import_module(cx.tcx, id) {
            llvm::AddFunctionAttrStringValue(
                llfn,
                llvm::AttributePlace::Function,
                cstr("wasm-import-module\0"),
                &module,
            );
        }
    }
}

fn cstr(s: &'static str) -> &CStr {
    CStr::from_bytes_with_nul(s.as_bytes()).expect("null-terminated string")
}

pub fn provide(providers: &mut Providers) {
    providers.target_features_whitelist = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            Lrc::new(llvm_util::all_known_features()
                .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
                .collect())
        } else {
            Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
                .iter()
                .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
                .collect())
        }
    };

    providers.wasm_custom_sections = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        let mut finder = WasmSectionFinder { tcx, list: Vec::new() };
        tcx.hir.krate().visit_all_item_likes(&mut finder);
        Lrc::new(finder.list)
    };

    provide_extern(providers);
}

struct WasmSectionFinder<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    list: Vec<DefId>,
}

impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for WasmSectionFinder<'a, 'tcx> {
    fn visit_item(&mut self, i: &'tcx hir::Item) {
        match i.node {
            hir::ItemConst(..) => {}
            _ => return,
        }
        if i.attrs.iter().any(|i| i.check_name("wasm_custom_section")) {
            self.list.push(self.tcx.hir.local_def_id(i.id));
        }
    }

    fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) {}

    fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) {}
}

pub fn provide_extern(providers: &mut Providers) {
    providers.wasm_import_module_map = |tcx, cnum| {
        let mut ret = FxHashMap();
        for lib in tcx.foreign_modules(cnum).iter() {
            let attrs = tcx.get_attrs(lib.def_id);
            let mut module = None;
            for attr in attrs.iter().filter(|a| a.check_name("wasm_import_module")) {
                module = attr.value_str();
            }
            let module = match module {
                Some(s) => s,
                None => continue,
            };
            for id in lib.foreign_items.iter() {
                assert_eq!(id.krate, cnum);
                ret.insert(*id, module.to_string());
            }
        }

        Lrc::new(ret)
    }
}

fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
    tcx.wasm_import_module_map(id.krate)
        .get(&id)
        .map(|s| CString::new(&s[..]).unwrap())
}
<commit_msg>Rollup merge of #51666 - marco-c:disable_probestack, r=nagisa<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
//! Set and unset common attributes on LLVM values.

use std::ffi::{CStr, CString};

use rustc::hir::{self, CodegenFnAttrFlags};
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::session::Session;
use rustc::session::config::Sanitizer;
use rustc::ty::TyCtxt;
use rustc::ty::query::Providers;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::PanicStrategy;

use attributes;
use llvm::{self, Attribute, ValueRef};
use llvm::AttributePlace::Function;
use llvm_util;
pub use syntax::attr::{self, InlineAttr};
use context::CodegenCx;

/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
    use self::InlineAttr::*;
    match inline {
        Hint   => Attribute::InlineHint.apply_llfn(Function, val),
        Always => Attribute::AlwaysInline.apply_llfn(Function, val),
        Never  => Attribute::NoInline.apply_llfn(Function, val),
        None   => {
            Attribute::InlineHint.unapply_llfn(Function, val);
            Attribute::AlwaysInline.unapply_llfn(Function, val);
            Attribute::NoInline.unapply_llfn(Function, val);
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
    Attribute::UWTable.toggle_llfn(Function, val, emit);
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
pub fn unwind(val: ValueRef, can_unwind: bool) {
    Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
}

/// Tell LLVM whether it should optimize function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
    Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
}

/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
#[inline]
pub fn naked(val: ValueRef, is_naked: bool) {
    Attribute::Naked.toggle_llfn(Function, val, is_naked);
}

pub fn set_frame_pointer_elimination(cx: &CodegenCx, llfn: ValueRef) {
    if cx.sess().must_not_eliminate_frame_pointers() {
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
            cstr("no-frame-pointer-elim\0"), cstr("true\0"));
    }
}

pub fn set_probestack(cx: &CodegenCx, llfn: ValueRef) {
    // Only use stack probes if the target specification indicates that we
    // should be using stack probes
    if !cx.sess().target.target.options.stack_probes {
        return
    }

    // Currently stack probes seem somewhat incompatible with the address
    // sanitizer. With asan we're already protected from stack overflow anyway
    // so we don't really need stack probes regardless.
    match cx.sess().opts.debugging_opts.sanitizer {
        Some(Sanitizer::Address) => return,
        _ => {}
    }

    // probestack doesn't play nice either with pgo-gen.
    if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
        return;
    }

    // probestack doesn't play nice either with gcov profiling.
    if cx.sess().opts.debugging_opts.profile {
        return;
    }

    // Flag our internal `__rust_probestack` function as the stack probe symbol.
    // This is defined in the `compiler-builtins` crate for each architecture.
    llvm::AddFunctionAttrStringValue(
        llfn, llvm::AttributePlace::Function,
        cstr("probe-stack\0"), cstr("__rust_probestack\0"));
}

pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
    const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
        "crt-static",
    ];

    let cmdline = sess.opts.cg.target_feature.split(',')
        .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
    sess.target.target.options.features.split(',')
        .chain(cmdline)
        .filter(|l| !l.is_empty())
}

/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(cx: &CodegenCx, llfn: ValueRef, id: DefId) {
    let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(id);

    inline(llfn, codegen_fn_attrs.inline);

    set_frame_pointer_elimination(cx, llfn);
    set_probestack(cx, llfn);

    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
        Attribute::Cold.apply_llfn(Function, llfn);
    }
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
        naked(llfn, true);
    }
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
        Attribute::NoAlias.apply_llfn(
            llvm::AttributePlace::ReturnValue, llfn);
    }

    let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
        Some(true)
    } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
        Some(false)

    // Perhaps questionable, but we assume that anything defined
    // *in Rust code* may unwind. Foreign items like `extern "C" {
    // fn foo(); }` are assumed not to unwind **unless** they have
    // a `#[unwind]` attribute.
    } else if !cx.tcx.is_foreign_item(id) {
        Some(true)
    } else {
        None
    };

    match can_unwind {
        Some(false) => attributes::unwind(llfn, false),
        Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
            attributes::unwind(llfn, true);
        }
        Some(true) | None => {}
    }

    let features = llvm_target_features(cx.tcx.sess)
        .map(|s| s.to_string())
        .chain(
            codegen_fn_attrs.target_features
                .iter()
                .map(|f| {
                    let feature = &*f.as_str();
                    format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
                })
        )
        .collect::<Vec<String>>()
        .join(",");

    if !features.is_empty() {
        let val = CString::new(features).unwrap();
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
            cstr("target-features\0"), &val);
    }

    // Note that currently the `wasm-import-module` doesn't do anything, but
    // eventually LLVM 7 should read this and ferry the appropriate import
    // module to the output file.
    if cx.tcx.sess.target.target.arch == "wasm32" {
        if let Some(module) = wasm_import_module(cx.tcx, id) {
            llvm::AddFunctionAttrStringValue(
                llfn,
                llvm::AttributePlace::Function,
                cstr("wasm-import-module\0"),
                &module,
            );
        }
    }
}

fn cstr(s: &'static str) -> &CStr {
    CStr::from_bytes_with_nul(s.as_bytes()).expect("null-terminated string")
}

pub fn provide(providers: &mut Providers) {
    providers.target_features_whitelist = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            Lrc::new(llvm_util::all_known_features()
                .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
                .collect())
        } else {
            Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
                .iter()
                .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
                .collect())
        }
    };

    providers.wasm_custom_sections = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        let mut finder = WasmSectionFinder { tcx, list: Vec::new() };
        tcx.hir.krate().visit_all_item_likes(&mut finder);
        Lrc::new(finder.list)
    };

    provide_extern(providers);
}

struct WasmSectionFinder<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    list: Vec<DefId>,
}

impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for WasmSectionFinder<'a, 'tcx> {
    fn visit_item(&mut self, i: &'tcx hir::Item) {
        match i.node {
            hir::ItemConst(..) => {}
            _ => return,
        }
        if i.attrs.iter().any(|i| i.check_name("wasm_custom_section")) {
            self.list.push(self.tcx.hir.local_def_id(i.id));
        }
    }

    fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) {}

    fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) {}
}

pub fn provide_extern(providers: &mut Providers) {
    providers.wasm_import_module_map = |tcx, cnum| {
        let mut ret = FxHashMap();
        for lib in tcx.foreign_modules(cnum).iter() {
            let attrs = tcx.get_attrs(lib.def_id);
            let mut module = None;
            for attr in attrs.iter().filter(|a| a.check_name("wasm_import_module")) {
                module = attr.value_str();
            }
            let module = match module {
                Some(s) => s,
                None => continue,
            };
            for id in lib.foreign_items.iter() {
                assert_eq!(id.krate, cnum);
                ret.insert(*id, module.to_string());
            }
        }

        Lrc::new(ret)
    }
}

fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
    tcx.wasm_import_module_map(id.krate)
        .get(&id)
        .map(|s| CString::new(&s[..]).unwrap())
}
<|endoftext|>


<commit_before>use std::error::Error;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};

generate_error_types!(ViewError, ViewErrorKind,
    StoreError     => "Store error",
    NoVersion      => "No version specified",
    PatternError   => "Error in Pattern",
    GlobBuildError => "Could not build glob() Argument"
);

<commit_msg>imag-view: Replace error module imports with macro helper<commit_after>generate_error_imports!();

generate_error_types!(ViewError, ViewErrorKind,
    StoreError     => "Store error",
    NoVersion      => "No version specified",
    PatternError   => "Error in Pattern",
    GlobBuildError => "Could not build glob() Argument"
);

<|endoftext|>


<commit_before><commit_msg>Add enum to represent store action<commit_after>pub enum StoreAction {
    Create,
    Retrieve,
    Update,
    Delete,

    // "Read" doesn't matter, as we do not use git on read actions, only when altering content.
}
<|endoftext|>


<commit_before><commit_msg>Add 404 handler.<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for issue 53820<commit_after>// check-pass
#![feature(slice_patterns)]

fn main() {
    const LARGE_SIZE: usize = 1024 * 1024;
    let [..] = [0u8; LARGE_SIZE];
    match [0u8; LARGE_SIZE] {
        [..] => {}
    }
}
<|endoftext|>


<commit_before><commit_msg>Add iteration tests<commit_after><|endoftext|>


<commit_before><commit_msg>Initial import<commit_after>extern mod png;

use std::num::{sqrt, min, max, cos, sin};

static WIDTH: int = 800;
static HEIGHT: int = 800;

struct Color {
  r: u8,
  g: u8,
  b: u8
}

static Red: Color = Color { r: 255, g: 0, b: 0 };
static Green: Color = Color { r: 0, g: 255, b: 0 };
static Blue: Color = Color { r: 0, g: 0, b: 255 };
static White: Color = Color { r: 255, g: 255, b: 255 };
static Black: Color = Color { r: 0, g: 0, b: 0 };

struct Point {
  x: f64,
  y: f64,
  z: f64
}

struct Spot {
  pos: Point,
  color: Color,
}

struct Scene {
  eye: Point,
  spot: Spot,
  objects: ~[Shape]
}

fn solve_poly(a: f64, b: f64, c: f64) -> f64 {
  let delta = b.pow(&2.0) - 4. * a * c;

  if delta < 0. {
    return 0.;
  }

  let sign = match c {
    _ if c < 0. => 1.,
    _ => -1.
  };
  let k = (-b + sign * sqrt(delta)) / (2. * a);
  return match k {
    _ if k > 0. => k,
    _ => 0.
  }
}

trait Drawable {
  fn hit(&self, eye: &Point, vector: &Point) -> f64;
  fn perp(&self, inter: &Point) -> ~Point;
}

struct Shape {
  pos: Point,
  shininess: f64,
  color: Color,
  shape: ~Drawable
}

impl Shape {
  fn get_light(&self, spot: &Spot, inter: &Point, light: &Point) -> Color {
    let perp = self.shape.perp(inter);
    let norme_l = sqrt(light.x.pow(&2.) + light.y.pow(&2.) + light.z.pow(&2.));
    let norme_n = sqrt(perp.x.pow(&2.) + perp.y.pow(&2.) + perp.z.pow(&2.));
    let cos_a = (light.x * perp.x + light.y * perp.y + light.z * perp.z) / (norme_l * norme_n);

    if cos_a <= 0. {
      return Black;
    }

    Color {
      r: ((self.color.r as f64) * cos_a * (1. - self.shininess) + (spot.color.r as f64) * cos_a * self.shininess) as u8,
      g: ((self.color.g as f64) * cos_a * (1. - self.shininess) + (spot.color.g as f64) * cos_a * self.shininess) as u8,
      b: ((self.color.b as f64) * cos_a * (1. - self.shininess) + (spot.color.b as f64) * cos_a * self.shininess) as u8
    }
  }
}

struct Sphere {
  radius: f64,
}

impl Drawable for Sphere {
  fn hit(&self, eye: &Point, vector: &Point) -> f64 {
    let a = vector.x.pow(&2.) + vector.y.pow(&2.) + vector.z.pow(&2.);
    let b = 2. * (eye.x * vector.x + eye.y * vector.y + eye.z * vector.z);
    let c = eye.x.pow(&2.) + eye.y.pow(&2.) + eye.z.pow(&2.) - self.radius.pow(&2.);
    return solve_poly(a, b, c);
  }

  fn perp(&self, inter: &Point) -> ~Point {
    ~Point { x: inter.x, y: inter.y, z: inter.z }
  }
}

struct Plane;

impl Drawable for Plane {
  fn hit(&self, eye: &Point, vector: &Point) -> f64 {
    match -eye.z / vector.z {
      k if k > 0. => k,
      _ => 0.
    }
  }

  fn perp(&self, inter: &Point) -> ~Point {
    ~Point { x: 0., y: 0., z: 100. }
  }
}

impl Scene {
  fn get_closest<'a>(&'a self, vector: &'a Point) -> (Option<&'a Shape>, f64) {
    let mut min: f64 = 0.;
    let mut closest: Option<&'a Shape> = None;

    for obj in self.objects.iter() {
      let e = Point { x: self.eye.x - obj.pos.x, y: self.eye.y - obj.pos.y, z: self.eye.z - obj.pos.z };
      let v = Point { x: vector.x, y: vector.y, z: vector.z };
      let k = obj.shape.hit(&e, &v);
      if k != 0. && (min == 0. || k < min) {
        min = k;
        closest = Some(obj);
      }
    }

    return (closest, min);
  }
}

fn main() {
  let mut pixels = ~[Black, ..((WIDTH * HEIGHT) as uint)];

  let scene = ~Scene {
    eye: Point { x: -300., y: 0., z: 200. },
    spot: Spot {
      pos: Point { x: -300., y: 100., z: 200. },
      color: White
    },
    objects: ~[
      // Shape {
      //   pos: Point { x: 0., y: 0., z: 100. },
      //   shininess: 0.2,
      //   color: Red,
      //   shape: ~Sphere { radius: 160. }
      // },
      Shape {
        pos: Point { x: 0., y: 0., z: 0.},
        shininess: 0.1,
        color: Green,
        shape: ~Plane
      },
    ]
  };

  for x in range(0, WIDTH) {
    for y in range(0, HEIGHT) {
      let vector = ~Point {
        x: 100.,
        y: (WIDTH / 2 - x) as f64,
        z: (HEIGHT / 2 - y) as f64
      };

      let (obj, k) = scene.get_closest(vector);

      if obj.is_none() {
        pixels[y * WIDTH + x] = Black;
      }
      else {
        let closest = obj.unwrap();

        // // Shadow
        // let inter = Point {
        //   x: eye.x + closest * vector.x,
        //   y: eye.y + closest * vector.y,
        //   z: eye.z + closest * vector.z
        // };
        // let light = Point {
        //   x: spot.pos.x - inter.x,
        //   y: spot.pos.y - inter.y,
        //   z: spot.pos.z - inter.z
        // };

        let inter = ~Point {
          x: (scene.eye.x - closest.pos.x) + k * vector.x,
          y: (scene.eye.y - closest.pos.y) + k * vector.y,
          z: (scene.eye.z - closest.pos.z) + k * vector.z
        };
        let light = ~Point {
          x: scene.spot.pos.x - inter.x,
          y: scene.spot.pos.y - inter.y,
          z: scene.spot.pos.z - inter.z
        };

        pixels[y * WIDTH + x] = match k {
          0. => Black,
          _ => closest.get_light(&scene.spot, inter, light)
        }
      }
    }
  }

  let img = png::Image {
    width: WIDTH as u32,
    height: HEIGHT as u32,
    color_type: png::RGB8,
    pixels: pixels.flat_map(|&Color { r, g, b }| { ~[r, g, b] })
  };

  png::store_png(&img, &Path::new("out.png"));
}
<|endoftext|>


<commit_before><commit_msg>client-id must be used by only one connection at a time.<commit_after><|endoftext|>


<commit_before><commit_msg>Use target_os instead of cfg(redox)<commit_after><|endoftext|>


<commit_before><commit_msg>Add test<commit_after>extern crate tempdir;
extern crate delta_l;

use delta_l::{DeltaL, Mode};
use tempdir::TempDir;

use std::fs::File;
use std::path::Path;
use std::io::{Write, Read, Result as IOResult};

#[test]
fn decrypt_is_orignal(){
    let dir = TempDir::new("delta-l_test-").unwrap();

    let original_path = &dir.path().join("test.txt");
    let mut original = File::create(original_path).unwrap();
    write!(original, "Hello World!\nI'm a test!").unwrap();

    let res_path = &dir.path().join("test.txt.delta");
    let res_vec = DeltaL::new(Mode::Encrypt{checksum: true}).execute(original_path).unwrap();
    save(res_vec, res_path).unwrap();

    let dec_vec = DeltaL::new(Mode::Decrypt).execute(res_path).unwrap();

    let original_vec = read(original_path).unwrap();

    assert_eq!(original_vec, dec_vec);
}

fn save(res_vec: Vec<u8>, to_path: &Path) -> IOResult<()>{
    let mut result_file = try!(File::create(to_path));

    result_file.write_all(&res_vec)
}

fn read(from_path: &Path) -> IOResult<Vec<u8>>{
    let mut f = try!(File::open(from_path));
    let mut buffer = Vec::<u8>::new();

    try!(f.read_to_end(&mut buffer));

    Ok(buffer)
}
<|endoftext|>


<commit_before><commit_msg>List Combos: Optimize a few things<commit_after><|endoftext|>


<commit_before><commit_msg>Initial commit with CPU<commit_after><|endoftext|>


<commit_before><commit_msg>add color<commit_after>#[derive(Copy, Clone, Debug)]
pub struct Color(f32, f32, f32, f32);

impl Color {
    /// Scale the brightness of the color
    pub fn scale(self, factor: f32) -> Color {
        Color(self.0 * factor, self.1 * factor, self.2 * factor, self.3)
    }

    /// Scale the brightness of the color
    pub fn alpha(self, factor: f32) -> Color {
        Color(self.0, self.1, self.2, self.3 * factor)
    }
}

impl From<(u8, u8, u8, u8)> for Color {
    fn from(tup: (u8, u8, u8, u8)) -> Color {
        Color(
            tup.0 as f32 / 255.0,
            tup.1 as f32 / 255.0,
            tup.2 as f32 / 255.0,
            tup.3 as f32 / 255.0,
        )
    }
}

impl From<[u8; 4]> for Color {
    fn from(arr: [u8; 4]) -> Color {
        Color(
            arr[0] as f32 / 255.0,
            arr[1] as f32 / 255.0,
            arr[2] as f32 / 255.0,
            arr[3] as f32 / 255.0,
        )
    }
}

impl From<(f32, f32, f32, f32)> for Color {
    fn from(tup: (f32, f32, f32, f32)) -> Color {
        Color(tup.0, tup.1, tup.2, tup.3)
    }
}

impl From<[f32; 4]> for Color {
    fn from(arr: [f32; 4]) -> Color {
        Color(arr[0], arr[1], arr[2], arr[3])
    }
}

pub const WHITE: Color = Color(0.0, 0.0, 1.0, 1.0);
pub const RED: Color = Color(1.0, 0.0, 0.0, 1.0);
pub const GREEN: Color = Color(0.0, 1.0, 0.0, 1.0);
pub const BLUE: Color = Color(0.0, 0.0, 1.0, 1.0);
pub const YELLOW: Color = Color(1.0, 1.0, 0.0, 1.0);
pub const CYAN: Color = Color(0.0, 1.0, 1.0, 1.0);
pub const MAGENTA: Color = Color(1.0, 0.0, 1.0, 1.0);
<|endoftext|>


<commit_before>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_void;
use ptr::null;
use str::as_c_str;
use ptr::addr_of;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_t = *mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_t);
  fn __gmpz_clear(x: mpz_t);
  fn __gmpz_set_str(rop: mpz_t, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_t) -> *c_char;
  fn __gmpz_sizeinbase(op: mpz_t, base: c_int) -> size_t;
  fn __gmpz_cmp(op: mpz_t, op2: mpz_t) -> c_int;
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

fn init() -> Mpz {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(addr_of(&mpz));
  Mpz { mpz: mpz }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }
  #[test]
  fn eq() {
    let x = init();
    x.set_str("4242142195", 10);
    let y = init();
    y.set_str("4242142195", 10);
    let z = init();
    z.set_str("4242142196", 10);

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }
  #[test]
  fn ord() {
    let x = init();
    x.set_str("40000000000000000000000", 10);
    let y = init();
    y.set_str("45000000000000000000000", 10);
    let z = init();
    z.set_str("50000000000000000000000", 10);

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }
}
<commit_msg>implement the Num trait<commit_after>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use ptr::null;
use ptr::addr_of;
use str::as_c_str;
use str::to_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_t = *mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_t);
  fn __gmpz_clear(x: mpz_t);
  fn __gmpz_set_str(rop: mpz_t, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_t) -> *c_char;
  fn __gmpz_sizeinbase(op: mpz_t, base: c_int) -> size_t;
  fn __gmpz_cmp(op: mpz_t, op2: mpz_t) -> c_int;
  fn __gmpz_cmp_ui(op1: mpz_t, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_t, op1: mpz_t, op2: mpz_t);
  fn __gmpz_sub(rop: mpz_t, op1: mpz_t, op2: mpz_t);
  fn __gmpz_mul(rop: mpz_t, op1: mpz_t, op2: mpz_t);
  fn __gmpz_neg(rop: mpz_t, op: mpz_t);
  fn __gmpz_tdiv_q(r: mpz_t, n: mpz_t, d: mpz_t);
  fn __gmpz_mod(r: mpz_t, n: mpz_t, d: mpz_t);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool unsafe {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz unsafe {
    fail ~"not implemented";
  }
}

fn init() -> Mpz {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(addr_of(&mpz));
  Mpz { mpz: mpz }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }

  #[test]
  fn eq() {
    let x = init();
    x.set_str("4242142195", 10);
    let y = init();
    y.set_str("4242142195", 10);
    let z = init();
    z.set_str("4242142196", 10);

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = init();
    x.set_str("40000000000000000000000", 10);
    let y = init();
    y.set_str("45000000000000000000000", 10);
    let z = init();
    z.set_str("50000000000000000000000", 10);

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x = init();
    let y = init();
    let mut z: Mpz;

    x.set_str("2", 10);
    y.set_str("3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / 3) == 0);

    x.set_str("2", 10);
    y.set_str("-3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / -3) == 0);
  }
}
<|endoftext|>


<commit_before><commit_msg>Initial 0 opcode support + syntax problems<commit_after><|endoftext|>


<commit_before><commit_msg>Initial import.<commit_after>
enum State {
    Name,
    Seq,
    Qual
}

#[deriving(Default)]
struct Record {
    name: String,
    seq: String,
    qual: String
}

fn read_fastq(file) {
    let (tx, rx) = channel();
    spawn(move || {
        let mut record : Record = None;
        for (i, line) in file.lines().enumerate() {
            match i % 4 {
                0 => {
                    if record != None {
                        tx.send(record);
                    }
                    record = Record();
                    record.name = line[1..-1];
                },
                1 => { record.seq = line; },
                2 => { skip; },
                3 => { record.qual = line; }
            }
        }
    });
    rx;
}

fn read_fastq(file) {
    let mut state = State::Name;
    let mut record = Nil;

    for (i, line) in file.lines().enumerate() {
        if line[0] == '>' and state != State::Seq {

        }
        match line[0] {
            '>' => {
                state = State::Name;
            },
            '+' => {
                state = State::Qual;
            },
            _ => {

            }
        }
        match state {
            State::Name => {
                if line[0] == '>' {
                    record = Record::new(line[1:]);
                    state = State::Seq;
                }
                // TODO error reporting
            },
            State::Seq => {
                if line[0] == '+' {
                    state = State::Qual;
                }
                else {
                    seq += line[:-1];
                }
            },
            State::Qual => {

            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Expose an RNG (the one used by our runtime) to Rust via std.<commit_after>/**
 * Bindings the runtime's random number generator (ISAAC).
 */

native "rust" mod rustrt {
  type rctx;
  fn rand_new() -> rctx;
  fn rand_next(rctx c) -> u32;
  fn rand_free(rctx c);
}

type rng = obj { fn next() -> u32; };

fn mk_rng() -> rng {
  obj rt_rng(rustrt.rctx c) {
    fn next() -> u32 {
      ret rustrt.rand_next(c);
    }
    drop {
      rustrt.rand_free(c);
    }
  }

  ret rt_rng(rustrt.rand_new());
}
<|endoftext|>


<commit_before><commit_msg>Add the little welcome line back in<commit_after><|endoftext|>


<commit_before><commit_msg>add test for nested macro def (#31946)<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

fn main() {
    println!("{}", {
        macro_rules! foo {
            ($name:expr) => { concat!("hello ", $name) }
        }
        foo!("rust")
    });
}
<|endoftext|>


<commit_before><commit_msg>cargo fmt<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Trigger needs to be a bitflags because oneshotness is independent from edge/level-triggering apparently"<commit_after><|endoftext|>


<commit_before><commit_msg>Implemented IdRange type<commit_after>use std::collections::HashSet;
use regex::Regex;

use rocket::request::FromParam;
use rocket::http::RawStr;

#[derive(Debug)]
pub struct IdRange(HashSet<u32>);

impl<'req> FromParam<'req> for IdRange {
    type Error = ();

    fn from_param(param: &'req RawStr) -> Result<Self, Self::Error> {

        let term_regex = Regex::new("(?P<from>[0-9]+)(?::(?P<to>[0-9]+))?").expect("invalid regex");

        let mut range = IdRange(HashSet::new());

        for term in param.split(",") {
            let caps = term_regex.captures(term).ok_or(())?;

            let from_str = caps.name("from").ok_or(())?.as_str();
            let from = from_str.parse().map_err(|_| ())?;

            if let Some(to_match) = caps.name("to") {
                let to = to_match.as_str().parse().map_err(|_| ())?;

                let (from, to) = if from <= to {
                    (from, to)
                } else {
                    (to, from)
                };

                for i in from..=to {
                    range.0.insert(i);
                }

            } else {
                range.0.insert(from);
            }
        }

        Ok(range)
    }
}
<|endoftext|>


<commit_before><commit_msg>examples/curl-easy2-report: introduce report example with Curl::Easy2<commit_after>use threescalers::{
    api_call::*,
    application::*,
    credentials::*,
    extensions::Extensions,
    http::{
        request::SetupRequest,
        Request,
    },
    service::*,
    transaction::Transaction,
    usage::Usage,
};

use threescalers::http::request::curl::BodyHandle;

use curl::easy::Easy2;

fn main() -> Result<(), threescalers::errors::Error> {
    let creds = Credentials::ServiceToken(ServiceToken::from("12[3]token"));
    let svc = Service::new("svc123", creds);
    let uks = ["userkey_1", "userkey_2", "userkey_3", "userkey 4", "userkey 5"];
    let apps = uks.into_iter()
                  .map(|uk| Application::from(UserKey::from(*uk)))
                  .collect::<Vec<_>>();

    println!("Apps: {:#?}", apps);

    let usages = [("metric11", 11),
                  ("metric12", 12),
                  ("metric21", 21),
                  ("metric22", 22),
                  ("metric31", 31),
                  ("metric32", 32),
                  ("metric41", 41),
                  ("metric42", 42),
                  ("metric51", 51),
                  ("metric52", 52)].chunks(2)
                                   .map(|metrics_and_values| Usage::new(metrics_and_values))
                                   .collect::<Vec<_>>();

    println!("Usages: {:#?}", usages);

    let ts = Default::default();

    let txns = apps.iter()
                   .zip(&usages)
                   .map(|(a, u)| Transaction::new(a, None, Some(u), Some(&ts)))
                   .collect::<Vec<_>>();

    let mut extensions = Extensions::new();
    extensions.insert("no_body", "1");
    extensions.insert("testing[=]", "0[=:=]0");
    let mut apicall = ApiCall::builder(&svc);
    let apicall = apicall.transactions(&txns)
                         .extensions(&extensions)
                         .kind(Kind::Report)
                         .build()?;
    let request = Request::from(&apicall);

    println!("apicall: {:#?}", apicall);
    println!("request: {:#?}", request);

    let _ = run_request(request);

    Ok(())
}

fn run_request(request: Request) -> Result<(), curl::Error> {
    let mut client = Easy2::new(BodyHandle::new());
    let _ = client.verbose(true).unwrap();
    client.setup_request(request, "https://echo-api.3scale.net");
    let result = exec_request(&client);
    show_response(client, result)
}

fn exec_request<H: std::fmt::Debug>(curlc: &Easy2<H>) -> Result<(), curl::Error> {
    println!("Client Easy2: {:#?}", curlc);
    curlc.perform()
}

// Not looking directly at the response but using the verbose mode.
fn show_response<H: std::fmt::Debug>(curlc: Easy2<H>,
                                     res: Result<(), curl::Error>)
                                     -> Result<(), curl::Error> {
    match res {
        Ok(_) => {
            println!("*** SUCCESS ***\n{:#?}", curlc);
            Ok(())
        }
        Err(e) => {
            println!("*** ERROR ***\n{:#?}", e);
            Err(e)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Created thread. Does not yet actually do anything...<commit_after><|endoftext|>


<commit_before>use codemap::span;
use ext::base::ext_ctxt;
use ast::tt_delim;
use parse::lexer::{new_tt_reader, reader};
use parse::parser::Parser;
use parse::common::parser_common;

fn expand_trace_macros(cx: ext_ctxt, sp: span,
                       tt: ~[ast::token_tree]) -> base::mac_result
{
    let sess = cx.parse_sess();
    let cfg = cx.cfg();
    let tt_rdr = new_tt_reader(cx.parse_sess().span_diagnostic,
                               cx.parse_sess().interner, None, tt);
    let rdr = tt_rdr as reader;
    let rust_parser = Parser(sess, cfg, rdr.dup());

    let arg = cx.str_of(rust_parser.parse_ident());
    match arg {
      ~"true"  => cx.set_trace_macros(true),
      ~"false" => cx.set_trace_macros(false),
      _ => cx.span_fatal(sp, ~"trace_macros! only accepts `true` or `false`")
    }
    let rust_parser = Parser(sess, cfg, rdr.dup());
    let result = rust_parser.parse_expr();
    base::mr_expr(result)
}
<commit_msg>Fix trace_macros so that it works.<commit_after>use codemap::span;
use ext::base::ext_ctxt;
use ast::tt_delim;
use parse::lexer::{new_tt_reader, reader};
use parse::parser::Parser;
use parse::common::parser_common;

fn expand_trace_macros(cx: ext_ctxt, sp: span,
                       tt: ~[ast::token_tree]) -> base::mac_result
{
    let sess = cx.parse_sess();
    let cfg = cx.cfg();
    let tt_rdr = new_tt_reader(cx.parse_sess().span_diagnostic,
                               cx.parse_sess().interner, None, tt);
    let rdr = tt_rdr as reader;
    let rust_parser = Parser(sess, cfg, rdr.dup());

    if rust_parser.is_keyword(~"true") {
        cx.set_trace_macros(true);
    } else if rust_parser.is_keyword(~"false") {
        cx.set_trace_macros(false);
    } else {
        cx.span_fatal(sp, ~"trace_macros! only accepts `true` or `false`")
    }

    rust_parser.bump();

    let rust_parser = Parser(sess, cfg, rdr.dup());
    let result = rust_parser.parse_expr();
    base::mr_expr(result)
}
<|endoftext|>


<commit_before><commit_msg>add volume method and change play to play_once<commit_after><|endoftext|>


<commit_before><commit_msg>Adds Rust Problem 25<commit_after>/// Problem 25
/// The Fibonacci sequence is defined by the recurrence relation:
///
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
///
/// 		F1 = 1
/// 		F2 = 1
/// 		F3 = 2
/// 		F4 = 3
/// 		F5 = 5
/// 		F6 = 8
/// 		F7 = 13
/// 		F8 = 21
/// 		F9 = 34
/// 		F10 = 55
/// 		F11 = 89
/// 		F12 = 144
///
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the index of the first term in the Fibonacci sequence to contain
/// 1000 digits?
fn main() {
	let mut a: Vec<u8> = vec![1];
	let mut b: Vec<u8> = vec![1];
	let mut c: Vec<u8> = vec![2];
	let mut i: u64 = 3;
	loop {
		// Vector digit addition
		let mut rem: u8 = 0;
		c.clear();
		let mut j = 0;
		loop {
			let mut s = rem;
			if j < a.len() {
				s += a[j];
			}
			if j < b.len() {
				s += b[j];
			}
			c.push(s%10);
			rem = s / 10;
			j += 1;
			if j >= a.len() && j >= b.len() && rem == 0 {
				break
			}
		}
		if c.len() >= 1000 {
			println!("Answer: {}", i);
			// println!("{:?}", c);
			break
		}
		a = b.to_vec();
		b = c.to_vec();
		i += 1;
	}
}
<|endoftext|>


<commit_before><commit_msg>More 8 opcodes<commit_after><|endoftext|>


<commit_before><commit_msg>prettier indentation for bitflags<commit_after><|endoftext|>


<commit_before><commit_msg>Add Error enum<commit_after>use std::fmt::{Display, Formatter, Result as FmtResult};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
use iron::prelude::*;
use iron::status::Status;
use iron::headers::{ContentType};
use iron::modifiers::Header;
use iron::mime::Mime;
use std::str::FromStr;

#[derive(Debug)]
pub enum Error {
    BadRequest,
    Unprocessable,
    NotFound,
    Unexpected,
}

impl Error {
    pub fn status(&self) -> Status {
        match *self {
            Error::BadRequest    => Status::BadRequest,
            Error::Unprocessable => Status::UnprocessableEntity,
            Error::NotFound      => Status::NotFound,
            Error::Unexpected    => Status::InternalServerError,
        }
    }

    pub fn as_response(&self) -> Response {
        let json_type = Header(ContentType(Mime::from_str("application/json").ok().unwrap()));
        Response::with((self.status(),
                        json_type,
                        self.to_json().to_string()))
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match *self {
            Error::BadRequest    => write!(f, "BadRequest"),
            Error::Unprocessable => write!(f, "Unproccesable"),
            Error::NotFound      => write!(f, "NotFound"),
            Error::Unexpected    => write!(f, "UnexpectedError"),
        }
    }
}

impl ToJson for Error {
    fn to_json(&self) -> Json {
        let mut d = BTreeMap::new();
        d.insert("message".to_string(), self.to_string().to_json());
        Json::Object(d)
    }
}

<|endoftext|>


<commit_before><commit_msg>Make more AST members public<commit_after><|endoftext|>