<commit_before>// Copyright 2012-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.

use super::*;

pub(crate) struct JsonFormatter<T> {
    out: OutputLocation<T>,
}

impl<T: Write> JsonFormatter<T> {
    pub fn new(out: OutputLocation<T>) -> Self {
        Self { out }
    }

    fn write_message(&mut self, s: &str) -> io::Result<()> {
        assert!(!s.contains('\n'));

        self.out.write_all(s.as_ref())?;
        self.out.write_all(b"\n")
    }

    fn write_event(
        &mut self,
        ty: &str,
        name: &str,
        evt: &str,
        extra: Option<String>,
    ) -> io::Result<()> {
        if let Some(extras) = extra {
            self.write_message(&*format!(
                r#"{{ "type": "{}", "name": "{}", "event": "{}", {} }}"#,
                ty, name, evt, extras
            ))
        } else {
            self.write_message(&*format!(
                r#"{{ "type": "{}", "name": "{}", "event": "{}" }}"#,
                ty, name, evt
            ))
        }
    }
}

impl<T: Write> OutputFormatter for JsonFormatter<T> {
    fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "suite", "event": "started", "test_count": {} }}"#,
            test_count
        ))
    }

    fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "test", "event": "started", "name": "{}" }}"#,
            desc.name
        ))
    }

    fn write_result(
        &mut self,
        desc: &TestDesc,
        result: &TestResult,
        stdout: &[u8],
    ) -> io::Result<()> {
        match *result {
            TrOk => self.write_event("test", desc.name.as_slice(), "ok", None),

            TrFailed => {
                let extra_data = if stdout.len() > 0 {
                    Some(format!(
                        r#""stdout": "{}""#,
                        EscapedString(String::from_utf8_lossy(stdout))
                    ))
                } else {
                    None
                };

                self.write_event("test", desc.name.as_slice(), "failed", extra_data)
            }

            TrFailedMsg(ref m) => self.write_event(
                "test",
                desc.name.as_slice(),
                "failed",
                Some(format!(r#""message": "{}""#, EscapedString(m))),
            ),

            TrIgnored => self.write_event("test", desc.name.as_slice(), "ignored", None),

            TrAllowedFail => {
                self.write_event("test", desc.name.as_slice(), "allowed_failure", None)
            }

            TrBench(ref bs) => {
                let median = bs.ns_iter_summ.median as usize;
                let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize;

                let mbps = if bs.mb_s == 0 {
                    String::new()
                } else {
                    format!(r#", "mib_per_second": {}"#, bs.mb_s)
                };

                let line = format!(
                    "{{ \"type\": \"bench\", \
                     \"name\": \"{}\", \
                     \"median\": {}, \
                     \"deviation\": {}{} }}",
                    desc.name, median, deviation, mbps
                );

                self.write_message(&*line)
            }
        }
    }

    fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "test", "event": "timeout", "name": "{}" }}"#,
            desc.name
        ))
    }

    fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
        self.write_message(&*format!(
            "{{ \"type\": \"suite\", \
             \"event\": \"{}\", \
             \"passed\": {}, \
             \"failed\": {}, \
             \"allowed_fail\": {}, \
             \"ignored\": {}, \
             \"measured\": {}, \
             \"filtered_out\": \"{}\" }}",
            if state.failed == 0 { "ok" } else { "failed" },
            state.passed,
            state.failed + state.allowed_fail,
            state.allowed_fail,
            state.ignored,
            state.measured,
            state.filtered_out
        ))?;

        Ok(state.failed == 0)
    }
}

/// A formatting utility used to print strings with characters in need of escaping.
/// Base code taken form `libserialize::json::escape_str`
struct EscapedString<S: AsRef<str>>(S);

impl<S: AsRef<str>> ::std::fmt::Display for EscapedString<S> {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        let mut start = 0;

        for (i, byte) in self.0.as_ref().bytes().enumerate() {
            let escaped = match byte {
                b'"' => "\\\"",
                b'\\' => "\\\\",
                b'\x00' => "\\u0000",
                b'\x01' => "\\u0001",
                b'\x02' => "\\u0002",
                b'\x03' => "\\u0003",
                b'\x04' => "\\u0004",
                b'\x05' => "\\u0005",
                b'\x06' => "\\u0006",
                b'\x07' => "\\u0007",
                b'\x08' => "\\b",
                b'\t' => "\\t",
                b'\n' => "\\n",
                b'\x0b' => "\\u000b",
                b'\x0c' => "\\f",
                b'\r' => "\\r",
                b'\x0e' => "\\u000e",
                b'\x0f' => "\\u000f",
                b'\x10' => "\\u0010",
                b'\x11' => "\\u0011",
                b'\x12' => "\\u0012",
                b'\x13' => "\\u0013",
                b'\x14' => "\\u0014",
                b'\x15' => "\\u0015",
                b'\x16' => "\\u0016",
                b'\x17' => "\\u0017",
                b'\x18' => "\\u0018",
                b'\x19' => "\\u0019",
                b'\x1a' => "\\u001a",
                b'\x1b' => "\\u001b",
                b'\x1c' => "\\u001c",
                b'\x1d' => "\\u001d",
                b'\x1e' => "\\u001e",
                b'\x1f' => "\\u001f",
                b'\x7f' => "\\u007f",
                _ => {
                    continue;
                }
            };

            if start < i {
                f.write_str(&self.0.as_ref()[start..i])?;
            }

            f.write_str(escaped)?;

            start = i + 1;
        }

        if start != self.0.as_ref().len() {
            f.write_str(&self.0.as_ref()[start..])?;
        }

        Ok(())
    }
}
<commit_msg>Make json test output formatter represent "filtered_out" as num<commit_after>// Copyright 2012-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.

use super::*;

pub(crate) struct JsonFormatter<T> {
    out: OutputLocation<T>,
}

impl<T: Write> JsonFormatter<T> {
    pub fn new(out: OutputLocation<T>) -> Self {
        Self { out }
    }

    fn write_message(&mut self, s: &str) -> io::Result<()> {
        assert!(!s.contains('\n'));

        self.out.write_all(s.as_ref())?;
        self.out.write_all(b"\n")
    }

    fn write_event(
        &mut self,
        ty: &str,
        name: &str,
        evt: &str,
        extra: Option<String>,
    ) -> io::Result<()> {
        if let Some(extras) = extra {
            self.write_message(&*format!(
                r#"{{ "type": "{}", "name": "{}", "event": "{}", {} }}"#,
                ty, name, evt, extras
            ))
        } else {
            self.write_message(&*format!(
                r#"{{ "type": "{}", "name": "{}", "event": "{}" }}"#,
                ty, name, evt
            ))
        }
    }
}

impl<T: Write> OutputFormatter for JsonFormatter<T> {
    fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "suite", "event": "started", "test_count": {} }}"#,
            test_count
        ))
    }

    fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "test", "event": "started", "name": "{}" }}"#,
            desc.name
        ))
    }

    fn write_result(
        &mut self,
        desc: &TestDesc,
        result: &TestResult,
        stdout: &[u8],
    ) -> io::Result<()> {
        match *result {
            TrOk => self.write_event("test", desc.name.as_slice(), "ok", None),

            TrFailed => {
                let extra_data = if stdout.len() > 0 {
                    Some(format!(
                        r#""stdout": "{}""#,
                        EscapedString(String::from_utf8_lossy(stdout))
                    ))
                } else {
                    None
                };

                self.write_event("test", desc.name.as_slice(), "failed", extra_data)
            }

            TrFailedMsg(ref m) => self.write_event(
                "test",
                desc.name.as_slice(),
                "failed",
                Some(format!(r#""message": "{}""#, EscapedString(m))),
            ),

            TrIgnored => self.write_event("test", desc.name.as_slice(), "ignored", None),

            TrAllowedFail => {
                self.write_event("test", desc.name.as_slice(), "allowed_failure", None)
            }

            TrBench(ref bs) => {
                let median = bs.ns_iter_summ.median as usize;
                let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize;

                let mbps = if bs.mb_s == 0 {
                    String::new()
                } else {
                    format!(r#", "mib_per_second": {}"#, bs.mb_s)
                };

                let line = format!(
                    "{{ \"type\": \"bench\", \
                     \"name\": \"{}\", \
                     \"median\": {}, \
                     \"deviation\": {}{} }}",
                    desc.name, median, deviation, mbps
                );

                self.write_message(&*line)
            }
        }
    }

    fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_message(&*format!(
            r#"{{ "type": "test", "event": "timeout", "name": "{}" }}"#,
            desc.name
        ))
    }

    fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
        self.write_message(&*format!(
            "{{ \"type\": \"suite\", \
             \"event\": \"{}\", \
             \"passed\": {}, \
             \"failed\": {}, \
             \"allowed_fail\": {}, \
             \"ignored\": {}, \
             \"measured\": {}, \
             \"filtered_out\": {} }}",
            if state.failed == 0 { "ok" } else { "failed" },
            state.passed,
            state.failed + state.allowed_fail,
            state.allowed_fail,
            state.ignored,
            state.measured,
            state.filtered_out
        ))?;

        Ok(state.failed == 0)
    }
}

