<commit_before>#![feature(plugin)]
#![plugin(glium_macros)]

extern crate glutin;

#[cfg(feature = "image")]
extern crate image;

#[macro_use]
extern crate glium;

#[cfg(feature = "image")]
use std::old_io::BufReader;
#[cfg(feature = "image")]
use glium::Surface;

mod support;

#[cfg(not(all(feature = "image", feature = "nalgebra")))]
fn main() {
    println!("This example requires the `image` feature to be enabled");
}

#[cfg(all(feature = "image", feature = "nalgebra"))]
fn main() {
    use glium::DisplayBuild;

    // building the display, ie. the main object
    let display = glutin::WindowBuilder::new()
        .build_glium()
        .unwrap();

    let image = image::load(BufReader::new(include_bytes!("../tests/fixture/opengl.png")),
        image::PNG).unwrap();
    let opengl_texture = glium::texture::CompressedTexture2d::new(&display, image);

    // building the vertex buffer, which contains all the vertices that we will draw
    let vertex_buffer = {
        #[vertex_format]
        #[derive(Copy)]
        struct Vertex {
            position: [f32; 3],
            tex_coords: [f32; 2],
        }

        glium::VertexBuffer::new(&display,
            vec![
                Vertex { position: [-0.5,  0.5, 5.0], tex_coords: [0.0, 1.0] },
                Vertex { position: [ 0.5,  0.5, 5.0], tex_coords: [1.0, 1.0] },
                Vertex { position: [-0.5, -0.5, 5.0], tex_coords: [0.0, 0.0] },
                Vertex { position: [ 0.5,  0.5, 5.0], tex_coords: [1.0, 1.0] },
                Vertex { position: [ 0.5, -0.5, 5.0], tex_coords: [1.0, 0.0] },
                Vertex { position: [-0.5, -0.5, 5.0], tex_coords: [0.0, 0.0] },
            ]
        )
    };

    // compiling shaders and linking them together
    let program = glium::Program::new(&display,
        glium::program::SourceCode {
            vertex_shader: "
                #version 430

                in vec3 position;
                in vec2 tex_coords;

                out vec3 v_position;
                out vec3 v_normal;
                out vec2 v_tex_coords;

                void main() {
                    v_position = position;
                    v_normal = vec3(0.0, 0.0, -1.0);
                    v_tex_coords = tex_coords;
                }
            ",
            tessellation_control_shader: Some("
                #version 430

                layout(vertices = 3) out;

                in vec3 v_position[];
                in vec3 v_normal[];
                in vec2 v_tex_coords[];

                out vec3 tc_position[];
                out vec3 tc_normal[];
                out vec2 tc_tex_coords[];

                uniform float inner_level;
                uniform float outer_level;

                void main() {
                    tc_position[gl_InvocationID] = v_position[gl_InvocationID];
                    tc_normal[gl_InvocationID]   = v_normal[gl_InvocationID];
                    tc_tex_coords[gl_InvocationID] = v_tex_coords[gl_InvocationID];

                    gl_TessLevelOuter[0] = outer_level;
                    gl_TessLevelOuter[1] = outer_level;
                    gl_TessLevelOuter[2] = outer_level;
                    gl_TessLevelOuter[3] = outer_level;
                    gl_TessLevelInner[0] = inner_level;
                    gl_TessLevelInner[1] = inner_level;
                }
            "),
            tessellation_evaluation_shader: Some("
                #version 430

                layout(triangles, equal_spacing, ccw) in;

                in vec3 tc_position[];
                in vec3 tc_normal[];
                in vec2 tc_tex_coords[];

                out vec4 te_position;
                out vec3 te_normal;
                out vec2 te_tex_coords;

                uniform mat4 projection_matrix;
                uniform mat4 view_matrix;

                uniform sampler2D height_texture;
                uniform float elevation;

                void main() {
                    vec3 pos = gl_TessCoord.x * tc_position[0] +
                               gl_TessCoord.y * tc_position[1] +
                               gl_TessCoord.z * tc_position[2];

                    vec3 normal = normalize(gl_TessCoord.x * tc_normal[0] +
                                            gl_TessCoord.y * tc_normal[1] +
                                            gl_TessCoord.z * tc_normal[2]);

                    vec2 tex_coords = gl_TessCoord.x * tc_tex_coords[0] +
                                      gl_TessCoord.y * tc_tex_coords[1] +
                                      gl_TessCoord.z * tc_tex_coords[2];

                    float height = length(texture(height_texture, tex_coords));
                    pos += normal * (height * elevation);

                    te_position = projection_matrix * view_matrix * vec4(pos, 1.0);
                    te_normal = vec3(view_matrix * vec4(normal, 1.0)).xyz;
                    te_tex_coords = tex_coords;
                }
            "),
            geometry_shader: Some("
                #version 430

                layout(triangles) in;
                layout(triangle_strip, max_vertices = 3) out;

                uniform mat4 view_matrix;

                in vec4 te_position[3];
                in vec3 te_normal[3];
                in vec2 te_tex_coords[3];

                out vec3 g_normal;
                out vec2 g_tex_coords;

                void main() {
                    g_normal = te_normal[0];
                    g_tex_coords = te_tex_coords[0];
                    gl_Position = te_position[0];
                    EmitVertex();

                    g_normal = te_normal[1];
                    g_tex_coords = te_tex_coords[1];
                    gl_Position = te_position[1];
                    EmitVertex();

                    g_normal = te_normal[2];
                    g_tex_coords = te_tex_coords[2];
                    gl_Position = te_position[2];
                    EmitVertex();

                    EndPrimitive();
                }
            "),
            fragment_shader: "
                #version 430

                in vec3 g_normal;
                in vec2 g_tex_coords;

                uniform sampler2D color_texture;

                const vec3 LIGHT = vec3(-0.2, 0.1, 0.8);

                void main() {
                    float lum = max(dot(normalize(g_normal), normalize(LIGHT)), 0.0);
                    vec3 tex_color = texture(color_texture, g_tex_coords).rgb;
                    vec3 color = (0.6 + 0.4 * lum) * tex_color;
                    gl_FragColor = vec4(color, 1.0);
                }
            ",
        }).unwrap();

    let mut camera = support::camera::CameraState::new();

    // the main loop
    support::start_loop(|| {
        // building the uniforms
        let uniforms = uniform! {
            inner_level: 32.0f32,
            outer_level: 32.0f32,
            projection_matrix: camera.get_perspective(),
            view_matrix: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0f32]
            ],
            height_texture: &opengl_texture,
            elevation: 0.6f32,
            color_texture: &opengl_texture
        };

        // drawing a frame
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);
        target.draw(&vertex_buffer,
                    &glium::index::NoIndices(glium::index::PrimitiveType::Patches {
                        vertices_per_patch: 3
                    }),
                    &program, &uniforms,
                    &std::default::Default::default()).unwrap();
        target.finish();

        // polling and handling the events received by the window
        for event in display.poll_events() {
            match event {
                glutin::Event::Closed => return support::Action::Stop,
                _ => ()
            }
        }

        support::Action::Continue
    });
}
<commit_msg>Slightly improve the displacement mapping example<commit_after>#![feature(plugin)]
#![plugin(glium_macros)]

extern crate glutin;

#[cfg(feature = "image")]
extern crate image;

#[macro_use]
extern crate glium;

#[cfg(feature = "image")]
use std::old_io::BufReader;
#[cfg(feature = "image")]
use glium::Surface;

mod support;

#[cfg(not(all(feature = "image", feature = "nalgebra")))]
fn main() {
    println!("This example requires the `image` feature to be enabled");
}

