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

//! Slices
//!
//! See `Slice`-structure documentation for more information on this module.

use core::{handle, buffer};
use core::{Primitive, Resources, VertexCount};
use core::command::InstanceParams;
use core::factory::Factory;
use core::memory::Bind;
use format::Format;
use pso;

/// A `Slice` dictates in which and in what order vertices get processed. It is required for
/// processing a PSO.
///
/// # Overview
/// A `Slice` object in essence dictates in what order the vertices in a `VertexBuffer` get
/// processed. To do this, it contains an internal index-buffer. This `Buffer` is a list of
/// indices into this `VertexBuffer` (vertex-index). A vertex-index of 0 represents the first
/// vertex in the `VertexBuffer`, a vertex-index of 1 represents the second, 2 represents the
/// third, and so on. The vertex-indices in the index-buffer are read in order; every vertex-index
/// tells the pipeline which vertex to process next.
///
/// Because the same index can re-appear multiple times, duplicate-vertices can be avoided. For
/// instance, if you want to draw a square, you need two triangles, and thus six vertices. Because
/// the same index can reappear multiple times, this means we can instead use 4 vertices, and 6
/// vertex-indices.
///
/// This index-buffer has a few variants. See the `IndexBuffer` documentation for a detailed
/// description.
///
/// The `start` and `end` fields say where in the index-buffer to start and stop reading.
/// Setting `start` to 0, and `end` to the length of the index-buffer, will cause the entire
/// index-buffer to be processed. The `base_vertex` dictates the index of the first vertex
/// in the `VertexBuffer`. This essentially moves the the start of the `VertexBuffer`, to the
/// vertex with this index.
///
/// # Constuction & Handling
/// The `Slice` structure can be constructed automatically when using a `Factory` to create a
/// vertex buffer. If needed, it can also be created manually.
///
/// A `Slice` is required to process a PSO, as it contains the needed information on in what order
/// to draw which vertices. As such, every `draw` call on an `Encoder` requires a `Slice`.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Slice<R: Resources> {
    /// The start index of the index-buffer. Processing will start at this location in the
    /// index-buffer.
    pub start: VertexCount,
    /// The end index in the index-buffer. Processing will stop at this location (exclusive) in
    /// the index buffer.
    pub end: VertexCount,
    /// This is the index of the first vertex in the `VertexBuffer`. This value will be added to
    /// every index in the index-buffer, effectively moving the start of the `VertexBuffer` to this
    /// base-vertex.
    pub base_vertex: VertexCount,
    /// Instancing configuration.
    pub instances: Option<InstanceParams>,
    /// Represents the type of index-buffer used.
    pub buffer: IndexBuffer<R>,
}

impl<R: Resources> Slice<R> {
    /// Creates a new `Slice` to match the supplied vertex buffer, from start to end, in order.
    pub fn new_match_vertex_buffer<V>(vbuf: &handle::Buffer<R, V>) -> Self
                                      where V: pso::buffer::Structure<Format> {
        Slice {
            start: 0,
            end: vbuf.len() as u32,
            base_vertex: 0,
            instances: None,
            buffer: IndexBuffer::Auto,
        }
    }

    /// Calculates the number of primitives of the specified type in this `Slice`.
    pub fn get_prim_count(&self, prim: Primitive) -> u32 {
        use core::Primitive as p;
        let nv = (self.end - self.start) as u32;
        match prim {
            p::PointList => nv,
            p::LineList => nv / 2,
            p::LineStrip => (nv-1),
            p::TriangleList => nv / 3,
            p::TriangleStrip => (nv-2) / 3,
            p::LineListAdjacency => nv / 4,
            p::LineStripAdjacency => (nv-3),
            p::TriangleListAdjacency => nv / 6,
            p::TriangleStripAdjacency => (nv-4) / 2,
            p::PatchList(num) => nv / (num as u32),
        }
    }

    /// Divides one slice into two at an index.
    ///
    /// The first will contain the range in the index-buffer [self.start, mid) (excluding the index mid itself) and the
    /// second will contain the range [mid, self.end).
    pub fn split_at(&self, mid: VertexCount) -> (Self, Self) {
        let mut first = self.clone();
        let mut second = self.clone();
        first.end = mid;
        second.start = mid;

        (first, second)
    }
}

/// Type of index-buffer used in a Slice.
///
/// The `Auto` variant represents a hypothetical index-buffer from 0 to infinity. In other words,
/// all vertices get processed in order. Do note that the `Slice`' `start` and `end` restrictions
/// still apply for this variant. To render every vertex in the `VertexBuffer`, you would set
/// `start` to 0, and `end` to the `VertexBuffer`'s length.
///
/// The `Index*` variants represent an actual `Buffer` with a list of vertex-indices. The numeric
/// suffix specifies the amount of bits to use per index. Each of these also contains a
/// base-vertex. This is the index of the first vertex in the `VertexBuffer`. This value will be
/// added to every index in the index-buffer, effectively moving the start of the `VertexBuffer` to
/// this base-vertex.
///
/// # Construction & Handling
/// A `IndexBuffer` can be constructed using the `IntoIndexBuffer` trait, from either a slice or a
/// `Buffer` of integers, using a factory.
///
/// An `IndexBuffer` is exclusively used to create `Slice`s.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum IndexBuffer<R: Resources> {
    /// Represents a hypothetical index-buffer from 0 to infinity. In other words, all vertices
    /// get processed in order.
    Auto,
    /// An index-buffer with unsigned 16 bit indices.
    Index16(handle::Buffer<R, u16>),
    /// An index-buffer with unsigned 32 bit indices.
    Index32(handle::Buffer<R, u32>),
}

impl<R: Resources> Default for IndexBuffer<R> {
    fn default() -> Self {
        IndexBuffer::Auto
    }
}
/// A helper trait to create `IndexBuffers` from different kinds of data.
pub trait IntoIndexBuffer<R: Resources> {
    /// Turns self into an `IndexBuffer`.
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, factory: &mut F) -> IndexBuffer<R>;
}

impl<R: Resources> IntoIndexBuffer<R> for IndexBuffer<R> {
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
        self
    }
}

impl<R: Resources> IntoIndexBuffer<R> for () {
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
        IndexBuffer::Auto
    }
}

macro_rules! impl_index_buffer {
    ($prim_ty:ty, $buf_ty:ident) => (
        impl<R: Resources> IntoIndexBuffer<R> for handle::Buffer<R, $prim_ty> {
            fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
                IndexBuffer::$buf_ty(self)
            }
        }

        impl<'s, R: Resources> IntoIndexBuffer<R> for &'s [$prim_ty] {
            fn into_index_buffer<F: Factory<R> + ?Sized>(self, factory: &mut F) -> IndexBuffer<R> {
                factory.create_buffer_immutable(self, buffer::Role::Index, Bind::empty())
                       .unwrap()
                       .into_index_buffer(factory)
            }
        }
    )
}

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

//! Slices
//!
//! See `Slice`-structure documentation for more information on this module.

use core::{handle, buffer};
use core::{Primitive, Resources, VertexCount};
use core::command::InstanceParams;
use core::factory::Factory;
use core::memory::Bind;
use format::Format;
use pso;

/// A `Slice` dictates in which and in what order vertices get processed. It is required for
/// processing a PSO.
///
/// # Overview
/// A `Slice` object in essence dictates in what order the vertices in a `VertexBuffer` get
/// processed. To do this, it contains an internal index-buffer. This `Buffer` is a list of
/// indices into this `VertexBuffer` (vertex-index). A vertex-index of 0 represents the first
/// vertex in the `VertexBuffer`, a vertex-index of 1 represents the second, 2 represents the
/// third, and so on. The vertex-indices in the index-buffer are read in order; every vertex-index
/// tells the pipeline which vertex to process next.
///
/// Because the same index can re-appear multiple times, duplicate-vertices can be avoided. For
/// instance, if you want to draw a square, you need two triangles, and thus six vertices. Because
/// the same index can reappear multiple times, this means we can instead use 4 vertices, and 6
/// vertex-indices.
///
/// This index-buffer has a few variants. See the `IndexBuffer` documentation for a detailed
/// description.
///
/// The `start` and `end` fields say where in the index-buffer to start and stop reading.
/// Setting `start` to 0, and `end` to the length of the index-buffer, will cause the entire
/// index-buffer to be processed. The `base_vertex` dictates the index of the first vertex
/// in the `VertexBuffer`. This essentially moves the the start of the `VertexBuffer`, to the
/// vertex with this index.
///
/// # Constuction & Handling
/// The `Slice` structure can be constructed automatically when using a `Factory` to create a
/// vertex buffer. If needed, it can also be created manually.
///
/// A `Slice` is required to process a PSO, as it contains the needed information on in what order
/// to draw which vertices. As such, every `draw` call on an `Encoder` requires a `Slice`.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Slice<R: Resources> {
    /// The start index of the index-buffer. Processing will start at this location in the
    /// index-buffer.
    pub start: VertexCount,
    /// The end index in the index-buffer. Processing will stop at this location (exclusive) in
    /// the index buffer.
    pub end: VertexCount,
    /// This is the index of the first vertex in the `VertexBuffer`. This value will be added to
    /// every index in the index-buffer, effectively moving the start of the `VertexBuffer` to this
    /// base-vertex.
    pub base_vertex: VertexCount,
    /// Instancing configuration.
    pub instances: Option<InstanceParams>,
    /// Represents the type of index-buffer used.
    pub buffer: IndexBuffer<R>,
}

