<commit_before>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate env_logger;
extern crate winit;
extern crate glutin;
extern crate gfx;
extern crate gfx_device_gl;
#[cfg(target_os = "windows")]
extern crate gfx_device_dx11;
extern crate gfx_window_glutin;
//extern crate gfx_window_glfw;
#[cfg(target_os = "windows")]
extern crate gfx_window_dxgi;

#[cfg(target_os = "macos")]
extern crate gfx_device_metal;
#[cfg(target_os = "macos")]
extern crate gfx_window_metal;

pub mod shade;

pub type ColorFormat = gfx::format::Rgba8;

#[cfg(target_os = "macos")]
pub type DepthFormat = gfx::format::Depth32F;
#[cfg(not(target_os = "macos"))]
pub type DepthFormat = gfx::format::DepthStencil;

pub struct Init<R: gfx::Resources> {
    pub backend: shade::Backend,
    pub color: gfx::handle::RenderTargetView<R, ColorFormat>,
    pub depth: gfx::handle::DepthStencilView<R, DepthFormat>,
    pub aspect_ratio: f32,
}

pub enum Backend {
    OpenGL2,
    Direct3D11 {
        pix_mode: bool,
    },
    Metal
}

pub struct Config {
    //pub backend: Backend,
    pub size: (u16, u16),
}

pub const DEFAULT_CONFIG: Config = Config {
    //backend: Backend::OpenGL2,
    size: (800, 520),
};

struct Harness {
    start: std::time::Instant,
    num_frames: f64,
}

impl Harness {
    fn new() -> Harness {
        Harness {
            start: std::time::Instant::now(),
            num_frames: 0.0,
        }
    }
    fn bump(&mut self) {
        self.num_frames += 1.0;
    }
}

impl Drop for Harness {
    fn drop(&mut self) {
        let time_end = self.start.elapsed();
        println!("Avg frame time: {} ms",
            ((time_end.as_secs() * 1000) as f64 + (time_end.subsec_nanos() / 1000_000) as f64) / self.num_frames
        );
    }
}

pub trait ApplicationBase<R: gfx::Resources, C: gfx::CommandBuffer<R>> {
    fn new<F>(F, gfx::Encoder<R, C>, Init<R>) -> Self where
        F: gfx::Factory<R>;
    fn render<D>(&mut self, &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>;
}

pub trait Application<R: gfx::Resources>: Sized {
    fn new<F: gfx::Factory<R>>(F, Init<R>) -> Self;
    fn render<C: gfx::CommandBuffer<R>>(&mut self, &mut gfx::Encoder<R, C>);
    #[cfg(target_os = "windows")]
    fn launch_default(name: &str) where WrapD3D11<Self>: ApplicationD3D11 {
        WrapD3D11::<Self>::launch(name, DEFAULT_CONFIG);
    }
    #[cfg(target_os = "linux")]
    fn launch_default(name: &str) where WrapGL2<Self>: ApplicationGL {
        WrapGL2::<Self>::launch(name, DEFAULT_CONFIG);
    }
    #[cfg(target_os = "macos")]
    fn launch_default(name: &str) where WrapMetal<Self>: ApplicationMetal {
        WrapMetal::<Self>::launch(name, DEFAULT_CONFIG)
    }
}

pub struct Wrap<R: gfx::Resources, C: gfx::CommandBuffer<R>, A>{
    encoder: gfx::Encoder<R, C>,
    app: A,
}

#[cfg(target_os = "macos")]
pub type WrapMetal<A> = Wrap<gfx_device_metal::Resources, gfx_device_metal::CommandBuffer, A>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBuffer = gfx_device_dx11::CommandBuffer<gfx_device_dx11::DeferredContext>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBufferFake = gfx_device_dx11::CommandBuffer<gfx_device_dx11::CommandList>;
#[cfg(target_os = "windows")]
pub type WrapD3D11<A> = Wrap<gfx_device_dx11::Resources, D3D11CommandBuffer, A>;
pub type WrapGL2<A> = Wrap<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer, A>;

impl<R, C, A> ApplicationBase<R, C> for Wrap<R, C, A> where
    R: gfx::Resources,
    C: gfx::CommandBuffer<R>,
    A: Application<R>
{
    fn new<F>(factory: F, encoder: gfx::Encoder<R, C>, init: Init<R>) -> Self where
        F: gfx::Factory<R>
    {
        Wrap {
            encoder: encoder,
            app: A::new(factory, init),
        }
    }

    fn render<D>(&mut self, device: &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>
    {
        self.app.render(&mut self.encoder);
        self.encoder.flush(device);
    }
}

pub trait ApplicationGL {
    fn launch(&str, Config);
}

#[cfg(target_os = "macos")]
pub trait ApplicationMetal {
    fn launch(&str, Config);
}

#[cfg(target_os = "windows")]
pub trait ApplicationD3D11 {
    fn launch(&str, Config);
}

impl<A> ApplicationGL for A where
    A: ApplicationBase<gfx_device_gl::Resources,
                       gfx_device_gl::CommandBuffer>
{
    fn launch(title: &str, config: Config) {
        use gfx::traits::Device;

        env_logger::init().unwrap();
        let gl_version = glutin::GlRequest::GlThenGles {
            opengl_version: (3, 2), //TODO: try more versions
            opengles_version: (2, 0),
        };
        let builder = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(config.size.0 as u32, config.size.1 as u32)
            .with_gl(gl_version)
            .with_vsync();
        let (window, mut device, mut factory, main_color, main_depth) =
            gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
        let (width, height) = window.get_inner_size().unwrap();
        let combuf = factory.create_command_buffer();
        let shade_lang = device.get_info().shading_language;

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: if shade_lang.is_embedded {
                shade::Backend::GlslEs(shade_lang)
            } else {
                shade::Backend::Glsl(shade_lang)
            },
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32,
        });

        let mut harness = Harness::new();
        'main: loop {
            // quit when Esc is pressed.
            for event in window.poll_events() {
                match event {
                    glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                    glutin::Event::Closed => break 'main,
                    _ => {},
                }
            }
            // draw a frame
            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "macos")]
impl<
    A: ApplicationBase<gfx_device_metal::Resources, gfx_device_metal::CommandBuffer>
> ApplicationMetal for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, mut device, mut factory, main_color) =
            gfx_window_metal::init::<ColorFormat>(title, config.size.0 as u32, config.size.1 as u32)
            .unwrap();

        let (width, height) = window.get_inner_size().unwrap();

        let main_depth = factory.create_depth_stencil_view_only(width as u16, height as u16).unwrap();

        let cmd_buf = factory.create_command_buffer();

        let mut app = Self::new(factory, cmd_buf.into(), Init {
            backend: shade::Backend::Msl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32
        });

        let mut harness = Harness::new();
        'main: loop {
            for event in window.poll_events() {
                match event {
                    winit::Event::KeyboardInput(_, _, Some(winit::VirtualKeyCode::Escape)) |
                    winit::Event::Closed => break 'main,
                    _ => {},
                }
            }

            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "windows")]
impl<
    A: ApplicationBase<gfx_device_dx11::Resources, D3D11CommandBuffer>
> ApplicationD3D11 for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, device, mut factory, main_color) =
            gfx_window_dxgi::init::<ColorFormat>(title, config.size.0, config.size.1)
            .unwrap();
        let main_depth = factory.create_depth_stencil_view_only(
            window.size.0, window.size.1).unwrap();

        //let combuf = factory.create_command_buffer();
        let combuf = factory.create_command_buffer_native();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Hlsl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: window.size.0 as f32 / window.size.1 as f32,
        });

        let mut device: gfx_device_dx11::Deferred = device.into();

        let mut harness = Harness::new();
        while window.dispatch() {
            app.render(&mut device);
            window.swap_buffers(1);
            device.cleanup();
            harness.bump();
        }
    }
}
<commit_msg>MTL - make metal not default on macOS<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate env_logger;
extern crate winit;
extern crate glutin;
extern crate gfx;
extern crate gfx_device_gl;
#[cfg(target_os = "windows")]
extern crate gfx_device_dx11;
extern crate gfx_window_glutin;
//extern crate gfx_window_glfw;
#[cfg(target_os = "windows")]
extern crate gfx_window_dxgi;