/// A formatting utility used to print strings with characters in need of escaping.
/// Base code taken form `libserialize::json::escape_str`
struct EscapedString<S: AsRef<str>>(S);

impl<S: AsRef<str>> ::std::fmt::Display for EscapedString<S> {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        let mut start = 0;

        for (i, byte) in self.0.as_ref().bytes().enumerate() {
            let escaped = match byte {
                b'"' => "\\\"",
                b'\\' => "\\\\",
                b'\x00' => "\\u0000",
                b'\x01' => "\\u0001",
                b'\x02' => "\\u0002",
                b'\x03' => "\\u0003",
                b'\x04' => "\\u0004",
                b'\x05' => "\\u0005",
                b'\x06' => "\\u0006",
                b'\x07' => "\\u0007",
                b'\x08' => "\\b",
                b'\t' => "\\t",
                b'\n' => "\\n",
                b'\x0b' => "\\u000b",
                b'\x0c' => "\\f",
                b'\r' => "\\r",
                b'\x0e' => "\\u000e",
                b'\x0f' => "\\u000f",
                b'\x10' => "\\u0010",
                b'\x11' => "\\u0011",
                b'\x12' => "\\u0012",
                b'\x13' => "\\u0013",
                b'\x14' => "\\u0014",
                b'\x15' => "\\u0015",
                b'\x16' => "\\u0016",
                b'\x17' => "\\u0017",
                b'\x18' => "\\u0018",
                b'\x19' => "\\u0019",
                b'\x1a' => "\\u001a",
                b'\x1b' => "\\u001b",
                b'\x1c' => "\\u001c",
                b'\x1d' => "\\u001d",
                b'\x1e' => "\\u001e",
                b'\x1f' => "\\u001f",
                b'\x7f' => "\\u007f",
                _ => {
                    continue;
                }
            };

            if start < i {
                f.write_str(&self.0.as_ref()[start..i])?;
            }

            f.write_str(escaped)?;

            start = i + 1;
        }

        if start != self.0.as_ref().len() {
            f.write_str(&self.0.as_ref()[start..])?;
        }

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


<commit_before><commit_msg>Move server to its own module.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
*  License, v. 2.0. If a copy of the MPL was not distributed with this
*  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*  Copyright (C) 2017  Juhamatti Kuusisaari / Mles developers
* */
use std::io::Error;
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use std::iter;
use std::io::ErrorKind;
use std::process;
use std::net::SocketAddr;
use std::thread;
use std::time::Duration;

use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
use tokio_io::io;
use tokio_io::AsyncRead;

use futures::Future;
use futures::stream::{self, Stream};
use futures::sync::mpsc::unbounded;

use local_db::*;
use frame::*;
use peer::*;
use super::*;

pub fn run(address: SocketAddr, peer: Option<SocketAddr>, keyval: String, keyaddr: String, hist_limit: usize, debug_flags: u64) {
    let mut core = Core::new().unwrap();
    let handle = core.handle();
    let socket = match TcpListener::bind(&address, &handle) {
        Ok(listener) => listener,
        Err(err) => {
            println!("Error: {}", err);
            process::exit(1);
        },
    };
    if 0 != debug_flags {
        println!("Listening on: {}", address);
    }

    let mles_db_hash: HashMap<String, MlesDb> = HashMap::new();
    let mles_db = Rc::new(RefCell::new(mles_db_hash));
    let channel_db = Rc::new(RefCell::new(HashMap::new()));

    let mut cnt = 0;

    let srv = socket.incoming().for_each(move |(stream, addr)| {
        let _val = stream.set_nodelay(true)
                         .map_err(|_| panic!("Cannot set to no delay"));
        let _val = stream.set_keepalive(Some(Duration::new(KEEPALIVE, 0)))
                         .map_err(|_| panic!("Cannot set keepalive"));
        cnt += 1;

        if 0 != debug_flags {
            println!("New connection: {}", addr);
        }
        let paddr = match stream.peer_addr() {
                Ok(paddr) => paddr,
                Err(_) => {
                    let addr = "0.0.0.0:0";
                    addr.parse::<SocketAddr>().unwrap()
                }
        };
        let mut is_addr_set = false;
        let mut keys = Vec::new();
        if !keyval.is_empty() {
            keys.push(keyval.clone());
        }
        else {
            keys.push(addr2str(&paddr));
            is_addr_set = true;
            if !keyaddr.is_empty() {
                keys.push(keyaddr.clone());
            }
        }

        let (reader, writer) = stream.split();
        let (tx, rx) = unbounded();

        let (tx_peer_for_msgs, rx_peer_for_msgs) = unbounded();

        let frame = io::read_exact(reader, vec![0;::HDRKEYL]);
        let frame = frame.and_then(move |(reader, hdr_key)| process_hdr(reader, hdr_key));
        let frame = frame.and_then(move |(reader, hdr_key, hdr_len)| {
            let tframe = io::read_exact(reader, vec![0;hdr_len]);
            tframe.and_then(move |(reader, message)| process_msg(reader, hdr_key, message))
        });

        // verify key
        let frame = frame.and_then(move |(reader, hdr_key, message)| process_key(reader, hdr_key, message, keys));

        let tx_inner = tx.clone();
        let channel_db_inner = channel_db.clone();
        let mles_db_inner = mles_db.clone();
        let keyaddr_inner = keyaddr.clone();
        let socket_once = frame.and_then(move |(reader, mut hdr_key, message, decoded_message)| {
                let channel = decoded_message.get_channel().clone();
                let mut mles_db_once = mles_db_inner.borrow_mut();
                let mut channel_db = channel_db_inner.borrow_mut();

                //pick the verified cid from header and use it as an identifier
                let cid = read_cid_from_hdr(&hdr_key);

                if !mles_db_once.contains_key(&channel) {
                    let chan = channel.clone();

                    //if peer is set, create peer channel thread
                    if peer::has_peer(&peer) {
                        let mut msg = hdr_key.clone();
                        msg.extend(message.clone());
                        let peer = peer.unwrap();
                        thread::spawn(move || peer_conn(hist_limit, peer, is_addr_set, keyaddr_inner, chan, msg, &tx_peer_for_msgs));
                    }

                    let mut mles_db_entry = MlesDb::new(hist_limit);
                    mles_db_entry.add_channel(cid, tx_inner.clone());
                    mles_db_once.insert(channel.clone(), mles_db_entry);

                }
                else if let Some(mles_db_entry) = mles_db_once.get_mut(&channel) {
                    if mles_db_entry.check_for_duplicate_cid(cid) {
                        println!("Duplicate cid {:x} detected", cid);
                        return Err(Error::new(ErrorKind::BrokenPipe, "duplicate cid"));
                    }
                    mles_db_entry.add_channel(cid, tx_inner.clone());
                    if peer::has_peer(&peer) {
                        if let Some(channelpeer_entry) = mles_db_entry.get_peer_tx() {
                            //sending tx to peer
                            let _res = channelpeer_entry.send(tx_inner.clone()).map_err(|err| {println!("Cannot reach peer: {}", err); ()});
                        }
                        else {
                            println!("Cannot find channel peer for channel {}", channel);
                        }
                    }
                    else {
                        // send history to client if peer is not set
                        for msg in mles_db_entry.get_messages() {
                            let _res = tx_inner.send(msg.clone()).map_err(|err| {println!("Send history failed: {}", err); ()});
                        }
                    }
                }
                else {
                    println!("Channel {} not found", channel);
                    return Err(Error::new(ErrorKind::BrokenPipe, "internal error"));
                }

                if let Some(mles_db_entry) = mles_db_once.get_mut(&channel) {
                    // add to history if no peer
                    if !peer::has_peer(&peer) {
                        hdr_key.extend(message);
                        mles_db_entry.add_message(hdr_key.clone());
                    }
                    //distribute to all
                    if let Some(channels) = mles_db_entry.get_channels() {
                        for (ocid, tx) in channels.iter() {
                            if *ocid != cid {
                                let _res = tx.send(hdr_key.clone()).map_err(|_| {
                                    //just ignore failures for now
                                    ()
                                });
                            }
                        }
                    }
                    mles_db_entry.add_tx_db(tx_inner.clone());
                }
                channel_db.insert(cnt, (cid, channel.clone()));
                if 0 != debug_flags {
                    println!("User {}:{:x} joined.", cnt, cid);
                }
                Ok((reader, cid, channel))
        });

        let mles_db_inner = mles_db.clone();
        let socket_next = socket_once.and_then(move |(reader, cid, channel)| {
            let channel_next = channel.clone();
            let iter = stream::iter(iter::repeat(()).map(Ok::<(), Error>));
            iter.fold(reader, move |reader, _| {
                let frame = io::read_exact(reader, vec![0;::HDRKEYL]);
                let frame = frame.and_then(move |(reader, hdr_key)| process_hdr_dummy_key(reader, hdr_key));

                let frame = frame.and_then(move |(reader, hdr_key, hdr_len)| {
                    let tframe = io::read_exact(reader, vec![0;hdr_len]);
                    tframe.and_then(move |(reader, message)| process_msg(reader, hdr_key, message))
                });

                let mles_db = mles_db_inner.clone();
                let channel = channel_next.clone();
                frame.map(move |(reader, mut hdr_key, message)| {
                    hdr_key.extend(message);

                    let mut mles_db_borrow = mles_db.borrow_mut();
                    if let Some(mles_db_entry) = mles_db_borrow.get_mut(&channel) {
                        // add to history if no peer
                        if !peer::has_peer(&peer) {
                            mles_db_entry.add_message(hdr_key.clone());
                        }

                        if let Some(channels) = mles_db_entry.get_channels() {
                            for (ocid, tx) in channels.iter() {
                                if *ocid != cid {
                                    let _res = tx.send(hdr_key.clone()).map_err(|_| {
                                        //just ignore failures for now
                                        ()
                                    });
                                }
                            }
                        }
                    }
                    else {
                        println!("Cannot distribute channel {}", channel);
                    }

                    reader
                })
            })
        });

        let mles_db_inner = mles_db.clone();
        let peer_writer = rx_peer_for_msgs.for_each(move |(peer_cid, channel, peer_tx, tx_orig_chan)| {
            let mut mles_db_once = mles_db_inner.borrow_mut();
            if let Some(mut mles_db_entry) = mles_db_once.get_mut(&channel) {
                //setting peer tx
                mles_db_entry.add_channel(peer_cid, peer_tx);
                mles_db_entry.set_peer_tx(tx_orig_chan.clone());
                //sending all tx's to (possibly restarted) peer
                for tx_entry in mles_db_entry.get_tx_db() {
                    let _res = tx_orig_chan.send(tx_entry.clone()).map_err(|err| {println!("Cannot reach peer: {}", err); ()});
                }
            }
            else {
                println!("Cannot find peer channel {}", channel);
            }
            Ok(())
        });
        handle.spawn(peer_writer.then(|_| {
            Ok(())
        }));

        let socket_writer = rx.fold(writer, |writer, msg| {
            let amt = io::write_all(writer, msg);
            let amt = amt.map(|(writer, _)| writer);
            amt.map_err(|_| ())
        });

        let mles_db_conn = mles_db.clone();
        let channel_db_conn = channel_db.clone();
        let socket_reader = socket_next.map_err(|_| ());
        let connection = socket_reader.map(|_| ()).select(socket_writer.map(|_| ()));
        handle.spawn(connection.then(move |_| {
            let mut mles_db = mles_db_conn.borrow_mut();
            let mut channel_db = channel_db_conn.borrow_mut();
            let mut chan_to_rem: Option<u32> = None;
            let mut chan_drop = false;
            if let Some(&mut (cid, ref channel)) = channel_db.get_mut(&cnt) {
                if let Some(mles_db_entry) = mles_db.get_mut(channel) {
                    mles_db_entry.rem_channel(cid);
                    chan_to_rem = Some(cid);
                    if 0 == mles_db_entry.get_channels_len() {
                        mles_db_entry.clear_tx_db();
                        if 0 == mles_db_entry.get_history_limit() {
                            chan_drop = true;
                        }
                    }
                }
                if chan_drop {
                    mles_db.remove(channel);
                }
            }
            if let Some(cid) = chan_to_rem {
                channel_db.remove(&cid);
                if 0 != debug_flags {
                    println!("Connection {} for user {}:{:x} closed.", addr, cnt, cid);
                }
            }
            Ok(())
        }));
        Ok(())
    });

    // execute server
    let _res = core.run(srv).map_err(|err| { println!("Main: {}", err); ()});
}

<|endoftext|>


<commit_before><commit_msg>Add src/compute_pipeline_state.rs<commit_after>use cocoa::base::id;
use sys::MTLComputePipelineState;

pub struct ComputePipelineState(id);

impl_from_into_raw!(ComputePipelineState, "MTLComputePipelineState");

impl ComputePipelineState {
    fn max_total_threads_per_thread_group(self) -> usize {
        self.0.maxTotalThreadsPerThreadGroup() as usize
    }