impl<R: Resources> Slice<R> {
    /// Creates a new `Slice` to match the supplied vertex buffer, from start to end, in order.
    pub fn new_match_vertex_buffer<V>(vbuf: &handle::Buffer<R, V>) -> Self
                                      where V: pso::buffer::Structure<Format> {
        Slice {
            start: 0,
            end: vbuf.len() as u32,
            base_vertex: 0,
            instances: None,
            buffer: IndexBuffer::Auto,
        }
    }

    /// Calculates the number of primitives of the specified type in this `Slice`.
    pub fn get_prim_count(&self, prim: Primitive) -> u32 {
        use core::Primitive as p;
        let nv = (self.end - self.start) as u32;
        match prim {
            p::PointList => nv,
            p::LineList => nv / 2,
            p::LineStrip => (nv-1),
            p::TriangleList => nv / 3,
            p::TriangleStrip => (nv-2) / 3,
            p::LineListAdjacency => nv / 4,
            p::LineStripAdjacency => (nv-3),
            p::TriangleListAdjacency => nv / 6,
            p::TriangleStripAdjacency => (nv-4) / 2,
            p::PatchList(num) => nv / (num as u32),
        }
    }

    /// Divides one slice into two at an index.
    ///
    /// The first will contain the range in the index-buffer [self.start, mid) (excluding the index mid itself) and the
    /// second will contain the range [mid, self.end).
    pub fn split_at(&self, mid: VertexCount) -> (Self, Self) {
        let mut first = self.clone();
        let mut second = self.clone();
        first.end = mid;
        second.start = mid;

        (first, second)
    }
}

/// Type of index-buffer used in a Slice.
///
/// The `Auto` variant represents a hypothetical index-buffer from 0 to infinity. In other words,
/// all vertices get processed in order. Do note that the `Slice`'s `start` and `end` restrictions
/// still apply for this variant. To render every vertex in the `VertexBuffer`, you would set
/// `start` to 0, and `end` to the `VertexBuffer`'s length.
///
/// The `Index*` variants represent an actual `Buffer` with a list of vertex-indices. The numeric
/// suffix specifies the amount of bits to use per index. Each of these also contains a
/// base-vertex. This is the index of the first vertex in the `VertexBuffer`. This value will be
/// added to every index in the index-buffer, effectively moving the start of the `VertexBuffer` to
/// this base-vertex.
///
/// # Construction & Handling
/// A `IndexBuffer` can be constructed using the `IntoIndexBuffer` trait, from either a slice or a
/// `Buffer` of integers, using a factory.
///
/// An `IndexBuffer` is exclusively used to create `Slice`s.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum IndexBuffer<R: Resources> {
    /// Represents a hypothetical index-buffer from 0 to infinity. In other words, all vertices
    /// get processed in order.
    Auto,
    /// An index-buffer with unsigned 16 bit indices.
    Index16(handle::Buffer<R, u16>),
    /// An index-buffer with unsigned 32 bit indices.
    Index32(handle::Buffer<R, u32>),
}

impl<R: Resources> Default for IndexBuffer<R> {
    fn default() -> Self {
        IndexBuffer::Auto
    }
}
/// A helper trait to create `IndexBuffers` from different kinds of data.
pub trait IntoIndexBuffer<R: Resources> {
    /// Turns self into an `IndexBuffer`.
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, factory: &mut F) -> IndexBuffer<R>;
}

impl<R: Resources> IntoIndexBuffer<R> for IndexBuffer<R> {
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
        self
    }
}

impl<R: Resources> IntoIndexBuffer<R> for () {
    fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
        IndexBuffer::Auto
    }
}

macro_rules! impl_index_buffer {
    ($prim_ty:ty, $buf_ty:ident) => (
        impl<R: Resources> IntoIndexBuffer<R> for handle::Buffer<R, $prim_ty> {
            fn into_index_buffer<F: Factory<R> + ?Sized>(self, _: &mut F) -> IndexBuffer<R> {
                IndexBuffer::$buf_ty(self)
            }
        }

        impl<'s, R: Resources> IntoIndexBuffer<R> for &'s [$prim_ty] {
            fn into_index_buffer<F: Factory<R> + ?Sized>(self, factory: &mut F) -> IndexBuffer<R> {
                factory.create_buffer_immutable(self, buffer::Role::Index, Bind::empty())
                       .unwrap()
                       .into_index_buffer(factory)
            }
        }
    )
}

impl_index_buffer!(u16, Index16);
impl_index_buffer!(u32, Index32);
<|endoftext|>


<commit_before>use super::*;
use redox::*;

impl Editor {
    pub fn exec(&mut self, Inst(n, cmd): Inst) {
        use super::Mode::*;
        use super::PrimitiveMode::*;
        use super::CommandMode::*;
        match self.cursor().mode {
            Command(Normal) => match cmd {
                'i' => {
                    self.cursor_mut().mode = Mode::Primitive(PrimitiveMode::Insert(
                        InsertOptions {
                            mode: InsertMode::Insert,
                        }));

                },
                'h' => self.left(n as usize),
                'j' => self.down(n as usize),
                'k' => self.up(n as usize),
                'l' => self.right(n as usize),
                'J' => self.down(15),
                'K' => self.up(15),
                'x' => self.delete(),
                'X' => {
                    self.previous();
                    self.delete();
                },
                '$' => self.cursor_mut().x = self.text[self.y()].len(),
                '0' => self.cursor_mut().x = 0,
                ' ' => self.next(),
                _ => {},
            },
            Primitive(Insert(_)) => {
                self.insert(cmd);
            },
        }
    }
}
<commit_msg>Add r command<commit_after>use super::*;
use redox::*;

impl Editor {
    pub fn exec(&mut self, Inst(n, cmd): Inst) {
        use super::Mode::*;
        use super::PrimitiveMode::*;
        use super::CommandMode::*;
        match self.cursor().mode {
            Command(Normal) => match cmd {
                'i' => {
                    self.cursor_mut().mode = Mode::Primitive(PrimitiveMode::Insert(
                        InsertOptions {
                            mode: InsertMode::Insert,
                        }));

                },
                'h' => self.left(n as usize),
                'j' => self.down(n as usize),
                'k' => self.up(n as usize),
                'l' => self.right(n as usize),
                'J' => self.down(15),
                'K' => self.up(15),
                'x' => self.delete(),
                'X' => {
                    self.previous();
                    self.delete();
                },
                '$' => self.cursor_mut().x = self.text[self.y()].len(),
                '0' => self.cursor_mut().x = 0,
                'r' => {
                    if let EventOption::Key(k) = self.window.poll()
                                                 .unwrap_or(Event::new())
                                                 .to_option() {
                        let x = self.x();
                        let y = self.y();
                        self.text[y][x] = k.character;
                    }
                },
                ' ' => self.next(),
                _ => {},
            },
            Primitive(Insert(_)) => {
                self.insert(cmd);
            },
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Added mod super example<commit_after>fn function() {
    println!("called `function()`");
}

mod my {
    pub fn indirect_call() {
        // Let's access all the functions named `function` from this scope
        print!("called `my::indirect_call()`, that\n> ");

        // `my::function` can be called directly
        function();

        {
            // This will bind to the `cool::function` in the *crate* scope
            // In this case the crate scope is the outermost scope
            use cool::function as root_cool_function;

            print!("> ");
            root_cool_function();
        }

        {
            // `self` refers to the current module scope, in this case: `my`
            use self::cool::function as my_cool_function;

            print!("> ");
            my_cool_function();
        }

        {
            // `super` refers to the parent scope, i.e. outside of the `my`
            // module
            use super::function as root_function;

            print!("> ");
            root_function();
        }
    }

    fn function() {
        println!("called `my::function()`");
    }

    mod cool {
        pub fn function() {
            println!("called `my::cool::function()`");
        }
    }
}

mod cool {
    pub fn function() {
        println!("called `cool::function()`");
    }
}

fn main() {
    my::indirect_call();
}
<|endoftext|>


<commit_before><commit_msg>Fix serverbound chat message field type and uncomment that packet<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: 'start-time' cannot be None<commit_after><|endoftext|>


<commit_before><commit_msg>Add Packet::write method<commit_after><|endoftext|>


<commit_before><commit_msg>Add utility functions for determine the type of a dbpage<commit_after><|endoftext|>


<commit_before><commit_msg>Use Vec as the container for database page, and use BufReader to read header<commit_after><|endoftext|>


<commit_before><commit_msg>Remove DeviceRef in favor of a pointer.<commit_after><|endoftext|>


<commit_before><commit_msg>[Rust] HowMuch (CodeWars)<commit_after>fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
    if m > n {
        std::mem::swap(&mut m, &mut n);
    }

    let mut result: Vec<(String, String, String)> = Vec::new();
    let mut c: f32;
    let mut b: f32;

    for i in m..n+1 {
        c = (i as f32-1f32)/9f32;
        b = (i as f32-2f32)/7f32;
        if c < 0f32 || b < 0f32 {
           continue;
        }
        if c.fract() == 0f32 && b.fract() == 0f32 {
            let r_tuple = (format!("M: {}", i),
                           format!("B: {}", b as i32),
                           format!("C: {}", c as i32));

            result.push(r_tuple);
        }
    }

    return result;
}

fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> () {
    let ans: String = format!("{:?}", how_much(m, n));
    let sol: String = format!("{:?}", exp);
    assert_eq!(ans, sol)
}
fn tests() {
    testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]);
    testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]);
    testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]);
    testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]);
    testing(2950, 2950, vec![]);
}