#[cfg(all(feature = "image", feature = "nalgebra"))]
fn main() {
    use glium::DisplayBuild;

    // building the display, ie. the main object
    let display = glutin::WindowBuilder::new()
        .build_glium()
        .unwrap();

    let image = image::load(BufReader::new(include_bytes!("../tests/fixture/opengl.png")),
        image::PNG).unwrap();
    let opengl_texture = glium::texture::CompressedTexture2d::new(&display, image);

    // building the vertex buffer, which contains all the vertices that we will draw
    let vertex_buffer = {
        #[vertex_format]
        #[derive(Copy)]
        struct Vertex {
            position: [f32; 3],
            tex_coords: [f32; 2],
        }

        glium::VertexBuffer::new(&display,
            vec![
                Vertex { position: [-0.5,  0.5, 3.0], tex_coords: [1.0, 1.0] },
                Vertex { position: [ 0.5,  0.5, 3.0], tex_coords: [0.0, 1.0] },
                Vertex { position: [-0.5, -0.5, 3.0], tex_coords: [1.0, 0.0] },
                Vertex { position: [ 0.5,  0.5, 3.0], tex_coords: [0.0, 1.0] },
                Vertex { position: [ 0.5, -0.5, 3.0], tex_coords: [0.0, 0.0] },
                Vertex { position: [-0.5, -0.5, 3.0], tex_coords: [1.0, 0.0] },
            ]
        )
    };

    // compiling shaders and linking them together
    let program = glium::Program::new(&display,
        glium::program::SourceCode {
            vertex_shader: "
                #version 430

                in vec3 position;
                in vec2 tex_coords;

                out vec3 v_position;
                out vec3 v_normal;
                out vec2 v_tex_coords;

                void main() {
                    v_position = position;
                    v_normal = vec3(0.0, 0.0, -1.0);
                    v_tex_coords = tex_coords;
                }
            ",
            tessellation_control_shader: Some("
                #version 430

                layout(vertices = 3) out;

                in vec3 v_position[];
                in vec3 v_normal[];
                in vec2 v_tex_coords[];

                out vec3 tc_position[];
                out vec3 tc_normal[];
                out vec2 tc_tex_coords[];

                uniform float inner_level;
                uniform float outer_level;

                void main() {
                    tc_position[gl_InvocationID] = v_position[gl_InvocationID];
                    tc_normal[gl_InvocationID]   = v_normal[gl_InvocationID];
                    tc_tex_coords[gl_InvocationID] = v_tex_coords[gl_InvocationID];

                    gl_TessLevelOuter[0] = outer_level;
                    gl_TessLevelOuter[1] = outer_level;
                    gl_TessLevelOuter[2] = outer_level;
                    gl_TessLevelOuter[3] = outer_level;
                    gl_TessLevelInner[0] = inner_level;
                    gl_TessLevelInner[1] = inner_level;
                }
            "),
            tessellation_evaluation_shader: Some("
                #version 430

                layout(triangles, equal_spacing, ccw) in;

                in vec3 tc_position[];
                in vec3 tc_normal[];
                in vec2 tc_tex_coords[];

                out vec4 te_position;
                out vec3 te_normal;
                out vec2 te_tex_coords;

                uniform mat4 projection_matrix;
                uniform mat4 view_matrix;

                uniform sampler2D height_texture;
                uniform float elevation;

                void main() {
                    vec3 pos = gl_TessCoord.x * tc_position[0] +
                               gl_TessCoord.y * tc_position[1] +
                               gl_TessCoord.z * tc_position[2];

                    vec3 normal = normalize(gl_TessCoord.x * tc_normal[0] +
                                            gl_TessCoord.y * tc_normal[1] +
                                            gl_TessCoord.z * tc_normal[2]);

                    vec2 tex_coords = gl_TessCoord.x * tc_tex_coords[0] +
                                      gl_TessCoord.y * tc_tex_coords[1] +
                                      gl_TessCoord.z * tc_tex_coords[2];

                    float height = length(texture(height_texture, tex_coords));
                    pos += normal * (height * elevation);

                    te_position = projection_matrix * view_matrix * vec4(pos, 1.0);
                    te_normal = vec3(view_matrix * vec4(normal, 1.0)).xyz;
                    te_tex_coords = tex_coords;
                }
            "),
            geometry_shader: Some("
                #version 430

                layout(triangles) in;
                layout(triangle_strip, max_vertices = 3) out;

                uniform mat4 view_matrix;

                in vec4 te_position[3];
                in vec3 te_normal[3];
                in vec2 te_tex_coords[3];

                out vec3 g_normal;
                out vec2 g_tex_coords;

                void main() {
                    g_normal = te_normal[0];
                    g_tex_coords = te_tex_coords[0];
                    gl_Position = te_position[0];
                    EmitVertex();

                    g_normal = te_normal[1];
                    g_tex_coords = te_tex_coords[1];
                    gl_Position = te_position[1];
                    EmitVertex();

                    g_normal = te_normal[2];
                    g_tex_coords = te_tex_coords[2];
                    gl_Position = te_position[2];
                    EmitVertex();

                    EndPrimitive();
                }
            "),
            fragment_shader: "
                #version 430

                in vec3 g_normal;
                in vec2 g_tex_coords;

                uniform sampler2D color_texture;

                const vec3 LIGHT = vec3(-0.2, 0.1, 0.8);

                void main() {
                    float lum = max(dot(normalize(g_normal), normalize(LIGHT)), 0.0);
                    vec3 tex_color = texture(color_texture, g_tex_coords).rgb;
                    vec3 color = (0.6 + 0.4 * lum) * tex_color;
                    gl_FragColor = vec4(color, 1.0);
                }
            ",
        }).unwrap();

    let mut camera = support::camera::CameraState::new();

    // the main loop
    support::start_loop(|| {
        // building the uniforms
        let uniforms = uniform! {
            inner_level: 64.0f32,
            outer_level: 64.0f32,
            projection_matrix: camera.get_perspective(),
            view_matrix: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0f32]
            ],
            height_texture: &opengl_texture,
            elevation: 0.3f32,
            color_texture: &opengl_texture
        };

        // drawing a frame
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);
        target.draw(&vertex_buffer,
                    &glium::index::NoIndices(glium::index::PrimitiveType::Patches {
                        vertices_per_patch: 3
                    }),
                    &program, &uniforms,
                    &std::default::Default::default()).unwrap();
        target.finish();

        // polling and handling the events received by the window
        for event in display.poll_events() {
            match event {
                glutin::Event::Closed => return support::Action::Stop,
                _ => ()
            }
        }

        support::Action::Continue
    });
}
<|endoftext|>


<commit_before><commit_msg>Add test for Gate<commit_after>extern crate ruyi;
extern crate futures;

use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;

use futures::{future, Future, Poll, Async};
use ruyi::reactor::{self, Gate, Timer, IntoTask};

static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

struct GateHolder {
    _gate: Option<Gate>,
    timer: Timer,
}

impl GateHolder {
    fn with_gate() -> Self {
        GateHolder {
            _gate: Some(reactor::gate().unwrap()),
            timer: Timer::new(Duration::from_millis(200)),
        }
    }

    fn without_gate() -> Self {
        GateHolder {
            _gate: None,
            timer: Timer::new(Duration::from_millis(200)),
        }
    }
}

impl Future for GateHolder {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.timer.poll() {
            Ok(Async::Ready(..)) => {
                COUNT.fetch_add(1, Ordering::Relaxed);
                Ok(Async::Ready(()))
            }
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(()) => Err(()),
        }
    }
}

#[test]
fn gate() {
    let task_without_gate =
        future::ok::<(), ()>(())
            .and_then(|_| Ok(reactor::spawn(GateHolder::without_gate().into_task())));
    reactor::run(task_without_gate).unwrap();
    assert_eq!(COUNT.load(Ordering::Relaxed), 0);

    let task_with_gate = future::ok::<(), ()>(())
        .and_then(|_| Ok(reactor::spawn(GateHolder::with_gate().into_task())));
    reactor::run(task_with_gate).unwrap();
    assert_eq!(COUNT.load(Ordering::Relaxed), 1);
}
<|endoftext|>


<commit_before><commit_msg>added to_array()<commit_after><|endoftext|>