    fn thread_execution_width(self) -> usize {
        self.0.threadExecutionWidth() as usize
    }
}
<|endoftext|>


<commit_before>use super::prelude::v1::*;

/// An linked list (used for entries)
pub enum LinkedList<T> {
    Elem(T, Box<LinkedList<T>>),
    Nil,
}

impl<T> LinkedList<T> {
    /// Follow
    pub fn follow(&self) -> Option<&Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Follow mutable
    pub fn follow_mut(&mut self) -> Option<&mut Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref mut l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Push
    pub fn push(&self, elem: T) -> Self {
        LinkedList::Elem(elem, Box::new(LinkedList::Nil))
    }
}

/// A entry in the hash map
pub struct Entry<K, V> {
    data: LinkedList<(K, V)>,
}

impl<K: PartialEq<K>, V> Entry<K, V> {
    pub fn get(&self, key: K) -> Option<&V> {
        let mut cur = self.data.follow();

        loop {
            let next;
            match cur {
                Some(&LinkedList::Elem((ref k, ref v), ref l)) => {
                    if &key == k {
                        return Some(v);
                    } else {
                        next = l.follow();
                    }
                },
                Some(&LinkedList::Nil) | None => {
                    return None;
                },
            }

            cur = next;
        }

    }
    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {

        let mut cur = self.data.follow_mut();

        loop {
            cur = match cur {
                Some(x) => match *x {
                    LinkedList::Elem((ref k, ref mut v), ref mut l) => {
                        if &key == k {
                            return Some(v);
                        } else {
                            l.follow_mut()
                        }
                    },
                    LinkedList::Nil => {
                        return None;
                    },
                },
                None => {
                    return None;
                },
            }

        }
    }
}

/// A hashtable
pub struct HashMap<K, V> {
    data: [Entry<K, V>; 256],
}
<commit_msg>Clean up hash maps<commit_after>use super::prelude::v1::*;

/// An linked list (used for entries)
pub enum LinkedList<T> {
    Elem(T, Box<LinkedList<T>>),
    Nil,
}

impl<T> LinkedList<T> {
    /// Follow
    pub fn follow(&self) -> Option<&Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Follow mutable
    pub fn follow_mut(&mut self) -> Option<&mut Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref mut l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Push
    pub fn push(&self, elem: T) -> Self {
        LinkedList::Elem(elem, Box::new(LinkedList::Nil))
    }
}

/// A entry in the hash map
pub struct Entry<K, V> {
    data: LinkedList<(K, V)>,
}

impl<K: PartialEq<K>, V> Entry<K, V> {
    pub fn get(&self, key: K) -> Option<&V> {
        let mut cur = self.data.follow();

        loop {
            cur = match cur {
                Some(&LinkedList::Elem((ref k, ref v), ref l)) => {
                    if &key == k {
                        return Some(v);
                    } else {
                        l.follow()
                    }
                },
                Some(&LinkedList::Nil) | None => {
                    return None;
                },
            }
        }

    }
    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {

        let mut cur = self.data.follow_mut();

        loop {
            cur = match cur {
                Some(x) => match *x {
                    LinkedList::Elem((ref k, ref mut v), ref mut l) => {
                        if &key == k {
                            return Some(v);
                        } else {
                            l.follow_mut()
                        }
                    },
                    LinkedList::Nil => {
                        return None;
                    },
                },
                None => {
                    return None;
                },
            }

        }
    }
}

/// A hashtable
pub struct HashMap<K, V> {
    data: [Entry<K, V>; 256],
}
<|endoftext|>


<commit_before><commit_msg>Remove not needed into_iter() call<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #354 - Kerollmops:patch-1, r=SimonSapin<commit_after><|endoftext|>


<commit_before><commit_msg> #41 visible voxel upload is now synchronized<commit_after><|endoftext|>


<commit_before><commit_msg>Update ed25519.rs<commit_after><|endoftext|>


<commit_before>use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use variables::Variables;
use super::status::SUCCESS;

pub struct History {
    history:             VecDeque<String>,
    pub previous_status: i32,
}

impl History {
    pub fn new() -> History {
        History {
            history:         VecDeque::with_capacity(1000),
            previous_status: SUCCESS,
        }
    }

