<commit_before><commit_msg>Add some microbenchmarks<commit_after>#![feature(test)]
extern crate test;
extern crate specs;

mod world {
    use test;
    use specs;

    #[derive(Clone, Debug)]
    struct CompInt(i32);
    impl specs::Component for CompInt {
        type Storage = specs::VecStorage<CompInt>;
    }
    #[derive(Clone, Debug)]
    struct CompBool(bool);
    impl specs::Component for CompBool {
        type Storage = specs::HashMapStorage<CompBool>;
    }

    fn create_world() -> specs::World {
        let mut w = specs::World::new();
        w.register::<CompInt>();
        w.register::<CompBool>();
        w
    }

    #[bench]
    fn world_build(b: &mut test::Bencher) {
        b.iter(|| specs::World::new());
    }

    #[bench]
    fn create_now(b: &mut test::Bencher) {
        let w = specs::World::new();
        b.iter(|| w.create_now().build());
    }

    #[bench]
    fn create_now_with_storage(b: &mut test::Bencher) {
        let w = create_world();
        b.iter(|| w.create_now().with(CompInt(0)).build());
    }

    #[bench]
    fn create_later(b: &mut test::Bencher) {
        let w = specs::World::new();
        b.iter(|| w.create_later());
    }

    #[bench]
    fn delete_now(b: &mut test::Bencher) {
        let w = specs::World::new();
        let mut eids: Vec<_> = (0..1_000_000).map(|_| w.create_now().build()).collect();
        b.iter(|| w.delete_now(eids.pop().unwrap()));
    }

    #[bench]
    fn delete_now_with_storage(b: &mut test::Bencher) {
        let w = create_world();
        let mut eids: Vec<_> = (0..1_000_000).map(|_| w.create_now().with(CompInt(1)).build()).collect();
        b.iter(|| w.delete_now(eids.pop().unwrap()));
    }

    #[bench]
    fn delete_later(b: &mut test::Bencher) {
        let w = specs::World::new();
        let mut eids: Vec<_> = (0..1_000_000).map(|_| w.create_now().build()).collect();
        b.iter(|| w.delete_later(eids.pop().unwrap()));
    }

    #[bench]
    fn maintain_noop(b: &mut test::Bencher) {
        let w = specs::World::new();
        b.iter(|| {
            w.maintain();
        });
    }

    #[bench]
    fn maintain_add_later(b: &mut test::Bencher) {
        let w = specs::World::new();
        b.iter(|| {
            w.create_later();
            w.maintain();
        });
    }

    #[bench]
    fn maintain_delete_later(b: &mut test::Bencher) {
        let w = specs::World::new();
        let mut eids: Vec<_> = (0..1_000_000).map(|_| w.create_now().build()).collect();
        b.iter(|| {
            w.delete_later(eids.pop().unwrap());
            w.maintain();
        });
    }
}

mod bitset {
    use test;
    use specs::BitSet;

    #[bench]
    fn add(b: &mut test::Bencher) {
        let mut bitset = BitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        b.iter(|| range.next().map(|i| bitset.add(i)))
    }

    #[bench]
    fn remove_set(b: &mut test::Bencher) {
        let mut bitset = BitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        for i in 0..1_000_000 {
            bitset.add(i);
        }
        b.iter(|| range.next().map(|i| bitset.remove(i)))
    }

    #[bench]
    fn remove_clear(b: &mut test::Bencher) {
        let mut bitset = BitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        b.iter(|| range.next().map(|i| bitset.remove(i)))
    }

    #[bench]
    fn contains(b: &mut test::Bencher) {
        let mut bitset = BitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        for i in 0..500_000 {
            // events are set, odds are to keep the branch
            // prediction from getting to aggressive
            bitset.add(i * 2);
        }
        b.iter(|| range.next().map(|i| bitset.contains(i)))
    }
}

mod atomic_bitset {
    use test;
    use specs::AtomicBitSet;

    #[bench]
    fn add(b: &mut test::Bencher) {
        let mut bitset = AtomicBitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        b.iter(|| range.next().map(|i| bitset.add(i)))
    }

    #[bench]
    fn add_atomic(b: &mut test::Bencher) {
        let bitset = AtomicBitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        b.iter(|| range.next().map(|i| bitset.add_atomic(i)))
    }

    #[bench]
    fn remove_set(b: &mut test::Bencher) {
        let mut bitset = AtomicBitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        for i in 0..1_000_000 {
            bitset.add(i);
        }
        b.iter(|| range.next().map(|i| bitset.remove(i)))
    }

    #[bench]
    fn remove_clear(b: &mut test::Bencher) {
        let mut bitset = AtomicBitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        b.iter(|| range.next().map(|i| bitset.remove(i)))
    }

    #[bench]
    fn contains(b: &mut test::Bencher) {
        let mut bitset = AtomicBitSet::with_capacity(1_000_000);
        let mut range = (0..1_000_000).cycle();
        for i in 0..500_000 {
            // events are set, odds are to keep the branch
            // prediction from getting to aggressive
            bitset.add(i * 2);
        }
        b.iter(|| range.next().map(|i| bitset.contains(i)))
    }
}<|endoftext|>


<commit_before>use request::Request;
use response::Response;
use http::status;
use std::fmt::Show;

pub trait RequestHandler : Sync + Send {
    fn handle(&self, &Request, &mut Response);
}

impl<R> RequestHandler for fn(request: &Request, response: &mut Response) -> R
        where R: ResponseFinalizer {
    fn handle(&self, req: &Request, res: &mut Response) {
        let r = (*self)(req, res);
        r.respond(res);
    }
}

pub trait ResponseFinalizer {
    fn respond(self, &mut Response);
}

impl ResponseFinalizer for () {
    fn respond(self, _: &mut Response) {}
}

impl ResponseFinalizer for String {
    fn respond(self, res: &mut Response) {
        res.origin.status = status::Ok;
        res.send(self);
    }
}

impl<'a> ResponseFinalizer for &'a str {
    fn respond(self, res: &mut Response) {
        res.origin.status = status::Ok;
        res.send(self);
    }
}

impl<'a, S: Show> ResponseFinalizer for &'a [S] {
    fn respond(self, res: &mut Response) {
        res.origin.status = status::Ok;
        for ref s in self.iter() {
            // FIXME : failure unhandled
            let _ = write!(res.origin, "{}", s);
        }
    }
}

impl ResponseFinalizer for (status::Status, String) {
    fn respond(self, res: &mut Response) {
        let (status, data) = self;
        res.origin.status = status;
        res.send(data);
    }
}

impl<'a> ResponseFinalizer for (status::Status, &'a str) {
    fn respond(self, res: &mut Response) {
        let (status, data) = self;
        res.origin.status = status;
        res.send(data);
    }
}

impl<'a> ResponseFinalizer for (uint, String) {
    fn respond(self, res: &mut Response) {
        let (status, data) = self;
        match FromPrimitive::from_uint(status) {
            Some(status) => {
                res.origin.status = status;
                res.send(data);
            }
            None => {
                res.origin.status = status::InternalServerError;
                res.send("ERROR") //FIXME
            }
        }
    }
}

impl<'a> ResponseFinalizer for (uint, &'a str) {
    fn respond(self, res: &mut Response) {
        let (status, data) = self;
        match FromPrimitive::from_uint(status) {
            Some(status) => {
                res.origin.status = status;
                res.send(data);
            }
            None => {
                res.origin.status = status::InternalServerError;
                res.send("ERROR") //FIXME
            }
        }
    }
}
<commit_msg>refactor(ResponseFinalizer): cleanup duplicate code with macros<commit_after>use request::Request;
use response::Response;
use http::status;
use std::fmt::Show;

pub trait RequestHandler : Sync + Send {
    fn handle(&self, &Request, &mut Response);
}

impl<R> RequestHandler for fn(request: &Request, response: &mut Response) -> R
        where R: ResponseFinalizer {
    fn handle(&self, req: &Request, res: &mut Response) {
        let r = (*self)(req, res);
        r.respond(res);
    }
}

pub trait ResponseFinalizer {
    fn respond(self, &mut Response);
}

impl ResponseFinalizer for () {
    fn respond(self, _: &mut Response) {}
}