<commit_before><commit_msg>fix typo in request_ref! macro<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Fuchsia tests in response to fuchsia-zircon update.<commit_after><|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.delete(window);
                                    *mode = Insert;
                                },
                                (Normal, 'o') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset <= 0 {
                                        editor.left();
                                    }
                                    editor.right();
                                    while (editor.cur() == ' ' ||
                                          editor.cur() == '\t') &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '0') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        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.offset < editor.string.len() {
                                        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.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' && editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' && editor.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '%') => {
                                    match editor.cur() {
                                        '(' | '[' | '{' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.right();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => 1,
                                                    ')' | ']' | '}' => -1,
                                                    _ => 0,
                                                };
                                                if editor.offset < editor.string.len() {
                                                    break;
                                                }
                                            }
                                        },
                                        ')' | ']' | '}' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.left();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => -1,
                                                    ')' | ']' | '}' => 1,
                                                    _ => 0,
                                                };
                                                if editor.offset >= 0 {
                                                    break;
                                                }
                                            }
                                        },
                                        _ => {},

                                    }
                                },
                                (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 0 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.offset < editor.string.len() {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset <= 0 {
                                        editor.left();
                                    }
                                    editor.right();
                                    while (editor.cur() == ' ' ||
                                          editor.cur() == '\t') &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal,  '0') => {
                                    editor.left();
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        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.offset < editor.string.len() {
                                        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.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' && editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' && editor.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '%') => {
                                    match editor.cur() {
                                        '(' | '[' | '{' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.right();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => 1,
                                                    ')' | ']' | '}' => -1,
                                                    _ => 0,
                                                };
                                                if editor.offset < editor.string.len() {
                                                    break;
                                                }
                                            }
                                        },
                                        ')' | ']' | '}' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.left();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => -1,
                                                    ')' | ']' | '}' => 1,
                                                    _ => 0,
                                                };
                                                if editor.offset >= 0 {
                                                    break;
                                                }
                                            }
                                        },
                                        _ => {},

                                    }
                                },
                                (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>Strip querystring<commit_after><|endoftext|>


<commit_before><commit_msg>started select.rs<commit_after><|endoftext|>


<commit_before><commit_msg>cargo: add start of rust rewrite<commit_after>// cargo.rs - Rust package manager

use rustc;
use std;

import rustc::syntax::{ast, codemap, visit};
import rustc::syntax::parse::parser;

import std::io;
import std::option;
import std::option::{none, some};
import std::run;
import std::str;
import std::tempfile;
import std::vec;

type pkg = {
    name: str,
    vers: str,
    uuid: str,
    desc: option::t<str>,
    sigs: option::t<str>
};

fn load_link(mis: [@ast::meta_item]) -> (option::t<str>,
                                         option::t<str>,
                                         option::t<str>) {
    let name = none;
    let vers = none;
    let uuid = none;
    for a: @ast::meta_item in mis {
        alt a.node {
            ast::meta_name_value(v, {node: ast::lit_str(s), span: _}) {
                alt v {
                    "name" { name = some(s); }
                    "vers" { vers = some(s); }
                    "uuid" { uuid = some(s); }
                    _ { }
                }
            }
        }
    }
    (name, vers, uuid)
}

fn load_pkg(filename: str) -> option::t<pkg> {
    let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
    let c = parser::parse_crate_from_crate_file(filename, [], sess);

    let name = none;
    let vers = none;
    let uuid = none;
    let desc = none;
    let sigs = none;

    for a in c.node.attrs {
        alt a.node.value.node {
            ast::meta_name_value(v, {node: ast::lit_str(s), span: _}) {
                alt v {
                    "desc" { desc = some(v); }
                    "sigs" { sigs = some(v); }
                    _ { }
                }
            }
            ast::meta_list(v, mis) {
                if v == "link" {
                    let (n, v, u) = load_link(mis);
                    name = n;
                    vers = v;
                    uuid = u;
                }
            }
        }
    }

    alt (name, vers, uuid) {
        (some(name0), some(vers0), some(uuid0)) {
            some({
                name: name0,
                vers: vers0,
                uuid: uuid0,
                desc: desc,
                sigs: sigs})
        }
        _ { ret none; }
    }
}

fn print(s: str) {
    io::stdout().write_line(s);
}

fn rest(s: str, start: uint) -> str {
    if (start >= str::char_len(s)) {
        ""
    } else {
        str::char_slice(s, start, str::char_len(s))
    }
}

fn install_file(path: str) -> option::t<str> {
    let wd = tempfile::mkdtemp("/tmp/cargo-work-", "");
    ret wd;
}

fn cmd_install(argv: [str]) {
    // cargo install <pkg>
    if vec::len(argv) < 3u {
        cmd_usage();
        ret;
    }

    let wd = if str::starts_with(argv[2], "file:") {
        let path = rest(argv[2], 5u);
        install_file(path)
    } else {
        none
    };
}

fn cmd_usage() {
    print("Usage: cargo <verb> [args...]");
}

fn main(argv: [str]) {
    if vec::len(argv) < 2u {
        cmd_usage();
        ret;
    }
    alt argv[1] {
        "usage" { cmd_usage(); }
        _ { cmd_usage(); }
    }
}

<|endoftext|>


<commit_before><commit_msg>Add test.<commit_after>#![warn(clippy::filetype_is_file)]

fn main() -> std::io::Result<()> {
    use std::fs;
    use std::ops::BitOr;

    // !filetype.is_dir()
    if fs::metadata("foo.txt")?.file_type().is_file() {
        // read file
    }

    // positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file() {
        // handle dir
    }

    // false positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file().bitor(true) {
        // ...
    }

    Ok(())
}<|endoftext|>


<commit_before><commit_msg>Sort use statements.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for namespaced enums<commit_after><|endoftext|>


<commit_before><commit_msg>Implement 'push' and 'pull'<commit_after><|endoftext|>


<commit_before>use russell_lab::{Matrix, Vector};

/// Defines a (bi-linear) Hexahedron with 8 nodes
///
/// The natural coordinates range from -1 to +1 with the geometry centred @ 0
///
/// ```text
///              4________________7
///            ,'|              ,'|
///          ,'  |            ,'  |
///        ,'    |          ,'    |
///      ,'      |        ,'      |
///    5'===============6'        |
///    |         |      |         |
///    |         |      |         |
///    |         0_____ | ________3
///    |       ,'       |       ,'
///    |     ,'         |     ,'
///    |   ,'           |   ,'
///    | ,'             | ,'
///    1________________2'
/// ```
///
/// # Example
///
/// ```
/// // import
/// use gemlab::Hex8;
/// use russell_lab::Vector;
///
/// // geometry object
/// let mut geo = Hex8::new();
/// let ndim = geo.get_ndim();
///
/// // compute shape fn and deriv @ ksi=(0,0,0) for all nodes
/// let ksi = Vector::new(ndim);
/// geo.calc_shape(&ksi);
/// geo.calc_deriv(&ksi);
///
/// // get shape fn and deriv for node m
/// let m = 0;
/// let sm = geo.get_shape(m);
/// let mut dsm_dksi = Vector::new(ndim);
/// geo.get_deriv(&mut dsm_dksi, m);
///
/// // check shape fn and deriv @ ksi for node m
/// assert_eq!(sm, 0.125);
/// assert_eq!(
///     format!("{}", dsm_dksi),
///     "┌        ┐\n\
///      │ -0.125 │\n\
///      │ -0.125 │\n\
///      │ -0.125 │\n\
///      └        ┘"
/// );
/// ```
pub struct Hex8 {
    // natural coordinates (nnode, ndim)
    //
    // ```text
    // ξᵐ = vector{r, s, t} @ node m
    // coords = [ξ⁰, ξ¹, ξ², ξ³, ξ⁴, ξ⁵, ξ⁶, ξ⁷, ξ⁸]
    // ```
    coords: Vec<Vector>,

    // shape functions @ natural coordinate (nnode)
    //
    // ```text
    // shape[m](ξ) = Sᵐ(ξ)
    // ```
    shape: Vector,

    // derivatives of shape functions w.r.t natural coordinate (nnode, ndim)
    //
    // ```text
    // deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    // ```
    deriv: Matrix,
}

const NDIM: usize = 3;
const NNODE: usize = 8;

impl Hex8 {
    /// Creates a new object with pre-calculated shape fn and derivatives
    pub fn new() -> Self {
        Hex8 {
            #[rustfmt::skip]
            coords: vec![
                Vector::from(&[-1.0, -1.0, -1.0]),
                Vector::from(&[ 1.0, -1.0, -1.0]),
                Vector::from(&[ 1.0,  1.0, -1.0]),
                Vector::from(&[-1.0,  1.0, -1.0]),
                Vector::from(&[-1.0, -1.0,  1.0]),
                Vector::from(&[ 1.0, -1.0,  1.0]),
                Vector::from(&[ 1.0,  1.0,  1.0]),
                Vector::from(&[-1.0,  1.0,  1.0]),
            ],
            shape: Vector::new(NNODE),
            deriv: Matrix::new(NNODE, NDIM),
        }
    }

    /// Calculates the shape functions at natural coordinate
    ///
    /// ```text
    /// shape[m](ξ) = Sᵐ(ξ)
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// use gemlab::Hex8;
    /// use russell_lab::Vector;
    /// let mut geo = Hex8::new();
    /// let ndim = geo.get_ndim();
    /// let ksi = Vector::new(ndim);
    /// geo.calc_shape(&ksi);
    /// ```
    pub fn calc_shape(&mut self, coord: &Vector) {
        let (r, s, t) = (coord[0], coord[1], coord[2]);

        self.shape[0] = (1.0 - r - s + r * s - t + s * t + r * t - r * s * t) / 8.0;
        self.shape[1] = (1.0 + r - s - r * s - t + s * t - r * t + r * s * t) / 8.0;
        self.shape[2] = (1.0 + r + s + r * s - t - s * t - r * t - r * s * t) / 8.0;
        self.shape[3] = (1.0 - r + s - r * s - t - s * t + r * t + r * s * t) / 8.0;
        self.shape[4] = (1.0 - r - s + r * s + t - s * t - r * t + r * s * t) / 8.0;
        self.shape[5] = (1.0 + r - s - r * s + t - s * t + r * t - r * s * t) / 8.0;
        self.shape[6] = (1.0 + r + s + r * s + t + s * t + r * t + r * s * t) / 8.0;
        self.shape[7] = (1.0 - r + s - r * s + t + s * t - r * t - r * s * t) / 8.0;
    }