    /// Add a command to the history buffer and remove the oldest commands when the max history
    /// size has been met.
    pub fn add(&mut self, command: String, variables: &Variables) {
        // Write this command to the history file if writing to the file is enabled.
        // TODO: Prevent evaluated files from writing to the log.
        if variables.expand_string("$HISTORY_FILE_ENABLED") == "1" && command.trim() != "" {
            let history_file = variables.expand_string("$HISTORY_FILE");
            History::write_to_disk(&history_file, History::get_file_size(variables), &command);
        }

        self.history.truncate(History::get_size(variables) - 1); // Make room for new item
        self.history.push_front(command);
    }

    /// If writing to the disk is enabled, this function will be used for logging history to the
    /// designated history file. If the history file does not exist, it will be created.
    fn write_to_disk(history_file: &str, max_size: usize, command: &str) {
        match OpenOptions::new().read(true).write(true).create(true).open(history_file) {
            Ok(mut file) => {
                // Determine the number of commands stored and the file length.
                let (file_length, commands_stored) = {
                    let mut commands_stored = 0;
                    let mut file_length = 0;
                    let file = File::open(history_file).unwrap();
                    for byte in file.bytes() {
                        if byte.unwrap_or(b' ') == b'\n' { commands_stored += 1; }
                        file_length += 1;
                    }
                    (file_length, commands_stored)
                };

                // Truncate the history file if the limit has been reached
                if commands_stored >= max_size {
                    let seek_point = {
                        let commands_to_delete = commands_stored - max_size + 1;
                        let mut matched = 0;
                        let mut bytes = 0;
                        let file = File::open(history_file).unwrap();
                        for byte in file.bytes() {
                            if byte.unwrap_or(b' ') == b'\n' { matched += 1; }
                            bytes += 1;
                            if matched == commands_to_delete { break }
                        }
                        bytes as u64
                    };

                    if let Err(message) = file.seek(SeekFrom::Start(seek_point)) {
                        println!("ion: unable to seek in history file: {}", message);
                    }

                    let mut buffer: Vec<u8> = Vec::with_capacity(file_length - seek_point as usize);
                    if let Err(message) = file.read_to_end(&mut buffer) {
                        println!("ion: unable to buffer history file: {}", message);
                    }

                    if let Err(message) = file.set_len(0) {
                        println!("ion: unable to truncate history file: {}", message);
                    }

                    if let Err(message) = io::copy(&mut buffer.as_slice(), &mut file) {
                        println!("ion: unable to write to history file: {}", message);
                    }
                }

                // Write the command to the history file.
                if let Err(message) = file.write_all(command.as_bytes()) {
                    println!("ion: unable to write to history file: {}", message);
                }
                if let Err(message) = file.write(b"\n") {
                    println!("ion: unable to write to history file: {}", message);
                }
            },
            Err(message) => println!("ion: error opening file: {}", message)
        }
    }

    /// Print the entire history list currently buffered to stdout directly.
    pub fn history<I: IntoIterator>(&self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        for command in self.history.iter().rev() {
            println!("{}", command);
        }
        SUCCESS
    }

    /// This function will take a map of variables as input and attempt to parse the value of the
    /// history size variable. If it succeeds, it will return the value of that variable, else it
    /// will return a default value of 1000.
    #[inline]
    fn get_size(variables: &Variables) -> usize {
        match variables.expand_string("$HISTORY_SIZE").parse::<usize>() {
            Ok(size) => size,
            _        => 1000,
        }
    }

    /// This function will take a map of variables as input and attempt to parse the value of the
    /// history file size variable. If it succeeds, it will return the value of that variable, else
    /// it will return a default value of 1000.
    #[inline]
    fn get_file_size(variables: &Variables) -> usize {
        match variables.expand_string("$HISTORY_FILE_SIZE").parse::<usize>() {
            Ok(size)  => size,
            Err(_)    => 1000,
        }
    }
}
<commit_msg>Seek to End for Appending<commit_after>use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use variables::Variables;
use super::status::SUCCESS;

pub struct History {
    history:             VecDeque<String>,
    pub previous_status: i32,
}

impl History {
    pub fn new() -> History {
        History {
            history:         VecDeque::with_capacity(1000),
            previous_status: SUCCESS,
        }
    }

    /// Add a command to the history buffer and remove the oldest commands when the max history
    /// size has been met.
    pub fn add(&mut self, command: String, variables: &Variables) {
        // Write this command to the history file if writing to the file is enabled.
        // TODO: Prevent evaluated files from writing to the log.
        if variables.expand_string("$HISTORY_FILE_ENABLED") == "1" && command.trim() != "" {
            let history_file = variables.expand_string("$HISTORY_FILE");
            History::write_to_disk(&history_file, History::get_file_size(variables), &command);
        }

        self.history.truncate(History::get_size(variables) - 1); // Make room for new item
        self.history.push_front(command);
    }

    /// If writing to the disk is enabled, this function will be used for logging history to the
    /// designated history file. If the history file does not exist, it will be created.
    fn write_to_disk(history_file: &str, max_size: usize, command: &str) {
        match OpenOptions::new().read(true).write(true).create(true).open(history_file) {
            Ok(mut file) => {
                // Determine the number of commands stored and the file length.
                let (file_length, commands_stored) = {
                    let mut commands_stored = 0;
                    let mut file_length = 0;
                    let file = File::open(history_file).unwrap();
                    for byte in file.bytes() {
                        if byte.unwrap_or(b' ') == b'\n' { commands_stored += 1; }
                        file_length += 1;
                    }
                    (file_length, commands_stored)
                };

                // If the max history file size has been reached, truncate the file so that only
                // N amount of commands are listed. To truncate the file, the seek point will be
                // discovered by counting the number of bytes until N newlines have been found and
                // then the file will be seeked to that point, copying all data after and rewriting
                // the file with the first N lines removed.
                if commands_stored >= max_size {
                    let seek_point = {
                        let commands_to_delete = commands_stored - max_size + 1;
                        let mut matched = 0;
                        let mut bytes = 0;
                        let file = File::open(history_file).unwrap();
                        for byte in file.bytes() {
                            if byte.unwrap_or(b' ') == b'\n' { matched += 1; }
                            bytes += 1;
                            if matched == commands_to_delete { break }
                        }
                        bytes as u64
                    };

                    if let Err(message) = file.seek(SeekFrom::Start(seek_point)) {
                        println!("ion: unable to seek in history file: {}", message);
                    }

                    let mut buffer: Vec<u8> = Vec::with_capacity(file_length - seek_point as usize);
                    if let Err(message) = file.read_to_end(&mut buffer) {
                        println!("ion: unable to buffer history file: {}", message);
                    }

                    if let Err(message) = file.set_len(0) {
                        println!("ion: unable to truncate history file: {}", message);
                    }

                    if let Err(message) = io::copy(&mut buffer.as_slice(), &mut file) {
                        println!("ion: unable to write to history file: {}", message);
                    }
                }

                // Seek to end for appending
                if let Err(message) = file.seek(SeekFrom::End(0)) {
                    println!("ion: unable to seek in history file: {}", message);
                }

                // Write the command to the history file.
                if let Err(message) = file.write_all(command.as_bytes()) {
                    println!("ion: unable to write to history file: {}", message);
                }
                if let Err(message) = file.write(b"\n") {
                    println!("ion: unable to write to history file: {}", message);
                }
            },
            Err(message) => println!("ion: error opening file: {}", message)
        }
    }

    /// Print the entire history list currently buffered to stdout directly.
    pub fn history<I: IntoIterator>(&self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        for command in self.history.iter().rev() {
            println!("{}", command);
        }
        SUCCESS
    }

    /// This function will take a map of variables as input and attempt to parse the value of the
    /// history size variable. If it succeeds, it will return the value of that variable, else it
    /// will return a default value of 1000.
    #[inline]
    fn get_size(variables: &Variables) -> usize {
        match variables.expand_string("$HISTORY_SIZE").parse::<usize>() {
            Ok(size) => size,
            _        => 1000,
        }
    }