#[cfg(target_os = "macos")]
extern crate gfx_device_metal;
#[cfg(target_os = "macos")]
extern crate gfx_window_metal;

pub mod shade;

pub type ColorFormat = gfx::format::Rgba8;

#[cfg(target_os = "macos")]
pub type DepthFormat = gfx::format::Depth32F;
#[cfg(not(target_os = "macos"))]
pub type DepthFormat = gfx::format::DepthStencil;

pub struct Init<R: gfx::Resources> {
    pub backend: shade::Backend,
    pub color: gfx::handle::RenderTargetView<R, ColorFormat>,
    pub depth: gfx::handle::DepthStencilView<R, DepthFormat>,
    pub aspect_ratio: f32,
}

pub enum Backend {
    OpenGL2,
    Direct3D11 {
        pix_mode: bool,
    },
    Metal
}

pub struct Config {
    //pub backend: Backend,
    pub size: (u16, u16),
}

pub const DEFAULT_CONFIG: Config = Config {
    //backend: Backend::OpenGL2,
    size: (800, 520),
};

struct Harness {
    start: std::time::Instant,
    num_frames: f64,
}

impl Harness {
    fn new() -> Harness {
        Harness {
            start: std::time::Instant::now(),
            num_frames: 0.0,
        }
    }
    fn bump(&mut self) {
        self.num_frames += 1.0;
    }
}

impl Drop for Harness {
    fn drop(&mut self) {
        let time_end = self.start.elapsed();
        println!("Avg frame time: {} ms",
            ((time_end.as_secs() * 1000) as f64 + (time_end.subsec_nanos() / 1000_000) as f64) / self.num_frames
        );
    }
}

pub trait ApplicationBase<R: gfx::Resources, C: gfx::CommandBuffer<R>> {
    fn new<F>(F, gfx::Encoder<R, C>, Init<R>) -> Self where
        F: gfx::Factory<R>;
    fn render<D>(&mut self, &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>;
}

pub trait Application<R: gfx::Resources>: Sized {
    fn new<F: gfx::Factory<R>>(F, Init<R>) -> Self;
    fn render<C: gfx::CommandBuffer<R>>(&mut self, &mut gfx::Encoder<R, C>);
    #[cfg(target_os = "windows")]
    fn launch_default(name: &str) where WrapD3D11<Self>: ApplicationD3D11 {
        WrapD3D11::<Self>::launch(name, DEFAULT_CONFIG);
    }
    #[cfg(not(target_os = "windows"))]
    fn launch_default(name: &str) where WrapGL2<Self>: ApplicationGL {
        WrapGL2::<Self>::launch(name, DEFAULT_CONFIG);
    }
    /*#[cfg(target_os = "macos")]
    fn launch_default(name: &str) where WrapMetal<Self>: ApplicationMetal {
        WrapMetal::<Self>::launch(name, DEFAULT_CONFIG)
    }*/
}

pub struct Wrap<R: gfx::Resources, C: gfx::CommandBuffer<R>, A>{
    encoder: gfx::Encoder<R, C>,
    app: A,
}

#[cfg(target_os = "macos")]
pub type WrapMetal<A> = Wrap<gfx_device_metal::Resources, gfx_device_metal::CommandBuffer, A>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBuffer = gfx_device_dx11::CommandBuffer<gfx_device_dx11::DeferredContext>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBufferFake = gfx_device_dx11::CommandBuffer<gfx_device_dx11::CommandList>;
#[cfg(target_os = "windows")]
pub type WrapD3D11<A> = Wrap<gfx_device_dx11::Resources, D3D11CommandBuffer, A>;
pub type WrapGL2<A> = Wrap<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer, A>;

impl<R, C, A> ApplicationBase<R, C> for Wrap<R, C, A> where
    R: gfx::Resources,
    C: gfx::CommandBuffer<R>,
    A: Application<R>
{
    fn new<F>(factory: F, encoder: gfx::Encoder<R, C>, init: Init<R>) -> Self where
        F: gfx::Factory<R>
    {
        Wrap {
            encoder: encoder,
            app: A::new(factory, init),
        }
    }

    fn render<D>(&mut self, device: &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>
    {
        self.app.render(&mut self.encoder);
        self.encoder.flush(device);
    }
}

pub trait ApplicationGL {
    fn launch(&str, Config);
}

#[cfg(target_os = "macos")]
pub trait ApplicationMetal {
    fn launch(&str, Config);
}

#[cfg(target_os = "windows")]
pub trait ApplicationD3D11 {
    fn launch(&str, Config);
}

impl<A> ApplicationGL for A where
    A: ApplicationBase<gfx_device_gl::Resources,
                       gfx_device_gl::CommandBuffer>
{
    fn launch(title: &str, config: Config) {
        use gfx::traits::Device;

        env_logger::init().unwrap();
        let gl_version = glutin::GlRequest::GlThenGles {
            opengl_version: (3, 2), //TODO: try more versions
            opengles_version: (2, 0),
        };
        let builder = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(config.size.0 as u32, config.size.1 as u32)
            .with_gl(gl_version)
            .with_vsync();
        let (window, mut device, mut factory, main_color, main_depth) =
            gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
        let (width, height) = window.get_inner_size().unwrap();
        let combuf = factory.create_command_buffer();
        let shade_lang = device.get_info().shading_language;

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: if shade_lang.is_embedded {
                shade::Backend::GlslEs(shade_lang)
            } else {
                shade::Backend::Glsl(shade_lang)
            },
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32,
        });

        let mut harness = Harness::new();
        'main: loop {
            // quit when Esc is pressed.
            for event in window.poll_events() {
                match event {
                    glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                    glutin::Event::Closed => break 'main,
                    _ => {},
                }
            }
            // draw a frame
            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "macos")]
impl<
    A: ApplicationBase<gfx_device_metal::Resources, gfx_device_metal::CommandBuffer>
> ApplicationMetal for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, mut device, mut factory, main_color) =
            gfx_window_metal::init::<ColorFormat>(title, config.size.0 as u32, config.size.1 as u32)
            .unwrap();

        let (width, height) = window.get_inner_size().unwrap();

        let main_depth = factory.create_depth_stencil_view_only(width as u16, height as u16).unwrap();

        let cmd_buf = factory.create_command_buffer();

        let mut app = Self::new(factory, cmd_buf.into(), Init {
            backend: shade::Backend::Msl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32
        });

        let mut harness = Harness::new();
        'main: loop {
            for event in window.poll_events() {
                match event {
                    winit::Event::KeyboardInput(_, _, Some(winit::VirtualKeyCode::Escape)) |
                    winit::Event::Closed => break 'main,
                    _ => {},
                }
            }

            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "windows")]
impl<
    A: ApplicationBase<gfx_device_dx11::Resources, D3D11CommandBuffer>