fn main() {
    tests();
}
<|endoftext|>


<commit_before><commit_msg>Fix a doctest and explain a particular weird quoting rule.<commit_after><|endoftext|>


<commit_before>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
								 (rand() % 300 + 50) as isize,
								 576,
								 400,
								 &"Sodium").unwrap();

    let mut editor = Editor::new();

    let mut inp = window.event_iter().map(|x| {
        x.to_option()
    }).inst_iter(&editor.cursor().mode);

    for i in inp {
        editor.exec(i, &mut inp);
    }
    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<commit_msg>Convert tabs to spaces and remove some tailing spaces<commit_after>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
                                 (rand() % 300 + 50) as isize,
                                 576,
                                 400,
                                 &"Sodium").unwrap();

    let mut editor = Editor::new();

    let mut inp = window.event_iter().map(|x| {
        x.to_option()
    }).inst_iter(&editor.cursor().mode);

    for i in inp {
        editor.exec(i, &mut inp);
    }
    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<|endoftext|>


<commit_before>//! Game window operations.

use input::InputEvent;

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Returns true if the window should close.
    fn should_close(&self) -> bool;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the window's size
    fn get_size(&self) -> (u32, u32) {
        let settings = self.get_settings();
        (settings.size[0], settings.size[1])
    }

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32) {
        self.get_size()
    }

    /// Swap buffers.
    fn swap_buffers(&self) {}

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool) {}

    /// Poll a event from window's event queue.
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

/// An implementation of GameWindow that represents running without a window at all
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Create a new nonexistant game window
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl Window for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn should_close(&self) -> bool {
        self.should_close
    }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_size(&self) -> (u32, u32) {
        (0, 0)
    }
}
<commit_msg>Move Window.get_size into implementations<commit_after>//! Game window operations.

use input::InputEvent;

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Returns true if the window should close.
    fn should_close(&self) -> bool;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the window's size
    fn get_size(&self) -> (u32, u32);

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32) {
        self.get_size()
    }

    /// Swap buffers.
    fn swap_buffers(&self) {}

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool) {}

    /// Poll a event from window's event queue.
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

/// An implementation of GameWindow that represents running without a window at all
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Create a new nonexistant game window
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl Window for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn should_close(&self) -> bool {
        self.should_close
    }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_size(&self) -> (u32, u32) {
        (0, 0)
    }
}
<|endoftext|>


<commit_before><commit_msg>begin mod worker<commit_after>//
// Copyright (c) 2016, Boris Popov <popov@whitekefir.ru>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

extern crate libc;
use self::libc::sleep;

pub fn main() {
    //
    //TODO work
    //
    unsafe {
        sleep(15);
    }
}
//mod program;
//use program::{NAME, VERSION};

//mod logger;
//use logger::{Logger};

//use forker::hello;
//use forker::hello;
//use libc;
//use libc::fork;
//use libc::exit;

    //let logger = logger::Logger{name: NAME, version: VERSION};
    //logger.start();
    //let logger = Logger::new(NAME, VERSION);
    //let logger = Logger::new(NAME, VERSION);

    //println!("{}", NAME);
    //let pi = program::Info{name: NAME, version: VERSION};
    //pi.init();
    //println!("{}", pi.name());
    //println!("{}", pi.version());
    /*
    println!("Hello, world!");
    hello();

    let x: i32;
    unsafe {
        x = libc::fork();
    }

    if x == 0 {
        unsafe {
            libc::sleep(10);
            libc::exit(2);
        }
    }
    //
    unsafe {
        sleep(5);
    }

    //pub unsafe extern fn fork() -> pid_t
    println!("Exit!");
    */
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ensures that public symbols are not removed completely
#![crate_type = "lib"]
// we can compile to a variety of platforms, because we don't need
// cross-compiled standard libraries.
#![feature(no_core)]
#![no_core]

#![feature(repr_simd, simd_ffi, link_llvm_intrinsics, lang_items)]

#[repr(C)]
#[derive(Copy)]
#[repr(simd)]
pub struct f32x4(f32, f32, f32, f32);

extern {
    #[link_name = "llvm.sqrt.v4f32"]
    fn vsqrt(x: f32x4) -> f32x4;
}

pub fn foo(x: f32x4) -> f32x4 {
    unsafe {vsqrt(x)}
}

#[repr(C)]
#[derive(Copy)]
#[repr(simd)]
pub struct i32x4(i32, i32, i32, i32);

extern {
    // _mm_sll_epi32
    #[cfg(any(target_arch = "x86",
              target_arch = "x86-64"))]
    #[link_name = "llvm.x86.sse2.psll.d"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;

    // vmaxq_s32
    #[cfg(any(target_arch = "arm"))]
    #[link_name = "llvm.arm.neon.vmaxs.v4i32"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;
    // vmaxq_s32
    #[cfg(any(target_arch = "aarch64"))]
    #[link_name = "llvm.aarch64.neon.maxs.v4i32"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;

    // just some substitute foreign symbol, not an LLVM intrinsic; so
    // we still get type checking, but not as detailed as (ab)using
    // LLVM.
    #[cfg(not(any(target_arch = "x86",
                  target_arch = "x86-64",
                  target_arch = "arm",
                  target_arch = "aarch64")))]
    fn integer(a: i32x4, b: i32x4) -> i32x4;
}

pub fn bar(a: i32x4, b: i32x4) -> i32x4 {
    unsafe {integer(a, b)}
}

#[lang = "sized"]
pub trait Sized { }

#[lang = "copy"]
pub trait Copy { }

pub mod marker {
    pub use Copy;
}
<commit_msg>Auto merge of #30547 - mmcco:cfg, r=sanxiyn<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ensures that public symbols are not removed completely
#![crate_type = "lib"]
// we can compile to a variety of platforms, because we don't need
// cross-compiled standard libraries.
#![feature(no_core)]
#![no_core]

#![feature(repr_simd, simd_ffi, link_llvm_intrinsics, lang_items)]

#[repr(C)]
#[derive(Copy)]
#[repr(simd)]
pub struct f32x4(f32, f32, f32, f32);

extern {
    #[link_name = "llvm.sqrt.v4f32"]
    fn vsqrt(x: f32x4) -> f32x4;
}

pub fn foo(x: f32x4) -> f32x4 {
    unsafe {vsqrt(x)}
}

#[repr(C)]
#[derive(Copy)]
#[repr(simd)]
pub struct i32x4(i32, i32, i32, i32);