    /// This function will take a map of variables as input and attempt to parse the value of the
    /// history file size variable. If it succeeds, it will return the value of that variable, else
    /// it will return a default value of 1000.
    #[inline]
    fn get_file_size(variables: &Variables) -> usize {
        match variables.expand_string("$HISTORY_FILE_SIZE").parse::<usize>() {
            Ok(size)  => size,
            Err(_)    => 1000,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove echo when client connected<commit_after><|endoftext|>


<commit_before><commit_msg>Clean tests.<commit_after><|endoftext|>


<commit_before><commit_msg>add regression test for #52078<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(nll)]
#![allow(unused_variables)]

// Regression test for #52078: we were failing to infer a relationship
// between `'a` and `'b` below due to inference variables introduced
// during the normalization process.
//
// compile-pass

struct Drain<'a, T: 'a> {
    _marker: ::std::marker::PhantomData<&'a T>,
}

trait Join {
    type Value;
    fn get(value: &mut Self::Value);
}

impl<'a, T> Join for Drain<'a, T> {
    type Value = &'a mut Option<T>;

    fn get<'b>(value: &'b mut Self::Value) {
    }
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Display uptime in print{,ln}!() messages<commit_after><|endoftext|>


<commit_before><commit_msg>00/00<commit_after><|endoftext|>


<commit_before><commit_msg>Reduce references to glslangValidator<commit_after><|endoftext|>


<commit_before><commit_msg>crosvm: add control socket for crosvm inter-process control<commit_after>// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Helper for sending and receiving control socket commands

use std::fs::remove_file;
use std::io::Result;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixDatagram;
use std::path::Path;

use libc::getpid;

use sys_util::Pollable;

#[derive(Debug, PartialEq)]
/// The set of commands that can be sent over a control socket.
pub enum Command {
    /// A command that could not be identified.
    Unknown,
    /// Stop the process in an orderly fashion.
    Stop,
}

impl Command {
    fn decode(data: &[u8]) -> Command {
        if data.is_empty() {
            return Command::Unknown;
        }
        if data[0] == b's' {
            return Command::Stop;
        }
        Command::Unknown
    }

    fn encode(&self, data: &mut [u8]) {
        if data.is_empty() {
            return;
        }
        match *self {
            Command::Unknown => data[0] = 0,
            Command::Stop => data[0] = b's',
        }
    }
}

/// The receiving side of a control socket.
pub struct ControlSocketRecv {
    s: UnixDatagram,
}

impl ControlSocketRecv {
    /// Binds a new control socket at `path`.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<ControlSocketRecv> {
        let path = path.as_ref();
        let control_socket = if path.is_dir() {
            // Getting the pid is always safe and never fails.
            let pid = unsafe { getpid() };
            UnixDatagram::bind(path.join(format!("crosvm-{}.sock", pid)))?
        } else {
            UnixDatagram::bind(path)?
        };
        Ok(ControlSocketRecv { s: control_socket })
    }

    /// Use the already connected `socket` as a control socket.
    pub fn with_socket(socket: UnixDatagram) -> ControlSocketRecv {
        ControlSocketRecv { s: socket }
    }

    /// Receives a command on this control socket.
    ///
    /// Note that this will block if there is no command waiting.
    pub fn recv(&self) -> Result<Command> {
        let mut buf = [0; 32];
        self.s.recv(&mut buf)?;
        Ok(Command::decode(&buf))
    }
}

// Safe because we return a genuine pollable fd that never changes and shares our lifetime.
unsafe impl Pollable for ControlSocketRecv {
    fn pollable_fd(&self) -> RawFd {
        self.s.as_raw_fd()
    }
}

impl Drop for ControlSocketRecv {
    fn drop(&mut self) {
        if let Ok(addr) = self.s.local_addr() {
            if let Some(path) = addr.as_pathname() {
                if let Err(e) = remove_file(path) {
                    println!("failed to remove control socket file: {:?}", e);
                }
            }
        }
    }
}

/// The sending side of the control socket.
pub struct ControlSocketSend {
    s: UnixDatagram,
}

impl ControlSocketSend {
    /// Connect to a control socket at `path`.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<ControlSocketSend> {
        let s = UnixDatagram::unbound()?;
        s.connect(path)?;
        Ok(ControlSocketSend { s: s })
    }

    /// Use the already connected `socket` as a control socket.
    pub fn with_socket(socket: UnixDatagram) -> ControlSocketSend {
        ControlSocketSend { s: socket }
    }

    /// Send a command to this control socket.
    pub fn send(&self, cmd: &Command) -> Result<()> {
        let mut buf = [0; 32];
        cmd.encode(&mut buf);
        self.s.send(&buf).map(|_| ())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env::temp_dir;
    use sys_util::Poller;

    #[test]
    fn send_recv() {
        let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
        let send = ControlSocketSend::with_socket(s1);
        let recv = ControlSocketRecv::with_socket(s2);
        send.send(&Command::Stop)
            .expect("failed to send stop command");
        let cmd = recv.recv().expect("failed to recv stop command");
        assert_eq!(cmd, Command::Stop);
    }

    #[test]
    fn poll_recv() {
        let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
        let send = ControlSocketSend::with_socket(s1);
        let recv = ControlSocketRecv::with_socket(s2);
        send.send(&Command::Stop)
            .expect("failed to send stop command");

        let mut poller = Poller::new(1);
        let polled = poller
            .poll(&[(0, &recv)])
            .expect("failed to poll recv socket");
        assert_eq!(polled, [0].as_ref());

        let cmd = recv.recv().expect("failed to recv stop command");
        assert_eq!(cmd, Command::Stop);
    }

    #[test]
    fn unknown() {
        let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
        let send = ControlSocketSend::with_socket(s1);
        let recv = ControlSocketRecv::with_socket(s2);
        send.send(&Command::Unknown)
            .expect("failed to send command");
        let cmd = recv.recv().expect("failed to recv command");
        assert_eq!(cmd, Command::Unknown);
    }

    #[test]
    fn recv_socket_remove_on_drop() {
        let pid = unsafe { getpid() };
        let mut temp_file = temp_dir();
        temp_file.push(format!("control_socket_drop_recv_socket_{}", pid));
        assert!(!temp_file.exists());
        {
            let recv = ControlSocketRecv::new(temp_file.to_str().unwrap());
            assert!(temp_file.exists());
        }
        assert!(!temp_file.exists());
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-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.

use cmp;
use mem;
use ptr;

/// Rotation is much faster if it has access to a little bit of memory. This
/// union provides a RawVec-like interface, but to a fixed-size stack buffer.
#[allow(unions_with_drop_fields)]
union RawArray<T> {
    /// Ensure this is appropriately aligned for T, and is big
    /// enough for two elements even if T is enormous.
    typed: [T; 2],
    /// For normally-sized types, especially things like u8, having more
    /// than 2 in the buffer is necessary for usefulness, so pad it out
    /// enough to be helpful, but not so big as to risk overflow.
    _extra: [usize; 32],
}

impl<T> RawArray<T> {
    fn new() -> Self {
        unsafe { mem::uninitialized() }
    }
    fn ptr(&self) -> *mut T {
        unsafe { &self.typed as *const T as *mut T }
    }
    fn cap() -> usize {
        if mem::size_of::<T>() == 0 {
            usize::max_value()
        } else {
            mem::size_of::<Self>() / mem::size_of::<T>()
        }
    }
}

/// Rotates the range `[mid-left, mid+right)` such that the element at `mid`
/// becomes the first element.  Equivalently, rotates the range `left`
/// elements to the left or `right` elements to the right.
///
/// # Safety
///
/// The specified range must be valid for reading and writing.
/// The type `T` must have non-zero size.
///
/// # Algorithm
///
/// For longer rotations, swap the left-most `delta = min(left, right)`
/// elements with the right-most `delta` elements.  LLVM vectorizes this,
/// which is profitable as we only reach this step for a "large enough"
/// rotation.  Doing this puts `delta` elements on the larger side into the
/// correct position, leaving a smaller rotate problem.  Demonstration:
///
/// ```text
/// [ 6 7 8 9 10 11 12 13 . 1 2 3 4 5 ]
/// 1 2 3 4 5 [ 11 12 13 . 6 7 8 9 10 ]
/// 1 2 3 4 5 [ 8 9 10 . 6 7 ] 11 12 13
/// 1 2 3 4 5 6 7 [ 10 . 8 9 ] 11 12 13
/// 1 2 3 4 5 6 7 [ 9 . 8 ] 10 11 12 13
/// 1 2 3 4 5 6 7 8 [ . ] 9 10 11 12 13
/// ```
///
/// Once the rotation is small enough, copy some elements into a stack
/// buffer, `memmove` the others, and move the ones back from the buffer.
pub unsafe fn ptr_rotate<T>(mut left: usize, mid: *mut T, mut right: usize) {
    loop {
        let delta = cmp::min(left, right);
        if delta <= RawArray::<T>::cap() {
            break;
        }

        ptr::swap_nonoverlapping(
            mid.offset(-(left as isize)),
            mid.offset((right-delta) as isize),
            delta);

        if left <= right {
            right -= delta;
        } else {
            left -= delta;
        }
    }

    let rawarray = RawArray::new();
    let buf = rawarray.ptr();

    let dim = mid.offset(-(left as isize)).offset(right as isize);
    if left <= right {
        ptr::copy_nonoverlapping(mid.offset(-(left as isize)), buf, left);
        ptr::copy(mid, mid.offset(-(left as isize)), right);
        ptr::copy_nonoverlapping(buf, dim, left);
    }
    else {
        ptr::copy_nonoverlapping(mid, buf, right);
        ptr::copy(mid.offset(-(left as isize)), dim, left);
        ptr::copy_nonoverlapping(buf, mid.offset(-(left as isize)), right);
    }
}
<commit_msg>fix safety-related comment in slice::rotate<commit_after>// Copyright 2012-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.

use cmp;
use mem;
use ptr;

/// Rotation is much faster if it has access to a little bit of memory. This
/// union provides a RawVec-like interface, but to a fixed-size stack buffer.
#[allow(unions_with_drop_fields)]
union RawArray<T> {
    /// Ensure this is appropriately aligned for T, and is big
    /// enough for two elements even if T is enormous.
    typed: [T; 2],
    /// For normally-sized types, especially things like u8, having more
    /// than 2 in the buffer is necessary for usefulness, so pad it out
    /// enough to be helpful, but not so big as to risk overflow.
    _extra: [usize; 32],
}

impl<T> RawArray<T> {
    fn new() -> Self {
        unsafe { mem::uninitialized() }
    }
    fn ptr(&self) -> *mut T {
        unsafe { &self.typed as *const T as *mut T }
    }
    fn cap() -> usize {
        if mem::size_of::<T>() == 0 {
            usize::max_value()
        } else {
            mem::size_of::<Self>() / mem::size_of::<T>()
        }
    }
}

/// Rotates the range `[mid-left, mid+right)` such that the element at `mid`
/// becomes the first element.  Equivalently, rotates the range `left`
/// elements to the left or `right` elements to the right.
///
/// # Safety
///
/// The specified range must be valid for reading and writing.
///
/// # Algorithm
///
/// For longer rotations, swap the left-most `delta = min(left, right)`
/// elements with the right-most `delta` elements.  LLVM vectorizes this,
/// which is profitable as we only reach this step for a "large enough"
/// rotation.  Doing this puts `delta` elements on the larger side into the
/// correct position, leaving a smaller rotate problem.  Demonstration:
///
/// ```text
/// [ 6 7 8 9 10 11 12 13 . 1 2 3 4 5 ]
/// 1 2 3 4 5 [ 11 12 13 . 6 7 8 9 10 ]
/// 1 2 3 4 5 [ 8 9 10 . 6 7 ] 11 12 13
/// 1 2 3 4 5 6 7 [ 10 . 8 9 ] 11 12 13
/// 1 2 3 4 5 6 7 [ 9 . 8 ] 10 11 12 13
/// 1 2 3 4 5 6 7 8 [ . ] 9 10 11 12 13
/// ```
///
/// Once the rotation is small enough, copy some elements into a stack
/// buffer, `memmove` the others, and move the ones back from the buffer.
pub unsafe fn ptr_rotate<T>(mut left: usize, mid: *mut T, mut right: usize) {
    loop {
        let delta = cmp::min(left, right);
        if delta <= RawArray::<T>::cap() {
            // We will always hit this immediately for ZST.
            break;
        }

        ptr::swap_nonoverlapping(
            mid.offset(-(left as isize)),
            mid.offset((right-delta) as isize),
            delta);

        if left <= right {
            right -= delta;
        } else {
            left -= delta;
        }
    }

    let rawarray = RawArray::new();
    let buf = rawarray.ptr();

    let dim = mid.offset(-(left as isize)).offset(right as isize);
    if left <= right {
        ptr::copy_nonoverlapping(mid.offset(-(left as isize)), buf, left);
        ptr::copy(mid, mid.offset(-(left as isize)), right);
        ptr::copy_nonoverlapping(buf, dim, left);
    }
    else {
        ptr::copy_nonoverlapping(mid, buf, right);
        ptr::copy(mid.offset(-(left as isize)), dim, left);
        ptr::copy_nonoverlapping(buf, mid.offset(-(left as isize)), right);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add missing files (again…)<commit_after>use std::cmp::ApproxEq;
use std::num::{Zero, One};
use nalgebra::traits::dim::Dim;
use nalgebra::traits::norm::Norm;
use nalgebra::traits::dot::Dot;
use nalgebra::traits::sub_dot::SubDot;
use nalgebra::traits::scalar_op::{ScalarMul, ScalarDiv};
use nalgebra::traits::division_ring::DivisionRing;
use geom::implicit::Implicit;
use geom::reflection::Reflection;
use geom::minkowski_sum::{AnnotatedPoint, AnnotatedMinkowskiSum};
use geom::cso::AnnotatedCSO;
use narrow::algorithm::johnson_simplex::JohnsonSimplex;
use narrow::algorithm::simplex::Simplex;

pub fn closest_points_johnson<G1: Implicit<V>,
                              G2: Implicit<V>,
                              V:  Norm<N> + Neg<V> + Add<V, V> + SubDot<N> +
                                  Dim + One + Zero + Copy + ScalarMul<N> +
                                  ScalarDiv<N> + Eq,
                              N:  Ord + ApproxEq<N> + DivisionRing + Bounded + Float + Eq>
                              (g1: &G1, g2: &G2) -> Option<(V, V)>
{ closest_points::<JohnsonSimplex<AnnotatedPoint<V>, N>, G1, G2, V, N>(g1, g2) }

pub fn closest_points_with_initial_direction_johnson
       <G1: Implicit<V>,
        G2: Implicit<V>,
        V:  Norm<N> + Neg<V> + Add<V, V> + SubDot<N> +
            Dim + Zero + Copy + ScalarMul<N> +
            ScalarDiv<N> + Eq,
        N:  Ord + ApproxEq<N> + DivisionRing + Bounded + Float + Eq>
       (g1: &G1, g2: &G2, dir: V) -> Option<(V, V)>
{
  closest_points_with_initial_direction
  ::<JohnsonSimplex<AnnotatedPoint<V>, N>, G1, G2, V, N>(g1, g2, dir)
}

pub fn closest_points<S:  Simplex<AnnotatedPoint<V>, N>,
                      G1: Implicit<V>,
                      G2: Implicit<V>,
                      V:  Norm<N> + Neg<V> + Add<V, V> + Dot<N> + Dim + One + Zero + Copy,
                      N:  Sub<N, N> + Ord + ApproxEq<N> + Mul<N, N> + Float>
                     (g1: &G1, g2: &G2) -> Option<(V, V)>
{ closest_points_with_initial_direction::<S, G1, G2, V, N>(g1, g2, One::one()) }

pub fn closest_points_with_initial_direction
       <S:  Simplex<AnnotatedPoint<V>, N>,
        G1: Implicit<V>,
        G2: Implicit<V>,
        V:  Norm<N> + Neg<V> + Add<V, V> + Dot<N> + Dim + Zero + Copy,
        N:  Sub<N, N> + Ord + ApproxEq<N> + Mul<N, N> + Float>
       (g1: &G1, g2: &G2, dir: V) -> Option<(V, V)>
{
  let rg2 = &Reflection::new(g2);
  let cso = AnnotatedMinkowskiSum::new(g1, rg2);

  match project_origin_with_initial_direction
        ::<S, AnnotatedCSO<G1, G2>, AnnotatedPoint<V>, N>(&cso, AnnotatedPoint::new_invalid(dir))
  {
    Some(ref pt) => Some((copy *pt.orig1(), -pt.orig2())),
    None         => None
  }
}

pub fn project_origin<S: Simplex<V, N>,
                      G: Implicit<V>,
                      V: Norm<N> + Neg<V> + Dot<N> + Dim + One,
                      N: Sub<N, N> + Ord + ApproxEq<N> + Mul<N, N> + Float>
                      (g: &G) -> Option<V>
{ project_origin_with_initial_direction::<S, G, V, N>(g, One::one()) }

pub fn project_origin_with_initial_direction<S: Simplex<V, N>,
                                             G: Implicit<V>,
                                             V: Norm<N> + Neg<V> + Dot<N> + Dim,
                                             N: Sub<N, N> + Ord + ApproxEq<N> +
                                                Mul<N, N> + Float>
                                            (geom: &G, dir: V) -> Option<V>
{
  let support_point = geom.support_point(&dir);

  project_origin_with_simplex(geom, &mut Simplex::new::<V, N, S>(support_point))
}

// The main algorithm
pub fn project_origin_with_simplex<S: Simplex<V, N>,
                                   G: Implicit<V>,
                                   V: Norm<N> + Neg<V> + Dot<N> + Dim,
                                   N: Sub<N, N> + Ord + ApproxEq<N> + Mul<N, N>
                                      + Float>
                                  (geom: &G, simplex: &mut S) -> Option<V>
{
  let mut proj       = simplex.project_origin_and_reduce();
  let mut sq_len_dir = proj.sqnorm();

  let _eps_tol = Float::epsilon::<N>(); // FIXME: * 100.0
  let _eps_rel = Float::epsilon::<N>(); // FIXME: .sqrt()
  let _dim     = Dim::dim::<V>();

  loop
  {
    let support_point = geom.support_point(&-proj);

    if (sq_len_dir - proj.dot(&support_point) <= _eps_rel * sq_len_dir)
    { return Some(proj) } // the distance found has a good enough precision

    simplex.add_point(support_point);

    proj = simplex.project_origin_and_reduce();

    let old_sq_len_dir = sq_len_dir;

    sq_len_dir = proj.sqnorm();

    if (simplex.dimension() == _dim || sq_len_dir <= _eps_tol * simplex.max_sq_len())
    { return None } // point inside of the cso

    if (sq_len_dir >= old_sq_len_dir) // upper bounds inconsistencies
    { return Some(proj) }
  }
}
<|endoftext|>


<commit_before><commit_msg>Ignore metrics with no valid key<commit_after><|endoftext|>


<commit_before><commit_msg>add broken build file<commit_after>extern crate pkg_config;

fn main() {
  pkg_config::find_library("opencv").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>updated build.rs to use 'git describe --all'<commit_after><|endoftext|>


<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.

//! A private parser implementation of IPv4, IPv6, and socket addresses.
//!
//! This module is "publicly exported" through the `FromStr` implementations
//! below.

use prelude::v1::*;

use str::FromStr;
use net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

struct Parser<'a> {
    // parsing as ASCII, so can use byte array
    s: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(s: &'a str) -> Parser<'a> {
        Parser {
            s: s.as_bytes(),
            pos: 0,
        }
    }

    fn is_eof(&self) -> bool {
        self.pos == self.s.len()
    }

    // Commit only if parser returns Some
    fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
        F: FnOnce(&mut Parser) -> Option<T>,
    {
        let pos = self.pos;
        let r = cb(self);
        if r.is_none() {
            self.pos = pos;
        }
        r
    }

    // Commit only if parser read till EOF
    fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
        F: FnOnce(&mut Parser) -> Option<T>,
    {
        self.read_atomically(move |p| {
            match cb(p) {
                Some(x) => if p.is_eof() {Some(x)} else {None},
                None => None,
            }
        })
    }

    // Return result of first successful parser
    fn read_or<T>(&mut self, parsers: &mut [Box<FnMut(&mut Parser) -> Option<T> + 'static>])
               -> Option<T> {
        for pf in parsers {
            match self.read_atomically(|p: &mut Parser| pf(p)) {
                Some(r) => return Some(r),
                None => {}
            }
        }
        None
    }

    // Apply 3 parsers sequentially
    fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
                                       pa: PA,
                                       pb: PB,
                                       pc: PC)
                                       -> Option<(A, B, C)> where
        PA: FnOnce(&mut Parser) -> Option<A>,
        PB: FnOnce(&mut Parser) -> Option<B>,
        PC: FnOnce(&mut Parser) -> Option<C>,
    {
        self.read_atomically(move |p| {
            let a = pa(p);
            let b = if a.is_some() { pb(p) } else { None };
            let c = if b.is_some() { pc(p) } else { None };
            match (a, b, c) {
                (Some(a), Some(b), Some(c)) => Some((a, b, c)),
                _ => None
            }
        })
    }

    // Read next char
    fn read_char(&mut self) -> Option<char> {
        if self.is_eof() {
            None
        } else {
            let r = self.s[self.pos] as char;
            self.pos += 1;
            Some(r)
        }
    }

    // Return char and advance iff next char is equal to requested
    fn read_given_char(&mut self, c: char) -> Option<char> {
        self.read_atomically(|p| {
            match p.read_char() {
                Some(next) if next == c => Some(next),
                _ => None,
            }
        })
    }

    // Read digit
    fn read_digit(&mut self, radix: u8) -> Option<u8> {
        fn parse_digit(c: char, radix: u8) -> Option<u8> {
            let c = c as u8;
            // assuming radix is either 10 or 16
            if c >= b'0' && c <= b'9' {
                Some(c - b'0')
            } else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) {
                Some(c - b'a' + 10)
            } else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) {
                Some(c - b'A' + 10)
            } else {
                None
            }
        }

        self.read_atomically(|p| {
            p.read_char().and_then(|c| parse_digit(c, radix))
        })
    }

    fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
        let mut r = 0;
        let mut digit_count = 0;
        loop {
            match self.read_digit(radix) {
                Some(d) => {
                    r = r * (radix as u32) + (d as u32);
                    digit_count += 1;
                    if digit_count > max_digits || r >= upto {
                        return None
                    }
                }
                None => {
                    if digit_count == 0 {
                        return None
                    } else {
                        return Some(r)
                    }
                }
            };
        }
    }

    // Read number, failing if max_digits of number value exceeded
    fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
        self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto))
    }

    fn read_ipv4_addr_impl(&mut self) -> Option<Ipv4Addr> {
        let mut bs = [0; 4];
        let mut i = 0;
        while i < 4 {
            if i != 0 && self.read_given_char('.').is_none() {
                return None;
            }

            let octet = self.read_number(10, 3, 0x100).map(|n| n as u8);
            match octet {
                Some(d) => bs[i] = d,
                None => return None,
            };
            i += 1;
        }
        Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3]))
    }