    /// Calculates the derivatives of shape functions at natural coordinate
    ///
    /// ```text
    /// deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    /// ```
    ///
    /// ```
    /// use gemlab::Hex8;
    /// use russell_lab::Vector;
    /// let mut geo = Hex8::new();
    /// let ndim = geo.get_ndim();
    /// let ksi = Vector::new(ndim);
    /// geo.calc_deriv(&ksi);
    /// ```
    pub fn calc_deriv(&mut self, coord: &Vector) {
        let (r, s, t) = (coord[0], coord[1], coord[2]);

        self.deriv[0][0] = (-1.0 + s + t - s * t) / 8.0;
        self.deriv[0][1] = (-1.0 + r + t - r * t) / 8.0;
        self.deriv[0][2] = (-1.0 + r + s - r * s) / 8.0;

        self.deriv[1][0] = (1.0 - s - t + s * t) / 8.0;
        self.deriv[1][1] = (-1.0 - r + t + r * t) / 8.0;
        self.deriv[1][2] = (-1.0 - r + s + r * s) / 8.0;

        self.deriv[2][0] = (1.0 + s - t - s * t) / 8.0;
        self.deriv[2][1] = (1.0 + r - t - r * t) / 8.0;
        self.deriv[2][2] = (-1.0 - r - s - r * s) / 8.0;

        self.deriv[3][0] = (-1.0 - s + t + s * t) / 8.0;
        self.deriv[3][1] = (1.0 - r - t + r * t) / 8.0;
        self.deriv[3][2] = (-1.0 + r - s + r * s) / 8.0;

        self.deriv[4][0] = (-1.0 + s - t + s * t) / 8.0;
        self.deriv[4][1] = (-1.0 + r - t + r * t) / 8.0;
        self.deriv[4][2] = (1.0 - r - s + r * s) / 8.0;

        self.deriv[5][0] = (1.0 - s + t - s * t) / 8.0;
        self.deriv[5][1] = (-1.0 - r - t - r * t) / 8.0;
        self.deriv[5][2] = (1.0 + r - s - r * s) / 8.0;

        self.deriv[6][0] = (1.0 + s + t + s * t) / 8.0;
        self.deriv[6][1] = (1.0 + r + t + r * t) / 8.0;
        self.deriv[6][2] = (1.0 + r + s + r * s) / 8.0;

        self.deriv[7][0] = (-1.0 - s - t - s * t) / 8.0;
        self.deriv[7][1] = (1.0 - r + t - r * t) / 8.0;
        self.deriv[7][2] = (1.0 - r + s - r * s) / 8.0;
    }

    /// Returns the previously computed shape function for node m
    ///
    /// ```text
    /// shape[m](ξ) = Sᵐ(ξ)
    /// ```
    pub fn get_shape(&self, m: usize) -> f64 {
        self.shape[m]
    }

    /// Returns the previously computed derivative of shape function for node m
    //
    // ```text
    // deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    // ```
    pub fn get_deriv(&self, deriv: &mut Vector, m: usize) {
        deriv[0] = self.deriv[m][0];
        deriv[1] = self.deriv[m][1];
        deriv[2] = self.deriv[m][2];
    }

    /// Returns the number of dimensions
    pub fn get_ndim(&self) -> usize {
        NDIM
    }

    /// Returns the number of nodes
    pub fn get_nnode(&self) -> usize {
        NNODE
    }

    /// Returns the natural coordinates @ node m
    //
    // ```text
    // coord = ξᵐ = vector{r, s, t} @ node m
    // ```
    pub fn get_coord(&self, coord: &mut Vector, m: usize) {
        coord[0] = self.coords[m][0];
        coord[1] = self.coords[m][1];
        coord[2] = self.coords[m][2];
    }
}

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

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

    // Holds arguments for numerical differentiation
    struct Arguments {
        geo: Hex8,      // geometry
        at_ksi: Vector, // at nat coord value
        ksi: Vector,    // temporary nat coord
        m: usize,       // shape: node index
        i: usize,       // nat coord: dimension index
    }

    // Computes the shape function @ m as a function of x = ksi[i]
    fn sm(x: f64, args: &mut Arguments) -> f64 {
        args.ksi[0] = args.at_ksi[0];
        args.ksi[1] = args.at_ksi[1];
        args.ksi[2] = args.at_ksi[2];
        args.ksi[args.i] = x;
        args.geo.calc_shape(&args.ksi);
        args.geo.get_shape(args.m)
    }

    #[test]
    fn new_works() {
        let geo = Hex8::new();
        assert_eq!(geo.coords.len(), NNODE);
        assert_eq!(geo.shape.dim(), NNODE);
        assert_eq!(geo.deriv.dims(), (NNODE, NDIM));
    }

    #[test]
    fn calc_shape_works() {
        let mut geo = Hex8::new();
        let mut ksi = Vector::new(NDIM);
        for m in 0..NNODE {
            geo.get_coord(&mut ksi, m);
            geo.calc_shape(&ksi);
            for n in 0..NNODE {
                let smn = geo.get_shape(n);
                if m == n {
                    assert_approx_eq!(smn, 1.0, 1e-15);
                } else {
                    assert_approx_eq!(smn, 0.0, 1e-15);
                }
            }
        }
    }

    #[test]
    fn calc_deriv_works() {
        let args = &mut Arguments {
            geo: Hex8::new(),
            at_ksi: Vector::from(&[0.25, 0.25, 0.25]),
            ksi: Vector::new(NDIM),
            m: 0,
            i: 0,
        };
        let mut geo = Hex8::new();
        let mut dsm_dksi = Vector::new(NDIM);
        geo.calc_deriv(&args.at_ksi);
        for m in 0..NNODE {
            geo.get_deriv(&mut dsm_dksi, m);
            args.m = m;
            for i in 0..NDIM {
                args.i = i;
                assert_deriv_approx_eq!(dsm_dksi[i], args.at_ksi[i], sm, args, 1e-13);
            }
        }
    }

    #[test]
    fn getters_work() {
        let geo = Hex8::new();
        assert_eq!(geo.get_ndim(), NDIM);
        assert_eq!(geo.get_nnode(), NNODE);
    }
}
<commit_msg>Simplify doc<commit_after>use russell_lab::{Matrix, Vector};

/// Defines a (bi-linear) Hexahedron with 8 nodes
///
/// The natural coordinates range from -1 to +1 with the geometry centred @ 0
///
/// ```text
///              4________________7
///            ,'|              ,'|
///          ,'  |            ,'  |
///        ,'    |          ,'    |
///      ,'      |        ,'      |
///    5'===============6'        |
///    |         |      |         |
///    |         |      |         |
///    |         0_____ | ________3
///    |       ,'       |       ,'
///    |     ,'         |     ,'
///    |   ,'           |   ,'
///    | ,'             | ,'
///    1________________2'
/// ```
///
/// # Example
///
/// ```
/// // import
/// use gemlab::Hex8;
/// use russell_lab::Vector;
///
/// // geometry object
/// let mut geo = Hex8::new();
/// let ndim = geo.get_ndim();
///
/// // compute shape fn and deriv @ ksi=(0,0,0) for all nodes
/// let ksi = Vector::new(ndim);
/// geo.calc_shape(&ksi);
/// geo.calc_deriv(&ksi);
///
/// // get shape fn and deriv for node m
/// let m = 0;
/// let sm = geo.get_shape(m);
/// let mut dsm_dksi = Vector::new(ndim);
/// geo.get_deriv(&mut dsm_dksi, m);
///
/// // check shape fn and deriv @ ksi for node m
/// assert_eq!(sm, 0.125);
/// assert_eq!(
///     format!("{}", dsm_dksi),
///     "┌        ┐\n\
///      │ -0.125 │\n\
///      │ -0.125 │\n\
///      │ -0.125 │\n\
///      └        ┘"
/// );
/// ```
pub struct Hex8 {
    // natural coordinates (nnode, ndim)
    //
    // ```text
    // ξᵐ = vector{r, s, t} @ node m
    // coords = [ξ⁰, ξ¹, ξ², ξ³, ξ⁴, ξ⁵, ξ⁶, ξ⁷, ξ⁸]
    // ```
    coords: Vec<Vector>,

    // shape functions @ natural coordinate (nnode)
    //
    // ```text
    // shape[m](ξ) = Sᵐ(ξ)
    // ```
    shape: Vector,

    // derivatives of shape functions w.r.t natural coordinate (nnode, ndim)
    //
    // ```text
    // deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    // ```
    deriv: Matrix,
}

const NDIM: usize = 3;
const NNODE: usize = 8;

impl Hex8 {
    /// Creates a new object with pre-calculated shape fn and derivatives
    pub fn new() -> Self {
        Hex8 {
            #[rustfmt::skip]
            coords: vec![
                Vector::from(&[-1.0, -1.0, -1.0]),
                Vector::from(&[ 1.0, -1.0, -1.0]),
                Vector::from(&[ 1.0,  1.0, -1.0]),
                Vector::from(&[-1.0,  1.0, -1.0]),
                Vector::from(&[-1.0, -1.0,  1.0]),
                Vector::from(&[ 1.0, -1.0,  1.0]),
                Vector::from(&[ 1.0,  1.0,  1.0]),
                Vector::from(&[-1.0,  1.0,  1.0]),
            ],
            shape: Vector::new(NNODE),
            deriv: Matrix::new(NNODE, NDIM),
        }
    }

    /// Calculates the shape functions at natural coordinate
    ///
    /// ```text
    /// shape[m](ξ) = Sᵐ(ξ)
    /// ```
    pub fn calc_shape(&mut self, coord: &Vector) {
        let (r, s, t) = (coord[0], coord[1], coord[2]);

        self.shape[0] = (1.0 - r - s + r * s - t + s * t + r * t - r * s * t) / 8.0;
        self.shape[1] = (1.0 + r - s - r * s - t + s * t - r * t + r * s * t) / 8.0;
        self.shape[2] = (1.0 + r + s + r * s - t - s * t - r * t - r * s * t) / 8.0;
        self.shape[3] = (1.0 - r + s - r * s - t - s * t + r * t + r * s * t) / 8.0;
        self.shape[4] = (1.0 - r - s + r * s + t - s * t - r * t + r * s * t) / 8.0;
        self.shape[5] = (1.0 + r - s - r * s + t - s * t + r * t - r * s * t) / 8.0;
        self.shape[6] = (1.0 + r + s + r * s + t + s * t + r * t + r * s * t) / 8.0;
        self.shape[7] = (1.0 - r + s - r * s + t + s * t - r * t - r * s * t) / 8.0;
    }