extern {
    // _mm_sll_epi32
    #[cfg(any(target_arch = "x86",
              target_arch = "x86-64"))]
    #[link_name = "llvm.x86.sse2.psll.d"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;

    // vmaxq_s32
    #[cfg(target_arch = "arm")]
    #[link_name = "llvm.arm.neon.vmaxs.v4i32"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;
    // vmaxq_s32
    #[cfg(target_arch = "aarch64")]
    #[link_name = "llvm.aarch64.neon.maxs.v4i32"]
    fn integer(a: i32x4, b: i32x4) -> i32x4;

    // just some substitute foreign symbol, not an LLVM intrinsic; so
    // we still get type checking, but not as detailed as (ab)using
    // LLVM.
    #[cfg(not(any(target_arch = "x86",
                  target_arch = "x86-64",
                  target_arch = "arm",
                  target_arch = "aarch64")))]
    fn integer(a: i32x4, b: i32x4) -> i32x4;
}

pub fn bar(a: i32x4, b: i32x4) -> i32x4 {
    unsafe {integer(a, b)}
}

#[lang = "sized"]
pub trait Sized { }

#[lang = "copy"]
pub trait Copy { }

pub mod marker {
    pub use Copy;
}
<|endoftext|>


<commit_before><commit_msg>Add a test that native mods don't need to declare an ABI<commit_after>// ABI is cdecl by default

native mod rustrt {
    fn unsupervise();
}

fn main() {
    rustrt::unsupervise();
}<|endoftext|>


<commit_before>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Issue #52129: ICE when trying to document the `quote` proc-macro from proc_macro

// As of this writing, we don't currently attempt to document proc-macros. However, we shouldn't
// crash when we try.

extern crate proc_macro;

pub use proc_macro::*;
<commit_msg>ignore rustdoc/doc-proc-macro on stage1<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-stage1

// Issue #52129: ICE when trying to document the `quote` proc-macro from proc_macro

// As of this writing, we don't currently attempt to document proc-macros. However, we shouldn't
// crash when we try.

extern crate proc_macro;

pub use proc_macro::*;
<|endoftext|>


<commit_before><commit_msg>More formatting tweaks<commit_after><|endoftext|>


<commit_before><commit_msg>chore: #[allow(unused_variables)]<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #17746<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Regression test for #17746

fn main() {}

struct A;

impl A {
    fn b(&mut self) {
        self.a()
    }
}

trait Foo {
    fn dummy(&self) {}
}
trait Bar {
    fn a(&self);
}