    // Read IPv4 address
    fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
        self.read_atomically(|p| p.read_ipv4_addr_impl())
    }

    fn read_ipv6_addr_impl(&mut self) -> Option<Ipv6Addr> {
        fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
            assert!(head.len() + tail.len() <= 8);
            let mut gs = [0; 8];
            gs.clone_from_slice(head);
            gs[(8 - tail.len()) .. 8].clone_from_slice(tail);
            Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
        }

        fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize)
                       -> (usize, bool) {
            let mut i = 0;
            while i < limit {
                if i < limit - 1 {
                    let ipv4 = p.read_atomically(|p| {
                        if i == 0 || p.read_given_char(':').is_some() {
                            p.read_ipv4_addr()
                        } else {
                            None
                        }
                    });
                    if let Some(v4_addr) = ipv4 {
                        let octets = v4_addr.octets();
                        groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16);
                        groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16);
                        return (i + 2, true);
                    }
                }

                let group = p.read_atomically(|p| {
                    if i == 0 || p.read_given_char(':').is_some() {
                        p.read_number(16, 4, 0x10000).map(|n| n as u16)
                    } else {
                        None
                    }
                });
                match group {
                    Some(g) => groups[i] = g,
                    None => return (i, false)
                }
                i += 1;
            }
            (i, false)
        }

        let mut head = [0; 8];
        let (head_size, head_ipv4) = read_groups(self, &mut head, 8);

        if head_size == 8 {
            return Some(Ipv6Addr::new(
                head[0], head[1], head[2], head[3],
                head[4], head[5], head[6], head[7]))
        }

        // IPv4 part is not allowed before `::`
        if head_ipv4 {
            return None
        }

        // read `::` if previous code parsed less than 8 groups
        if !self.read_given_char(':').is_some() || !self.read_given_char(':').is_some() {
            return None;
        }

        let mut tail = [0; 8];
        let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size);
        Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size]))
    }

    fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
        self.read_atomically(|p| p.read_ipv6_addr_impl())
    }

    fn read_ip_addr(&mut self) -> Option<IpAddr> {
        let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr().map(|v4| IpAddr::V4(v4));
        let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr().map(|v6| IpAddr::V6(v6));
        self.read_or(&mut [Box::new(ipv4_addr), Box::new(ipv6_addr)])
    }

    fn read_socket_addr(&mut self) -> Option<SocketAddr> {
        let ip_addr = |p: &mut Parser| {
            let ipv4_p = |p: &mut Parser| p.read_ip_addr();
            let ipv6_p = |p: &mut Parser| {
                let open_br = |p: &mut Parser| p.read_given_char('[');
                let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
                let clos_br = |p: &mut Parser| p.read_given_char(']');
                p.read_seq_3::<char, Ipv6Addr, char, _, _, _>(open_br, ip_addr, clos_br)
                        .map(|t| match t { (_, ip, _) => IpAddr::V6(ip) })
            };
            p.read_or(&mut [Box::new(ipv4_p), Box::new(ipv6_p)])
        };
        let colon = |p: &mut Parser| p.read_given_char(':');
        let port  = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);

        // host, colon, port
        self.read_seq_3(ip_addr, colon, port).map(|t| {
            let (ip, _, port): (IpAddr, char, u16) = t;
            match ip {
                IpAddr::V4(ip) => SocketAddr::V4(SocketAddrV4::new(ip, port)),
                IpAddr::V6(ip) => SocketAddr::V6(SocketAddrV6::new(ip, port, 0, 0)),
            }
        })
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for IpAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ip_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for Ipv4Addr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ipv4_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for Ipv6Addr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ipv6_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for SocketAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_socket_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(())),
        }
    }
}