> ApplicationD3D11 for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, device, mut factory, main_color) =
            gfx_window_dxgi::init::<ColorFormat>(title, config.size.0, config.size.1)
            .unwrap();
        let main_depth = factory.create_depth_stencil_view_only(
            window.size.0, window.size.1).unwrap();

        //let combuf = factory.create_command_buffer();
        let combuf = factory.create_command_buffer_native();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Hlsl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: window.size.0 as f32 / window.size.1 as f32,
        });

        let mut device: gfx_device_dx11::Deferred = device.into();

        let mut harness = Harness::new();
        while window.dispatch() {
            app.render(&mut device);
            window.swap_buffers(1);
            device.cleanup();
            harness.bump();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>stats for npc, now display target npc quickstats<commit_after><|endoftext|>


<commit_before><commit_msg>Ensure an error is raised on infinite recursion<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.

// Verify the compiler fails with an error on infinite function
// recursions.

struct Data(~Option<Data>);

fn generic<T>( _ : ~[(Data,T)] ) {let rec : ~[(Data,(bool,T))] = ~[]; generic( rec ); } //~ ERROR overly deep expansion of inlined function

fn main () {
    // Use generic<T> at least once to trigger instantiation.
    let input : ~[(Data,())] = ~[];
    generic(input);
}
<|endoftext|>


<commit_before>import std::option;
import std::getopts;
import std::test;
import std::fs;
import std::str;
import std::vec;
import std::ivec;
import std::task;

import common::cx;
import common::config;
import common::mode_run_pass;
import common::mode_run_fail;
import common::mode_compile_fail;
import common::mode;
import util::logv;

fn main(args: vec[str]) {

    let ivec_args =
        {
            let ivec_args = ~[];
            for arg: str  in args { ivec_args += ~[arg]; }
            ivec_args
        };

    let config = parse_config(ivec_args);
    log_config(config);
    run_tests(config);
}

fn parse_config(args: &str[]) -> config {
    let opts =
        ~[getopts::reqopt("compile-lib-path"),
          getopts::reqopt("run-lib-path"), getopts::reqopt("rustc-path"),
          getopts::reqopt("src-base"), getopts::reqopt("build-base"),
          getopts::reqopt("stage-id"), getopts::reqopt("mode"),
          getopts::optflag("ignored"), getopts::optopt("runtool"),
          getopts::optopt("rustcflags"), getopts::optflag("verbose")];

    check (ivec::is_not_empty(args));
    let args_ = ivec::tail(args);
    let match =
        alt getopts::getopts_ivec(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { fail getopts::fail_str(f) }
        };

    ret {compile_lib_path: getopts::opt_str(match, "compile-lib-path"),
         run_lib_path: getopts::opt_str(match, "run-lib-path"),
         rustc_path: getopts::opt_str(match, "rustc-path"),
         src_base: getopts::opt_str(match, "src-base"),
         build_base: getopts::opt_str(match, "build-base"),
         stage_id: getopts::opt_str(match, "stage-id"),
         mode: str_mode(getopts::opt_str(match, "mode")),
         run_ignored: getopts::opt_present(match, "ignored"),
         filter:
             if vec::len(match.free) > 0u {
                 option::some(match.free.(0))
             } else { option::none },
         runtool: getopts::opt_maybe_str(match, "runtool"),
         rustcflags: getopts::opt_maybe_str(match, "rustcflags"),
         verbose: getopts::opt_present(match, "verbose")};
}

fn log_config(config: &config) {
    let c = config;
    logv(c, #fmt("configuration:"));
    logv(c, #fmt("compile_lib_path: %s", config.compile_lib_path));
    logv(c, #fmt("run_lib_path: %s", config.run_lib_path));
    logv(c, #fmt("rustc_path: %s", config.rustc_path));
    logv(c, #fmt("src_base: %s", config.src_base));
    logv(c, #fmt("build_base: %s", config.build_base));
    logv(c, #fmt("stage_id: %s", config.stage_id));
    logv(c, #fmt("mode: %s", mode_str(config.mode)));
    logv(c, #fmt("run_ignored: %b", config.run_ignored));
    logv(c, #fmt("filter: %s", opt_str(config.filter)));
    logv(c, #fmt("runtool: %s", opt_str(config.runtool)));
    logv(c, #fmt("rustcflags: %s", opt_str(config.rustcflags)));
    logv(c, #fmt("verbose: %b", config.verbose));
    logv(c, #fmt("\n"));
}

fn opt_str(maybestr: option::t[str]) -> str {
    alt maybestr { option::some(s) { s } option::none. { "(none)" } }
}

fn str_opt(maybestr: str) -> option::t[str] {
    if maybestr != "(none)" { option::some(maybestr) } else { option::none }
}

fn str_mode(s: str) -> mode {
    alt s {
      "compile-fail" { mode_compile_fail }
      "run-fail" { mode_run_fail }
      "run-pass" { mode_run_pass }
      _ { fail "invalid mode" }
    }
}

fn mode_str(mode: mode) -> str {
    alt mode {
      mode_compile_fail. { "compile-fail" }
      mode_run_fail. { "run-fail" }
      mode_run_pass. { "run-pass" }
    }
}

fn run_tests(config: &config) {
    let opts = test_opts(config);
    let cx = {config: config, procsrv: procsrv::mk()};
    let tests = make_tests(cx);
    test::run_tests_console_(opts, tests.tests, tests.to_task);
    procsrv::close(cx.procsrv);
}

fn test_opts(config: &config) -> test::test_opts {
    {filter: config.filter, run_ignored: config.run_ignored}
}

type tests_and_conv_fn =
    {tests: test::test_desc[], to_task: fn(&fn() ) -> task };

fn make_tests(cx: &cx) -> tests_and_conv_fn {
    log #fmt("making tests from %s", cx.config.src_base);
    let configport = port[str]();
    let tests = ~[];
    for file: str  in fs::list_dir(cx.config.src_base) {
        log #fmt("inspecting file %s", file);
        if is_test(file) { tests += ~[make_test(cx, file, configport)]; }
    }
    ret {tests: tests, to_task: bind closure_to_task(cx, configport, _)};
}

fn is_test(testfile: &str) -> bool {
    let name = fs::basename(testfile);
    (str::ends_with(name, ".rs") || str::ends_with(name, ".rc")) &&
        !(str::starts_with(name, ".") || str::starts_with(name, "#") ||
              str::starts_with(name, "~"))
}

fn make_test(cx: &cx, testfile: &str, configport: &port[str]) ->
   test::test_desc {
    {name: testfile,
     fn: make_test_closure(testfile, chan(configport)),
            ignore: header::is_test_ignored(cx.config.stage_id, testfile)}
}

/*
So this is kind of crappy:

A test is just defined as a function, as you might expect, but tests have to
run their own tasks. Unfortunately, if your test needs dynamic data then it
needs to be a closure, and transferring closures across tasks without
committing a host of memory management transgressions is just impossible.

To get around this, the standard test runner allows you the opportunity do
your own conversion from a test function to a task. It gives you your function
and you give it back a task.

So that's what we're going to do. Here's where it gets stupid. To get the
the data out of the test function we are going to run the test function,
which will do nothing but send the data for that test to a port we've set
up. Then we'll spawn that data into another task and return the task.
Really convoluted. Need to think up of a better definition for tests.
*/

fn make_test_closure(testfile: &str, configchan: chan[str]) -> test::test_fn {
    bind send_config(testfile, configchan)
}

fn send_config(testfile: str, configchan: chan[str]) {
    task::send(configchan, testfile);
}

/*
FIXME: Good god forgive me.

So actually shuttling structural data across tasks isn't possible at this
time, but we can send strings! Sadly, I need the whole config record, in the
test task so, instead of fixing the mechanism in the compiler I'm going to
break up the config record and pass everything individually to the spawned
function.
*/

fn closure_to_task(cx: cx, configport: port[str], testfn: &fn() ) -> task {
    testfn();
    let testfile = task::recv(configport);
    ret spawn run_test_task(cx.config.compile_lib_path,
                            cx.config.run_lib_path, cx.config.rustc_path,
                            cx.config.src_base, cx.config.build_base,
                            cx.config.stage_id, mode_str(cx.config.mode),
                            cx.config.run_ignored, opt_str(cx.config.filter),
                            opt_str(cx.config.runtool),
                            opt_str(cx.config.rustcflags), cx.config.verbose,
                            task::clone_chan(cx.procsrv.chan), testfile);
}

fn run_test_task(compile_lib_path: str, run_lib_path: str, rustc_path: str,
                 src_base: str, build_base: str, stage_id: str, mode: str,
                 run_ignored: bool, opt_filter: str, opt_runtool: str,
                 opt_rustcflags: str, verbose: bool,
                 procsrv_chan: procsrv::reqchan, testfile: str) {

    let config =
        {compile_lib_path: compile_lib_path,
         run_lib_path: run_lib_path,
         rustc_path: rustc_path,
         src_base: src_base,
         build_base: build_base,
         stage_id: stage_id,
         mode: str_mode(mode),
         run_ignored: run_ignored,
         filter: str_opt(opt_filter),
         runtool: str_opt(opt_runtool),
         rustcflags: str_opt(opt_rustcflags),
         verbose: verbose};

    let procsrv = procsrv::from_chan(procsrv_chan);

    let cx = {config: config, procsrv: procsrv};

    runtest::run(cx, testfile);
}

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Replace an open-coded conversion with ivec::from_vec<commit_after>import std::option;
import std::getopts;
import std::test;
import std::fs;
import std::str;
import std::vec;
import std::ivec;
import std::task;

import common::cx;
import common::config;
import common::mode_run_pass;
import common::mode_run_fail;
import common::mode_compile_fail;
import common::mode;
import util::logv;

fn main(args: vec[str]) {

    let ivec_args = ivec::from_vec(args);

    let config = parse_config(ivec_args);
    log_config(config);
    run_tests(config);
}

fn parse_config(args: &str[]) -> config {
    let opts =
        ~[getopts::reqopt("compile-lib-path"),
          getopts::reqopt("run-lib-path"), getopts::reqopt("rustc-path"),
          getopts::reqopt("src-base"), getopts::reqopt("build-base"),
          getopts::reqopt("stage-id"), getopts::reqopt("mode"),
          getopts::optflag("ignored"), getopts::optopt("runtool"),
          getopts::optopt("rustcflags"), getopts::optflag("verbose")];

    check (ivec::is_not_empty(args));
    let args_ = ivec::tail(args);
    let match =
        alt getopts::getopts_ivec(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { fail getopts::fail_str(f) }
        };

    ret {compile_lib_path: getopts::opt_str(match, "compile-lib-path"),
         run_lib_path: getopts::opt_str(match, "run-lib-path"),
         rustc_path: getopts::opt_str(match, "rustc-path"),
         src_base: getopts::opt_str(match, "src-base"),
         build_base: getopts::opt_str(match, "build-base"),
         stage_id: getopts::opt_str(match, "stage-id"),
         mode: str_mode(getopts::opt_str(match, "mode")),
         run_ignored: getopts::opt_present(match, "ignored"),
         filter:
             if vec::len(match.free) > 0u {
                 option::some(match.free.(0))
             } else { option::none },
         runtool: getopts::opt_maybe_str(match, "runtool"),
         rustcflags: getopts::opt_maybe_str(match, "rustcflags"),
         verbose: getopts::opt_present(match, "verbose")};
}

fn log_config(config: &config) {
    let c = config;
    logv(c, #fmt("configuration:"));
    logv(c, #fmt("compile_lib_path: %s", config.compile_lib_path));
    logv(c, #fmt("run_lib_path: %s", config.run_lib_path));
    logv(c, #fmt("rustc_path: %s", config.rustc_path));
    logv(c, #fmt("src_base: %s", config.src_base));
    logv(c, #fmt("build_base: %s", config.build_base));
    logv(c, #fmt("stage_id: %s", config.stage_id));
    logv(c, #fmt("mode: %s", mode_str(config.mode)));
    logv(c, #fmt("run_ignored: %b", config.run_ignored));
    logv(c, #fmt("filter: %s", opt_str(config.filter)));
    logv(c, #fmt("runtool: %s", opt_str(config.runtool)));
    logv(c, #fmt("rustcflags: %s", opt_str(config.rustcflags)));
    logv(c, #fmt("verbose: %b", config.verbose));
    logv(c, #fmt("\n"));
}

fn opt_str(maybestr: option::t[str]) -> str {
    alt maybestr { option::some(s) { s } option::none. { "(none)" } }
}

fn str_opt(maybestr: str) -> option::t[str] {
    if maybestr != "(none)" { option::some(maybestr) } else { option::none }
}

fn str_mode(s: str) -> mode {
    alt s {
      "compile-fail" { mode_compile_fail }
      "run-fail" { mode_run_fail }
      "run-pass" { mode_run_pass }
      _ { fail "invalid mode" }
    }
}

fn mode_str(mode: mode) -> str {
    alt mode {
      mode_compile_fail. { "compile-fail" }
      mode_run_fail. { "run-fail" }
      mode_run_pass. { "run-pass" }
    }
}

fn run_tests(config: &config) {
    let opts = test_opts(config);
    let cx = {config: config, procsrv: procsrv::mk()};
    let tests = make_tests(cx);
    test::run_tests_console_(opts, tests.tests, tests.to_task);
    procsrv::close(cx.procsrv);
}

fn test_opts(config: &config) -> test::test_opts {
    {filter: config.filter, run_ignored: config.run_ignored}
}

type tests_and_conv_fn =
    {tests: test::test_desc[], to_task: fn(&fn() ) -> task };

fn make_tests(cx: &cx) -> tests_and_conv_fn {
    log #fmt("making tests from %s", cx.config.src_base);
    let configport = port[str]();
    let tests = ~[];
    for file: str  in fs::list_dir(cx.config.src_base) {
        log #fmt("inspecting file %s", file);
        if is_test(file) { tests += ~[make_test(cx, file, configport)]; }
    }
    ret {tests: tests, to_task: bind closure_to_task(cx, configport, _)};
}

fn is_test(testfile: &str) -> bool {
    let name = fs::basename(testfile);
    (str::ends_with(name, ".rs") || str::ends_with(name, ".rc")) &&
        !(str::starts_with(name, ".") || str::starts_with(name, "#") ||
              str::starts_with(name, "~"))
}

fn make_test(cx: &cx, testfile: &str, configport: &port[str]) ->
   test::test_desc {
    {name: testfile,
     fn: make_test_closure(testfile, chan(configport)),
            ignore: header::is_test_ignored(cx.config.stage_id, testfile)}
}

/*
So this is kind of crappy:

A test is just defined as a function, as you might expect, but tests have to
run their own tasks. Unfortunately, if your test needs dynamic data then it
needs to be a closure, and transferring closures across tasks without
committing a host of memory management transgressions is just impossible.

To get around this, the standard test runner allows you the opportunity do
your own conversion from a test function to a task. It gives you your function
and you give it back a task.

So that's what we're going to do. Here's where it gets stupid. To get the
the data out of the test function we are going to run the test function,
which will do nothing but send the data for that test to a port we've set
up. Then we'll spawn that data into another task and return the task.
Really convoluted. Need to think up of a better definition for tests.
*/

fn make_test_closure(testfile: &str, configchan: chan[str]) -> test::test_fn {
    bind send_config(testfile, configchan)
}

fn send_config(testfile: str, configchan: chan[str]) {
    task::send(configchan, testfile);
}

/*
FIXME: Good god forgive me.

So actually shuttling structural data across tasks isn't possible at this
time, but we can send strings! Sadly, I need the whole config record, in the
test task so, instead of fixing the mechanism in the compiler I'm going to
break up the config record and pass everything individually to the spawned
function.
*/

fn closure_to_task(cx: cx, configport: port[str], testfn: &fn() ) -> task {
    testfn();
    let testfile = task::recv(configport);
    ret spawn run_test_task(cx.config.compile_lib_path,
                            cx.config.run_lib_path, cx.config.rustc_path,
                            cx.config.src_base, cx.config.build_base,
                            cx.config.stage_id, mode_str(cx.config.mode),
                            cx.config.run_ignored, opt_str(cx.config.filter),
                            opt_str(cx.config.runtool),
                            opt_str(cx.config.rustcflags), cx.config.verbose,
                            task::clone_chan(cx.procsrv.chan), testfile);
}

fn run_test_task(compile_lib_path: str, run_lib_path: str, rustc_path: str,
                 src_base: str, build_base: str, stage_id: str, mode: str,
                 run_ignored: bool, opt_filter: str, opt_runtool: str,
                 opt_rustcflags: str, verbose: bool,
                 procsrv_chan: procsrv::reqchan, testfile: str) {

    let config =
        {compile_lib_path: compile_lib_path,
         run_lib_path: run_lib_path,
         rustc_path: rustc_path,
         src_base: src_base,
         build_base: build_base,
         stage_id: stage_id,
         mode: str_mode(mode),
         run_ignored: run_ignored,
         filter: str_opt(opt_filter),
         runtool: str_opt(opt_runtool),
         rustcflags: str_opt(opt_rustcflags),
         verbose: verbose};

    let procsrv = procsrv::from_chan(procsrv_chan);

    let cx = {config: config, procsrv: procsrv};

    runtest::run(cx, testfile);
}

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|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.

// error-pattern:explicit failure

#[no_uv];

extern mod native;

#[start]
fn start(argc: int, argv: **u8) -> int {
    do native::start(argc, argv) {
        fail!();
    }
}
<commit_msg>auto merge of #11518 : brson/rust/moreandroidxfails, 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.

// xfail-android (FIXME #11419)
// error-pattern:explicit failure

#[no_uv];

extern mod native;

#[start]
fn start(argc: int, argv: **u8) -> int {
    do native::start(argc, argv) {
        fail!();
    }
}
<|endoftext|>


<commit_before><commit_msg>wip: base32.rs<commit_after>//
// base32.rs - base32 implementation
//
// The Base32 Alphabet
//
// Value Encoding  Value Encoding  Value Encoding  Value Encoding
//     0 A             9 J            18 S            27 3
//     1 B            10 K            19 T            28 4
//     2 C            11 L            20 U            29 5
//     3 D            12 M            21 V            30 6
//     4 E            13 N            22 W            31 7
//     5 F            14 O            23 X
//     6 G            15 P            24 Y         (pad) =
//     7 H            16 Q            25 Z
//     8 I            17 R            26 2
//

use std;

export mk;

const padd: u8 = 61u8;

iface base32 {
    fn encode(src: [u8]) -> [u8];
    fn decode(src: [u8]) -> [u8];
    fn hex_encode(src: [u8]) -> [u8];
    fn hex_decode(src: [u8]) -> [u8];
}

fn mk() -> base32 {
    type _base32 = {table: [u8], table_hex: [u8]};

    impl of base32 for _base32 {
        fn encode(src: [u8]) -> [u8] {
            b32encode(self.table, src)
        }
        fn decode(src: [u8]) -> [u8] {
            b32decode(self.table, src)
        }
        fn hex_encode(src: [u8]) -> [u8] {
            b32encode(self.table_hex, src)
        }
        fn hex_decode(src: [u8]) -> [u8] {
            b32decode(self.table_hex, src)
        }
    }

    let table = vec::init_elt_mut(32u, 0u8), i = 0u8;
    u8::range(65u8, 91u8)  { |j| table[i] = j; i += 1u8; }
    u8::range(50u8, 56u8)  { |j| table[i] = j; i += 1u8; }

    let table_hex = vec::init_elt_mut(32u, 0u8), i = 0u8;
    u8::range(48u8, 58u8)  { |j| table_hex[i] = j; i += 1u8; }
    u8::range(65u8, 87u8)  { |j| table_hex[i] = j; i += 1u8; }

    {table: vec::from_mut(table),
     table_hex: vec::from_mut(table_hex)} as base32
}

fn b32encode(table: [u8], src: [u8]) -> [u8] {
    let srclen = vec::len(src);
    let targ = if srclen % 5u == 0u {
        vec::init_elt_mut(srclen / 5u * 8u, 0u8)
    } else {
        vec::init_elt_mut((srclen / 5u + 1u) * 8u, 0u8)
    };
    let input = vec::init_elt_mut(5u, 0u8);
    let output = vec::init_elt_mut(8u, 0u8);
    let curr = 0u, src_curr = 0u;

    while srclen > 4u {
        input[0] = src[src_curr];
        input[1] = src[src_curr + 1u];
        input[2] = src[src_curr + 2u];
        input[3] = src[src_curr + 3u];
        input[4] = src[src_curr + 4u];
        srclen -= 5u; src_curr += 5u;

        output[0] = input[0] >> 3u8;
        output[1] = (input[0] & 0x07_u8) << 2u8 | input[1] >> 6u8;
        output[2] = (input[1] & 0x3f_u8) >> 1u8;
        output[3] = (input[1] & 0x01_u8) << 4u8 | input[2] >> 4u8;
        output[4] = (input[2] & 0x0f_u8) << 1u8 | input[3] >> 7u8;
        output[5] = (input[3] & 0x7f_u8) >> 2u8;
        output[6] = (input[3] & 0x03_u8) << 3u8 | input[4] >> 5u8;
        output[7] = input[4] & 0x1f_u8;

        targ[curr] = table[output[0]]; curr += 1u;
        targ[curr] = table[output[1]]; curr += 1u;
        targ[curr] = table[output[2]]; curr += 1u;
        targ[curr] = table[output[3]]; curr += 1u;
        targ[curr] = table[output[4]]; curr += 1u;
        targ[curr] = table[output[5]]; curr += 1u;
        targ[curr] = table[output[6]]; curr += 1u;
        targ[curr] = table[output[7]]; curr += 1u;
    }

    if srclen != 0u {
        input[0] = 0u8; input[1] = 0u8; input[2] = 0u8;
        input[3] = 0u8; input[4] = 0u8;

        alt srclen {
          1u {input[0] = src[src_curr];}
          2u {input[0] = src[src_curr];
              input[1] = src[src_curr + 1u];}
          3u {input[0] = src[src_curr];
              input[1] = src[src_curr + 1u];
              input[2] = src[src_curr + 2u];}
          4u {input[0] = src[src_curr];
              input[1] = src[src_curr + 1u];
              input[2] = src[src_curr + 2u];
              input[3] = src[src_curr + 3u];}
          _ { }
        }

        output[0] = input[0] >> 3u8;
        output[1] = (input[0] & 0x07_u8) << 2u8 | input[1] >> 6u8;
        output[2] = (input[1] & 0x3f_u8) >> 1u8;
        output[3] = (input[1] & 0x01_u8) << 4u8 | input[2] >> 4u8;
        output[4] = (input[2] & 0x0f_u8) << 1u8 | input[3] >> 7u8;
        output[5] = (input[3] & 0x7f_u8) >> 2u8;
        output[6] = (input[3] & 0x03_u8) << 3u8 | input[4] >> 5u8;

        targ[curr] = table[output[0]]; curr += 1u;
        targ[curr] = table[output[1]]; curr += 1u;
        targ[curr] =
            if srclen > 1u { table[output[2]] } else { padd }; curr += 1u;
        targ[curr] =
            if srclen > 1u { table[output[3]] } else { padd }; curr += 1u;
        targ[curr] =
            if srclen > 2u { table[output[4]] } else { padd }; curr += 1u;
        targ[curr] =
            if srclen > 3u { table[output[5]] } else { padd }; curr += 1u;
        targ[curr] =
            if srclen > 3u { table[output[6]] } else { padd }; curr += 1u;
        targ[curr] = padd;
    }

    vec::from_mut(targ)
}

fn b32decode(table: [u8], src: [u8]) -> [u8] {
    let srclen = vec::len(src);

    if srclen % 8u != 0u { fail "malformed base32 string"; }
    if srclen == 0u { ret []; }

    []
}

mod tests {
    import std::map;
    import core::str::{bytes, from_bytes};
    enum mode {
        t_encode,
        t_decode,
        t_hex_encode,
        t_hex_decode,
    }
    fn setup(t: mode) -> map::hashmap<str, str> {
        let m = map::new_str_hash::<str>();
        alt t {
          t_decode { }
          t_encode {
            m.insert("fooba", "MZXW6YTB");
            m.insert("foob",  "MZXW6YQ=");
            m.insert("foo",   "MZXW6===");
            m.insert("fo",    "MZXQ====");
            m.insert("f",     "MY======");
          }
          t_hex_decode { }
          t_hex_encode {
            m.insert("fooba", "CPNMUOJ1");
            m.insert("foob",  "CPNMUOG=");
            m.insert("foo",   "CPNMU===");
            m.insert("fo",    "CPNG====");
            m.insert("f",     "CO======");
          }
        }
        m.insert("", "");
        m
    }
    fn do_test(t: mode) {
        let b32 = mk();
        let m = setup(t);
        m.keys { |k|
            let expected = m.get(k);
            let actual = alt t {
              t_decode { from_bytes(b32.decode(bytes(k))) }
              t_encode { from_bytes(b32.encode(bytes(k))) }
              t_hex_decode { from_bytes(b32.hex_decode(bytes(k))) }
              t_hex_encode { from_bytes(b32.hex_encode(bytes(k))) }
            };
            #debug("expected: %s", expected);
            #debug("actual:   %s", actual);
            assert expected == actual;
        }
    }
    #[test]
    fn encode() { do_test(t_encode); }
    #[test]
    fn hex_encode() { do_test(t_hex_encode); }
    #[test]
    fn decode() { do_test(t_decode); }
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue #34634<commit_after>// Test that `wrapping_div` only checks divisor once.
// This test checks that there is only a single compare agains -1 and -1 is not present as a
// switch case (the second check present until rustc 1.12).
// This test also verifies that a single panic call is generated (for the division by zero case).

// compile-flags: -O
#![crate_type = "lib"]

// CHECK-LABEL: @f
#[no_mangle]
pub fn f(x: i32, y: i32) -> i32 {
    // CHECK-COUNT-1: icmp eq i32 %y, -1
    // CHECK-COUNT-1: panic
    // CHECK-NOT: i32 -1, label
    x.wrapping_div(y)
}
<|endoftext|>


<commit_before><commit_msg>Add equivalent test in src/test/rustdoc<commit_after>// edition:2018

#![no_core]
#![feature(no_core)]

// @count issue_89852/index.html '//*[@class="macro"]' 2
// @has - '//*[@class="macro"]/@href' 'macro.repro.html'
#[macro_export]
macro_rules! repro {
    () => {};
}

// @!has issue_89852/macro.repro.html '//*[@class="macro"]/@content' 'repro2'
pub use crate::repro as repro2;
<|endoftext|>


<commit_before><commit_msg>Add rustc_serialization test code.<commit_after>use rustc_serialize::{Encoder, Encodable, Decodable};

pub struct SchemaBuilder {
  types: Vec<String>
}

pub enum SchemaBuilderError {
  Unsupported
}

impl Encoder for SchemaBuilder {
  type Error = SchemaBuilderError;

  fn emit_nil(&mut self) -> Result<(), Self::Error>
  {
    println!("nil");
    Ok(())
  }

  fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>
  {
    println!("usize");
    Ok(())
  }

  fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>
  {
    println!("u64");
    Ok(())
  }

  fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>
  {
    println!("u32");
    Ok(())
  }

  fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>
  {
    println!("u16");
    Ok(())
  }

  fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>
  {
    println!("u8");
    Ok(())
  }

  fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>
  {
    println!("isize");
    Ok(())
  }

  fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>
  {
    println!("i64");
    Ok(())
  }

  fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>
  {
    println!("i32");
    Ok(())
  }

  fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>
  {
    println!("i16");
    Ok(())
  }

  fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>
  {
    println!("i8");
    Ok(())
  }

  fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>
  {
    println!("u8");
    Ok(())
  }

  fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>
  {
    println!("f64");
    Ok(())
  }

  fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>
  {
    println!("f32");
    Ok(())
  }

  fn emit_char(&mut self, v: char) -> Result<(), Self::Error>
  {
    println!("char");
    Ok(())
  }

  fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>
  {
    println!("str");
    Ok(())
  }

  fn emit_enum<F>(&mut self, name: &str, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("enum");
    Ok(())
  }

  fn emit_enum_variant<F>(&mut self, v_name: &str,
                          v_id: usize,
                          len: usize,
                          f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("enum_variant");
    Ok(())
  }

  fn emit_enum_variant_arg<F>(&mut self, a_idx: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("enum_variant_arg");
    Ok(())
  }

  fn emit_enum_struct_variant<F>(&mut self, v_name: &str,
                                 v_id: usize,
                                 len: usize,
                                 f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("enum_struct_variant");
    Ok(())
  }

  fn emit_enum_struct_variant_field<F>(&mut self,
                                       f_name: &str,
                                       f_idx: usize,
                                       f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("enum_struct_variant_field");
    Ok(())
  }

  fn emit_struct<F>(&mut self, name: &str, len: usize, f: F)
                    -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("struct enter: {}", name);
    let res = f(self);
    println!("struct leave: {}", name);

    res
  }

  fn emit_struct_field<F>(&mut self, f_name: &str, f_idx: usize, f: F)
                          -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("struct_field: {}::{}", f_idx, f_name);
    f(self)
  }

  fn emit_tuple<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("tuple");
    Ok(())
  }

  fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("tuple_arg");
    Ok(())
  }

  fn emit_tuple_struct<F>(&mut self, name: &str, len: usize, f: F)
                          -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("tuple_struct");
    Ok(())
  }

  fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F)
                              -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("tuple_struct_arg");
    Ok(())
  }

  // Specialized types:
  fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("option");
    Ok(())
  }

  fn emit_option_none(&mut self) -> Result<(), Self::Error>
  {
    println!("option_none");
    Ok(())
  }

  fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("option_some");
    Ok(())
  }

  fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("seq");
    Ok(())
  }

  fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
   {
     println!("seq_elt");
     Ok(())
   }

  fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("emit_map");
    Ok(())
  }

  fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("map_elt_key");
    Ok(())
  }

  fn emit_map_elt_val<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
    where F: FnOnce(&mut Self) -> Result<(), Self::Error>
  {
    println!("map_elt_val");
    Ok(())
  }
}

#[derive(RustcEncodable)]
pub struct Test {
  id  : usize,
  name: String
}

#[test]
pub fn test() {
  let mut b = SchemaBuilder {types: Vec::new()};
  let t = Test {id: 1, name: "xxx".to_string()};
  //let x: Encodable = &t;
  t.encode(&mut b);
}

<|endoftext|>


<commit_before><commit_msg>jsonちょっと読めるようになった<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests/types/eui48.rs to excercise MacAddress::parse_str() functionality in canonical form<commit_after>extern crate eui48;

use types::test_type;

#[test]
fn test_eui48_params() {
    test_type("MACADDR", &[(Some(eui48::MacAddress::parse_str("12-34-56-AB-CD-EF").unwrap()),
        "'12-34-56-ab-cd-ef'"), (None, "NULL")])
}
<|endoftext|>


<commit_before>use std::fmt::Debug;
use std::collections::HashMap;
use test::Bencher;

use rustc_serialize::{Decoder, Decodable};

use serde;
use serde::de::{Deserializer, Deserialize};

//////////////////////////////////////////////////////////////////////////////

#[derive(PartialEq, Debug)]
pub enum Error {
    EndOfStream,
    SyntaxError,
    MissingField,
}

impl serde::de::Error for Error {
    fn syntax(_: &str) -> Error { Error::SyntaxError }

    fn end_of_stream() -> Error { Error::EndOfStream }

    fn unknown_field(_: &str) -> Error { Error::SyntaxError }

    fn missing_field(_: &'static str) -> Error {
        Error::MissingField
    }
}

//////////////////////////////////////////////////////////////////////////////

mod decoder {
    use std::collections::HashMap;
    use std::collections::hash_map::IntoIter;
    use rustc_serialize;

    use super::Error;
    use self::Value::{StringValue, IsizeValue};

    enum Value {
        StringValue(String),
        IsizeValue(isize),
    }

    pub struct IsizeDecoder {
        len: usize,
        iter: IntoIter<String, isize>,
        stack: Vec<Value>,
    }

    impl IsizeDecoder {
        #[inline]
        pub fn new(values: HashMap<String, isize>) -> IsizeDecoder {
            IsizeDecoder {
                len: values.len(),
                iter: values.into_iter(),
                stack: vec!(),
            }
        }
    }

    impl rustc_serialize::Decoder for IsizeDecoder {
        type Error = Error;

        fn error(&mut self, _msg: &str) -> Error {
            Error::SyntaxError
        }

        // Primitive types:
        fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
        fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
        fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
        fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
        fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
        fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
        #[inline]
        fn read_isize(&mut self) -> Result<isize, Error> {
            match self.stack.pop() {
                Some(IsizeValue(x)) => Ok(x),
                Some(_) => Err(Error::SyntaxError),
                None => Err(Error::EndOfStream),
            }
        }
        fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
        fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
        fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
        fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
        fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
        fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
        fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
        fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
        #[inline]
        fn read_str(&mut self) -> Result<String, Error> {
            match self.stack.pop() {
                Some(StringValue(x)) => Ok(x),
                Some(_) => Err(Error::SyntaxError),
                None => Err(Error::EndOfStream),
            }
        }

        // Compound types:
        fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        // Specialized types:
        fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        #[inline]
        fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            let len = self.len;
            f(self, len)
        }
        #[inline]
        fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            match self.iter.next() {
                Some((key, value)) => {
                    self.stack.push(IsizeValue(value));
                    self.stack.push(StringValue(key));
                    f(self)
                }
                None => {
                    Err(Error::SyntaxError)
                }
            }
        }

        #[inline]
        fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            f(self)
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

mod deserializer {
    use std::collections::HashMap;
    use std::collections::hash_map;

    use super::Error;

    use serde::de;

    #[derive(PartialEq, Debug)]
    enum State {
        StartState,
        KeyState(String),
        ValueState(isize),
    }

    pub struct IsizeDeserializer {
        stack: Vec<State>,
        iter: hash_map::IntoIter<String, isize>,
    }

    impl IsizeDeserializer {
        #[inline]
        pub fn new(values: HashMap<String, isize>) -> IsizeDeserializer {
            IsizeDeserializer {
                stack: vec!(State::StartState),
                iter: values.into_iter(),
            }
        }
    }

    impl de::Deserializer for IsizeDeserializer {
        type Error = Error;

        fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
            where V: de::Visitor,
        {
            match self.stack.pop() {
                Some(State::StartState) => {
                    visitor.visit_map(self)
                }
                Some(State::KeyState(key)) => {
                    visitor.visit_string(key)
                }
                Some(State::ValueState(value)) => {
                    visitor.visit_isize(value)
                }
                None => {
                    Err(Error::EndOfStream)
                }
            }
        }
    }

    impl de::MapVisitor for IsizeDeserializer {
        type Error = Error;

        fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
            where K: de::Deserialize,
        {
            match self.iter.next() {
                Some((key, value)) => {
                    self.stack.push(State::ValueState(value));
                    self.stack.push(State::KeyState(key));
                    Ok(Some(try!(de::Deserialize::deserialize(self))))
                }
                None => {
                    Ok(None)
                }
            }
        }

        fn visit_value<V>(&mut self) -> Result<V, Error>
            where V: de::Deserialize,
        {
            de::Deserialize::deserialize(self)
        }

        fn end(&mut self) -> Result<(), Error> {
            match self.iter.next() {
                Some(_) => Err(Error::SyntaxError),
                None => Ok(()),
            }
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            self.iter.size_hint()
        }
    }

/*
    impl Iterator for IsizeDeserializer {
        type Item = Result<de::Token, Error>;

        #[inline]
        fn next(&mut self) -> Option<Result<de::Token, Error>> {
            match self.stack.pop() {
                Some(StartState) => {
                    self.stack.push(KeyOrEndState);
                    Some(Ok(de::Token::MapStart(self.len)))
                }
                Some(KeyOrEndState) => {
                    match self.iter.next() {
                        Some((key, value)) => {
                            self.stack.push(ValueState(value));
                            Some(Ok(de::Token::String(key)))
                        }
                        None => {
                            self.stack.push(EndState);
                            Some(Ok(de::Token::End))
                        }
                    }
                }
                Some(ValueState(x)) => {
                    self.stack.push(KeyOrEndState);
                    Some(Ok(de::Token::Isize(x)))
                }
                Some(EndState) => {
                    None
                }
                None => {
                    None
                }
            }
        }
    }

    impl de::Deserializer<Error> for IsizeDeserializer {
        #[inline]
        fn end_of_stream(&mut self) -> Error {
            EndOfStream
        }

        #[inline]
        fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
            SyntaxError
        }

        #[inline]
        fn unexpected_name(&mut self, _token: de::Token) -> Error {
            SyntaxError
        }

        #[inline]
        fn conversion_error(&mut self, _token: de::Token) -> Error {
            SyntaxError
        }

        #[inline]
        fn missing_field<
            T: de::Deserialize<IsizeDeserializer, Error>
        >(&mut self, _field: &'static str) -> Result<T, Error> {
            Err(Error::SyntaxError)
        }
    }
*/
}

//////////////////////////////////////////////////////////////////////////////

fn run_decoder<
    D: Decoder<Error=Error>,
    T: Clone + PartialEq + Debug + Decodable
>(mut d: D, value: T) {
    let v = Decodable::decode(&mut d);

    assert_eq!(Ok(value), v);
}

#[bench]
fn bench_decoder_000(b: &mut Bencher) {
    b.iter(|| {
        let m: HashMap<String, isize> = HashMap::new();
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

#[bench]
fn bench_decoder_003(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in (0 .. 3) {
            m.insert(i.to_string(), i);
        }
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

#[bench]
fn bench_decoder_100(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in (0 .. 100) {
            m.insert(i.to_string(), i);
        }
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

fn run_deserializer<D, T>(mut d: D, value: T)
    where D: Deserializer,
          D::Error: Debug + PartialEq,
          T: Clone + PartialEq + Debug + Deserialize
{
    let v = T::deserialize(&mut d);

    assert_eq!(Ok(value), v);
}

#[bench]
fn bench_deserializer_000(b: &mut Bencher) {
    b.iter(|| {
        let m: HashMap<String, isize> = HashMap::new();
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}

#[bench]
fn bench_deserializer_003(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in (0 .. 3) {
            m.insert(i.to_string(), i);
        }
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}

#[bench]
fn bench_deserializer_100(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in (0 .. 100) {
            m.insert(i.to_string(), i);
        }
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}
<commit_msg>chore(tests): Silence some warnings<commit_after>use std::fmt::Debug;
use std::collections::HashMap;
use test::Bencher;

use rustc_serialize::{Decoder, Decodable};

use serde;
use serde::de::{Deserializer, Deserialize};

//////////////////////////////////////////////////////////////////////////////

#[derive(PartialEq, Debug)]
pub enum Error {
    EndOfStream,
    SyntaxError,
    MissingField,
}

impl serde::de::Error for Error {
    fn syntax(_: &str) -> Error { Error::SyntaxError }

    fn end_of_stream() -> Error { Error::EndOfStream }

    fn unknown_field(_: &str) -> Error { Error::SyntaxError }

    fn missing_field(_: &'static str) -> Error {
        Error::MissingField
    }
}

//////////////////////////////////////////////////////////////////////////////

mod decoder {
    use std::collections::HashMap;
    use std::collections::hash_map::IntoIter;
    use rustc_serialize;

    use super::Error;
    use self::Value::{StringValue, IsizeValue};

    enum Value {
        StringValue(String),
        IsizeValue(isize),
    }

    pub struct IsizeDecoder {
        len: usize,
        iter: IntoIter<String, isize>,
        stack: Vec<Value>,
    }

    impl IsizeDecoder {
        #[inline]
        pub fn new(values: HashMap<String, isize>) -> IsizeDecoder {
            IsizeDecoder {
                len: values.len(),
                iter: values.into_iter(),
                stack: vec!(),
            }
        }
    }

    impl rustc_serialize::Decoder for IsizeDecoder {
        type Error = Error;

        fn error(&mut self, _msg: &str) -> Error {
            Error::SyntaxError
        }

        // Primitive types:
        fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
        fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
        fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
        fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
        fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
        fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
        #[inline]
        fn read_isize(&mut self) -> Result<isize, Error> {
            match self.stack.pop() {
                Some(IsizeValue(x)) => Ok(x),
                Some(_) => Err(Error::SyntaxError),
                None => Err(Error::EndOfStream),
            }
        }
        fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
        fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
        fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
        fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
        fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
        fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
        fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
        fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
        #[inline]
        fn read_str(&mut self) -> Result<String, Error> {
            match self.stack.pop() {
                Some(StringValue(x)) => Ok(x),
                Some(_) => Err(Error::SyntaxError),
                None => Err(Error::EndOfStream),
            }
        }

        // Compound types:
        fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        // Specialized types:
        fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            Err(Error::SyntaxError)
        }

        #[inline]
        fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
        {
            let len = self.len;
            f(self, len)
        }
        #[inline]
        fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            match self.iter.next() {
                Some((key, value)) => {
                    self.stack.push(IsizeValue(value));
                    self.stack.push(StringValue(key));
                    f(self)
                }
                None => {
                    Err(Error::SyntaxError)
                }
            }
        }

        #[inline]
        fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
            F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
        {
            f(self)
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

mod deserializer {
    use std::collections::HashMap;
    use std::collections::hash_map;

    use super::Error;

    use serde::de;

    #[derive(PartialEq, Debug)]
    enum State {
        StartState,
        KeyState(String),
        ValueState(isize),
    }

    pub struct IsizeDeserializer {
        stack: Vec<State>,
        iter: hash_map::IntoIter<String, isize>,
    }

    impl IsizeDeserializer {
        #[inline]
        pub fn new(values: HashMap<String, isize>) -> IsizeDeserializer {
            IsizeDeserializer {
                stack: vec!(State::StartState),
                iter: values.into_iter(),
            }
        }
    }

    impl de::Deserializer for IsizeDeserializer {
        type Error = Error;

        fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
            where V: de::Visitor,
        {
            match self.stack.pop() {
                Some(State::StartState) => {
                    visitor.visit_map(self)
                }
                Some(State::KeyState(key)) => {
                    visitor.visit_string(key)
                }
                Some(State::ValueState(value)) => {
                    visitor.visit_isize(value)
                }
                None => {
                    Err(Error::EndOfStream)
                }
            }
        }
    }

    impl de::MapVisitor for IsizeDeserializer {
        type Error = Error;

        fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
            where K: de::Deserialize,
        {
            match self.iter.next() {
                Some((key, value)) => {
                    self.stack.push(State::ValueState(value));
                    self.stack.push(State::KeyState(key));
                    Ok(Some(try!(de::Deserialize::deserialize(self))))
                }
                None => {
                    Ok(None)
                }
            }
        }

        fn visit_value<V>(&mut self) -> Result<V, Error>
            where V: de::Deserialize,
        {
            de::Deserialize::deserialize(self)
        }

        fn end(&mut self) -> Result<(), Error> {
            match self.iter.next() {
                Some(_) => Err(Error::SyntaxError),
                None => Ok(()),
            }
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            self.iter.size_hint()
        }
    }

/*
    impl Iterator for IsizeDeserializer {
        type Item = Result<de::Token, Error>;

        #[inline]
        fn next(&mut self) -> Option<Result<de::Token, Error>> {
            match self.stack.pop() {
                Some(StartState) => {
                    self.stack.push(KeyOrEndState);
                    Some(Ok(de::Token::MapStart(self.len)))
                }
                Some(KeyOrEndState) => {
                    match self.iter.next() {
                        Some((key, value)) => {
                            self.stack.push(ValueState(value));
                            Some(Ok(de::Token::String(key)))
                        }
                        None => {
                            self.stack.push(EndState);
                            Some(Ok(de::Token::End))
                        }
                    }
                }
                Some(ValueState(x)) => {
                    self.stack.push(KeyOrEndState);
                    Some(Ok(de::Token::Isize(x)))
                }
                Some(EndState) => {
                    None
                }
                None => {
                    None
                }
            }
        }
    }

    impl de::Deserializer<Error> for IsizeDeserializer {
        #[inline]
        fn end_of_stream(&mut self) -> Error {
            EndOfStream
        }

        #[inline]
        fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
            SyntaxError
        }

        #[inline]
        fn unexpected_name(&mut self, _token: de::Token) -> Error {
            SyntaxError
        }

        #[inline]
        fn conversion_error(&mut self, _token: de::Token) -> Error {
            SyntaxError
        }

        #[inline]
        fn missing_field<
            T: de::Deserialize<IsizeDeserializer, Error>
        >(&mut self, _field: &'static str) -> Result<T, Error> {
            Err(Error::SyntaxError)
        }
    }
*/
}

//////////////////////////////////////////////////////////////////////////////

fn run_decoder<
    D: Decoder<Error=Error>,
    T: Clone + PartialEq + Debug + Decodable
>(mut d: D, value: T) {
    let v = Decodable::decode(&mut d);

    assert_eq!(Ok(value), v);
}

#[bench]
fn bench_decoder_000(b: &mut Bencher) {
    b.iter(|| {
        let m: HashMap<String, isize> = HashMap::new();
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

#[bench]
fn bench_decoder_003(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in 0 .. 3 {
            m.insert(i.to_string(), i);
        }
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

#[bench]
fn bench_decoder_100(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in 0 .. 100 {
            m.insert(i.to_string(), i);
        }
        run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
    })
}

fn run_deserializer<D, T>(mut d: D, value: T)
    where D: Deserializer,
          D::Error: Debug + PartialEq,
          T: Clone + PartialEq + Debug + Deserialize
{
    let v = T::deserialize(&mut d);

    assert_eq!(Ok(value), v);
}

#[bench]
fn bench_deserializer_000(b: &mut Bencher) {
    b.iter(|| {
        let m: HashMap<String, isize> = HashMap::new();
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}

#[bench]
fn bench_deserializer_003(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in 0 .. 3 {
            m.insert(i.to_string(), i);
        }
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}

#[bench]
fn bench_deserializer_100(b: &mut Bencher) {
    b.iter(|| {
        let mut m: HashMap<String, isize> = HashMap::new();
        for i in 0 .. 100 {
            m.insert(i.to_string(), i);
        }
        run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
    })
}
<|endoftext|>


<commit_before><commit_msg>Add problem #40<commit_after>extern mod euler;
use euler::calc::{ num_to_digits };

// d_(a*10 + b)
//    0 1 2 3 4 5 6 7 8 9
// 0  - 1 2 3 4 5 6 7 8 9
// 1  1 0 1 1 1 2 1 3 1 4
// 2  1 5 1 6 1 7 1 8 1 9
// 3  2 0 2 1 2 2 2 3 2 4
// 4  2 5 2 6 2 7 2 8 2 9
// 5  3 0 3 1 3 2 3 3 3 4
//
// [1,   9]   => 9
// [10,  99]  => 90
// [100, 999] => 900
//
// num => idx
// 1 <= n <= 9       => i = n
// 10 <= n <= 99     => i = 2 * (n - 10) + 10 = 2n - 10
// 100 <= n <= 999   => i = 3 * (n - 100) + 2 * 100 - 10 = 3n - 110
// 1000 <= n <= 9999 => i = 4 * (n - 1000) + 3 * 1000 - 110 = 4n - 1110
//
struct Area {
    num_digit: uint,
    min_val: uint,
    max_val: uint,
    min_idx: uint,
    max_idx: uint
}

struct IdxValueMap {
    priv area: ~[Area]
}

fn IdxValueMap() -> IdxValueMap {
    return IdxValueMap { area: ~[ Area {
        num_digit: 0,
        min_val: 0,
        max_val: 0,
        min_idx: 0,
        max_idx: 0
    } ] };
}

impl IdxValueMap {
    priv fn extend(&mut self) {
        let last = self.area.last();
        let num_digit = last.num_digit + 1;
        let min_val = last.max_val + 1;
        let max_val = min_val * 10 - 1;
        let min_idx = last.max_idx + 1;
        let max_idx = last.max_idx + (max_val - min_val + 1) * num_digit;
        self.area.push(Area {
            num_digit: num_digit,
            min_val: min_val, max_val: max_val,
            min_idx: min_idx, max_idx: max_idx
        });
    }

    priv fn each_area(&mut self, f: fn(Area) -> bool) {
        for uint::range(0, self.area.len()) |i| {
            if !f(self.area[i]) { return; }
        }
        loop {
            self.extend();
            if !f(self.area.last()) { return; }
        }
    }

    priv fn get_area_by_idx(&mut self, idx: uint) -> Area {
        for self.each_area |area| {
            if area.min_idx <= idx && idx <= area.max_idx {
                return area;
            }
        }
        util::unreachable();
    }

    pub fn get_value_by_idx(&mut self, idx: uint) -> uint {
        let area = self.get_area_by_idx(idx);
        return area.min_val + ((idx - area.min_idx) / area.num_digit);
   }
    pub fn get_digit_by_idx(&mut self, idx: uint) -> uint {
        let area = self.get_area_by_idx(idx);
        let val  = area.min_val + ((idx - area.min_idx) / area.num_digit);
        return num_to_digits(val, 10)[(idx - area.min_idx) % area.num_digit];
    }
}

fn main() {
    let mut map = IdxValueMap();
    let idx = &[ 1, 10, 100, 1000, 10000, 100000, 1000000 ];
    let mut prod = 1;
    for idx.each |i| {
        prod *= map.get_digit_by_idx(*i);
    }
    io::println(fmt!("answer: %u", prod));
}
<|endoftext|>


<commit_before><commit_msg>Fix the mdcs_node_host plugin on linux platforms.<commit_after><|endoftext|>


<commit_before>resource r(_r: int) {}

fn main() {
    let x = r(3);
    *x = 4; //! ERROR assigning to resource content
}<commit_msg>Remove obsolete test<commit_after><|endoftext|>


<commit_before><commit_msg>add sleep example<commit_after>extern crate coio;

fn main() {
    coio::spawn(|| {
        for i in 0.. {
            println!("Qua  {}", i);
            coio::sleep_ms(2000);
        }
    });

    coio::spawn(|| {
        for i in 0.. {
            println!("Purr {}", i);
            coio::sleep_ms(1000);
        }
    });

    coio::run(2);
}
<|endoftext|>


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