impl Foo for A {}
impl<T> Bar for T where T: Foo {
    fn a(&self) {}
}
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[derive(Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Array<T> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

// FIXME(#7622): merge with `Array` once `[T; N]: Clone` where `T: Clone`
#[derive(Clone, Copy)]
struct CopyArray<T: Copy> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Fn<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: fn(),
    f01: fn(A),
    f02: fn(A, B),
    f03: fn(A, B, C),
    f04: fn(A, B, C, D),
    f05: fn(A, B, C, D, E),
    f06: fn(A, B, C, D, E, F),
    f07: fn(A, B, C, D, E, F, G),
    f08: fn(A, B, C, D, E, F, G, H),
    f09: fn(A, B, C, D, E, F, G, H, I),
    f10: fn(A, B, C, D, E, F, G, H, I, J),
    f11: fn(A, B, C, D, E, F, G, H, I, J, K),
    f12: fn(A, B, C, D, E, F, G, H, I, J, K, L),
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Tuple<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: (),
    f01: (A),
    f02: (A, B),
    f03: (A, B, C),
    f04: (A, B, C, D),
    f05: (A, B, C, D, E),
    f06: (A, B, C, D, E, F),
    f07: (A, B, C, D, E, F, G),
    f08: (A, B, C, D, E, F, G, H),
    f09: (A, B, C, D, E, F, G, H, I),
    f10: (A, B, C, D, E, F, G, H, I, J),
    f11: (A, B, C, D, E, F, G, H, I, J, K),
    f12: (A, B, C, D, E, F, G, H, I, J, K, L),
}

fn main() {}
<commit_msg>update FIXME(#7622) to point to issue 44580 (tracking issue for const generics)<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[derive(Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Array<T> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

// FIXME(#44580): merge with `Array` once `[T; N]: Clone` where `T: Clone`
#[derive(Clone, Copy)]
struct CopyArray<T: Copy> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Fn<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: fn(),
    f01: fn(A),
    f02: fn(A, B),
    f03: fn(A, B, C),
    f04: fn(A, B, C, D),
    f05: fn(A, B, C, D, E),
    f06: fn(A, B, C, D, E, F),
    f07: fn(A, B, C, D, E, F, G),
    f08: fn(A, B, C, D, E, F, G, H),
    f09: fn(A, B, C, D, E, F, G, H, I),
    f10: fn(A, B, C, D, E, F, G, H, I, J),
    f11: fn(A, B, C, D, E, F, G, H, I, J, K),
    f12: fn(A, B, C, D, E, F, G, H, I, J, K, L),
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Tuple<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: (),
    f01: (A),
    f02: (A, B),
    f03: (A, B, C),
    f04: (A, B, C, D),
    f05: (A, B, C, D, E),
    f06: (A, B, C, D, E, F),
    f07: (A, B, C, D, E, F, G),
    f08: (A, B, C, D, E, F, G, H),
    f09: (A, B, C, D, E, F, G, H, I),
    f10: (A, B, C, D, E, F, G, H, I, J),
    f11: (A, B, C, D, E, F, G, H, I, J, K),
    f12: (A, B, C, D, E, F, G, H, I, J, K, L),
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test case for #30276<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct Test([i32]);
fn main() {
    let _x: fn(_) -> Test = Test;
}
<|endoftext|>


<commit_before><commit_msg>Fix match same arms bug found by clippy<commit_after><|endoftext|>


<commit_before><commit_msg>Add Day 21 solution<commit_after>// advent21.rs
// RPG

#[macro_use] extern crate scan_fmt;

use std::io;
use std::cmp::max;

fn main() {
    let mut input = String::new();
    let mut boss = Stats {hit_points: 0, damage: 0, armor: 0};

    io::stdin().read_line(&mut input).ok().expect("Failed to read line");
    let hit_points = scan_fmt!(&input, "Hit Points: {}", i32);
    boss.hit_points = hit_points.unwrap();

    input.clear();
    io::stdin().read_line(&mut input).ok().expect("Failed to read line");
    let damage = scan_fmt!(&input, "Damage: {}", i32);
    boss.damage = damage.unwrap();

    input.clear();
    io::stdin().read_line(&mut input).ok().expect("Failed to read line");
    let armor = scan_fmt!(&input, "Armor: {}", i32);
    boss.armor = armor.unwrap();

    let cost = find_least_gold(&boss);
    println!("Least gold needed: {}", cost);

    let cost2 = find_most_gold(&boss);
    println!("Most gold needed: {}", cost2);

}

struct Stats {
    hit_points: i32,
    damage: i32,
    armor: i32,
}

fn does_player_win(player: &Stats, boss: &Stats) -> bool {
    let mut player_hp = player.hit_points;
    let mut boss_hp = boss.hit_points;

    let player_damage = max(1, player.damage - boss.armor);
    let boss_damage = max(1, boss.damage - player.armor);

    loop {
        if player_hp <= 0 {
            return false;
        }
        boss_hp -= player_damage;

        if boss_hp <= 0 {
            return true;
        }

        player_hp -= boss_damage;
    }
}

#[derive(Clone)]
struct Item {
    cost: i32,
    damage: i32,
    armor: i32,
}

fn add_items(item1: &Item, item2: &Item) -> Item {
    Item {
        cost: item1.cost + item2.cost,
        damage: item1.damage + item2.damage,
        armor: item1.armor + item2.armor,
    }
}

fn find_item_combinations() -> Vec<Item> {
    let weapons = vec![
        Item {cost: 8, damage: 4, armor: 0},
        Item {cost: 10, damage: 5, armor: 0},
        Item {cost: 25, damage: 6, armor: 0},
        Item {cost: 40, damage: 7, armor: 0},
        Item {cost: 74, damage: 8, armor: 0},
        ];
    let armors = vec![
        Item {cost: 13, damage: 0, armor: 1},
        Item {cost: 31, damage: 0, armor: 2},
        Item {cost: 53, damage: 0, armor: 3},
        Item {cost: 75, damage: 0, armor: 4},
        Item {cost: 102, damage: 0, armor: 5},
        ];
    let rings = vec![
        Item {cost: 25, damage: 1, armor: 0},
        Item {cost: 50, damage: 2, armor: 0},
        Item {cost: 100, damage: 3, armor: 0},
        Item {cost: 20, damage: 0, armor: 1},
        Item {cost: 40, damage: 0, armor: 2},
        Item {cost: 80, damage: 0, armor: 3},
        ];

    let mut combos = Vec::new();

    // exactly 1 weapon
    // 0 or 1 armor
    // 0 - 2 rings
    for w in &weapons {
        // 0 armor, 0 rings
        combos.push(w.clone());

        // 0 armor, 0 - 2 rings
        enumerate_rings(&mut combos, &rings, &w);

        // 1 armor, 0 - 2 rings
        for a in &armors {
            let base = add_items(&w, &a);
            enumerate_rings(&mut combos, &rings, &base);
        }
    }

    combos
}

fn stats_from_items(item_total: &Item) -> Stats {
    Stats {hit_points: 100, damage: item_total.damage, armor: item_total.armor}
}

// Find least gold needed to defeat a given boss
fn find_least_gold(boss: &Stats) -> i32 {
    let combos = find_item_combinations();

    combos.iter()
        .filter(|combo| does_player_win(&stats_from_items(&combo), boss))
        .map(|combo| combo.cost)
        .min().unwrap()
}

fn enumerate_rings(combos: &mut Vec<Item>, rings: &[Item], base: &Item) {
    // 0 - 2 rings
    for bit_mask in 0..(1 << rings.len()) {
        if count_bits(bit_mask) <= 2 {
            let ring_sum = rings.iter().enumerate()
                .filter(|&(i, _)| bit_mask & (1 << i) != 0)
                .fold(base.clone(), |acc, (_, r)| add_items(&acc, r));
            combos.push(ring_sum);
        }
    }
}

// copied from Day 17
fn count_bits(x: u32) -> u32 {
    let mut total = 0;
    let mut val = x;

    while val > 0 {
        if (val & 1) != 0 {
            total += 1;
        }
        val >>= 1;
    }

    total
}

#[test]
fn test_does_player_win() {
    let player = Stats{hit_points: 8, damage: 5, armor: 5};
    let boss = Stats{hit_points: 12, damage: 7, armor: 2};
    let boss2 = Stats{hit_points: 12, damage: 7, armor: 3};

    assert!(does_player_win(&player, &boss));
    assert!(!does_player_win(&player, &boss2));
}

// part 2

// Find most gold you can spend and still lose to a given boss
fn find_most_gold(boss: &Stats) -> i32 {
    let combos = find_item_combinations();

    combos.iter()
        .filter(|combo| !does_player_win(&stats_from_items(&combo), boss))
        .map(|combo| combo.cost)
        .max().unwrap()
}

<|endoftext|>


<commit_before><commit_msg>Remove log<commit_after><|endoftext|>


<commit_before><commit_msg>add a self-test that actually inspects a mount<commit_after>//! Test that this very testfile is accessible in our own mount.

#![feature(path)]
#![feature(path_ext)]

extern crate gitfs;

use std::fs::PathExt;
use std::path::Path;

#[test]
fn mounted_test_exists() {
    let git_dir = Path::new(".git");
    let mount = git_dir.join("fs");
    let file = mount.join("HEAD").join(file!());

    // NB: If this isn't a git checkout, we'll fail here, sorry!
    let fs = gitfs::GitFS::new(&git_dir).unwrap();

    assert!(!file.exists(), "{:?} shouldn't exist before mounting!", file);

    let session = fs.spawn_mount(&mount).unwrap();

    assert!(file.exists(), "{:?} should exist in the mount!", file);

    drop(session);

    assert!(!file.exists(), "{:?} shouldn't exist after unmounting!", file);
}
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(warnings)]

extern crate build_helper;
extern crate gcc;

use std::env;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if cfg!(feature = "backtrace") && !target.contains("apple") && !target.contains("msvc") &&
        !target.contains("emscripten") && !target.contains("fuchsia") && !target.contains("redox") {
        let _ = build_libbacktrace(&host, &target);
    }

    if target.contains("linux") {
        if target.contains("android") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=log");
            println!("cargo:rustc-link-lib=gcc");
        } else if !target.contains("musl") || target.contains("mips") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=rt");
            println!("cargo:rustc-link-lib=pthread");
        }
    } else if target.contains("freebsd") {
        println!("cargo:rustc-link-lib=execinfo");
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("dragonfly") || target.contains("bitrig") ||
              target.contains("netbsd") || target.contains("openbsd") {
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("solaris") {
        println!("cargo:rustc-link-lib=socket");
        println!("cargo:rustc-link-lib=posix4");
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("apple-darwin") {
        println!("cargo:rustc-link-lib=System");

        // res_init and friends require -lresolv on macOS/iOS.
        // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-ios") {
        println!("cargo:rustc-link-lib=System");
        println!("cargo:rustc-link-lib=objc");
        println!("cargo:rustc-link-lib=framework=Security");
        println!("cargo:rustc-link-lib=framework=Foundation");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("windows") {
        println!("cargo:rustc-link-lib=advapi32");
        println!("cargo:rustc-link-lib=ws2_32");
        println!("cargo:rustc-link-lib=userenv");
        println!("cargo:rustc-link-lib=shell32");
    } else if target.contains("fuchsia") {
        // use system-provided libbacktrace
        if cfg!(feature = "backtrace") {
            println!("cargo:rustc-link-lib=backtrace");
        }
        println!("cargo:rustc-link-lib=magenta");
        println!("cargo:rustc-link-lib=mxio");
        println!("cargo:rustc-link-lib=launchpad"); // for std::process
    }
}

fn build_libbacktrace(host: &str, target: &str) -> Result<(), ()> {
    let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", ".libs")?;

    let compiler = gcc::Config::new().get_compiler();
    // only msvc returns None for ar so unwrap is okay
    let ar = build_helper::cc2ar(compiler.path(), target).unwrap();
    let mut cflags = compiler.args().iter().map(|s| s.to_str().unwrap())
                             .collect::<Vec<_>>().join(" ");
    cflags.push_str(" -fvisibility=hidden");
    run(Command::new("sh")
                .current_dir(&native.out_dir)
                .arg(native.src_dir.join("configure").to_str().unwrap()
                                   .replace("C:\\", "/c/")
                                   .replace("\\", "/"))
                .arg("--with-pic")
                .arg("--disable-multilib")
                .arg("--disable-shared")
                .arg("--disable-host-shared")
                .arg(format!("--host={}", build_helper::gnu_target(target)))
                .arg(format!("--build={}", build_helper::gnu_target(host)))
                .env("CC", compiler.path())
                .env("AR", &ar)
                .env("RANLIB", format!("{} s", ar.display()))
                .env("CFLAGS", cflags));

    run(Command::new(build_helper::make(host))
                .current_dir(&native.out_dir)
                .arg(format!("INCDIR={}", native.src_dir.display()))
                .arg("-j").arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set")));
    Ok(())
}
<commit_msg>DNS functions are in libresolv on Solaris, just like on MacOS<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(warnings)]

extern crate build_helper;
extern crate gcc;

use std::env;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if cfg!(feature = "backtrace") && !target.contains("apple") && !target.contains("msvc") &&
        !target.contains("emscripten") && !target.contains("fuchsia") && !target.contains("redox") {
        let _ = build_libbacktrace(&host, &target);
    }

    if target.contains("linux") {
        if target.contains("android") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=log");
            println!("cargo:rustc-link-lib=gcc");
        } else if !target.contains("musl") || target.contains("mips") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=rt");
            println!("cargo:rustc-link-lib=pthread");
        }
    } else if target.contains("freebsd") {
        println!("cargo:rustc-link-lib=execinfo");
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("dragonfly") || target.contains("bitrig") ||
              target.contains("netbsd") || target.contains("openbsd") {
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("solaris") {
        println!("cargo:rustc-link-lib=socket");
        println!("cargo:rustc-link-lib=posix4");
        println!("cargo:rustc-link-lib=pthread");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-darwin") {
        println!("cargo:rustc-link-lib=System");

        // res_init and friends require -lresolv on macOS/iOS.
        // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-ios") {
        println!("cargo:rustc-link-lib=System");
        println!("cargo:rustc-link-lib=objc");
        println!("cargo:rustc-link-lib=framework=Security");
        println!("cargo:rustc-link-lib=framework=Foundation");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("windows") {
        println!("cargo:rustc-link-lib=advapi32");
        println!("cargo:rustc-link-lib=ws2_32");
        println!("cargo:rustc-link-lib=userenv");
        println!("cargo:rustc-link-lib=shell32");
    } else if target.contains("fuchsia") {
        // use system-provided libbacktrace
        if cfg!(feature = "backtrace") {
            println!("cargo:rustc-link-lib=backtrace");
        }
        println!("cargo:rustc-link-lib=magenta");
        println!("cargo:rustc-link-lib=mxio");
        println!("cargo:rustc-link-lib=launchpad"); // for std::process
    }
}

fn build_libbacktrace(host: &str, target: &str) -> Result<(), ()> {
    let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", ".libs")?;

    let compiler = gcc::Config::new().get_compiler();
    // only msvc returns None for ar so unwrap is okay
    let ar = build_helper::cc2ar(compiler.path(), target).unwrap();
    let mut cflags = compiler.args().iter().map(|s| s.to_str().unwrap())
                             .collect::<Vec<_>>().join(" ");
    cflags.push_str(" -fvisibility=hidden");
    run(Command::new("sh")
                .current_dir(&native.out_dir)
                .arg(native.src_dir.join("configure").to_str().unwrap()
                                   .replace("C:\\", "/c/")
                                   .replace("\\", "/"))
                .arg("--with-pic")
                .arg("--disable-multilib")
                .arg("--disable-shared")
                .arg("--disable-host-shared")
                .arg(format!("--host={}", build_helper::gnu_target(target)))
                .arg(format!("--build={}", build_helper::gnu_target(host)))
                .env("CC", compiler.path())
                .env("AR", &ar)
                .env("RANLIB", format!("{} s", ar.display()))
                .env("CFLAGS", cflags));

    run(Command::new(build_helper::make(host))
                .current_dir(&native.out_dir)
                .arg(format!("INCDIR={}", native.src_dir.display()))
                .arg("-j").arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set")));
    Ok(())
}
<|endoftext|>


<commit_before>use std::cmp::Ordering;

use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;

use error::{LinkError, LinkErrorKind};
use result::Result;

use toml::Value;
use itertools::Itertools;

pub type Link = StoreId;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            new_links.push(link);
        }

        let new_links = links_into_values(new_links);
        if new_links.iter().any(|o| o.is_none()) {
            return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
        }
        let new_links = new_links.into_iter().map(|o| o.unwrap()).collect();
        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(new_link);
                        rewrite_links(self.get_header_mut(), links)
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc   = link.get_location().clone();
        let other_loc = link.get_location().clone();

        link.get_internal_links()
            .and_then(|links| {
                let links = links.into_iter().filter(|l| l.clone() != own_loc).collect();
                rewrite_links(self.get_header_mut(), links)
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|links| {
                        let links = links.into_iter().filter(|l| l.clone() != other_loc).collect();
                        rewrite_links(link.get_header_mut(), links)
                    })
            })
    }

}