impl<'a, S: Show> ResponseFinalizer for &'a [S] {
    fn respond(self, res: &mut Response) {
        res.origin.status = status::Ok;
        for ref s in self.iter() {
            // FIXME : failure unhandled
            let _ = write!(res.origin, "{}", s);
        }
    }
}

macro_rules! dual_impl(
    ($view:ty, $alloc:ty |$s:ident, $res:ident| $b:block) => (
        impl<'a> ResponseFinalizer for $view {
            fn respond($s, $res: &mut Response) $b
        }

        impl ResponseFinalizer for $alloc {
            fn respond($s, $res: &mut Response) $b
        }
    )
)

dual_impl!(&'a str,
           String
            |self, res| {
                res.origin.status = status::Ok;
                res.send(self);
            })

dual_impl!((status::Status, &'a str),
           (status::Status, String)
            |self, res| {
                let (status, data) = self;
                res.origin.status = status;
                res.send(data);
            })

dual_impl!((uint, &'a str),
           (uint, String)
           |self, res| {
                let (status, data) = self;
                match FromPrimitive::from_uint(status) {
                    Some(status) => {
                        res.origin.status = status;
                        res.send(data);
                    }
                    None => {
                        res.origin.status = status::InternalServerError;
                        res.send("ERROR") //FIXME
                    }
                }
            })
<|endoftext|>


<commit_before><commit_msg>Add first integration test<commit_after>extern crate httpd = "tiny-http";

use std::io::net::tcp::TcpStream;

#[test]
fn basic_handling() {
    let (server, port) = httpd::Server::new_with_random_port().unwrap();

    let mut stream = std::io::net::tcp::TcpStream::connect("127.0.0.1", port);
    write!(stream, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");

    let request = server.recv().unwrap();
    assert!(request.get_method().equiv(&"get"));
    //assert!(request.get_url() == "/");
    request.respond(httpd::Response::from_string(format!("hello world")));

    server.try_recv().unwrap();

    let content = stream.read_to_string().unwrap();
    assert!(content.as_slice().ends_with("hello world"));
}
<|endoftext|>


<commit_before><commit_msg>Fix Sphinx integration tests<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #5620 : catamorphism/rust/issue-4325, r=catamorphism<commit_after>// Copyright 2013 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.

struct Node<'self, T> {
  val: T,
  next: Option<&'self Node<'self, T>>
}

impl<'self, T> Node<'self, T> {
  fn get(&self) -> &'self T {
    match self.next {
      Some(ref next) => next.get(),
      None => &self.val
    }
  }
}

fn main() {}
<|endoftext|>


<commit_before>/* 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 https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::XRViewBinding::{XREye, XRViewMethods};
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding;
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::XRWebGLLayerInit;
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::XRWebGLLayerMethods;
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextBinding::WebGLRenderingContextMethods;
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope;
use crate::dom::webgl_validations::types::TexImageTarget;
use crate::dom::webglframebuffer::WebGLFramebuffer;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use crate::dom::window::Window;
use crate::dom::xrsession::XRSession;
use crate::dom::xrview::XRView;
use crate::dom::xrviewport::XRViewport;
use dom_struct::dom_struct;
use js::rust::CustomAutoRooter;
use std::convert::TryInto;
use webxr_api::Views;

#[dom_struct]
pub struct XRWebGLLayer {
    reflector_: Reflector,
    antialias: bool,
    depth: bool,
    stencil: bool,
    alpha: bool,
    context: Dom<WebGLRenderingContext>,
    session: Dom<XRSession>,
    framebuffer: Dom<WebGLFramebuffer>,
}

impl XRWebGLLayer {
    pub fn new_inherited(
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
        framebuffer: &WebGLFramebuffer,
    ) -> XRWebGLLayer {
        XRWebGLLayer {
            reflector_: Reflector::new(),
            antialias: init.antialias,
            depth: init.depth,
            stencil: init.stencil,
            alpha: init.alpha,
            context: Dom::from_ref(context),
            session: Dom::from_ref(session),
            framebuffer: Dom::from_ref(framebuffer),
        }
    }

    pub fn new(
        global: &GlobalScope,
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
        framebuffer: &WebGLFramebuffer,
    ) -> DomRoot<XRWebGLLayer> {
        reflect_dom_object(
            Box::new(XRWebGLLayer::new_inherited(
                session,
                context,
                init,
                framebuffer,
            )),
            global,
            XRWebGLLayerBinding::Wrap,
        )
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-xrwebgllayer
    pub fn Constructor(
        global: &Window,
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
    ) -> Fallible<DomRoot<Self>> {
        // Step 2
        if session.is_ended() {
            return Err(Error::InvalidState);
        }
        // XXXManishearth step 3: throw error if context is lost
        // XXXManishearth step 4: check XR compat flag for immersive sessions

        let cx = global.get_cx();
        let old_fbo = context.bound_framebuffer();
        let old_rbo = context.bound_renderbuffer();
        let old_texture = context
            .textures()
            .active_texture_for_image_target(TexImageTarget::Texture2D);

        // Step 9.2. "Initialize layer’s framebuffer to a new opaque framebuffer created with
        // context and layerInit’s depth, stencil, and alpha values."
        let framebuffer = context.CreateFramebuffer().ok_or(Error::Operation)?;

        // Step 9.3. "Allocate and initialize resources compatible with session’s XR device,
        // including GPU accessible memory buffers, as required to support the compositing of layer."

        // Create a new texture with size given by the session's recommended resolution
        let texture = context.CreateTexture().ok_or(Error::Operation)?;
        let render_buffer = context.CreateRenderbuffer().ok_or(Error::Operation)?;
        let resolution = session.with_session(|s| s.recommended_framebuffer_resolution());
        let mut pixels = CustomAutoRooter::new(None);
        let mut clear_bits = constants::COLOR_BUFFER_BIT;

        let formats = context.formats();

        context.BindTexture(constants::TEXTURE_2D, Some(&texture));
        let sc = context.TexImage2D(
            constants::TEXTURE_2D,
            0,
            formats.texture_format,
            resolution.width,
            resolution.height,
            0,
            formats.texture_format,
            formats.texture_type,
            pixels.root(*cx),
        );

        // Bind the new texture to the framebuffer
        context.BindFramebuffer(constants::FRAMEBUFFER, Some(&framebuffer));
        context.FramebufferTexture2D(
            constants::FRAMEBUFFER,
            constants::COLOR_ATTACHMENT0,
            constants::TEXTURE_2D,
            Some(&texture),
            0,
        );

        // Create backing store and bind a renderbuffer if requested
        if init.depth || init.stencil {
            let (internal_format, attachment) = if init.depth && init.stencil {
                clear_bits |= constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT;
                (
                    constants::DEPTH_STENCIL,
                    constants::DEPTH_STENCIL_ATTACHMENT,
                )
            } else if init.depth {
                clear_bits |= constants::DEPTH_BUFFER_BIT;
                (constants::DEPTH_COMPONENT16, constants::DEPTH_ATTACHMENT)
            } else {
                clear_bits |= constants::STENCIL_BUFFER_BIT;
                (constants::STENCIL_INDEX8, constants::STENCIL_ATTACHMENT)
            };
            context.BindRenderbuffer(constants::RENDERBUFFER, Some(&render_buffer));
            context.RenderbufferStorage(
                constants::RENDERBUFFER,
                internal_format,
                resolution.width,
                resolution.height,
            );
            context.FramebufferRenderbuffer(
                constants::FRAMEBUFFER,
                attachment,
                constants::RENDERBUFFER,
                Some(&render_buffer),
            );
        }

        context.initialize_framebuffer(clear_bits);

        // Restore the WebGL state while complaining about global mutable state
        let fb_status = context.CheckFramebufferStatus(constants::FRAMEBUFFER);
        let gl_status = context.GetError();
        context.BindTexture(constants::TEXTURE_2D, old_texture.as_ref().map(|t| &**t));
        context.BindFramebuffer(constants::FRAMEBUFFER, old_fbo.as_ref().map(|f| &**f));
        context.BindRenderbuffer(constants::RENDERBUFFER, old_rbo.as_ref().map(|f| &**f));

        // Step 9.4: "If layer’s resources were unable to be created for any reason,
        // throw an OperationError and abort these steps."
        if let Err(err) = sc {
            error!("TexImage2D error {:?} while creating XR context", err);
            return Err(Error::Operation);
        }
        if fb_status != constants::FRAMEBUFFER_COMPLETE {
            error!(
                "Framebuffer error {:x} while creating XR context",
                fb_status
            );
            return Err(Error::Operation);
        }
        if gl_status != constants::NO_ERROR {
            error!("GL error {:x} while creating XR context", gl_status);
            return Err(Error::Operation);
        }

        // Step 10. "Return layer."
        Ok(XRWebGLLayer::new(
            &global.global(),
            session,
            context,
            init,
            &framebuffer,
        ))
    }

    pub fn session(&self) -> &XRSession {
        &self.session
    }

    pub fn framebuffer(&self) -> &WebGLFramebuffer {
        &self.framebuffer
    }
}

impl XRWebGLLayerMethods for XRWebGLLayer {
    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-depth
    fn Depth(&self) -> bool {
        self.depth
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-stencil
    fn Stencil(&self) -> bool {
        self.stencil
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-antialias
    fn Antialias(&self) -> bool {
        self.antialias
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-alpha
    fn Alpha(&self) -> bool {
        self.alpha
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-context
    fn Context(&self) -> DomRoot<WebGLRenderingContext> {
        DomRoot::from_ref(&self.context)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebuffer
    fn Framebuffer(&self) -> DomRoot<WebGLFramebuffer> {
        DomRoot::from_ref(&self.framebuffer)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferwidth
    fn FramebufferWidth(&self) -> u32 {
        self.framebuffer
            .size()
            .unwrap_or((0, 0))
            .0
            .try_into()
            .unwrap_or(0)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferheight
    fn FramebufferHeight(&self) -> u32 {
        self.framebuffer
            .size()
            .unwrap_or((0, 0))
            .1
            .try_into()
            .unwrap_or(0)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-getviewport
    fn GetViewport(&self, view: &XRView) -> Option<DomRoot<XRViewport>> {
        if self.session != view.session() {
            return None;
        }

        let views = self.session.with_session(|s| s.views().clone());

        let viewport = match (view.Eye(), views) {
            (XREye::None, Views::Mono(view)) => view.viewport,
            (XREye::Left, Views::Stereo(view, _)) => view.viewport,
            (XREye::Right, Views::Stereo(_, view)) => view.viewport,
            // The spec doesn't really say what to do in this case
            // https://github.com/immersive-web/webxr/issues/769
            _ => return None,
        };

        Some(XRViewport::new(&self.global(), viewport))
    }
}
<commit_msg>Auto merge of #24408 - servo:jdm-patch-31, r=Manishearth<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 https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::XRViewBinding::{XREye, XRViewMethods};
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding;
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::XRWebGLLayerInit;
use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::XRWebGLLayerMethods;
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextBinding::WebGLRenderingContextMethods;
use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope;
use crate::dom::webgl_validations::types::TexImageTarget;
use crate::dom::webglframebuffer::WebGLFramebuffer;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use crate::dom::window::Window;
use crate::dom::xrsession::XRSession;
use crate::dom::xrview::XRView;
use crate::dom::xrviewport::XRViewport;
use dom_struct::dom_struct;
use js::rust::CustomAutoRooter;
use std::convert::TryInto;
use webxr_api::Views;

#[dom_struct]
pub struct XRWebGLLayer {
    reflector_: Reflector,
    antialias: bool,
    depth: bool,
    stencil: bool,
    alpha: bool,
    context: Dom<WebGLRenderingContext>,
    session: Dom<XRSession>,
    framebuffer: Dom<WebGLFramebuffer>,
}

impl XRWebGLLayer {
    pub fn new_inherited(
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
        framebuffer: &WebGLFramebuffer,
    ) -> XRWebGLLayer {
        XRWebGLLayer {
            reflector_: Reflector::new(),
            antialias: init.antialias,
            depth: init.depth,
            stencil: init.stencil,
            alpha: init.alpha,
            context: Dom::from_ref(context),
            session: Dom::from_ref(session),
            framebuffer: Dom::from_ref(framebuffer),
        }
    }

    pub fn new(
        global: &GlobalScope,
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
        framebuffer: &WebGLFramebuffer,
    ) -> DomRoot<XRWebGLLayer> {
        reflect_dom_object(
            Box::new(XRWebGLLayer::new_inherited(
                session,
                context,
                init,
                framebuffer,
            )),
            global,
            XRWebGLLayerBinding::Wrap,
        )
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-xrwebgllayer
    pub fn Constructor(
        global: &Window,
        session: &XRSession,
        context: &WebGLRenderingContext,
        init: &XRWebGLLayerInit,
    ) -> Fallible<DomRoot<Self>> {
        // Step 2
        if session.is_ended() {
            return Err(Error::InvalidState);
        }
        // XXXManishearth step 3: throw error if context is lost
        // XXXManishearth step 4: check XR compat flag for immersive sessions

        let cx = global.get_cx();
        let old_fbo = context.bound_framebuffer();
        let old_rbo = context.bound_renderbuffer();
        let old_texture = context
            .textures()
            .active_texture_for_image_target(TexImageTarget::Texture2D);

        // Step 9.2. "Initialize layer’s framebuffer to a new opaque framebuffer created with
        // context and layerInit’s depth, stencil, and alpha values."
        let framebuffer = context.CreateFramebuffer().ok_or(Error::Operation)?;

        // Step 9.3. "Allocate and initialize resources compatible with session’s XR device,
        // including GPU accessible memory buffers, as required to support the compositing of layer."

        // Create a new texture with size given by the session's recommended resolution
        let texture = context.CreateTexture().ok_or(Error::Operation)?;
        let render_buffer = context.CreateRenderbuffer().ok_or(Error::Operation)?;
        let resolution = session.with_session(|s| s.recommended_framebuffer_resolution());
        let mut pixels = CustomAutoRooter::new(None);
        let mut clear_bits = constants::COLOR_BUFFER_BIT;

        let formats = context.formats();

        context.BindTexture(constants::TEXTURE_2D, Some(&texture));
        let sc = context.TexImage2D(
            constants::TEXTURE_2D,
            0,
            formats.texture_format,
            resolution.width,
            resolution.height,
            0,
            formats.texture_format,
            formats.texture_type,
            pixels.root(*cx),
        );

        // Bind the new texture to the framebuffer
        context.BindFramebuffer(constants::FRAMEBUFFER, Some(&framebuffer));
        context.FramebufferTexture2D(
            constants::FRAMEBUFFER,
            constants::COLOR_ATTACHMENT0,
            constants::TEXTURE_2D,
            Some(&texture),
            0,
        );

        // Create backing store and bind a renderbuffer if requested
        if init.depth || init.stencil {
            let (internal_format, attachment) = if init.depth && init.stencil {
                clear_bits |= constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT;
                (
                    constants::DEPTH_STENCIL,
                    constants::DEPTH_STENCIL_ATTACHMENT,
                )
            } else if init.depth {
                clear_bits |= constants::DEPTH_BUFFER_BIT;
                (constants::DEPTH_COMPONENT16, constants::DEPTH_ATTACHMENT)
            } else {
                clear_bits |= constants::STENCIL_BUFFER_BIT;
                (constants::STENCIL_INDEX8, constants::STENCIL_ATTACHMENT)
            };
            context.BindRenderbuffer(constants::RENDERBUFFER, Some(&render_buffer));
            context.RenderbufferStorage(
                constants::RENDERBUFFER,
                internal_format,
                resolution.width,
                resolution.height,
            );
            context.FramebufferRenderbuffer(
                constants::FRAMEBUFFER,
                attachment,
                constants::RENDERBUFFER,
                Some(&render_buffer),
            );
        }

        context.initialize_framebuffer(clear_bits);

        // Restore the WebGL state while complaining about global mutable state
        let fb_status = context.CheckFramebufferStatus(constants::FRAMEBUFFER);
        let gl_status = context.GetError();
        context.BindTexture(constants::TEXTURE_2D, old_texture.as_ref().map(|t| &**t));
        context.BindFramebuffer(constants::FRAMEBUFFER, old_fbo.as_ref().map(|f| &**f));
        context.BindRenderbuffer(constants::RENDERBUFFER, old_rbo.as_ref().map(|f| &**f));

        // Step 9.4: "If layer’s resources were unable to be created for any reason,
        // throw an OperationError and abort these steps."
        if let Err(err) = sc {
            error!("TexImage2D error {:?} while creating XR context", err);
            return Err(Error::Operation);
        }
        if fb_status != constants::FRAMEBUFFER_COMPLETE {
            error!(
                "Framebuffer error {:x} while creating XR context",
                fb_status
            );
            return Err(Error::Operation);
        }
        if gl_status != constants::NO_ERROR {
            error!("GL error {:x} while creating XR context", gl_status);
            return Err(Error::Operation);
        }

        // Ensure that we finish setting up this layer before continuing.
        context.Finish();

        // Step 10. "Return layer."
        Ok(XRWebGLLayer::new(
            &global.global(),
            session,
            context,
            init,
            &framebuffer,
        ))
    }

    pub fn session(&self) -> &XRSession {
        &self.session
    }

    pub fn framebuffer(&self) -> &WebGLFramebuffer {
        &self.framebuffer
    }
}

impl XRWebGLLayerMethods for XRWebGLLayer {
    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-depth
    fn Depth(&self) -> bool {
        self.depth
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-stencil
    fn Stencil(&self) -> bool {
        self.stencil
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-antialias
    fn Antialias(&self) -> bool {
        self.antialias
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-alpha
    fn Alpha(&self) -> bool {
        self.alpha
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-context
    fn Context(&self) -> DomRoot<WebGLRenderingContext> {
        DomRoot::from_ref(&self.context)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebuffer
    fn Framebuffer(&self) -> DomRoot<WebGLFramebuffer> {
        DomRoot::from_ref(&self.framebuffer)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferwidth
    fn FramebufferWidth(&self) -> u32 {
        self.framebuffer
            .size()
            .unwrap_or((0, 0))
            .0
            .try_into()
            .unwrap_or(0)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferheight
    fn FramebufferHeight(&self) -> u32 {
        self.framebuffer
            .size()
            .unwrap_or((0, 0))
            .1
            .try_into()
            .unwrap_or(0)
    }

    /// https://immersive-web.github.io/webxr/#dom-xrwebgllayer-getviewport
    fn GetViewport(&self, view: &XRView) -> Option<DomRoot<XRViewport>> {
        if self.session != view.session() {
            return None;
        }

        let views = self.session.with_session(|s| s.views().clone());

        let viewport = match (view.Eye(), views) {
            (XREye::None, Views::Mono(view)) => view.viewport,
            (XREye::Left, Views::Stereo(view, _)) => view.viewport,
            (XREye::Right, Views::Stereo(_, view)) => view.viewport,
            // The spec doesn't really say what to do in this case
            // https://github.com/immersive-web/webxr/issues/769
            _ => return None,
        };

        Some(XRViewport::new(&self.global(), viewport))
    }
}
<|endoftext|>


<commit_before><commit_msg>Add frame related types<commit_after>pub const MAX_CHANNELS: usize = 8;

pub struct Frame {
  pub header: Header,
  pub footer: Footer,
}

#[derive(Clone, Copy)]
pub enum ChannelAssignment {
  Independent = 0,
  LeftSide    = 1,
  RightSide   = 2,
  MiddleSide  = 3,
}

#[derive(Clone, Copy)]
pub enum NumberType {
  Frame(u32),
  Sample(u64),
}

pub struct Header {
  pub block_size: u32,
  pub sample_rate: u32,
  pub channel_assignment: ChannelAssignment,
  pub bits_per_sample: usize,
  pub number: NumberType,
  pub crc: u8,
}

pub struct Footer(pub u16);
<|endoftext|>


<commit_before>use redox::*;

// TODO: Structure using loops

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'K') => {
                                    for _ in 1..15 {
                                        editor.up();
                                    }
                                },
                                (Normal, 'J') => {
                                    for _ in 1..15 {
                                        editor.down();
                                    }
                                },
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 'c') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 's') => {
                                    editor.backspace(window);
                                    *mode = Insert;
                                },
                                (Normal, 'o') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.right();
                                    while editor.cur() == ' ' ||
                                          editor.cur() == '\t' {
                                        editor.right();
                                    }
                                }
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.right();
                                    }
                                },
                                (Normal, '0') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.delete(window);
                                    }
                                },
                                (Normal, 'w') => {
                                    editor.save(window);
                                },
                                (Normal, 'e') => {
                                    editor.right();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' {
                                        editor.right();
                                    }
                                },
                                (Normal, 'b') => {
                                    editor.left();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' {
                                        editor.right()
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, c) => {
                                    editor.insert(c, window);
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<commit_msg>Fix s command<commit_after>use redox::*;

// TODO: Structure using loops

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'K') => {
                                    for _ in 1..15 {
                                        editor.up();
                                    }
                                },
                                (Normal, 'J') => {
                                    for _ in 1..15 {
                                        editor.down();
                                    }
                                },
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 'c') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 's') => {
                                    editor.delete(window);
                                    *mode = Insert;
                                },
                                (Normal, 'o') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.right();
                                    while editor.cur() == ' ' ||
                                          editor.cur() == '\t' {
                                        editor.right();
                                    }
                                }
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.right();
                                    }
                                },
                                (Normal, '0') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' {
                                        editor.delete(window);
                                    }
                                },
                                (Normal, 'w') => {
                                    editor.save(window);
                                },
                                (Normal, 'e') => {
                                    editor.right();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' {
                                        editor.right();
                                    }
                                },
                                (Normal, 'b') => {
                                    editor.left();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' {
                                        editor.right()
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, c) => {
                                    editor.insert(c, window);
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>fix build<commit_after><|endoftext|>


<commit_before><commit_msg>Set HTML content type on login page.<commit_after><|endoftext|>


<commit_before><commit_msg>Convert port number from isize to u16<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Eq<commit_after><|endoftext|>


<commit_before><commit_msg>Added System trait<commit_after><|endoftext|>


<commit_before><commit_msg>added CXXFLAGS=-std=c++11 to make<commit_after><|endoftext|>


<commit_before><commit_msg>deprecated items removed<commit_after><|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::DisableEffect()`<commit_after><|endoftext|>


<commit_before><commit_msg>Add documentation for all (current) types.<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing lib.rs<commit_after>extern crate petgraph;

use std::str::FromStr;
use std::fmt::Debug;
use std::io::BufRead;

use petgraph::graph::NodeIndex;
use petgraph::{Directed, Graph};

pub trait Visitor<NodeWt, EdgeWt> {
    fn init(&mut self, num_nodes: usize, num_edges: usize);
    fn node(&mut self, node_id: usize, node_weight: Option<NodeWt>);
    fn endnode(&mut self, _node_id: usize) {
    }
    fn edge(&mut self, src_id: usize, dst_id: usize, edge_weight: Option<EdgeWt>);
}

pub fn read_sgf<R, V, NodeWt, EdgeWt, I>(rd: &mut R, visitor: &mut V)
    where R: BufRead,
          V: Visitor<NodeWt, EdgeWt>,
          NodeWt: FromStr<Err = I>,
          EdgeWt: FromStr<Err = I>,
          I: Debug
{
    let mut meta: Option<(usize, usize)> = None;

    for line in rd.lines() {
        let line = line.unwrap();
        let line = line.trim();

        if line.starts_with("#") {
            // skip comment
            continue;
        }

        if meta.is_none() {
            // First non-comment line is expected to be meta
            let mut m = line.split_whitespace();
            let _version = match m.next() {
                Some("SGF/1") => {
                    1
                }
                _ => {
                    panic!("Invalid format");
                }
            };
            let num_nodes: usize = match m.next() {
                Some(ns) => {
                    ns.parse().unwrap()
                }
                _ => {
                    panic!("Invalid format");
                }
            };
            let num_edges: usize = match m.next() {
                Some(ns) => {
                    ns.parse().unwrap()
                }
                _ => {
                    panic!("Invalid format");
                }
            };

            meta = Some((num_nodes, num_edges));

            visitor.init(num_nodes, num_edges);
        } else {
            let mut i = line.splitn(2, '|');
            let (node_id, node_weight) = match i.next() {
                Some(ns) => {
                    let mut it = ns.splitn(2, ":");
                    let node_id: usize = it.next().unwrap().parse().unwrap();
                    let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap());
                    (node_id, node_weight)
                }
                _ => {
                    panic!("Invalid format");
                }
            };
            visitor.node(node_id, node_weight);

            let edge_s = i.next().unwrap();
            for es in edge_s.split(',') {
                let mut it = es.splitn(2, ":");
                let target_id: usize = it.next()
                                         .unwrap()
                                         .parse()
                                         .unwrap();

                let edge_weight: Option<EdgeWt> = it.next()
                                                    .map(|s| s.parse::<EdgeWt>().unwrap());

                visitor.edge(node_id, target_id, edge_weight);
            }

            visitor.endnode(node_id);
        }
    }
}

pub struct PetgraphReader<NodeWt: Default, EdgeWt: Default> {
    graph: Graph<NodeWt, EdgeWt, Directed>,
}

impl<NodeWt, EdgeWt, I> PetgraphReader<NodeWt, EdgeWt>
where NodeWt: Default+FromStr<Err = I>,
      EdgeWt: Default+FromStr<Err = I>,
      I:Debug
{
    pub fn new() -> PetgraphReader<NodeWt, EdgeWt> {
        PetgraphReader { graph: Graph::new() }
    }

    pub fn from_sgf<R: BufRead>(rd: &mut R) -> Graph<NodeWt, EdgeWt, Directed> {
        let mut visitor = Self::new();
        read_sgf(rd, &mut visitor);
        return visitor.graph;
    }
}

impl<NodeWt:Default, EdgeWt:Default> Visitor<NodeWt, EdgeWt> for PetgraphReader<NodeWt, EdgeWt> {
    fn init(&mut self, num_nodes: usize, _num_edges: usize) {
        for _ in 0..num_nodes {
            self.graph.add_node(NodeWt::default());
        }
    }

    fn node(&mut self, node_id: usize, node_weight: Option<NodeWt>) {
        *self.graph.node_weight_mut(NodeIndex::new(node_id)).unwrap() =
            node_weight.unwrap_or(NodeWt::default());
    }

    fn edge(&mut self, src_id: usize, dst_id: usize, edge_weight: Option<EdgeWt>) {
        let _ = self.graph.add_edge(NodeIndex::new(src_id),
                                    NodeIndex::new(dst_id),
                                    edge_weight.unwrap_or(EdgeWt::default()));
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix parsing of long opts and short ops<commit_after><|endoftext|>


<commit_before><commit_msg>Implement writev<commit_after><|endoftext|>


<commit_before><commit_msg>print work<commit_after><|endoftext|>


<commit_before>#![crate_name = "liquid"]
#![doc(html_root_url = "https://cobalt-org.github.io/liquid-rust/")]

#![deny(warnings)]

extern crate regex;

use std::collections::HashMap;
use lexer::Token;
use lexer::Element;
use tags::{comment_block, raw_block, for_block, if_block};
use std::default::Default;
use error::Result;

pub use value::Value;
pub use context::Context;
pub use template::Template;
pub use error::Error;

pub mod lexer;
pub mod parser;

mod error;
mod template;
mod output;
mod text;
mod tags;
mod filters;
mod value;
mod variable;
mod context;

/// The ErrorMode to use.
/// This currently does not have an effect, until
/// ErrorModes are properly implemented.
#[derive(Clone, Copy)]
pub enum ErrorMode{
    Strict,
    Warn,
    Lax
}

impl Default for ErrorMode {
   fn default() -> ErrorMode { ErrorMode::Warn }
}

/// A trait for creating custom tags. This is a simple type alias for a function.
///
/// This function will be called whenever the parser encounters a tag and returns
/// a new [Renderable](trait.Renderable.html) based on its parameters. The received parameters
/// specify the name of the tag, the argument [Tokens](lexer/enum.Token.html) passed to
/// the tag and the global [LiquidOptions](struct.LiquidOptions.html).
///
/// ## Minimal Example
/// ```
/// # use std::default::Default;
/// # use liquid::Renderable;
/// # use liquid::LiquidOptions;
/// # use liquid::Context;
/// # use liquid::Error;
/// # use liquid::Tag;
/// # use liquid::lexer::Token;
/// struct HelloWorld;
///
/// impl Renderable for HelloWorld {
///     fn render(&self, _context: &mut Context) -> Result<Option<String>, Error>{
///         Ok(Some("Hello World!".to_owned()))
///     }
/// }
///
/// fn hw_block(tag_name: &str, arguments: &[Token], options: &LiquidOptions) -> Box<Renderable> {
///      Box::new(HelloWorld) as Box<Renderable>
/// }
///
/// let mut options : LiquidOptions = Default::default();
/// options.tags.insert("hello_world".to_owned(), Box::new(hw_block) as Box<Tag>);
///
/// let template = liquid::parse("{{hello_world}}", options).unwrap();
/// let mut data = Context::new();
/// let output = template.render(&mut data);
/// assert_eq!(output.unwrap(), Some("Hello World!".to_owned()));
/// ```
pub type Tag = Fn(&str, &[Token], &LiquidOptions) -> Box<Renderable>;

/// A trait for creating custom custom block-size tags (`{% if something %}{% endif %}`). This is a simple type alias for a function.
///
/// This function will be called whenever the parser encounters a block and returns
/// a new `Renderable` based on its parameters. The received parameters specify the name
/// of the block, the argument [Tokens](lexer/enum.Token.html) passed to
/// the block, a Vec of all [Elements](lexer/enum.Element.html) inside the block and the global [LiquidOptions](struct.LiquidOptions.html).
pub type Block = Fn(&str, &[Token], Vec<Element>, &LiquidOptions) -> Result<Box<Renderable>>;

/// Any object (tag/block) that can be rendered by liquid must implement this trait.
pub trait Renderable{
    fn render(&self, context: &mut Context) -> Result<Option<String>>;
}

#[derive(Default)]
pub struct LiquidOptions {
    pub blocks : HashMap<String, Box<Block>>,
    pub tags : HashMap<String, Box<Tag>>,
    pub error_mode : ErrorMode
}

/// Parses a liquid template, returning a Template object.
/// # Examples
///
/// ## Minimal Template
///
/// ```
/// use std::default::Default;
/// use liquid::Renderable;
/// use liquid::LiquidOptions;
/// use liquid::Context;
///
/// let mut options : LiquidOptions = Default::default();
/// let template = liquid::parse("Liquid!", options).unwrap();
/// let mut data = Context::new();
/// let output = template.render(&mut data);
/// assert_eq!(output.unwrap(), Some("Liquid!".to_owned()));
/// ```
///
pub fn parse (text: &str, options: LiquidOptions) -> Result<Template>{
    let mut options = options;
    let tokens = try!(lexer::tokenize(&text));
    options.blocks.insert("raw".to_owned(), Box::new(raw_block));
    options.blocks.insert("if".to_owned(), Box::new(if_block));
    options.blocks.insert("for".to_owned(), Box::new(for_block));
    options.blocks.insert("comment".to_owned(), Box::new(comment_block));

    parser::parse(&tokens, &options).map(|renderables| Template::new(renderables))
}

<commit_msg>Expose FilterResult and FilterError<commit_after>#![crate_name = "liquid"]
#![doc(html_root_url = "https://cobalt-org.github.io/liquid-rust/")]

#![deny(warnings)]

extern crate regex;

use std::collections::HashMap;
use lexer::Token;
use lexer::Element;
use tags::{comment_block, raw_block, for_block, if_block};
use std::default::Default;
use error::Result;

pub use value::Value;
pub use context::Context;
pub use template::Template;
pub use error::Error;
pub use filters::FilterResult;
pub use filters::FilterError;

pub mod lexer;
pub mod parser;

mod error;
mod template;
mod output;
mod text;
mod tags;
mod filters;
mod value;
mod variable;
mod context;

/// The ErrorMode to use.
/// This currently does not have an effect, until
/// ErrorModes are properly implemented.
#[derive(Clone, Copy)]
pub enum ErrorMode{
    Strict,
    Warn,
    Lax
}

impl Default for ErrorMode {
   fn default() -> ErrorMode { ErrorMode::Warn }
}

/// A trait for creating custom tags. This is a simple type alias for a function.
///
/// This function will be called whenever the parser encounters a tag and returns
/// a new [Renderable](trait.Renderable.html) based on its parameters. The received parameters
/// specify the name of the tag, the argument [Tokens](lexer/enum.Token.html) passed to
/// the tag and the global [LiquidOptions](struct.LiquidOptions.html).
///
/// ## Minimal Example
/// ```
/// # use std::default::Default;
/// # use liquid::Renderable;
/// # use liquid::LiquidOptions;
/// # use liquid::Context;
/// # use liquid::Error;
/// # use liquid::Tag;
/// # use liquid::lexer::Token;
/// struct HelloWorld;
///
/// impl Renderable for HelloWorld {
///     fn render(&self, _context: &mut Context) -> Result<Option<String>, Error>{
///         Ok(Some("Hello World!".to_owned()))
///     }
/// }
///
/// fn hw_block(tag_name: &str, arguments: &[Token], options: &LiquidOptions) -> Box<Renderable> {
///      Box::new(HelloWorld) as Box<Renderable>
/// }
///
/// let mut options : LiquidOptions = Default::default();
/// options.tags.insert("hello_world".to_owned(), Box::new(hw_block) as Box<Tag>);
///
/// let template = liquid::parse("{{hello_world}}", options).unwrap();
/// let mut data = Context::new();
/// let output = template.render(&mut data);
/// assert_eq!(output.unwrap(), Some("Hello World!".to_owned()));
/// ```
pub type Tag = Fn(&str, &[Token], &LiquidOptions) -> Box<Renderable>;

/// A trait for creating custom custom block-size tags (`{% if something %}{% endif %}`). This is a simple type alias for a function.
///
/// This function will be called whenever the parser encounters a block and returns
/// a new `Renderable` based on its parameters. The received parameters specify the name
/// of the block, the argument [Tokens](lexer/enum.Token.html) passed to
/// the block, a Vec of all [Elements](lexer/enum.Element.html) inside the block and the global [LiquidOptions](struct.LiquidOptions.html).
pub type Block = Fn(&str, &[Token], Vec<Element>, &LiquidOptions) -> Result<Box<Renderable>>;

/// Any object (tag/block) that can be rendered by liquid must implement this trait.
pub trait Renderable{
    fn render(&self, context: &mut Context) -> Result<Option<String>>;
}

#[derive(Default)]
pub struct LiquidOptions {
    pub blocks : HashMap<String, Box<Block>>,
    pub tags : HashMap<String, Box<Tag>>,
    pub error_mode : ErrorMode
}

/// Parses a liquid template, returning a Template object.
/// # Examples
///
/// ## Minimal Template
///
/// ```
/// use std::default::Default;
/// use liquid::Renderable;
/// use liquid::LiquidOptions;
/// use liquid::Context;
///
/// let mut options : LiquidOptions = Default::default();
/// let template = liquid::parse("Liquid!", options).unwrap();
/// let mut data = Context::new();
/// let output = template.render(&mut data);
/// assert_eq!(output.unwrap(), Some("Liquid!".to_owned()));
/// ```
///
pub fn parse (text: &str, options: LiquidOptions) -> Result<Template>{
    let mut options = options;
    let tokens = try!(lexer::tokenize(&text));
    options.blocks.insert("raw".to_owned(), Box::new(raw_block));
    options.blocks.insert("if".to_owned(), Box::new(if_block));
    options.blocks.insert("for".to_owned(), Box::new(for_block));
    options.blocks.insert("comment".to_owned(), Box::new(comment_block));

    parser::parse(&tokens, &options).map(|renderables| Template::new(renderables))
}

<|endoftext|>


<commit_before><commit_msg>First try for scheduling API<commit_after>#![feature(box_patterns)]

#[macro_use]
extern crate derive_new;
extern crate chrono;
extern crate take_mut;

#[cfg(test)]
#[macro_use]
extern crate assert_matches;

mod schedule_tree;

use chrono::{DateTime, Duration, UTC};
use schedule_tree::ScheduleTree;

#[derive(Debug, PartialEq, new, Clone)]
pub struct Task<'a> {
    content: &'a str,
    deadline: Option<DateTime<UTC>>,
    duration: Duration,
    importance: u8,
}

#[derive(Debug, new)]
struct ScheduledTask<'b, 'a: 'b> {
    task: &'b Task<'a>,
    when: DateTime<UTC>,
}

#[derive(Debug)]
pub struct Schedule<'b, 'a: 'b>(Vec<ScheduledTask<'b, 'a>>);

impl<'b, 'a> Schedule<'b, 'a> {
    /// Schedules tasks according to their deadlines, importance and duration.
    /// First, all tasks --- starting with the most important until the least important --- are
    /// scheduled as close as possible to their deadline.
    /// Next, all tasks --- starting with the most urgent one until the least urgent --- are put as
    /// close to the present as possible. This is too take care of contingencies like falling sick.
    /// A downside might be that a lot of time is spent doing urgent but non-important tasks.
    ///
    /// Args:
    ///     tasks: ordered list of tasks to schedule, ordered from most important to least
    ///     important.
    pub fn schedule<'c: 'b>(tasks: &'c [Task<'a>]) -> Schedule<'b, 'a> {
        let mut tree = ScheduleTree::new();
        for task in tasks {
            // TODO unwrap
            let start = task.deadline.unwrap() - task.duration;
            // TODO schedule close before the deadline
            tree.schedule_exact(start, task.duration, task);
        }
        let importance_schedule = tree.iter().map(|entry| {
            ScheduledTask::new(entry.data, entry.start)
        }).collect();
        // TODO let urgent_first_schedule = importance_schedule
        Schedule(importance_schedule)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_tasks_are_planned() {
        let tasks = taskset1();
        let schedule = Schedule::schedule(&tasks);
        for scheduled_task in schedule.0 {
            assert!(tasks.contains(&scheduled_task.task))
        }
    }

    #[test]
    fn tasks_are_in_order() {
        let tasks = taskset1();
        let schedule = Schedule::schedule(&tasks);
        assert!(schedule.0[0].task.deadline < schedule.0[1].task.deadline);
        assert!(schedule.0[0].when < schedule.0[1].when);
    }

    fn taskset1<'a>() -> Vec<Task<'a>> {
        let task1 = Task {
            content: "do stuff",
            deadline: Some(UTC::now() + Duration::days(3)),
            duration: Duration::hours(2),
            importance: 5,
        };
        let task2 = Task {
            content: "contemplate life",
            deadline: Some(UTC::now() + Duration::days(4)),
            duration: Duration::hours(12),
            importance: 6,
        };
        vec![task1, task2]
    }
}
<|endoftext|>


<commit_before><commit_msg>Change one operation over to new higher level fn<commit_after><|endoftext|>


<commit_before><commit_msg>Being work to handle directives<commit_after><|endoftext|>


<commit_before><commit_msg>generalize random population sampling<commit_after><|endoftext|>


<commit_before><commit_msg>Reorganize drawing into 8-pixel high blocks<commit_after><|endoftext|>


<commit_before><commit_msg>Convert vip timing to clocks, not ns<commit_after><|endoftext|>


<commit_before><commit_msg>Fix up VSU timing<commit_after><|endoftext|>


<commit_before><commit_msg>Proper output bit masking<commit_after><|endoftext|>


<commit_before>// Copyright 2014 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 std::fs::File;
use std::io::prelude::*;
use std::io;
use std::path::Path;
use std::str;

#[derive(Clone)]
pub struct ExternalHtml{
    /// Content that will be included inline in the <head> section of a
    /// rendered Markdown file or generated documentation
    pub in_header: String,
    /// Content that will be included inline between <body> and the content of
    /// a rendered Markdown file or generated documentation
    pub before_content: String,
    /// Content that will be included inline between the content and </body> of
    /// a rendered Markdown file or generated documentation
    pub after_content: String
}

impl ExternalHtml {
    pub fn load(in_header: &[String], before_content: &[String], after_content: &[String])
            -> Option<ExternalHtml> {
        match (load_external_files(in_header),
               load_external_files(before_content),
               load_external_files(after_content)) {
            (Some(ih), Some(bc), Some(ac)) => Some(ExternalHtml {
                in_header: ih,
                before_content: bc,
                after_content: ac
            }),
            _ => None
        }
    }
}

pub enum LoadStringError {
    ReadFail,
    BadUtf8,
}

pub fn load_string<P: AsRef<Path>>(file_path: P) -> Result<String, LoadStringError> {
    let file_path = file_path.as_ref();
    let mut contents = vec![];
    let result = File::open(file_path)
                      .and_then(|mut f| f.read_to_end(&mut contents));
    if let Err(e) = result {
        let _ = writeln!(&mut io::stderr(),
                         "error reading `{}`: {}",
                         file_path.display(), e);
        return Err(LoadStringError::ReadFail);
    }
    match str::from_utf8(&contents) {
        Ok(s) => Ok(s.to_string()),
        Err(_) => {
            let _ = writeln!(&mut io::stderr(),
                             "error reading `{}`: not UTF-8",
                             file_path.display());
            Err(LoadStringError::BadUtf8)
        }
    }
}

pub fn load_external_files(names: &[String]) -> Option<String> {
    let mut out = String::new();
    for name in names {
        let s = match load_string(name) {
            Ok(s) => s,
            Err(_) => return None,
        };
        out.push_str(&s);
        out.push('\n');
    }
    Some(out)
}
<commit_msg>Make `ExternalHtml::load` short-circuited.<commit_after>// Copyright 2014 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 std::fs::File;
use std::io::prelude::*;
use std::io;
use std::path::Path;
use std::str;

#[derive(Clone)]
pub struct ExternalHtml{
    /// Content that will be included inline in the <head> section of a
    /// rendered Markdown file or generated documentation
    pub in_header: String,
    /// Content that will be included inline between <body> and the content of
    /// a rendered Markdown file or generated documentation
    pub before_content: String,
    /// Content that will be included inline between the content and </body> of
    /// a rendered Markdown file or generated documentation
    pub after_content: String
}

impl ExternalHtml {
    pub fn load(in_header: &[String], before_content: &[String], after_content: &[String])
            -> Option<ExternalHtml> {
        load_external_files(in_header)
            .and_then(|ih|
                load_external_files(before_content)
                    .map(|bc| (ih, bc))
            )
            .and_then(|(ih, bc)|
                load_external_files(after_content)
                    .map(|ac| (ih, bc, ac))
            )
            .map(|(ih, bc, ac)|
                ExternalHtml {
                    in_header: ih,
                    before_content: bc,
                    after_content: ac,
                }
            )
    }
}

pub enum LoadStringError {
    ReadFail,
    BadUtf8,
}

pub fn load_string<P: AsRef<Path>>(file_path: P) -> Result<String, LoadStringError> {
    let file_path = file_path.as_ref();
    let mut contents = vec![];
    let result = File::open(file_path)
                      .and_then(|mut f| f.read_to_end(&mut contents));
    if let Err(e) = result {
        let _ = writeln!(&mut io::stderr(),
                         "error reading `{}`: {}",
                         file_path.display(), e);
        return Err(LoadStringError::ReadFail);
    }
    match str::from_utf8(&contents) {
        Ok(s) => Ok(s.to_string()),
        Err(_) => {
            let _ = writeln!(&mut io::stderr(),
                             "error reading `{}`: not UTF-8",
                             file_path.display());
            Err(LoadStringError::BadUtf8)
        }
    }
}

pub fn load_external_files(names: &[String]) -> Option<String> {
    let mut out = String::new();
    for name in names {
        let s = match load_string(name) {
            Ok(s) => s,
            Err(_) => return None,
        };
        out.push_str(&s);
        out.push('\n');
    }
    Some(out)
}
<|endoftext|>


<commit_before><commit_msg>Add custom_format example<commit_after>use std::collections::HashMap;

use config::{Config, File, FileExtensions, Format, Value, ValueKind};

fn main() {
    let config = Config::builder()
        .add_source(File::from_str("bad", MyFormat))
        .add_source(File::from_str("good", MyFormat))
        .build();

    match config {
        Ok(cfg) => println!("A config: {:#?}", cfg),
        Err(e) => println!("An error: {}", e),
    }
}

#[derive(Debug, Clone)]
pub struct MyFormat;

impl Format for MyFormat {
    fn parse(
        &self,
        uri: Option<&String>,
        text: &str,
    ) -> Result<
        std::collections::HashMap<String, config::Value>,
        Box<dyn std::error::Error + Send + Sync>,
    > {
        // Let's assume our format is somewhat crippled, but this is fine
        // In real life anything can be used here - nom, serde or other.
        //
        // For some more real-life examples refer to format implementation within the library code
        let mut result = HashMap::new();

        if text == "good" {
            result.insert(
                "key".to_string(),
                Value::new(uri, ValueKind::String(text.into())),
            );
        } else {
            println!("Something went wrong in {:?}", uri);
        }

        Ok(result)
    }
}

// As crazy as it seems for config sourced from a string, legacy demands its sacrifice
// It is only required for File source, custom sources can use Format without caring for extensions
static MY_FORMAT_EXT: Vec<&'static str> = vec![];
impl FileExtensions for MyFormat {
    fn extensions(&self) -> &Vec<&'static str> {
        &MY_FORMAT_EXT
    }
}
<|endoftext|>


<commit_before><commit_msg>Create ex3.rs<commit_after>// Make me compile!

struct Foo {
    capacity: i32,
}

fn main() {
    println!("{:?}", Foo { capacity: 3 });
}
<|endoftext|>


<commit_before>import std::{io, term};
import io::writer_util;
import syntax::codemap;
import codemap::span;

export emitter, emit_diagnostic;
export diagnostictype, fatal, error, warning, note;
export handler, mk_codemap_handler;

type emitter = fn@(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype);

iface handler {
    fn span_fatal(sp: span, msg: str) -> !;
    fn fatal(msg: str) -> !;
    fn span_err(sp: span, msg: str);
    fn err(msg: str);
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn span_warn(sp: span, msg: str);
    fn warn(msg: str);
    fn span_note(sp: span, msg: str);
    fn note(msg: str);
    fn span_bug(sp: span, msg: str) -> !;
    fn bug(msg: str) -> !;
    fn span_unimpl(sp: span, msg: str) -> !;
    fn unimpl(msg: str) -> !;
}

type codemap_t = @{
    cm: codemap::codemap,
    mutable err_count: uint,
    emit: emitter
};

impl codemap_handler of handler for codemap_t {
    fn span_fatal(sp: span, msg: str) -> ! {
        self.emit(some((self.cm, sp)), msg, fatal);
        fail;
    }
    fn fatal(msg: str) -> ! {
        self.emit(none, msg, fatal);
        fail;
    }
    fn span_err(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, error);
        self.err_count += 1u;
    }
    fn err(msg: str) {
        self.emit(none, msg, error);
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        if self.err_count > 0u {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, warning);
    }
    fn warn(msg: str) {
        self.emit(none, msg, warning);
    }
    fn span_note(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, note);
    }
    fn note(msg: str) {
        self.emit(none, msg, note);
    }
    fn span_bug(sp: span, msg: str) -> ! {
        self.span_fatal(sp, #fmt["internal compiler error %s", msg]);
    }
    fn bug(msg: str) -> ! {
        self.fatal(#fmt["internal compiler error %s", msg]);
    }
    fn span_unimpl(sp: span, msg: str) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(msg: str) -> ! { self.bug("unimplemented " + msg); }
}

fn mk_codemap_handler(cm: codemap::codemap,
                      emitter: option<emitter>) -> handler {

    let emit = alt emitter {
      some(e) { e }
      none. {
        let f = fn@(cmsp: option<(codemap::codemap, span)>,
            msg: str, t: diagnostictype) {
            emit_diagnostic(cmsp, msg, t);
        };
        f
      }
    };

    @{
        cm: cm,
        mutable err_count: 0u,
        emit: emit
    } as handler
}

tag diagnostictype {
    fatal;
    error;
    warning;
    note;
}

fn diagnosticstr(t: diagnostictype) -> str {
    alt t {
      fatal. { "error" }
      error. { "error" }
      warning. { "warning" }
      note. { "note" }
    }
}

fn diagnosticcolor(t: diagnostictype) -> u8 {
    alt t {
      fatal. { term::color_bright_red }
      error. { term::color_bright_red }
      warning. { term::color_bright_yellow }
      note. { term::color_bright_green }
    }
}

fn print_diagnostic(topic: str, t: diagnostictype, msg: str) {
    if str::is_not_empty(topic) {
        io::stdout().write_str(#fmt["%s ", topic]);
    }
    if term::color_supported() {
        term::fg(io::stdout(), diagnosticcolor(t));
    }
    io::stdout().write_str(#fmt["%s:", diagnosticstr(t)]);
    if term::color_supported() {
        term::reset(io::stdout());
    }
    io::stdout().write_str(#fmt[" %s\n", msg]);
}

fn emit_diagnostic(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype) {
    alt cmsp {
      some((cm, sp)) {
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, t, msg);
        highlight_lines(cm, sp, lines);
      }
      none. {
        print_diagnostic("", t, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    // If we're not looking at a real file then we can't re-open it to
    // pull out the lines
    if lines.name == "-" { ret; }

    // FIXME: reading in the entire file is the worst possible way to
    //        get access to the necessary lines.
    let file = alt io::read_whole_file_str(lines.name) {
      result::ok(file) { file }
      result::err(e) {
        emit_diagnostic(none, e, fatal);
        fail;
      }
    };
    let fm = codemap::get_filemap(cm, lines.name);

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let elided = false;
    let display_lines = lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for line: uint in display_lines {
        io::stdout().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int, file);
        if !str::ends_with(s, "\n") { s += "\n"; }
        io::stdout().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let indent = str::char_len(s);
        let out = "";
        while indent > 0u { out += " "; indent -= 1u; }
        out += "...\n";
        io::stdout().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let digits = 0u;
        let num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let left = str::char_len(fm.name) + digits + lo.col + 3u;
        let s = "";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += "^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stdout().write_str(s + "\n");
    }
}
<commit_msg>rustc: Make it not an error when the source can't be loaded for highlighting<commit_after>import std::{io, term};
import io::writer_util;
import syntax::codemap;
import codemap::span;

export emitter, emit_diagnostic;
export diagnostictype, fatal, error, warning, note;
export handler, mk_codemap_handler;

type emitter = fn@(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype);

iface handler {
    fn span_fatal(sp: span, msg: str) -> !;
    fn fatal(msg: str) -> !;
    fn span_err(sp: span, msg: str);
    fn err(msg: str);
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn span_warn(sp: span, msg: str);
    fn warn(msg: str);
    fn span_note(sp: span, msg: str);
    fn note(msg: str);
    fn span_bug(sp: span, msg: str) -> !;
    fn bug(msg: str) -> !;
    fn span_unimpl(sp: span, msg: str) -> !;
    fn unimpl(msg: str) -> !;
}

type codemap_t = @{
    cm: codemap::codemap,
    mutable err_count: uint,
    emit: emitter
};

impl codemap_handler of handler for codemap_t {
    fn span_fatal(sp: span, msg: str) -> ! {
        self.emit(some((self.cm, sp)), msg, fatal);
        fail;
    }
    fn fatal(msg: str) -> ! {
        self.emit(none, msg, fatal);
        fail;
    }
    fn span_err(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, error);
        self.err_count += 1u;
    }
    fn err(msg: str) {
        self.emit(none, msg, error);
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        if self.err_count > 0u {
            self.fatal("aborting due to previous errors");
        }
    }
    fn span_warn(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, warning);
    }
    fn warn(msg: str) {
        self.emit(none, msg, warning);
    }
    fn span_note(sp: span, msg: str) {
        self.emit(some((self.cm, sp)), msg, note);
    }
    fn note(msg: str) {
        self.emit(none, msg, note);
    }
    fn span_bug(sp: span, msg: str) -> ! {
        self.span_fatal(sp, #fmt["internal compiler error %s", msg]);
    }
    fn bug(msg: str) -> ! {
        self.fatal(#fmt["internal compiler error %s", msg]);
    }
    fn span_unimpl(sp: span, msg: str) -> ! {
        self.span_bug(sp, "unimplemented " + msg);
    }
    fn unimpl(msg: str) -> ! { self.bug("unimplemented " + msg); }
}

fn mk_codemap_handler(cm: codemap::codemap,
                      emitter: option<emitter>) -> handler {

    let emit = alt emitter {
      some(e) { e }
      none. {
        let f = fn@(cmsp: option<(codemap::codemap, span)>,
            msg: str, t: diagnostictype) {
            emit_diagnostic(cmsp, msg, t);
        };
        f
      }
    };

    @{
        cm: cm,
        mutable err_count: 0u,
        emit: emit
    } as handler
}

tag diagnostictype {
    fatal;
    error;
    warning;
    note;
}

fn diagnosticstr(t: diagnostictype) -> str {
    alt t {
      fatal. { "error" }
      error. { "error" }
      warning. { "warning" }
      note. { "note" }
    }
}

fn diagnosticcolor(t: diagnostictype) -> u8 {
    alt t {
      fatal. { term::color_bright_red }
      error. { term::color_bright_red }
      warning. { term::color_bright_yellow }
      note. { term::color_bright_green }
    }
}

fn print_diagnostic(topic: str, t: diagnostictype, msg: str) {
    if str::is_not_empty(topic) {
        io::stdout().write_str(#fmt["%s ", topic]);
    }
    if term::color_supported() {
        term::fg(io::stdout(), diagnosticcolor(t));
    }
    io::stdout().write_str(#fmt["%s:", diagnosticstr(t)]);
    if term::color_supported() {
        term::reset(io::stdout());
    }
    io::stdout().write_str(#fmt[" %s\n", msg]);
}

fn emit_diagnostic(cmsp: option<(codemap::codemap, span)>,
                   msg: str, t: diagnostictype) {
    alt cmsp {
      some((cm, sp)) {
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, t, msg);
        highlight_lines(cm, sp, lines);
      }
      none. {
        print_diagnostic("", t, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    // If we're not looking at a real file then we can't re-open it to
    // pull out the lines
    if lines.name == "-" { ret; }

    // FIXME: reading in the entire file is the worst possible way to
    //        get access to the necessary lines.
    let file = alt io::read_whole_file_str(lines.name) {
      result::ok(file) { file }
      result::err(e) {
        // Hard to report errors while reporting an error
        ret;
      }
    };
    let fm = codemap::get_filemap(cm, lines.name);

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let elided = false;
    let display_lines = lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for line: uint in display_lines {
        io::stdout().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int, file);
        if !str::ends_with(s, "\n") { s += "\n"; }
        io::stdout().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let indent = str::char_len(s);
        let out = "";
        while indent > 0u { out += " "; indent -= 1u; }
        out += "...\n";
        io::stdout().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let digits = 0u;
        let num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let left = str::char_len(fm.name) + digits + lo.col + 3u;
        let s = "";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += "^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stdout().write_str(s + "\n");
    }
}
<|endoftext|>


<commit_before><commit_msg>Refactor error handling<commit_after><|endoftext|>


<commit_before><commit_msg>Add insertion sort implementation.<commit_after>/* Sample insertion sort program in Rust.
   Tested to compile with rust-0.6.
 */
extern mod extra;
extern mod benchmark;
use std::vec;
use benchmark::Benchmark;

fn insertion_sort<T:Ord+Copy>(arr: ~[T]) -> ~[T] {
    let mut index = 0;
    let length = arr.len();
    let mut result = copy arr;

    while index < length {
        let valueToInsert = result[index];
        let mut holePos = index;

        while holePos > 0 && valueToInsert < result[holePos - 1] {
            vec::swap(result, holePos, holePos - 1);
            holePos -= 1;
        }
        index += 1;
    }

    return result
}

fn main() {
    let mut bench = Benchmark::new();
    bench.run(insertion_sort);
}

<|endoftext|>


<commit_before><commit_msg>fix(Argon2): make `Argon2Settings` `Copy` and `Clone`<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #18862 : murarth/rust/issue-18566-test, r=alexcrichton<commit_after>// Copyright 2014 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(tuple_indexing)]

struct MyPtr<'a>(&'a mut uint);
impl<'a> Deref<uint> for MyPtr<'a> {
    fn deref<'b>(&'b self) -> &'b uint { self.0 }
}

trait Tr {
    fn poke(&self, s: &mut uint);
}

impl Tr for uint {
    fn poke(&self, s: &mut uint)  {
        *s = 2;
    }
}

fn main() {
    let s = &mut 1u;

    MyPtr(s).poke(s);
    //~^ ERROR cannot borrow `*s` as mutable more than once at a time
}
<|endoftext|>