/// An error returned when parsing an IP address or a socket address.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug, Clone, PartialEq)]
pub struct AddrParseError(());
<commit_msg>Implement Error for AddrParseError<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.

//! A private parser implementation of IPv4, IPv6, and socket addresses.
//!
//! This module is "publicly exported" through the `FromStr` implementations
//! below.

use prelude::v1::*;

use error::Error;
use fmt;
use net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use str::FromStr;

struct Parser<'a> {
    // parsing as ASCII, so can use byte array
    s: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(s: &'a str) -> Parser<'a> {
        Parser {
            s: s.as_bytes(),
            pos: 0,
        }
    }

    fn is_eof(&self) -> bool {
        self.pos == self.s.len()
    }

    // Commit only if parser returns Some
    fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
        F: FnOnce(&mut Parser) -> Option<T>,
    {
        let pos = self.pos;
        let r = cb(self);
        if r.is_none() {
            self.pos = pos;
        }
        r
    }

    // Commit only if parser read till EOF
    fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
        F: FnOnce(&mut Parser) -> Option<T>,
    {
        self.read_atomically(move |p| {
            match cb(p) {
                Some(x) => if p.is_eof() {Some(x)} else {None},
                None => None,
            }
        })
    }

    // Return result of first successful parser
    fn read_or<T>(&mut self, parsers: &mut [Box<FnMut(&mut Parser) -> Option<T> + 'static>])
               -> Option<T> {
        for pf in parsers {
            match self.read_atomically(|p: &mut Parser| pf(p)) {
                Some(r) => return Some(r),
                None => {}
            }
        }
        None
    }

    // Apply 3 parsers sequentially
    fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
                                       pa: PA,
                                       pb: PB,
                                       pc: PC)
                                       -> Option<(A, B, C)> where
        PA: FnOnce(&mut Parser) -> Option<A>,
        PB: FnOnce(&mut Parser) -> Option<B>,
        PC: FnOnce(&mut Parser) -> Option<C>,
    {
        self.read_atomically(move |p| {
            let a = pa(p);
            let b = if a.is_some() { pb(p) } else { None };
            let c = if b.is_some() { pc(p) } else { None };
            match (a, b, c) {
                (Some(a), Some(b), Some(c)) => Some((a, b, c)),
                _ => None
            }
        })
    }

    // Read next char
    fn read_char(&mut self) -> Option<char> {
        if self.is_eof() {
            None
        } else {
            let r = self.s[self.pos] as char;
            self.pos += 1;
            Some(r)
        }
    }

    // Return char and advance iff next char is equal to requested
    fn read_given_char(&mut self, c: char) -> Option<char> {
        self.read_atomically(|p| {
            match p.read_char() {
                Some(next) if next == c => Some(next),
                _ => None,
            }
        })
    }

    // Read digit
    fn read_digit(&mut self, radix: u8) -> Option<u8> {
        fn parse_digit(c: char, radix: u8) -> Option<u8> {
            let c = c as u8;
            // assuming radix is either 10 or 16
            if c >= b'0' && c <= b'9' {
                Some(c - b'0')
            } else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) {
                Some(c - b'a' + 10)
            } else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) {
                Some(c - b'A' + 10)
            } else {
                None
            }
        }

        self.read_atomically(|p| {
            p.read_char().and_then(|c| parse_digit(c, radix))
        })
    }

    fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
        let mut r = 0;
        let mut digit_count = 0;
        loop {
            match self.read_digit(radix) {
                Some(d) => {
                    r = r * (radix as u32) + (d as u32);
                    digit_count += 1;
                    if digit_count > max_digits || r >= upto {
                        return None
                    }
                }
                None => {
                    if digit_count == 0 {
                        return None
                    } else {
                        return Some(r)
                    }
                }
            };
        }
    }

    // Read number, failing if max_digits of number value exceeded
    fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
        self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto))
    }

    fn read_ipv4_addr_impl(&mut self) -> Option<Ipv4Addr> {
        let mut bs = [0; 4];
        let mut i = 0;
        while i < 4 {
            if i != 0 && self.read_given_char('.').is_none() {
                return None;
            }

            let octet = self.read_number(10, 3, 0x100).map(|n| n as u8);
            match octet {
                Some(d) => bs[i] = d,
                None => return None,
            };
            i += 1;
        }
        Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3]))
    }

    // Read IPv4 address
    fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
        self.read_atomically(|p| p.read_ipv4_addr_impl())
    }

    fn read_ipv6_addr_impl(&mut self) -> Option<Ipv6Addr> {
        fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
            assert!(head.len() + tail.len() <= 8);
            let mut gs = [0; 8];
            gs.clone_from_slice(head);
            gs[(8 - tail.len()) .. 8].clone_from_slice(tail);
            Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
        }

        fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize)
                       -> (usize, bool) {
            let mut i = 0;
            while i < limit {
                if i < limit - 1 {
                    let ipv4 = p.read_atomically(|p| {
                        if i == 0 || p.read_given_char(':').is_some() {
                            p.read_ipv4_addr()
                        } else {
                            None
                        }
                    });
                    if let Some(v4_addr) = ipv4 {
                        let octets = v4_addr.octets();
                        groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16);
                        groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16);
                        return (i + 2, true);
                    }
                }

                let group = p.read_atomically(|p| {
                    if i == 0 || p.read_given_char(':').is_some() {
                        p.read_number(16, 4, 0x10000).map(|n| n as u16)
                    } else {
                        None
                    }
                });
                match group {
                    Some(g) => groups[i] = g,
                    None => return (i, false)
                }
                i += 1;
            }
            (i, false)
        }

        let mut head = [0; 8];
        let (head_size, head_ipv4) = read_groups(self, &mut head, 8);

        if head_size == 8 {
            return Some(Ipv6Addr::new(
                head[0], head[1], head[2], head[3],
                head[4], head[5], head[6], head[7]))
        }

        // IPv4 part is not allowed before `::`
        if head_ipv4 {
            return None
        }

        // read `::` if previous code parsed less than 8 groups
        if !self.read_given_char(':').is_some() || !self.read_given_char(':').is_some() {
            return None;
        }

        let mut tail = [0; 8];
        let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size);
        Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size]))
    }

    fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
        self.read_atomically(|p| p.read_ipv6_addr_impl())
    }

    fn read_ip_addr(&mut self) -> Option<IpAddr> {
        let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr().map(|v4| IpAddr::V4(v4));
        let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr().map(|v6| IpAddr::V6(v6));
        self.read_or(&mut [Box::new(ipv4_addr), Box::new(ipv6_addr)])
    }

    fn read_socket_addr(&mut self) -> Option<SocketAddr> {
        let ip_addr = |p: &mut Parser| {
            let ipv4_p = |p: &mut Parser| p.read_ip_addr();
            let ipv6_p = |p: &mut Parser| {
                let open_br = |p: &mut Parser| p.read_given_char('[');
                let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
                let clos_br = |p: &mut Parser| p.read_given_char(']');
                p.read_seq_3::<char, Ipv6Addr, char, _, _, _>(open_br, ip_addr, clos_br)
                        .map(|t| match t { (_, ip, _) => IpAddr::V6(ip) })
            };
            p.read_or(&mut [Box::new(ipv4_p), Box::new(ipv6_p)])
        };
        let colon = |p: &mut Parser| p.read_given_char(':');
        let port  = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);

        // host, colon, port
        self.read_seq_3(ip_addr, colon, port).map(|t| {
            let (ip, _, port): (IpAddr, char, u16) = t;
            match ip {
                IpAddr::V4(ip) => SocketAddr::V4(SocketAddrV4::new(ip, port)),
                IpAddr::V6(ip) => SocketAddr::V6(SocketAddrV6::new(ip, port, 0, 0)),
            }
        })
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for IpAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ip_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for Ipv4Addr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ipv4_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for Ipv6Addr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_ipv6_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(()))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for SocketAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
        match Parser::new(s).read_till_eof(|p| p.read_socket_addr()) {
            Some(s) => Ok(s),
            None => Err(AddrParseError(())),
        }
    }
}

/// An error returned when parsing an IP address or a socket address.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug, Clone, PartialEq)]
pub struct AddrParseError(());

impl fmt::Display for AddrParseError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(self.description())
    }
}

impl Error for AddrParseError {
    fn description(&self) -> &str {
        "invalid IP address syntax"
    }
}
<|endoftext|>


<commit_before><commit_msg>Create struct_handler.rs<commit_after>extern crate iron;

use iron::Handler;
use iron::status;
use iron::IronResult;
use iron::Response;
use iron::Request;
use iron::Iron;

struct MessageHandler {
    message: String
}

impl Handler for MessageHandler {
    fn handle(&self, _: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, self.message.clone())))
    }
}

fn main() {
    let echo = MessageHandler {
        message: "You've found the index page!".to_string()
    };

    let mut router = Router::new();
    router.get("/", echo, "index");

    Iron::new(router).http("localhost:3000").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Remove unnecessary static lifetime.<commit_after><|endoftext|>


<commit_before><commit_msg>Update should_use_metadata function<commit_after><|endoftext|>