fn links_into_values(links: Vec<StoreId>) -> Vec<Option<Value>> {
    links
        .into_iter()
        .map(|s| s.to_str().map(String::from))
        .unique()
        .map(|elem| elem.map(Value::String))
        .sorted_by(|a, b| {
            match (a, b) {
                (&Some(Value::String(ref a)), &Some(Value::String(ref b))) => Ord::cmp(a, b),
                (&None, _) | (_, &None) => Ordering::Equal,
                _                                              => unreachable!()
            }
        })
}

fn rewrite_links(header: &mut EntryHeader, links: Vec<StoreId>) -> Result<()> {
    let links = links_into_values(links);

    if links.iter().any(|o| o.is_none()) {
        // if any type convert failed we fail as well
        Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
    } else {
        // I know it is ugly
        let links = links.into_iter().map(|opt| opt.unwrap()).collect();
        let process = header.set("imag.links", Value::Array(links));
        process_rw_result(process).map(|_| ())
    }
}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    target.get_internal_links()
        .and_then(|mut links| {
            links.push(from);
            let links = links_into_values(links);
            if links.iter().any(|o| o.is_none()) {
                Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
            } else {
                let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            }
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        debug!("RW action on store failed. Generating LinkError");
        let lerr  = LinkError::new(LinkErrorKind::EntryHeaderReadError,
                                   Some(Box::new(links.unwrap_err())));
        return Err(lerr);
    }
    let links = links.unwrap();

    if links.is_none() {
        debug!("We got no value from the header!");
        return Ok(vec![])
    }
    let links = links.unwrap();

    let links = {
        match links {
            Value::Array(a) => a,
            _ => {
                debug!("We expected an Array for the links, but there was a non-Array!");
                return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
            },
        }
    };

    if !links.iter().all(|l| is_match!(*l, Value::String(_))) {
        debug!("At least one of the Values which were expected in the Array of links is a non-String!");
        debug!("Generating LinkError");
        return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => StoreId::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    debug!("Ok, the RW action was successful, returning link vector now!");
    Ok(links)
}

<commit_msg>Use IntoError to have less noise in the error construction code<commit_after>use std::cmp::Ordering;

use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;
use libimagerror::into::IntoError;

use error::LinkErrorKind as LEK;
use result::Result;

use toml::Value;
use itertools::Itertools;

pub type Link = StoreId;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            new_links.push(link);
        }

        let new_links = links_into_values(new_links);
        if new_links.iter().any(|o| o.is_none()) {
            return Err(LEK::InternalConversionError.into());
        }
        let new_links = new_links.into_iter().map(|o| o.unwrap()).collect();
        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(new_link);
                        rewrite_links(self.get_header_mut(), links)
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc   = link.get_location().clone();
        let other_loc = link.get_location().clone();

        link.get_internal_links()
            .and_then(|links| {
                let links = links.into_iter().filter(|l| l.clone() != own_loc).collect();
                rewrite_links(self.get_header_mut(), links)
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|links| {
                        let links = links.into_iter().filter(|l| l.clone() != other_loc).collect();
                        rewrite_links(link.get_header_mut(), links)
                    })
            })
    }

}

fn links_into_values(links: Vec<StoreId>) -> Vec<Option<Value>> {
    links
        .into_iter()
        .map(|s| s.to_str().map(String::from))
        .unique()
        .map(|elem| elem.map(Value::String))
        .sorted_by(|a, b| {
            match (a, b) {
                (&Some(Value::String(ref a)), &Some(Value::String(ref b))) => Ord::cmp(a, b),
                (&None, _) | (_, &None) => Ordering::Equal,
                _                                              => unreachable!()
            }
        })
}