    /// Calculates the derivatives of shape functions at natural coordinate
    ///
    /// ```text
    /// deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    /// ```
    pub fn calc_deriv(&mut self, coord: &Vector) {
        let (r, s, t) = (coord[0], coord[1], coord[2]);

        self.deriv[0][0] = (-1.0 + s + t - s * t) / 8.0;
        self.deriv[0][1] = (-1.0 + r + t - r * t) / 8.0;
        self.deriv[0][2] = (-1.0 + r + s - r * s) / 8.0;

        self.deriv[1][0] = (1.0 - s - t + s * t) / 8.0;
        self.deriv[1][1] = (-1.0 - r + t + r * t) / 8.0;
        self.deriv[1][2] = (-1.0 - r + s + r * s) / 8.0;

        self.deriv[2][0] = (1.0 + s - t - s * t) / 8.0;
        self.deriv[2][1] = (1.0 + r - t - r * t) / 8.0;
        self.deriv[2][2] = (-1.0 - r - s - r * s) / 8.0;

        self.deriv[3][0] = (-1.0 - s + t + s * t) / 8.0;
        self.deriv[3][1] = (1.0 - r - t + r * t) / 8.0;
        self.deriv[3][2] = (-1.0 + r - s + r * s) / 8.0;

        self.deriv[4][0] = (-1.0 + s - t + s * t) / 8.0;
        self.deriv[4][1] = (-1.0 + r - t + r * t) / 8.0;
        self.deriv[4][2] = (1.0 - r - s + r * s) / 8.0;

        self.deriv[5][0] = (1.0 - s + t - s * t) / 8.0;
        self.deriv[5][1] = (-1.0 - r - t - r * t) / 8.0;
        self.deriv[5][2] = (1.0 + r - s - r * s) / 8.0;

        self.deriv[6][0] = (1.0 + s + t + s * t) / 8.0;
        self.deriv[6][1] = (1.0 + r + t + r * t) / 8.0;
        self.deriv[6][2] = (1.0 + r + s + r * s) / 8.0;

        self.deriv[7][0] = (-1.0 - s - t - s * t) / 8.0;
        self.deriv[7][1] = (1.0 - r + t - r * t) / 8.0;
        self.deriv[7][2] = (1.0 - r + s - r * s) / 8.0;
    }

    /// Returns the previously computed shape function for node m
    ///
    /// ```text
    /// shape[m](ξ) = Sᵐ(ξ)
    /// ```
    pub fn get_shape(&self, m: usize) -> f64 {
        self.shape[m]
    }

    /// Returns the previously computed derivative of shape function for node m
    //
    // ```text
    // deriv[m][i](ξ) = ({dSᵐ(ξ)/dξ}_ξ)[i]
    // ```
    pub fn get_deriv(&self, deriv: &mut Vector, m: usize) {
        deriv[0] = self.deriv[m][0];
        deriv[1] = self.deriv[m][1];
        deriv[2] = self.deriv[m][2];
    }

    /// Returns the number of dimensions
    pub fn get_ndim(&self) -> usize {
        NDIM
    }

    /// Returns the number of nodes
    pub fn get_nnode(&self) -> usize {
        NNODE
    }

    /// Returns the natural coordinates @ node m
    //
    // ```text
    // coord = ξᵐ = vector{r, s, t} @ node m
    // ```
    pub fn get_coord(&self, coord: &mut Vector, m: usize) {
        coord[0] = self.coords[m][0];
        coord[1] = self.coords[m][1];
        coord[2] = self.coords[m][2];
    }
}

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

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

    // Holds arguments for numerical differentiation
    struct Arguments {
        geo: Hex8,      // geometry
        at_ksi: Vector, // at nat coord value
        ksi: Vector,    // temporary nat coord
        m: usize,       // shape: node index
        i: usize,       // nat coord: dimension index
    }

    // Computes the shape function @ m as a function of x = ksi[i]
    fn sm(x: f64, args: &mut Arguments) -> f64 {
        args.ksi[0] = args.at_ksi[0];
        args.ksi[1] = args.at_ksi[1];
        args.ksi[2] = args.at_ksi[2];
        args.ksi[args.i] = x;
        args.geo.calc_shape(&args.ksi);
        args.geo.get_shape(args.m)
    }

    #[test]
    fn new_works() {
        let geo = Hex8::new();
        assert_eq!(geo.coords.len(), NNODE);
        assert_eq!(geo.shape.dim(), NNODE);
        assert_eq!(geo.deriv.dims(), (NNODE, NDIM));
    }

    #[test]
    fn calc_shape_works() {
        let mut geo = Hex8::new();
        let mut ksi = Vector::new(NDIM);
        for m in 0..NNODE {
            geo.get_coord(&mut ksi, m);
            geo.calc_shape(&ksi);
            for n in 0..NNODE {
                let smn = geo.get_shape(n);
                if m == n {
                    assert_approx_eq!(smn, 1.0, 1e-15);
                } else {
                    assert_approx_eq!(smn, 0.0, 1e-15);
                }
            }
        }
    }

    #[test]
    fn calc_deriv_works() {
        let args = &mut Arguments {
            geo: Hex8::new(),
            at_ksi: Vector::from(&[0.25, 0.25, 0.25]),
            ksi: Vector::new(NDIM),
            m: 0,
            i: 0,
        };
        let mut geo = Hex8::new();
        let mut dsm_dksi = Vector::new(NDIM);
        geo.calc_deriv(&args.at_ksi);
        for m in 0..NNODE {
            geo.get_deriv(&mut dsm_dksi, m);
            args.m = m;
            for i in 0..NDIM {
                args.i = i;
                assert_deriv_approx_eq!(dsm_dksi[i], args.at_ksi[i], sm, args, 1e-13);
            }
        }
    }

    #[test]
    fn getters_work() {
        let geo = Hex8::new();
        assert_eq!(geo.get_ndim(), NDIM);
        assert_eq!(geo.get_nnode(), NNODE);
    }
}
<|endoftext|>


<commit_before><commit_msg>Make display resolution public<commit_after><|endoftext|>


<commit_before><commit_msg>impl ToGlibPtr and FromGlibPtrNone for FontFace<commit_after><|endoftext|>


<commit_before><commit_msg>some access_log parsing work<commit_after>use std::collections::HashMap;
use std::str::Utf8Error;
use std::num::ParseFloatError;
use std::fmt::{self, Display};

use vsl::{VslRecord, VslRecordTag, VslIdent};

use nom::IResult;

pub type TimeStamp = f64;

#[derive(Debug, Clone)]
pub struct AccessRecord {
    pub ident: VslIdent,
    pub start: TimeStamp,
    pub end: TimeStamp,
    pub transaction_type: TransactionType,
    pub transaction: HttpTransaction,
}

#[derive(Debug, Clone)]
pub enum TransactionType {
    Client,
    Backend {
        parent: VslIdent,
        reason: String,
    },
}

impl TransactionType {
    #[allow(dead_code)]
    pub fn is_backend(&self) -> bool {
        match self {
            &TransactionType::Backend { parent: _, reason: _ } => true,
            _ => false
        }
    }

    #[allow(dead_code)]
    pub fn get_backend_parent(&self) -> VslIdent {
        match self {
            &TransactionType::Backend { ref parent, reason: _ } => *parent,
            _ => panic!("unwrap_backend called on TransactionType that was Backend")
        }
    }

    #[allow(dead_code)]
    pub fn get_backend_reason(&self) -> &str {
        match self {
            &TransactionType::Backend { parent: _, ref reason } => reason,
            _ => panic!("unwrap_backend called on TransactionType that was Backend")
        }
    }
}

#[derive(Debug, Clone)]
pub struct HttpTransaction {
    pub request: HttpRequest,
    pub response: HttpResponse,
}

#[derive(Debug, Clone)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    pub protocol: String,
    pub headers: Vec<(String, String)>,
}

#[derive(Debug, Clone)]
pub struct HttpResponse {
    pub status_name: String,
    pub status_code: u32,
    pub headers: Vec<(String, String)>,
}

#[derive(Debug, Clone)]
struct RecordBuilder {
    ident: VslIdent,
    transaction_type: Option<TransactionType>,
    start: Option<TimeStamp>,
    end: Option<TimeStamp>,
    method: Option<String>,
    url: Option<String>,
    protocol: Option<String>,
    status_name: Option<String>,
    status_code: Option<u32>,
    headers: HashMap<String, String>,
}

#[derive(Debug)]
enum RecordBuilderResult {
    Building(RecordBuilder),
    Ready(AccessRecord),
}

#[derive(Debug)]
enum RecordBuilderError {
    VslBodyUtf8Error(Utf8Error),
}

impl Display for RecordBuilderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &RecordBuilderError::VslBodyUtf8Error(ref e) => write!(f, "VSL record body is not valid UTF-8 encoded string: {}", e),
        }
    }
}