fn rewrite_links(header: &mut EntryHeader, links: Vec<StoreId>) -> Result<()> {
    let links = links_into_values(links);

    if links.iter().any(|o| o.is_none()) {
        // if any type convert failed we fail as well
        Err(LEK::InternalConversionError.into())
    } else {
        // I know it is ugly
        let links = links.into_iter().map(|opt| opt.unwrap()).collect();
        let process = header.set("imag.links", Value::Array(links));
        process_rw_result(process).map(|_| ())
    }
}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    target.get_internal_links()
        .and_then(|mut links| {
            links.push(from);
            let links = links_into_values(links);
            if links.iter().any(|o| o.is_none()) {
                Err(LEK::InternalConversionError.into())
            } else {
                let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            }
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        debug!("RW action on store failed. Generating LinkError");
        return Err(LEK::EntryHeaderReadError.into_error_with_cause(Box::new(links.unwrap_err())))
    }
    let links = links.unwrap();

    if links.is_none() {
        debug!("We got no value from the header!");
        return Ok(vec![])
    }
    let links = links.unwrap();

    let links = {
        match links {
            Value::Array(a) => a,
            _ => {
                debug!("We expected an Array for the links, but there was a non-Array!");
                return Err(LEK::ExistingLinkTypeWrong.into());
            },
        }
    };

    if !links.iter().all(|l| is_match!(*l, Value::String(_))) {
        debug!("At least one of the Values which were expected in the Array of links is a non-String!");
        debug!("Generating LinkError");
        return Err(LEK::ExistingLinkTypeWrong.into());
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => StoreId::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    debug!("Ok, the RW action was successful, returning link vector now!");
    Ok(links)
}

<|endoftext|>


<commit_before><commit_msg>Add console example<commit_after>//! An extremely simple libtock-rs example. Just prints out a message
//! using the Console capsule, then terminates.

#![no_main]
#![no_std]
use core::fmt::Write;
use libtock2::console::Console;
use libtock2::runtime::{set_main, stack_size};

set_main! {main}
stack_size! {0x100}

fn main() {
    writeln!(Console::writer(), "Hello world!").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2399<commit_after>// https://leetcode.com/problems/check-distances-between-same-letters/
pub fn check_distances(s: String, distance: Vec<i32>) -> bool {
    todo!()
}

fn main() {
    println!(
        "{}",
        check_distances(
            "abaccb".to_string(),
            vec![1, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        )
    ); // true
    println!(
        "{}",
        check_distances(
            "aa".to_string(),
            vec![1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        )
    ); // false
}
<|endoftext|>


<commit_before><commit_msg>Optimization: Get the Message-Id from the header, if it is there<commit_after><|endoftext|>


<commit_before><commit_msg>config: remove commented code<commit_after><|endoftext|>


<commit_before><commit_msg>Outsource hashing itself so that we can re-use it<commit_after><|endoftext|>


<commit_before><commit_msg>Format and organization<commit_after><|endoftext|>


<commit_before><commit_msg>Remove old unsafe device code.<commit_after><|endoftext|>


<commit_before>// run-pass
// ignore-wasm

// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
// as well as some compile time properties we expect.

#![feature(dbg_macro)]

#[derive(Copy, Clone, Debug)]
struct Unit;

#[derive(Copy, Clone, Debug, PartialEq)]
struct Point<T> {
    x: T,
    y: T,
}

#[derive(Debug, PartialEq)]
struct NoCopy(usize);

fn test() {
    let a: Unit = dbg!(Unit);
    let _: Unit = dbg!(a);
    // We can move `a` because it's Copy.
    drop(a);

    // `Point<T>` will be faithfully formatted according to `{:#?}`.
    let a = Point { x: 42, y: 24 };
    let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
    let c: Point<u8> = dbg!(b);
    // Identity conversion:
    assert_eq!(a, b);
    assert_eq!(a, c);
    // We can move `b` because it's Copy.
    drop(b);

    // Test that we can borrow and that successive applications is still identity.
    let a = NoCopy(1337);
    let b: &NoCopy = dbg!(dbg!(&a));
    assert_eq!(&a, b);

    // Test involving lifetimes of temporaries:
    fn f<'a>(x: &'a u8) -> &'a u8 { x }
    let a: &u8 = dbg!(f(&42));
    assert_eq!(a, &42);

    // Test side effects:
    let mut foo = 41;
    assert_eq!(7331, dbg!({
        foo += 1;
        eprintln!("before");
        7331
    }));
    assert_eq!(foo, 42);
}

fn validate_stderr(stderr: Vec<String>) {
    assert_eq!(stderr, &[
        ":22] Unit = Unit",

        ":23] a = Unit",

        ":29] Point{x: 42, y: 24,} = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":30] b = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":39] &a = NoCopy(",
        "    1337",
        ")",

        ":39] dbg!(& a) = NoCopy(",
        "    1337",
        ")",
        ":44] f(&42) = 42",

        "before",
        ":49] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
    ]);
}

fn main() {
    // The following is a hack to deal with compiletest's inability
    // to check the output (to stdout) of run-pass tests.
    use std::env;
    use std::process::Command;

    let mut args = env::args();
    let prog = args.next().unwrap();
    let child = args.next();
    if let Some("child") = child.as_ref().map(|s| &**s) {
        // Only run the test if we've been spawned as 'child'
        test()
    } else {
        // This essentially spawns as 'child' to run the tests
        // and then it collects output of stderr and checks the output
        // against what we expect.
        let out = Command::new(&prog).arg("child").output().unwrap();
        assert!(out.status.success());
        assert!(out.stdout.is_empty());

        let stderr = String::from_utf8(out.stderr).unwrap();
        let stderr = stderr.lines().map(|mut s| {
            if s.starts_with("[") {
                // Strip `[` and file path:
                s = s.trim_start_matches("[");
                assert!(s.starts_with(file!()));
                s = s.trim_start_matches(file!());
            }
            s.to_owned()
        }).collect();

        validate_stderr(stderr);
    }
}
<commit_msg>dbg_macro:  more things...<commit_after>// run-pass
// ignore-wasm
// ignore-wasm32
// ignore-cloudabi no processes
// ignore-emscripten no processes

// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
// as well as some compile time properties we expect.

#![feature(dbg_macro)]

#[derive(Copy, Clone, Debug)]
struct Unit;

#[derive(Copy, Clone, Debug, PartialEq)]
struct Point<T> {
    x: T,
    y: T,
}

#[derive(Debug, PartialEq)]
struct NoCopy(usize);

fn test() {
    let a: Unit = dbg!(Unit);
    let _: Unit = dbg!(a);
    // We can move `a` because it's Copy.
    drop(a);

    // `Point<T>` will be faithfully formatted according to `{:#?}`.
    let a = Point { x: 42, y: 24 };
    let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
    let c: Point<u8> = dbg!(b);
    // Identity conversion:
    assert_eq!(a, b);
    assert_eq!(a, c);
    // We can move `b` because it's Copy.
    drop(b);

    // Test that we can borrow and that successive applications is still identity.
    let a = NoCopy(1337);
    let b: &NoCopy = dbg!(dbg!(&a));
    assert_eq!(&a, b);

    // Test involving lifetimes of temporaries:
    fn f<'a>(x: &'a u8) -> &'a u8 { x }
    let a: &u8 = dbg!(f(&42));
    assert_eq!(a, &42);

    // Test side effects:
    let mut foo = 41;
    assert_eq!(7331, dbg!({
        foo += 1;
        eprintln!("before");
        7331
    }));
    assert_eq!(foo, 42);
}

fn validate_stderr(stderr: Vec<String>) {
    assert_eq!(stderr, &[
        ":22] Unit = Unit",

        ":23] a = Unit",

        ":29] Point{x: 42, y: 24,} = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":30] b = Point {",
        "    x: 42,",
        "    y: 24",
        "}",

        ":39] &a = NoCopy(",
        "    1337",
        ")",

        ":39] dbg!(& a) = NoCopy(",
        "    1337",
        ")",
        ":44] f(&42) = 42",

        "before",
        ":49] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
    ]);
}

fn main() {
    // The following is a hack to deal with compiletest's inability
    // to check the output (to stdout) of run-pass tests.
    use std::env;
    use std::process::Command;

    let mut args = env::args();
    let prog = args.next().unwrap();
    let child = args.next();
    if let Some("child") = child.as_ref().map(|s| &**s) {
        // Only run the test if we've been spawned as 'child'
        test()
    } else {
        // This essentially spawns as 'child' to run the tests
        // and then it collects output of stderr and checks the output
        // against what we expect.
        let out = Command::new(&prog).arg("child").output().unwrap();
        assert!(out.status.success());
        assert!(out.stdout.is_empty());

        let stderr = String::from_utf8(out.stderr).unwrap();
        let stderr = stderr.lines().map(|mut s| {
            if s.starts_with("[") {
                // Strip `[` and file path:
                s = s.trim_start_matches("[");
                assert!(s.starts_with(file!()));
                s = s.trim_start_matches(file!());
            }
            s.to_owned()
        }).collect();

        validate_stderr(stderr);
    }
}
<|endoftext|>


<commit_before><commit_msg>Move Frame<commit_after><|endoftext|>


<commit_before><commit_msg>Ignore distance between stations for now.<commit_after><|endoftext|>


<commit_before><commit_msg>More solutions<commit_after>// https://leetcode.com/problems/car-fleet/

pub trait Solution {
    fn car_fleet(target: i32, position: Vec<i32>, speed: Vec<i32>) -> i32;
}
pub struct Solution1;
pub struct Solution2;

impl Solution1 {
    #[inline]
    fn compute_duration(target: i32, pos: i32, speed: i32) -> f64 {
        (target as f64 - pos as f64) / speed as f64
    }
}

impl Solution for Solution1 {
    // This solution is based on stack
    // 1. Calculate durations from the position and speed of each car.
    // 2. Sort positions. Also sort durations by their corresponding positions.
    // 3. Iterate through positions and durations. For each new duration, pop
    //    anything in the stack that has a smaller duration (runs faster). Then
    //    push the new duration into the stack.
    // 4. Return the size of the stack. Each element represents a fleet.
    fn car_fleet(target: i32, position: Vec<i32>, speed: Vec<i32>) -> i32 {
        if position.len() == 0 {
            return 0;
        }
        let durations: Vec<f64> = speed
            .into_iter()
            .enumerate()
            .map(|(idx, spd)| Self::compute_duration(target, position[idx], spd))
            .collect();
        let mut pos_dur_pairs: Vec<(i32, f64)> = position.into_iter().zip(durations).collect();
        pos_dur_pairs.sort_by(|a, b| a.0.cmp(&b.0));

        let mut stack: Vec<f64> = Vec::new();

        for (_, dur) in pos_dur_pairs {
            while !stack.is_empty() && stack.last().unwrap() <= &dur {
                stack.pop();
            }
            stack.push(dur);
        }

        return stack.len() as i32;
    }
}

impl Solution for Solution2 {
    // This is the fastest submitted solution in leetcode so far. The idea is
    // instead of iterating forward, by iterating in the reverse order, we can
    // get rid of the stack because if a car behind me reaches the target later
    // than me, it definitely forms a new fleet. The same goes with all cars
    // behind it.
    fn car_fleet(target: i32, position: Vec<i32>, speed: Vec<i32>) -> i32 {
        let n = position.len();
        let mut pos_speed = vec![(0, 0); n];

        for i in 0..n {
            pos_speed[i] = (position[i], speed[i]);
        }

        pos_speed.sort_unstable_by(|a, b| b.cmp(&a));

        // println!("{:?}", pos_speed);

        let mut result = 0;
        let mut current = 0f64;

        for i in 0..n {
            let (pos, speed) = pos_speed[i];
            let time = (target - pos) as f64 / speed as f64;

            if time > current {
                result += 1;
                current = time;
            }
        }
        return result as i32;
    }
}

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

    mod solution1 {
        use super::*;

        #[test]
        fn test_1() {
            assert_eq!(
                Solution1::car_fleet(12, vec![10, 8, 0, 5, 3], vec![2, 4, 1, 1, 3]),
                3
            );
        }

        #[test]
        fn test_2() {
            assert_eq!(Solution1::car_fleet(10, vec![3], vec![3]), 1);
        }

        #[test]
        fn test_3() {
            assert_eq!(Solution1::car_fleet(100, vec![0, 2, 4], vec![4, 2, 1]), 1);
        }
    }

    mod solution2 {
        use super::*;

        #[test]
        fn test_1() {
            assert_eq!(
                Solution2::car_fleet(12, vec![10, 8, 0, 5, 3], vec![2, 4, 1, 1, 3]),
                3
            );
        }

        #[test]
        fn test_2() {
            assert_eq!(Solution2::car_fleet(10, vec![3], vec![3]), 1);
        }

        #[test]
        fn test_3() {
            assert_eq!(Solution2::car_fleet(100, vec![0, 2, 4], vec![4, 2, 1]), 1);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for expanding doc strings in macros.<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-pretty - token trees can't pretty print

#![feature(macro_rules)]

macro_rules! descriptions {
    ($name:ident is $desc:expr) => {
        // Check that we will correctly expand attributes
        #[doc = $desc]
        #[allow(dead_code)]
        const $name : &'static str = $desc;
    }
}

// item
descriptions!(DOG is "an animal")
descriptions!(RUST is "a language")

pub fn main() {
}
<|endoftext|>


<commit_before><commit_msg>split LCG into library and binary<commit_after>extern crate rand;

pub use rand::{Rng, SeedableRng};

pub struct BsdLcg {
    state: u32,
}

impl Rng for BsdLcg {
    fn next_u32(&mut self) -> u32 {
        self.state = self.state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
        self.state %= 1 << 31;
        self.state
    }
}

impl SeedableRng<u32> for BsdLcg {
    fn from_seed(seed: u32) -> Self {
        Self { state: seed }
    }
    fn reseed(&mut self, seed: u32) {
        self.state = seed;
    }
}

pub struct MsLcg {
    state: u32,
}

impl Rng for MsLcg {
    // Because this only uses the high 16 bits of the state (`>> 16`), this should technically use
    // `next_u16`, but the `rand` crate does not provide it.  If serious usage is required,
    // implementing this function as a concatenation of two `next_u16`s (elsewhere defined) should
    // work.
    fn next_u32(&mut self) -> u32 {
        self.state = self.state.wrapping_mul(214_013).wrapping_add(2_531_011);
        self.state %= 1 << 31;
        self.state >> 16 //  rand_n = state_n / 2^16
    }
}

impl SeedableRng<u32> for MsLcg {
    fn from_seed(seed: u32) -> Self {
        Self { state: seed }
    }
    fn reseed(&mut self, seed: u32) {
        self.state = seed;
    }
}

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

    #[test]
    fn test_ms() {
        let mut rng = MsLcg::from_seed(1);

        for &num in &[41, 18467, 6334, 26500, 19169] {
            assert_eq!(rng.next_u32(), num);
        }
    }

    #[test]
    fn test_bsd() {
        let mut rng = BsdLcg::from_seed(1);

        for &num in &[1103527590, 377401575, 662824084, 1147902781, 2035015474] {
            assert_eq!(rng.next_u32(), num);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add example with threads and a shared counter<commit_after>// same as threaded.rs, except that the counter is thread safe
// and report the correct number of requests, parallel or not

extern crate rotor;
extern crate rotor_http;

use std::env;
use std::thread;
use std::time::Duration;

use rotor::{Scope, Time};
use rotor_http::server::{Fsm, RecvMode, Server, Head, Response};
use rotor::mio::tcp::TcpListener;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

struct Context {
    counter: Arc<AtomicUsize>,
}

trait Counter {
    fn increment(&mut self);
    fn get(&self) -> usize;
}

impl Counter for Context {
    fn increment(&mut self) { self.counter.fetch_add(1, Ordering::SeqCst); }
    fn get(&self) -> usize { self.counter.load(Ordering::SeqCst) }
}

#[derive(Debug, Clone)]
enum HelloWorld {
    Hello,
    GetNum,
    HelloName(String),
    PageNotFound,
}

fn send_string(res: &mut Response, data: &[u8]) {
    res.status(200, "OK");
    res.add_length(data.len() as u64).unwrap();
    res.done_headers().unwrap();
    res.write_body(data);
    res.done();
}

impl Server for HelloWorld {
    type Seed = ();
    type Context = Context;
    fn headers_received(_seed: (), head: Head, _res: &mut Response,
        scope: &mut Scope<Context>)
        -> Option<(Self, RecvMode, Time)>
    {
        use self::HelloWorld::*;
        scope.increment();
        Some((match head.path {
            "/" => Hello,
            "/num" => GetNum,
            p if p.starts_with('/') => HelloName(p[1..].to_string()),
            _ => PageNotFound
        }, RecvMode::Buffered(1024), scope.now() + Duration::new(10, 0)))
    }
    fn request_received(self, _data: &[u8], res: &mut Response,
        scope: &mut Scope<Context>)
        -> Option<Self>
    {
        use self::HelloWorld::*;
        match self {
            Hello => {
                send_string(res, b"Hello World!");
            }
            GetNum => {
                send_string(res,
                    format!("This host has been visited {} times",
                        scope.get())
                    .as_bytes());
            }
            HelloName(name) => {
                send_string(res, format!("Hello {}!", name).as_bytes());
            }
            PageNotFound => {
                let data = b"404 - Page not found";
                res.status(404, "Not Found");
                res.add_length(data.len() as u64).unwrap();
                res.done_headers().unwrap();
                res.write_body(data);
                res.done();
            }
        }
        None
    }
    fn request_chunk(self, _chunk: &[u8], _response: &mut Response,
        _scope: &mut Scope<Context>)
        -> Option<Self>
    {
        unreachable!();
    }

    /// End of request body, only for Progressive requests
    fn request_end(self, _response: &mut Response, _scope: &mut Scope<Context>)
        -> Option<Self>
    {
        unreachable!();
    }

    fn timeout(self, _response: &mut Response, _scope: &mut Scope<Context>)
        -> Option<(Self, Time)>
    {
        unimplemented!();
    }
    fn wakeup(self, _response: &mut Response, _scope: &mut Scope<Context>)
        -> Option<Self>
    {
        unimplemented!();
    }
}

fn main() {
    let lst = TcpListener::bind(&"127.0.0.1:3000".parse().unwrap()).unwrap();
    let threads = env::var("THREADS").unwrap_or("2".to_string())
        .parse().unwrap();
    let mut children = Vec::new();
    let counter = Arc::new(AtomicUsize::new(0));
    for _ in 0..threads {
        let counter_ref = counter.clone();
        let listener = lst.try_clone().unwrap();
        children.push(thread::spawn(move || {
            let event_loop = rotor::Loop::new(
                &rotor::Config::new()).unwrap();
            let mut loop_inst = event_loop.instantiate(Context {
                counter: counter_ref,
            });
            loop_inst.add_machine_with(|scope| {
                Fsm::<HelloWorld, _>::new(listener, (), scope)
            }).unwrap();
            loop_inst.run().unwrap();
        }));
    }
    for child in children {
        child.join().unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix #7093<commit_after><|endoftext|>


<commit_before><commit_msg>style: Undo minor debugging change.<commit_after><|endoftext|>