use nom::{space, eof};
named!(label<&str, &str>, terminated!(take_until_s!(": "), tag_s!(": ")));
named!(space_terminated<&str, &str>, terminated!(is_not_s!(" "), space));
named!(space_terminated_eof<&str, &str>, terminated!(is_not_s!(" "), eof));

named!(SLT_Timestamp<&str, (&str, &str, &str, &str)>, tuple!(
        label,                      // Event label
        space_terminated,           // Absolute time of event
        space_terminated,           // Time since start of work unit
        space_terminated_eof));     // Time since last timestamp

impl RecordBuilder {
    fn new(ident: VslIdent) -> RecordBuilder {
        RecordBuilder {
            ident: ident,
            transaction_type: None,
            start: None,
            end: None,
            method: None,
            url: None,
            protocol: None,
            status_name: None,
            status_code: None,
            headers: HashMap::new()
        }
    }

    fn apply<'r>(self, vsl: &'r VslRecord) -> Result<RecordBuilderResult, RecordBuilderError> {
        let builder = match vsl.body() {
            Ok(body) => match vsl.tag {
                VslRecordTag::SLT_Begin => {
                    // nom?
                    let mut elements = body.splitn(3, ' ');

                    //TODO: error handling
                    let transaction_type = elements.next().unwrap();
                    let parent = elements.next().unwrap();
                    let reason = elements.next().unwrap();

                    let parent = parent.parse().unwrap();

                    let transaction_type = match transaction_type {
                        "bereq" => TransactionType::Backend { parent: parent, reason: reason.to_owned() },
                        _ => panic!("unimpl transaction_type")
                    };

                    RecordBuilder { transaction_type: Some(transaction_type), .. self }
                }
                VslRecordTag::SLT_Timestamp => {
                    if let IResult::Done(_, (label, timestamp, _sice_work_start, _since_last_timestamp)) =  SLT_Timestamp(body) {
                        match label {
                            "Start" => RecordBuilder { start: Some(try!(timestamp.parse())), .. self },
                            _ => {
                                warn!("Unknown SLT_Timestamp label variant: {}", label);
                                self
                            }
                        }
                    } else {
                        panic!("foobar!")
                    }
                }
                _ => panic!("unimpl tag")
            },
            Err(err) => return Err(RecordBuilderError::VslBodyUtf8Error(err))
        };

        Ok(RecordBuilderResult::Building(builder))
    }
}

#[derive(Debug)]
pub struct State {
    builders: HashMap<VslIdent, RecordBuilder>
}

impl State {
    pub fn new() -> State {
        State { builders: HashMap::new() }
    }

    pub fn apply(&mut self, vsl: &VslRecord) -> Option<AccessRecord> {
        //TODO: use entry API
        let builder = match self.builders.remove(&vsl.ident) {
            Some(builder) => builder,
            None => RecordBuilder::new(vsl.ident),
        };

        match builder.apply(vsl) {
            Ok(result) => match result {
                RecordBuilderResult::Building(builder) => {
                    self.builders.insert(vsl.ident, builder);
                    return None
                }
                RecordBuilderResult::Ready(record) => return Some(record),
            },
            Err(err) => {
                //TODO: define proper error and return to main loop
                error!("Error while building record with ident {}: {}", vsl.ident, err);
                return None
            }
        }
    }

    #[cfg(test)]
    fn get(&self, ident: VslIdent) -> Option<&RecordBuilder> {
        self.builders.get(&ident)
    }
}

#[cfg(test)]
mod access_log_state_tests {
    pub use super::*;
    use vsl::{VslRecord, VslRecordTag};

    #[test]
    fn apply_begin() {
        let mut state = State::new();

        state.apply(&VslRecord::from_str(VslRecordTag::SLT_Begin, 123, "bereq 321 fetch"));

        let builder = state.get(123).unwrap().clone();
        let transaction_type = builder.transaction_type.unwrap();

        assert_eq!(transaction_type.get_backend_parent(), 321);
        assert_eq!(transaction_type.get_backend_reason(), "fetch");
    }

    #[test]
    fn apply_timestamp() {
        let mut state = State::new();

        state.apply(&VslRecord::from_str(VslRecordTag::SLT_Timestamp, 123, "Start: 1469180762.484544 0.000000 0.000000"));

        let builder = state.get(123).unwrap().clone();
        assert_eq!(builder.start, Some(1469180762.484544));
    }
}
<|endoftext|>


<commit_before>/*!
   A parallel word-frequency counting program.

   This is meant primarily to demonstrate Rust's MapReduce framework.

   It takes a list of files on the command line and outputs a list of
   words along with how many times each word is used.

*/

// xfail-pretty

#[legacy_modes];

extern mod std;

use option = option;
use option::Some;
use option::None;
use std::map;
use std::map::HashMap;
use hash::Hash;
use io::WriterUtil;

use std::time;

use comm::Chan;
use comm::Port;
use comm::recv;
use comm::send;
use cmp::Eq;
use to_bytes::IterBytes;

macro_rules! move_out (
    { $x:expr } => { unsafe { let y <- *ptr::addr_of($x); y } }
)

trait word_reader {
    fn read_word() -> Option<~str>;
}

// These used to be in task, but they disappeard.
type joinable_task = Port<()>;
fn spawn_joinable(+f: fn~()) -> joinable_task {
    let p = Port();
    let c = Chan(p);
    do task::spawn() |move f| {
        f();
        c.send(());
    }
    p
}

fn join(t: joinable_task) {
    t.recv()
}

impl io::Reader: word_reader {
    fn read_word() -> Option<~str> { read_word(self) }
}

fn file_word_reader(filename: ~str) -> word_reader {
    match io::file_reader(&Path(filename)) {
      result::Ok(f) => { f as word_reader }
      result::Err(e) => { fail fmt!("%?", e) }
    }
}

fn map(f: fn~() -> word_reader, emit: map_reduce::putter<~str, int>) {
    let f = f();
    loop {
        match f.read_word() {
          Some(w) => { emit(w, 1); }
          None => { break; }
        }
    }
}

fn reduce(&&word: ~str, get: map_reduce::getter<int>) {
    let mut count = 0;

    loop { match get() { Some(_) => { count += 1; } None => { break; } } }

    io::println(fmt!("%s\t%?", word, count));
}

struct box<T> {
    mut contents: Option<T>,
}

impl<T> box<T> {
    fn swap(f: fn(+v: T) -> T) {
        let mut tmp = None;
        self.contents <-> tmp;
        self.contents = Some(f(option::unwrap(tmp)));
    }

    fn unwrap() -> T {
        let mut tmp = None;
        self.contents <-> tmp;
        option::unwrap(tmp)
    }
}

fn box<T>(+x: T) -> box<T> {
    box {
        contents: Some(x)
    }
}

mod map_reduce {
    #[legacy_exports];
    export putter;
    export getter;
    export mapper;
    export reducer;
    export map_reduce;

    type putter<K: Send, V: Send> = fn(K, V);

    type mapper<K1: Send, K2: Send, V: Send> = fn~(K1, putter<K2, V>);

    type getter<V: Send> = fn() -> Option<V>;

    type reducer<K: Copy Send, V: Copy Send> = fn~(K, getter<V>);

    enum ctrl_proto<K: Copy Send, V: Copy Send> {
        find_reducer(K, Chan<Chan<reduce_proto<V>>>),
        mapper_done
    }

    proto! ctrl_proto (
        open: send<K: Copy Send, V: Copy Send> {
            find_reducer(K) -> reducer_response<K, V>,
            mapper_done -> !
        }

        reducer_response: recv<K: Copy Send, V: Copy Send> {
            reducer(Chan<reduce_proto<V>>) -> open<K, V>
        }
    )

    enum reduce_proto<V: Copy Send> { emit_val(V), done, addref, release }

    fn start_mappers<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send,
                     V: Copy Send>(
        map: mapper<K1, K2, V>,
        &ctrls: ~[ctrl_proto::server::open<K2, V>],
        inputs: ~[K1])
        -> ~[joinable_task]
    {
        let mut tasks = ~[];
        for inputs.each |i| {
            let (ctrl, ctrl_server) = ctrl_proto::init();
            let ctrl = box(ctrl);
            let i = copy *i;
            tasks.push(spawn_joinable(|move i| map_task(map, ctrl, i)));
            ctrls.push(ctrl_server);
        }
        return tasks;
    }

    fn map_task<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send, V: Copy Send>(
        map: mapper<K1, K2, V>,
        ctrl: box<ctrl_proto::client::open<K2, V>>,
        input: K1)
    {
        // log(error, "map_task " + input);
        let intermediates = map::HashMap();

        do map(input) |key, val| {
            let mut c = None;
            let found = intermediates.find(key);
            match found {
              Some(_c) => { c = Some(_c); }
              None => {
                do ctrl.swap |ctrl| {
                    let ctrl = ctrl_proto::client::find_reducer(ctrl, key);
                    match pipes::recv(ctrl) {
                      ctrl_proto::reducer(c_, ctrl) => {
                        c = Some(c_);
                        move_out!(ctrl)
                      }
                    }
                }
                intermediates.insert(key, c.get());
                send(c.get(), addref);
              }
            }
            send(c.get(), emit_val(val));
        }

        fn finish<K: Copy Send, V: Copy Send>(_k: K, v: Chan<reduce_proto<V>>)
        {
            send(v, release);
        }
        for intermediates.each_value |v| { send(v, release) }
        ctrl_proto::client::mapper_done(ctrl.unwrap());
    }

    fn reduce_task<K: Copy Send, V: Copy Send>(
        reduce: reducer<K, V>,
        key: K,
        out: Chan<Chan<reduce_proto<V>>>)
    {
        let p = Port();

        send(out, Chan(p));

        let mut ref_count = 0;
        let mut is_done = false;

        fn get<V: Copy Send>(p: Port<reduce_proto<V>>,
                             &ref_count: int, &is_done: bool)
           -> Option<V> {
            while !is_done || ref_count > 0 {
                match recv(p) {
                  emit_val(v) => {
                    // error!("received %d", v);
                    return Some(v);
                  }
                  done => {
                    // error!("all done");
                    is_done = true;
                  }
                  addref => { ref_count += 1; }
                  release => { ref_count -= 1; }
                }
            }
            return None;
        }

        reduce(key, || get(p, ref_count, is_done) );
    }

    fn map_reduce<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send, V: Copy Send>(
        map: mapper<K1, K2, V>,
        reduce: reducer<K2, V>,
        inputs: ~[K1])
    {
        let mut ctrl = ~[];

        // This task becomes the master control task. It task::_spawns
        // to do the rest.

        let reducers = map::HashMap();
        let mut tasks = start_mappers(map, ctrl, inputs);
        let mut num_mappers = vec::len(inputs) as int;

        while num_mappers > 0 {
            let (_ready, message, ctrls) = pipes::select(ctrl);
            match option::unwrap(message) {
              ctrl_proto::mapper_done => {
                // error!("received mapper terminated.");
                num_mappers -= 1;
                ctrl = ctrls;
              }
              ctrl_proto::find_reducer(k, cc) => {
                let c;
                // log(error, "finding reducer for " + k);
                match reducers.find(k) {
                  Some(_c) => {
                    // log(error,
                    // "reusing existing reducer for " + k);
                    c = _c;
                  }
                  None => {
                    // log(error, "creating new reducer for " + k);
                    let p = Port();
                    let ch = Chan(p);
                    let r = reduce, kk = k;
                    tasks.push(spawn_joinable(|| reduce_task(r, kk, ch) ));
                    c = recv(p);
                    reducers.insert(k, c);
                  }
                }
                ctrl = vec::append_one(
                    ctrls,
                    ctrl_proto::server::reducer(move_out!(cc), c));
              }
            }
        }

        for reducers.each_value |v| { send(v, done) }

        for tasks.each |t| { join(*t); }
    }
}

fn main(++argv: ~[~str]) {
    if vec::len(argv) < 2u && !os::getenv(~"RUST_BENCH").is_some() {
        let out = io::stdout();

        out.write_line(fmt!("Usage: %s <filename> ...", argv[0]));

        return;
    }

    let readers: ~[fn~() -> word_reader]  = if argv.len() >= 2 {
        vec::view(argv, 1u, argv.len()).map(|f| {
            let f = *f;
            fn~() -> word_reader { file_word_reader(f) }
        })
    }
    else {
        let num_readers = 50;
        let words_per_reader = 600;
        vec::from_fn(
            num_readers,
            |_i| fn~() -> word_reader {
                random_word_reader(words_per_reader) as word_reader
            })
    };

    let start = time::precise_time_ns();

    map_reduce::map_reduce(map, reduce, readers);
    let stop = time::precise_time_ns();

    let elapsed = (stop - start) / 1000000u64;

    log(error, ~"MapReduce completed in "
             + u64::str(elapsed) + ~"ms");
}

fn read_word(r: io::Reader) -> Option<~str> {
    let mut w = ~"";

    while !r.eof() {
        let c = r.read_char();

        if is_word_char(c) {
            w += str::from_char(c);
        } else { if w != ~"" { return Some(w); } }
    }
    return None;
}

fn is_word_char(c: char) -> bool {
    char::is_alphabetic(c) || char::is_digit(c) || c == '_'
}

struct random_word_reader {
    mut remaining: uint,
    rng: rand::Rng,
}

impl random_word_reader: word_reader {
    fn read_word() -> Option<~str> {
        if self.remaining > 0 {
            self.remaining -= 1;
            let len = self.rng.gen_uint_range(1, 4);
            Some(self.rng.gen_str(len))
        }
        else { None }
    }
}

fn random_word_reader(count: uint) -> random_word_reader {
    random_word_reader {
        remaining: count,
        rng: rand::Rng()
    }
}
<commit_msg>Unbreak test/bench/task-perf-word-count-generic<commit_after>/*!
   A parallel word-frequency counting program.

   This is meant primarily to demonstrate Rust's MapReduce framework.

   It takes a list of files on the command line and outputs a list of
   words along with how many times each word is used.

*/

// xfail-pretty

#[legacy_modes];

extern mod std;

use option = option;
use option::Some;
use option::None;
use std::map;
use std::map::HashMap;
use hash::Hash;
use io::{ReaderUtil, WriterUtil};

use std::time;

use comm::Chan;
use comm::Port;
use comm::recv;
use comm::send;
use cmp::Eq;
use to_bytes::IterBytes;

macro_rules! move_out (
    { $x:expr } => { unsafe { let y <- *ptr::addr_of($x); y } }
)

trait word_reader {
    fn read_word() -> Option<~str>;
}

// These used to be in task, but they disappeard.
type joinable_task = Port<()>;
fn spawn_joinable(+f: fn~()) -> joinable_task {
    let p = Port();
    let c = Chan(p);
    do task::spawn() |move f| {
        f();
        c.send(());
    }
    p
}

fn join(t: joinable_task) {
    t.recv()
}

impl io::Reader: word_reader {
    fn read_word() -> Option<~str> { read_word(self) }
}

fn file_word_reader(filename: ~str) -> word_reader {
    match io::file_reader(&Path(filename)) {
      result::Ok(f) => { f as word_reader }
      result::Err(e) => { fail fmt!("%?", e) }
    }
}

fn map(f: fn~() -> word_reader, emit: map_reduce::putter<~str, int>) {
    let f = f();
    loop {
        match f.read_word() {
          Some(w) => { emit(w, 1); }
          None => { break; }
        }
    }
}

fn reduce(&&word: ~str, get: map_reduce::getter<int>) {
    let mut count = 0;

    loop { match get() { Some(_) => { count += 1; } None => { break; } } }

    io::println(fmt!("%s\t%?", word, count));
}

struct box<T> {
    mut contents: Option<T>,
}

impl<T> box<T> {
    fn swap(f: fn(+v: T) -> T) {
        let mut tmp = None;
        self.contents <-> tmp;
        self.contents = Some(f(option::unwrap(tmp)));
    }

    fn unwrap() -> T {
        let mut tmp = None;
        self.contents <-> tmp;
        option::unwrap(tmp)
    }
}

fn box<T>(+x: T) -> box<T> {
    box {
        contents: Some(x)
    }
}

mod map_reduce {
    #[legacy_exports];
    export putter;
    export getter;
    export mapper;
    export reducer;
    export map_reduce;

    type putter<K: Send, V: Send> = fn(K, V);

    type mapper<K1: Send, K2: Send, V: Send> = fn~(K1, putter<K2, V>);

    type getter<V: Send> = fn() -> Option<V>;

    type reducer<K: Copy Send, V: Copy Send> = fn~(K, getter<V>);

    enum ctrl_proto<K: Copy Send, V: Copy Send> {
        find_reducer(K, Chan<Chan<reduce_proto<V>>>),
        mapper_done
    }

    proto! ctrl_proto (
        open: send<K: Copy Send, V: Copy Send> {
            find_reducer(K) -> reducer_response<K, V>,
            mapper_done -> !
        }

        reducer_response: recv<K: Copy Send, V: Copy Send> {
            reducer(Chan<reduce_proto<V>>) -> open<K, V>
        }
    )

    enum reduce_proto<V: Copy Send> { emit_val(V), done, addref, release }

    fn start_mappers<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send,
                     V: Copy Send>(
        map: mapper<K1, K2, V>,
        &ctrls: ~[ctrl_proto::server::open<K2, V>],
        inputs: ~[K1])
        -> ~[joinable_task]
    {
        let mut tasks = ~[];
        for inputs.each |i| {
            let (ctrl, ctrl_server) = ctrl_proto::init();
            let ctrl = box(ctrl);
            let i = copy *i;
            tasks.push(spawn_joinable(|move i| map_task(map, ctrl, i)));
            ctrls.push(ctrl_server);
        }
        return tasks;
    }

    fn map_task<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send, V: Copy Send>(
        map: mapper<K1, K2, V>,
        ctrl: box<ctrl_proto::client::open<K2, V>>,
        input: K1)
    {
        // log(error, "map_task " + input);
        let intermediates = map::HashMap();

        do map(input) |key, val| {
            let mut c = None;
            let found = intermediates.find(key);
            match found {
              Some(_c) => { c = Some(_c); }
              None => {
                do ctrl.swap |ctrl| {
                    let ctrl = ctrl_proto::client::find_reducer(ctrl, key);
                    match pipes::recv(ctrl) {
                      ctrl_proto::reducer(c_, ctrl) => {
                        c = Some(c_);
                        move_out!(ctrl)
                      }
                    }
                }
                intermediates.insert(key, c.get());
                send(c.get(), addref);
              }
            }
            send(c.get(), emit_val(val));
        }

        fn finish<K: Copy Send, V: Copy Send>(_k: K, v: Chan<reduce_proto<V>>)
        {
            send(v, release);
        }
        for intermediates.each_value |v| { send(v, release) }
        ctrl_proto::client::mapper_done(ctrl.unwrap());
    }

    fn reduce_task<K: Copy Send, V: Copy Send>(
        reduce: reducer<K, V>,
        key: K,
        out: Chan<Chan<reduce_proto<V>>>)
    {
        let p = Port();

        send(out, Chan(p));

        let mut ref_count = 0;
        let mut is_done = false;

        fn get<V: Copy Send>(p: Port<reduce_proto<V>>,
                             &ref_count: int, &is_done: bool)
           -> Option<V> {
            while !is_done || ref_count > 0 {
                match recv(p) {
                  emit_val(v) => {
                    // error!("received %d", v);
                    return Some(v);
                  }
                  done => {
                    // error!("all done");
                    is_done = true;
                  }
                  addref => { ref_count += 1; }
                  release => { ref_count -= 1; }
                }
            }
            return None;
        }

        reduce(key, || get(p, ref_count, is_done) );
    }

    fn map_reduce<K1: Copy Send, K2: Hash IterBytes Eq Const Copy Send, V: Copy Send>(
        map: mapper<K1, K2, V>,
        reduce: reducer<K2, V>,
        inputs: ~[K1])
    {
        let mut ctrl = ~[];

        // This task becomes the master control task. It task::_spawns
        // to do the rest.

        let reducers = map::HashMap();
        let mut tasks = start_mappers(map, ctrl, inputs);
        let mut num_mappers = vec::len(inputs) as int;

        while num_mappers > 0 {
            let (_ready, message, ctrls) = pipes::select(ctrl);
            match option::unwrap(message) {
              ctrl_proto::mapper_done => {
                // error!("received mapper terminated.");
                num_mappers -= 1;
                ctrl = ctrls;
              }
              ctrl_proto::find_reducer(k, cc) => {
                let c;
                // log(error, "finding reducer for " + k);
                match reducers.find(k) {
                  Some(_c) => {
                    // log(error,
                    // "reusing existing reducer for " + k);
                    c = _c;
                  }
                  None => {
                    // log(error, "creating new reducer for " + k);
                    let p = Port();
                    let ch = Chan(p);
                    let r = reduce, kk = k;
                    tasks.push(spawn_joinable(|| reduce_task(r, kk, ch) ));
                    c = recv(p);
                    reducers.insert(k, c);
                  }
                }
                ctrl = vec::append_one(
                    ctrls,
                    ctrl_proto::server::reducer(move_out!(cc), c));
              }
            }
        }

        for reducers.each_value |v| { send(v, done) }

        for tasks.each |t| { join(*t); }
    }
}

fn main(++argv: ~[~str]) {
    if vec::len(argv) < 2u && !os::getenv(~"RUST_BENCH").is_some() {
        let out = io::stdout();

        out.write_line(fmt!("Usage: %s <filename> ...", argv[0]));

        return;
    }

    let readers: ~[fn~() -> word_reader]  = if argv.len() >= 2 {
        vec::view(argv, 1u, argv.len()).map(|f| {
            let f = *f;
            fn~() -> word_reader { file_word_reader(f) }
        })
    }
    else {
        let num_readers = 50;
        let words_per_reader = 600;
        vec::from_fn(
            num_readers,
            |_i| fn~() -> word_reader {
                random_word_reader(words_per_reader) as word_reader
            })
    };

    let start = time::precise_time_ns();

    map_reduce::map_reduce(map, reduce, readers);
    let stop = time::precise_time_ns();

    let elapsed = (stop - start) / 1000000u64;

    log(error, ~"MapReduce completed in "
             + u64::str(elapsed) + ~"ms");
}

fn read_word(r: io::Reader) -> Option<~str> {
    let mut w = ~"";

    while !r.eof() {
        let c = r.read_char();

        if is_word_char(c) {
            w += str::from_char(c);
        } else { if w != ~"" { return Some(w); } }
    }
    return None;
}

fn is_word_char(c: char) -> bool {
    char::is_alphabetic(c) || char::is_digit(c) || c == '_'
}

struct random_word_reader {
    mut remaining: uint,
    rng: rand::Rng,
}

impl random_word_reader: word_reader {
    fn read_word() -> Option<~str> {
        if self.remaining > 0 {
            self.remaining -= 1;
            let len = self.rng.gen_uint_range(1, 4);
            Some(self.rng.gen_str(len))
        }
        else { None }
    }
}

fn random_word_reader(count: uint) -> random_word_reader {
    random_word_reader {
        remaining: count,
        rng: rand::Rng()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add first integration test<commit_after>extern crate spaceapi_server;

use std::net::Ipv4Addr;
use std::net::TcpStream;
use std::io::ErrorKind;

use spaceapi_server::SpaceapiServer;
use spaceapi_server::api;
use spaceapi_server::api::optional::Optional;

/// Create a new status object containing test data.
fn get_status() -> api::Status {
    api::Status::new(
        "ourspace",
        "https://example.com/logo.png",
        "https://example.com/",
        api::Location {
            address: Optional::Value("Street 1, Zürich, Switzerland".into()),
            lat: 47.123,
            lon: 8.88,
        },
        api::Contact {
            irc: Optional::Absent,
            twitter: Optional::Absent,
            foursquare: Optional::Absent,
            email: Optional::Value("hi@example.com".into()),
        },
        vec![
            "email".into(),
            "twitter".into(),
        ],
    )
}

/// Create a new SpaceapiServer instance listening on the specified port.
fn get_server(ip: Ipv4Addr, port: u16, status: api::Status) -> SpaceapiServer {
    // Start and return a server instance
    SpaceapiServer::new(ip, port, status, "redis://127.0.0.1/", vec![]).unwrap()
}

#[test]
fn server_starts() {
    //! Test that the spaceapi server starts at all.

    // Ip / port for test server
    let ip = Ipv4Addr::new(127, 0, 0, 1);
    let port = 3344;

    // Test data
    let status = get_status();

    // Connection to port should fail right now
    let connect_result = TcpStream::connect((ip, port));
    assert!(connect_result.is_err());
    assert_eq!(connect_result.unwrap_err().kind(), ErrorKind::ConnectionRefused);

    // Instantiate and start server
    let server = get_server(ip, port, status);
    let mut listening = server.serve().unwrap();

    // Connecting to server should work now
    let connect_result = TcpStream::connect((ip, port));
    assert!(connect_result.is_ok());

    // Close server
    listening.close().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Add new tests directory<commit_after>extern crate sorting;

#[test]
fn it_works() {
    assert_eq!(4, sorting::add_two(2));
}
<|endoftext|>


<commit_before><commit_msg>Add some preparatory code for adding the 'else'-keyword.<commit_after><|endoftext|>


<commit_before><commit_msg>Add mainloop example like a R client.<commit_after>extern crate libr;
use std::env;
use std::ffi::CString;
use libr::ffi::embedded::Rf_initialize_R;
use libr::ffi::interface::*;

fn main() {
    if let Err(_) = env::var("R_HOME") {
        panic!("Rembedded test need R_HOME be setted");
    }
    let mut args = env::args()
                       .map(|arg| CString::new(arg.as_bytes()).unwrap().into_raw())
                       .collect::<Vec<_>>();
    unsafe {
        R_running_as_main_program = 1;
        Rf_initialize_R(args.len() as i32, args.as_mut_ptr());
        Rf_mainloop();
        return;
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a generic conversion utility<commit_after>use std::str;
use std::num::FromStrRadix;
use std::num::ToStrRadix;

static HEX_ARRAY: &'static [u8] = b"0123456789abcdef";

pub fn bytes_to_hex_string(bytes: &[u8]) -> String {
    let mut v = Vec::with_capacity(bytes.len() * 2);

    for &byte in bytes.iter() {
        v.push(HEX_ARRAY[(byte >> 4) as uint]);
        v.push(HEX_ARRAY[(byte & 0xf) as uint]);
    }

    str::from_utf8(v.as_slice()).unwrap().into_string()
}

pub fn hex_string_to_bytes(hex: &str) -> Vec<u8> {
    let mut data = Vec::new();

    for index in range(0, hex.len() / 2).map(|x| x * 2) {
        let value: u8 = FromStrRadix::from_str_radix(hex.slice(index, index + 2), 16).unwrap();
        data.push(value);
    }

    data
}<|endoftext|>


<commit_before><commit_msg>Added OEL Because apparently these are a thing and Kitsu now supports them.<commit_after><|endoftext|>


<commit_before><commit_msg>need 1 to use<commit_after><|endoftext|>